2017. október 5., csütörtök

Custom validator for REST parameter in Spring Boot


Using Spring boot applications, it is very easy to let the Spring framework to do the validation of the REST input parameter. You only need to add the corresponding validation annotations to the properties of the parameter class, and mark the parameter with @Valid annotation in the method header.


@RequestMapping(value = "/register", method = { RequestMethod.POST })
public RestResponse register(HttpServletRequest httpServletRequest, 
       @Valid @RequestBody PushRegistrationRequest registrationRequest) {



In case of your REST input object is validated with the @Valid annotation, most of the time, it is enough to  use default validations, like @NotNull, @Pattern, @Size, etc. Sometimes though you need to do more complex validations, considering multiple properties. To achieve this, you need to write your own annotation, and a corresponding validation class.

The annotation looks like this:


@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = { HasCorrectAppIdValidator.class })
public @interface HasCorrectAppId {
 String message() default "App id is incorrect";

 Class<?>[] groups() default {};

 Class<? extends Payload>[] payload() default {};
}

  As you can see above, in the validatedBy attribute, you can define a validation class. the validator class needs to implement the javax.validation.ConstraintValidator interface.


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class HasCorrectAppIdValidator implements ConstraintValidator<HasCorrectAppId, PushRegistrationRequest> {

 @Override
 public void initialize(HasCorrectAppId constraintAnnotation) {
  // do nothing
 }

 @Override
 public boolean isValid(PushRegistrationRequest value, ConstraintValidatorContext context) {
  if (IOS.equals(value.getOs()) && value.getAppId().length() != 64) {
   String errorMessage = "length must be 64 for " + ClientOperationSystem.IOS;
   createErrorInContext(context, errorMessage);
   return false;

  } else if (ANDROID.equals(value.getOs()) && value.getAppId().length() < 65) {
   String errorMessage = "length must be greater than 65 for " + ClientOperationSystem.ANDROID;
   createErrorInContext(context, errorMessage);
   return false;
  }
  return true;
 }

 private void createErrorInContext(ConstraintValidatorContext context, String errorMessage) {
  context.disableDefaultConstraintViolation();
  context.buildConstraintViolationWithTemplate(errorMessage)
    .addPropertyNode("appId")
    .addConstraintViolation();
 }
}


That's it. In order to use tell to the framework to use the validator is, to annotate the parameter class with the new annotation.




@HasCorrectAppId
public class PushRegistrationRequest implements Serializable {
    ...
}


2017. szeptember 15., péntek

Using @ElementCollection in Spring JPA queries


In my domain model, I had a list of Strings to be stored. As it is a typical reason of using element collections, I decided to do so.

Using element collection in the domain model has the following advantages:
  • The domain model remains simple. No additional type, 
  • The connected list is bounded to the "master" entity. You do not need to take care of the maintenance of the elements by defining cascade type
  • The data was static, so only read from database was needed, therefore creating a one to many connection seemed not necessary. 
  • It is even possible to define an enumeration as type of the element collection. It gives the possibility to store only predefined values in the field.
My entity class looks like this:

@SuppressWarnings("serial")
@Entity
@Table(name = "SMART_HOME_SUBSCRIPTION")
@Data
public class SmartHomeSubscription implements Serializable {

 @Id
 @Column(name = "ID", unique = true, nullable = false, length = 36)
 private String id;

 @Column(name = "NAME", nullable = false, unique = true, length = 20)
 private String name;

 @ElementCollection(fetch = FetchType.EAGER)
 @CollectionTable(name = "ADDON", joinColumns = @JoinColumn(name = "SMART_HOME_SUBSCRIPTION_ID"))
 @Column(name = "NAME")
 private Set<String> addonNames = new HashSet<>();

 @ElementCollection(targetClass = AllowedFunction.class, fetch = FetchType.EAGER)
 @CollectionTable(name = "ALLOWED_FUNCTION", joinColumns = @JoinColumn(name = "SMART_HOME_SUBSCRIPTION_ID"))
 @Column(name = "NAME")
 @Enumerated(EnumType.STRING)
 private Set<AllowedFunction> allowedFunctions = new HashSet<>();
}

So how it is possible to use these element collections in queries in Spring JPA repository?

As you can see, the items of the element collection with String and annotated type can be used simple as Strings in the query. Equal and IN operator can be used to them such as for normal String fields.    


 @Query(value = "SELECT count(s) FROM SmartHomeSubscription s INNER JOIN s.allowedFunctions f INNER JOIN s.addonNames a WHERE f = :allowedFunction AND a IN :addonNames")
 public int getNumberOfAddonsValidForFunction(@Param("allowedFunction") AllowedFunction allowedFunction,
   @Param("addonNames") List<String> addonNames);










2017. szeptember 14., csütörtök

Create Spring service used only in test environment

Create Spring service used only in test environment

In my project, we use three different environments for running the application.
  • Production
  • SIT (system integration)
  • Local development
In the production environment thee is a third party system, that authenticates the user and automatically adds a header value to the request.

I wanted to implement a feature, which always requires the authentication information. So I needed to add mocked information into the REST request header in SIT and Local development environment.

I used a Service to process the request, and created additional subclasses for Local development and SIT environments. The subclasses must not be annotated as service. Otherwise you get exception at startup, marking that your service class in not unique.

The configuration of my local development environment looks like this:

@Configuration
@EnableScheduling
@EnableAsync
@EnableAspectJAutoProxy
@EnableTransactionManagement
@Profile("backend_localdev")
@EnableConfigurationProperties(DaoConfiguration.class)
public class BackendConfigurationLocalDev extends BackendConfiguration {

 @SuppressWarnings("unused")
 @Autowired
 private DaoConfiguration daoConfiguration;

 @Bean(value = "crbService")
 public CrbService getCrbService() {
  return new CrbServiceLocalDev();
 }
}


In order to add header values to the REST request, I implemented a HttpServletRequestWrapper class.

My service for local development looks like this:


public class CrbServiceLocalDev extends CrbService {

 // Logger instance
 private static final Logger log = LoggerFactory.getLogger(CrbServiceLocalDev.class);

 private static final String HARDCODED_CRB_USER_STATUS_HEADER_VALUE = "{\"key\":\"value\"}";

 @Override
 public CrbUserInfo createCrbUserInfo(HttpServletRequest request) {
  log.warn("Entering CrbServiceLocalDev.createCrbUserInfo(). Must be used only for local development");

  HttpServletRequestWrapper wrapper = new LocalDevHttpServletRequestWrapper(request);
  return super.createCrbUserInfo(wrapper);
 }

 private class LocalDevHttpServletRequestWrapper extends HttpServletRequestWrapper {

  public LocalDevHttpServletRequestWrapper(HttpServletRequest request) {
   super(request);
  }

  @Override
  public String getHeader(String name) {

   if (StringUtils.isBlank(name)) {
    return super.getHeader(name);
   }

   final String value = getRequest().getParameter(name);
   if (!StringUtils.isBlank(value)) {
    return value;
   }

   if (MobileAppCrbUserStatus.HEADER_PARAM_X_CRB_USERSTATUS.equals(name)) {
    log.warn("Hardcoded userstatus header value is returned: {}", HARDCODED_CRB_USER_STATUS_HEADER_VALUE);
    return HARDCODED_CRB_USER_STATUS_HEADER_VALUE;
   }

   return super.getHeader(name);
  }
 }

}



2017. augusztus 29., kedd

Setting up a convenient Eclipse working environment


Here I would like to list all task, I need to do when setting up my Eclipse environment


Plug-ins to be installed
  • More Unit - the best tool for generating and maintaining unit test created for Eclipse 
  • JRebel - in case of server side programming, you can save a huge amount of time with it. It is commerctal, but a community version also can be used. This version is full featured, only sends messages sometimes to your Facebook wall. 
  • Lombok - enhances the Java language with annotation based elements, bringing it closer to the features of Scala, and other modern, Java-like languages. I suse it to avoid coding boilerplate code. You can generate getter/setter, toString, etc. 
  • Findbugs - static code analysis tool
  • PMD - static code analysis tool
  • Ucdetector - detects unnecesary code in your application. Also can be used to lower the accessibility of your classes or elements.
  • JIRA connector 
  • Eclipse class decompiler
  • InstaSearch - makes searching way faster with Lucence based search engine. 
  • QuickRex - evaluating Regular expressions directly in Eclipse
Settings to be made
  • add source to java packages
  • set toString generation
  • set formatter
  • set comparison to ignore white spaces by default
  • set multi monitor environment. Do not forget to stop Eclipse always with File/Exit, instead of closing any of the windows.
  • import your collection of short-keys 

Export your environment

Using prototype in Spring singleton service



I wanted to use a Spring bean, with private fields in order to build an object. Previously the builder class was really as an example of the builder pattern implemented. It was able to build the required object based on the parameters, defined for the builder.

Later on, after the requirement changed, the builder had to use other services in order to get detailed information for the build process. In this case you have the following possibilities:
  • define all services as parameter of the build process, and use them when needed.
    I did not choose this option, as it would not have resulted a clear interface for the builder. The dependent services are mandatory for the build process, but the builder can not force to define them in its interface. So the client has to set up the builder correctly before using it. It would have resulted such a restriction, what I did not want to build into my system.
  • Implement the builder as a Spring singleton bean. In this case the singleton must not have a state, so it is not possible to define the build parameters as field of the bean. It would make the implementation less readable, while the parameters must have been passed to the private methods several times.
So I chose to concert my builder class into a Spring prototype bean. The necessary parameters must be set by the client, but the necessary services are injected with CDI by the container.

The result looked like this:


@Service(value = "logicBuilderService")
@Scope("prototype")
public final class LogicBuilderService {

 @Autowired
 private DeviceDAO deviceDao;

 @Autowired
 private SupportedDeviceDao supportedDeviceDao;

 // contains eagerly initialized device and channel collection
 @Setter
 private Gateway gateway;

 @Setter
 private LogicRequest request;

 public Logic build() {
  Logic logic = createNewLogic();
  addTrigger(logic);
  addActions(logic);

  return logic;
 }
....


At the client side, you need to use an Objectfactory, in order to get a new instance of the service. Whenever you need a new, clean instance of the builder, you get it from the Spring framework, without the properties set.


 @Autowired
 private ObjectFactory<LogicBuilderService> prototypeFactory;

 private LogicBuilderService getNewLogicBuilderServiceInstance(Gateway gateway, LogicRequest request) {
  LogicBuilderService logicBuilder = prototypeFactory.getObject();
  logicBuilder.setGateway(gateway);
  logicBuilder.setRequest(request);

  return logicBuilder;
 }

In order to use the LogicBuilderService in a unit test, you need to mock the ObjectFactory, so it returns a new instance of the builder for all calls.


@Mock
 private ObjectFactory<LogicBuilderService> prototypeFactory;

 @InjectMocks
 private LogicRestService logicRestService;

 @Before
 public void setup() {
  when(prototypeFactory.getObject()).thenReturn(new LogicBuilderService());
 }



2016. december 19., hétfő

Using logging in your unit test

When running unit test, you are not supposed to be checking the logs, generated by the test framework. One of the first principles of the test driving development paradigm is, that you should be able to run your tests automatically, without any developer interaction. You also should not be forced to check any output besides the running result. Also you should never check the log, to be able to decide if running the test was successful.

So long the theory.

In fact, sometimes it is very helpful, if you can analyse logging from your unit test. As you are working test driven, you use the unit test runner also for developing the code. In order to get a closer view to the process you are implementing, during the development phase, it can spare a lots of time and debugging, if you can have a look at the logs.

The problem is, that you do not want the change the log level in your code, to let JUnit process to log your debug or trace level logs. As JUnit is running with default INFO level (depending on the actual logging implementation you are using), you need to find a way to change the logging level fast.

Change the logging level in Eclipse

You can define a custom log configuration file for your JUnit runner

-Djava.util.logging.config.file=scr/test/resources/logging.properties












To define a custom log settings file, you need to open the actual run configuration, and add the path of the file as program argument.

Although this method is handy to use, when you have a central run configuration, and you want to run it several time during your development, in most cases it is inconvenient. You need to define the same run-time argument for all run or debug configuration, which makes the development slow.

Set log level programmatically    

Thanks to the API of logging frameworks, it is possible to set the log level dynamically in your code. The @Before method is just a right place for it. Unfortunately you need to remember slightly different API calls for different logging frameworks, but if you stick to one, it is not a huge problem.

Here you can see implementation for Log4J and Slf4j, the two most used by me.



As you can see, once you got a reference to the root logger, you are free to change any settings the given API allows to you.

Please consider, that logging on such a wide scale is usually unnecessary after the development phase. I usually use this possibility only when creating new features, and remove it or comment it out after the code works as desired.



Custom toString builder for Eclipse




If you are not satisfied the way, how Eclipse generates the toString method for your classes, and you are not so lucky to use the Lombok project, you have the possibility to set custom toString builder for Eclipse.

In the Generate toString dialog you can configure the code style.





By clicking on the Configure button, you can open the Configure Custom toString Builder dialog.




Here you can define the class used for generating the toString method. In the above example I use the ToStringBuilder from Apache Commons (org.apache.commons.lang.builder.ToStringBuilder), but you can implement your own builder class, that meets the requirements.

The generated method looks like this:

    @Override
    public String toString() {
        ToStringBuilder builder = new ToStringBuilder(this);
        builder.append("period", period).append("orderPosition", orderPosition).append("selectable", selectable).append("name_e", name_e);
        return builder.toString();
    }


As I wanted to generate toString in XML and JSON format, I have implemented my own tostring builder classes.

My builders have the advantage, that they do not use reflection, to generate the String representation of the classes. The disadvantage is, that they work only with relative simple classes. But as I try to keep my classes clean and simple, it is not a real problem for my projects.

It is relative easy to implement a class, which satisfies the requirement of a custom Eclipse ToString() Builder. Here is an example, how I created a JSON-like toString() builder class:



Please note, that in order for Eclipse to use the fluent API, for calling the append() method, I needed to implement the Builder Interface.

The configuration of the class to be used as a builder looks like this:




The generated method looks like this: