So many men, so many minds. When we are implementing software for different customers we sometimes need to handle various requirements for the same project. For example Customer A needs SAML authentication and customer B needs LDAP authentication. With Spring Profiles (available from Spring 3.1) we are able to provide a way to segregate parts of our implemented application configuration. This blog will help us to make certain code or rather certain Spring beans only available for specific requirements. For example the example used in this blog can be used to activate the required authentication provider for the provider manager when using Spring Security. Profiles can be configured by annotations and/or by xml. Annotations @Component or @Configuration annotated beans can contain the annotation @Profile to only load them in a certain environment.
@Component
@Profile("ldap")
public class LDAPAuthentication {
public LDAPAuthentication() {
System.out.println("LDAP Authentication set by annotations");
}
}
@Component
@Profile("saml")
public class SAMLAuthentication {
public SAMLAuthentication() {
System.out.println("SAML Authentication set by annotations");
}
}
Continue reading →
I get this question quite often and I struggled with it many times before: How do I work with temporary files in my JUnit testcases? I would like to explain two simple ways of working with temporary files in JUnit.
Create a temporary file with the Java File API and mark it directly as deleteOnExit()
. The created file will be deleted when the JVM exits.
Continue reading →
Grails has some useful tags for rendering errors of an object in a view. Below we see an example whichs renders the errors for a single bean.
<g:hasErrors bean="${person}">
<g:renderErrors bean="${person}"/>
</g:hasErrors>
Continue reading →
We are building a Spring Boot application with a REST interface and at some point we wanted to test our REST interface, and if possible, integrate this testing with our regular unit tests. One way of doing this, would be to @Autowire
our REST controllers and call our endpoints using that. However, this won't give full converage, since it will skip things like JSON deserialisation and global exception handling. So the ideal situation for us would be to start our application when the unit test start, and close it again, after the last unit test. It just so happens that Spring Boot does this all for us with one annotation: @IntegrationTest
. Here is an example implementation of an abstract class you can use for your unit-tests which will automatically start the application prior to starting your unit tests, caching it, and close it again at the end.
package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
// Your spring configuration class containing the @EnableAutoConfiguration
// annotation
@SpringApplicationConfiguration(classes = Application.class)
// Makes sure the application starts at a random free port, caches it throughout
// all unit tests, and closes it again at the end.
@IntegrationTest("server.port:0")
@WebAppConfiguration
public abstract class AbstractIntegrationTest {
// Will contain the random free port number
@Value("${local.server.port}")
private int port;
/**
* Returns the base url for your rest interface
*
* @return
*/
private String getBaseUrl() {
return "http://localhost:" + port;
}
// Some convenience methods to help you interact with your rest interface
/**
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceReturnTypeClass
* should be the the return type of the service
* @param parametersInOrderOfAppearance
* should be the parameters of the requestMappingUrl ({}) in
* order of appearance
* @return the result of the service, or null on error
*/
protected T getEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object... parametersInOrderOfAppearance) {
// Make a rest template do do the service call
final TestRestTemplate restTemplate = new TestRestTemplate();
// Add correct headers, none for this example
final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
try {
// Do a call the the url
final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,
parametersInOrderOfAppearance);
// Return result
return entity.getBody();
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
/**
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceListReturnTypeClass
* should be the the generic type of the list the service
* returns, eg: List * @param parametersInOrderOfAppearance
* should be the parameters of the requestMappingUrl ({}) in
* order of appearance
* @return the result of the service, or null on error
*/
protected List getList(final String requestMappingUrl, final Class serviceListReturnTypeClass, final Object... parametersInOrderOfAppearance) {
final ObjectMapper mapper = new ObjectMapper();
final TestRestTemplate restTemplate = new TestRestTemplate();
final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
try {
// Retrieve list
final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance);
final List> entries = entity.getBody();
final List returnList = new ArrayList();
for (final Map entry : entries) {
// Fill return list with converted objects
returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass));
}
return returnList;
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
/**
*
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceReturnTypeClass
* should be the the return type of the service
* @param objectToPost
* Object that will be posted to the url
* @return
*/
protected T postEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object objectToPost) {
final TestRestTemplate restTemplate = new TestRestTemplate();
final ObjectMapper mapper = new ObjectMapper();
try {
final HttpEntity requestEntity = new HttpEntity(mapper.writeValueAsString(objectToPost));
final ResponseEntity entity = restTemplate.postForEntity(getBaseUrl() + requestMappingUrl, requestEntity, serviceReturnTypeClass);
return entity.getBody();
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
}
Continue reading →
Defining a maven plugin on a submodule in a multi-module maven project can give us a 'No plugin found' error. Especially if we have a multi-module project and we want to apply a maven plugin in only one specific module this error occur pretty often. Let's say we have a multi-module root pom which looks like this.
4.0.0
com.jdriven.blog
maven-plugin-multimodule
0.1-SNAPSHOT
pom
module1
module2
Continue reading →
Since version 2.2 Grails, has better support for managing namespace configuration. This helps to prevent common namespace problems. For example most applications which have security functionality, have for example a UserDetailService
which can conflict when you have the Grails SpringSecurity
plugin installed. Grails version 2.2. and later comes with four useful techniques to make sure the right class is used
If Grails does not find an existing service with a similar name, Grails will automatically generate an alias for you service with the name of the plugin prefix. For example when you have a plugin called UserUtilities
and a service called UserDetailService
, you can use UserUtilitiesUserDetailService
for dependency injection which will not conflict with the SpringSecurity UserDetailService
Continue reading →
At the release of Java 8 the most attention went to the Lamda’s, the new Date API and the Nashorn Javascript engine. In the shade of these, there are smaller but also interesting changes. Amongst them is the introduction of a StringJoiner. The StringJoiner is a utility to delimit a list of characters or strings. You may recognize the code below:
String getString(List<String> items)
StringBuilder sb = new StringBuilder();
for(String item : items) {
if(sb.length != 0) {
sb.append(",");
}
sb.append(item);
}
return sb.toString();
}
Continue reading →
Grails is built on Groovy which is known as a dynamic language. The dynamic nature of Groovy offers a lot of powerful features but also defers the detection of errors from compile time to runtime. To shorten the feedback cycle for your code Groovy has a handy annotation which will make sure that your classes is are statically compiled. This will give you fast feedback for a lot of mistakes and you also will benefit from the increased performance offered by the static complication. Unfortunately in Grails this annotation prevents you from using the very useful dynamic GORM methods like list()
, get()
and the dynamic finder methods. Groovy does not recognize these Grails methods during compile time; see the example below.
@CompileStatic
class BookController(){
def save(){
//This will successfully compile
}
def get(){
Book.findByName(params.name)
//this will throw a compile error since the findByName method is not known
//at compile time
}
@CompileStatic(TypeCheckingMode.SKIP)
def delete(){
//by setting the TypeCheckinMode, this method will be skipped
}
}
Continue reading →
One of the handy features of Groovy is to change the behavior of classes using MOP (Meta-Object Protocol). We change the metaClass
property of a class to alter an implementation. You can for example override a static method of a class. See the example below:
class UserSpec extends Specification {
def “test user”() {
given:
// we can mock static methods...
User.metaClass.static.findByName = { name ->
new User(name: ‘Albert’) }
when:
User user = User.findByName(‘Albert’)
then:
user.name == ‘Albert’
when:
// .. but also non-static methods
user.metaClass.getName = { return ‘Dries’ }
then:
user.name == ‘Dries’
}
}
Continue reading →
Being passionate about AngularJS, me and two fellow JDriven colleagues visited the ngEurope conference. The amount of presentations during ngEurope was somewhat overwhelming, especially during the mornings without any scheduled break. Good thing I made some notes, that the slides are already available on-line and that someone published quite detailed notes for all sessions. Without all this I might simply have forgotten about some very interesting and relevant details. During ngEurope there was a all lot of attention for the just released 1.3 version of AngularJS and the coming 2.0 release.
The latest AngularJS 1.3 release features some great performance improvements (3.5x faster digest and 4.4x faster DOM manipulation) and much less pressure on the garbage collector (GC). However in order to achieve this the AngularJS team did decide drop the support for Internet Explorer 8 (which is default IE version on Windows 7). To allow for even more (optional) speed improvement one time (one way) binding support has been added. Using one time binding no $watch will be registered for the binding; typically you would use one time bindings to speed up rendering the elements of ngRepeat. Additionally a lot of improvements are done on the ngModel directive. First of all a $validators pipeline had been introduced as an alternative to invoking $setValidity from a parser / formatter function. Which also fixes the "input not showing invalid model values” bug ( #1422). Yet another great improvement are the new async validators that allows for (asynchronous) model validation on the back-end. The ngModel directive is now accompanied by the ngModelOptions directive that allows you to configure (the controller of) the ngModel directive. We now can specify when we want the model value to be updated. For instance after a short delay (a so called debounce) or on blur (i.e. when focussing another field). And using ngModelOptions we can now configure the usage of (jQuery) style getter / setter function on our model (instead of using plain data properties). Using ngMessages (multiple different) error messages can now be shown much easier in a switch–case like style for a form element. Besides preformance- and ngModel (related) improvements AngularJS also features some other noteworthy features:
Continue reading →
Since version 2.3 Grails has excellent support for creating REST APIs. This new support comes with some new console commands. Besides the well known generate-controller
command, Grails now comes with a new command which let you generate restful controllers for a given domain class. In the following example, we will create a restful controller using the new generate-restful-controller command.
First we create a domain object
$ grails create-domain-class grails.data.Movie
Continue reading →
Just a small reminder. Javascript allows you to call methods based on their name. So if a DOM element has a addClass and removeClass which both take the same argument we could write:
var someClass = 'some-class';
var hasClass = element.hasClass(someClass);
if(hasClass){
element.addClass(someClass);
} else {
element.removeClass(someClass);
}
Continue reading →