1.2.0.BUILD-SNAPSHOT

© 2017 The original authors.
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Springlets Documentation

This section provides a brief overview of the Springlets reference documentation. You can read this reference guide in a linear fashion, or you can skip sections if something doesn’t interest you.

1. About the documentation

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

2. Getting help

If you are having trouble with the Springlets utilities, you can look for help in the following places:

  • Learn the Spring basics — Springlets builds on many other Spring projects, check the spring.io web-site for a wealth of reference documentation. If you are just starting out with Spring, try one of the Spring guides. //* TODO: Ask a question - we monitor stackoverflow.com for questions // tagged with springlets.

  • Report bugs with Springlets at github.com/DISID/springlets/issues .

All of Springlets is open source, including the documentation! If you find problems with the docs; or if you just want to improve them, please get involved.

3. First steps

If you’re just getting started with Springlets take a look at the Getting Started Guide

4. Learning about Springlets features

To learn about the features provided by the Springlets libraries, just go to the Springlets features guide!

5. Advanced topics

Lastly, we have a few topics for the more advanced user.

Getting started

This section will allow you to get started with the Springlets library. First you’ll find an introduction to Springlets and then the installation instructions.

6. Introducing Springlets

Springlets provides a series of heterogeneus utilities and Spring Boot starters not currently available in the Spring projects like Spring Framework, Spring Data or Spring Boot, as well as other open source projects used in Java web projects.

Our goal in Springlets is to follow the conventions used in the Spring projects (naming, versioning, project structure, …) as close as possible. As a matter of fact, you can easily view to which Spring project are related most Springlet modules, as their name has been created by replacing the spring prefix with springlets.

7. System Requirements

The Springlets 1.x versions will be associated to the Spring IO platform Athens releases. As a result, Springlets 1.x will depend on the Spring Framework 4.3 releases. Also JDK 7 and 8 are supported.

Dependencies are provided through Maven Central to be used in Maven (3.2+), but other tools like can be also used.

For other requirements, just take a look at the related Spring projects requirements.

8. Installing Springlets

Springlets can be used with “classic” Java development tools. Regardless, you will need Java SDK v1.7 or higher. You should check your current Java installation before you begin:

$ java -version

Installation instructions for the Java developer

You can use Springlets in the same way as any standard Java library. Simply include the appropriate springlets-*.jar files on your classpath.

Although you could just copy the Springlets jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).

Maven installation

Springlets is compatible with Apache Maven 3.2 or above. If you don’t already have Maven installed you can follow the instructions at maven.apache.org.

On many operating systems Maven can be installed via a package manager. If you’re an OSX Homebrew user try brew install maven. Ubuntu users can run sudo apt-get install maven.

Springlets dependencies use the io.springlets groupId. Depending on your project’s needs, you just have to select which springlets dependency have to include in your project.

Upgrading from an earlier version of Springlets

If you are upgrading from an earlier release of Springlets check the “release notes” hosted on the project wiki. You’ll find upgrade instructions along with a list of “new and noteworthy” features for each release.

Springlets features

This section provides a guide of the Springlets features and how to use them in your own projects. If you haven’t already, please read the Getting started section beforehand. There you will find installation instructions to add the Springlets libraries to your project.

9. Springlets for Spring Framework features

Springlets for Spring Framework provides additional features for the following Spring Framework modules:

Spring Context

To use Springlets for the Spring Framework context module just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-context</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities:

Validation of collections

Spring performs validation by default only on single objects. If you have a collection of objects to be validated, you can use the Springlets CollectionValidator.

CollectionValidator will iterate over the elements of a Collection and run the validation process for each of them individually. An example of use can be found in the validator advice section

Enums i18n

In an application which supports many locales you have to show labels in the current locale. By default, when you have objects with properties of type enum their name is used to show them.

As an example, if we have the following enum:

public enum PetType {

    DOG, CAT, BIRD
}

Then you have an object with a property type of PetType type which is shown in a page, like in the next example of a Thymeleaf template fragment:

<li id="pet-type-field">
  <strong data-th-text="#{label_pet_type}">type</strong>
  <span data-th-text="${{pet.type}}">typeValue</span>
</li>

The result will be:

<li id="pet-type-field">
  <strong>Type:</strong>
  <span>DOG</span>
</li>

To provide an easy way to manage the i18n of enums in any use case where an enum is converted to text through the ConversionService, Springlets registers the EnumToMessageConverter class. It will look for a message with the following format: enum_CLASS_NAME, being CLASS the enum simple class name, and name the enum value name. If it is not found it defaults to the enum name.

With the previous example, you just would have to add the following entries to your messages*.properties:

messages.properties
enum_PetType_DOG = Dog
enum_PetType_CAT = Cat
enum_PetType_Bird = Bird
messages-es.properties
enum_PetType_DOG = Perro
enum_PetType_CAT = Gato
enum_PetType_Bird = Pájaro

This way, the sample html template with an Spanish locale would generate the following:

<li id="pet-type-field">
  <strong>Tipo:</strong>
  <span>Perro</span>
</li>

Objects i18n

Similar to the i18n of enums, sometimes you have an object property that you would like to show as a String. This is usually the case of a JPA entity with a relation to another one.

By default, the object value is converted to String by calling it’s toString() method. But this is not a good idea, as this method is not defined to provide a text to show an object in user interfaces. Also it doesn’t support formatting related to a property or to a locale.

Springlets provides some utilities and an annotation to easily manage the conversion of properties and objects to String, in a way similar to the Spring @DateTimeFormat and @NumberFormat annotations.

The annotation is @EntityFormat. Although the typical use case is for entities, it will work on any Java class. It can be used at:

  • class level: sets the default format to convert an object of the class. If the annotation is used without any parameters, the toString() method is used to generate the String.

  • property level: sets the format to convert the values of that property. The annotation can be included without parameters, in which case the format will be the one defined the property’s type class level.

The annotation provides the following parameters:

  • expression: a SpEL expression that can be created with the object properties.

Example:

@EntityFormat("#{name} (#{type})")
public class Pet {

  private String name;

  @NumberFormat
  private Float weight;

  private PetType type;

  // Constructors, getters, setters, ...
}

With this expression, an instance of Pet with name "Rocky" and PetType DOG will be shown as "Rocky (Dog)".

  • message: message code to use to get an internationalized expression to apply based on the current {@link Locale}.

This is an example using the message property and the @EntityFormat annotation applied to a property:

Pet.java
public class Pet {

  private String name;

  @NumberFormat
  private Float weight;

  private PetType type;

  @EntityFormat(message = "format_pet_owner")
  private Owner owner;

  // Constructors, getters, setters, ...
}
messages.properties
format_pet_owner=#{lastName}, #{firstName}
messages-es.properties
format_pet_owner=#{firstName} #{lastName}

With this configuration, if a Pet.owner property is formatted, depending on the current locale, one of the two formats will be applied.

Parsing objects

If you use the @EntityFormat annotation to format a property, it will be used also in the other way around to get the object from a text value, as a Parser will be automatically created to handle the conversion.

This comes handy, for example, when you provide a Rest service with a parameter which is an object with a relation to another one. This way the message only needs to provide an object text identifier as the property value.

Spring Data provides a similar utility to convert and object identifier as String to the real object, by converting the text to the object identifier type and then loading the object through its Repository. But if you have a Service layer between your controllers and your repositories, this utility goes over it.

To avoid that problem, the EntityParser looks for a component in the Spring context which implements the EntityParser interface for the object type and its identifier type. This allows, for example, to make your services implement that interface to resolve the object instances.

For example, if you have a Pet JPA Entity, with a related PetService which uses a PetRepository to load the data form a database. The PetService would implement the EntityResolver as follows:

Pet.java
@Entity
@EntityFormat("#{name} (#{type})")
public class Pet {

    @Id
    private Long id;

    // Other properties, getters/setters, ...
}
PetService.java
@Service
public class PetService implements EntityResolver<Pet, Long> {

    public Class<Pet> getEntityType() {
        return Pet.class;
    }

    public Class<Long> getIdType() {
        return Long.class;
    }

    public Pet findOne(Long id) {
        return getPetRepository().findOne(id);
    }

    // Other methods and properties ...
}

Then, another entity could have a property of type Pet,

Visit.java
@Entity
public class Visit {

    @EntityFormat
    private Pet pet;

    // Other properties, getters/setters, ...
}

This way, if you have a Rest Controller that allows to create visits for Pets, the method would allow to receive a JSON message with a property pet having as value the identifier of the Pet to assign to the Visit.

Take into account the conversion to and from text provided by the EntityFormat annotation will not be reversible. The conversion to text will be performed using the provided expression, but the conversion to object will expect the object identifier. Can be made reversible if you provide an expression that uses the object identifier, but that won’t be usually the case.

Spring MVC

To use Springlets for Spring MVC just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-web</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities for the Spring MVC web framework:

Sending a BindingResult in a RestController

In a Spring MVC HTML view is a common practice to provide binding and validation information to the user when data is sent through a form. This is achieved through the BindingResult class, which is created by Spring MVC with the results of the binding process.

If you would like to use the same technique in a Spring MVC RestController, or a controller annotated with @ResponseBody, whose response is converted to JSON or XML through the Jackson library, Springlets provides a Jackson Serializer.

To enable it, just add the @EnableSpringletsWebJacksonSupport annotation to a configuration class. If you are using Spring boot, there is an even easier way to do it just by including a boot starter. More details can be found in the Springlets for Spring Boot features.

Once enabled, you can use the @Valid annotation with the @RequestBody parameter and return a BindingResult object in your controller methods that will be serialized by Jackson and returned in the response.

An example in a @RestController annotated class to update a Pet entity would be:

@PutMapping(name = "update")
public ResponseEntity<?> update(@Valid @RequestBody Pet pet, BindingResult result) {

    if (result.hasErrors()) {
        return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
    }

    // Update the pet
    // ...

    return ResponseEntity.ok().build();
}

Enabling support for hibernate 5 lazy properties in Jackson

If you try to serialize a JPA Entity with Jackson, maybe because it’s the result of a JPA query returned in a RestController, if there are any lazy loaded properties still not loaded, it will fail. Jackson doesn’t know how to serialize those attributes by default.

To solve it you have to add the Hibernate 5 Jackson module and register it, which is automatically performed by the @EnableSpringletsWebJacksonSupport annotation.

Default exception for not found responses

When a request is made for a resource that doesn’t exist, usually a 404 response (Not Found) is returned.

As this is a typical scenario, springlets provides a NotFoundException annotated with @ResponseStatus(HttpStatus.NOT_FOUND) that you can throw in those cases:

@ModelAttribute
public Owner getOwner(@PathVariable("owner") Long id) {
    Owner owner = ownerService.findOne(id);
    if (owner == null) {
        throw new NotFoundException(String.format("Owner with identifier '%s' not found", id));
    }
    return owner;
}

Controller advices

There are some controller advices usually used in web projects that are provided by default by springlets. All of them are available just by adding the @EnableSpringletsWebMvcAdvices annotation to your configuration classes.

StringTrimmerAdvice

Registers a StringTrimmerEditor in the data binder to be able to trim strings that come as parameters.

The editor can be configured with the springlets.mvc.advices.trimeditor.* properties.

JsonpAdvice

Registers a controller advice to instruct the MappingJackson2HttpMessageConverter to serialize with JSONP formatting.

The advice can be configured with the springlets.mvc.advices.jsonp.* properties.

ValidatorAdvice

Controller advice that adds the Springlets CollectionValidator to the WebDataBinder. This way you can have Collections of objects as parameters in your controllers that can be validated, like in the following example:

@PostMapping(value = "/batch", name = "createBatch")
public ResponseEntity<?> createBatch(@Valid @RequestBody Collection<Owner> owners, BindingResult result) {

    if (result.hasErrors()) {
        return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
    }

    getOwnerService().save(owners);

    return ResponseEntity.created(listURI().toUri()).build();
}

Spring MVC provides an API to generate links to controller methods (see docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-links-to-controllers), avoiding to hard code URI paths in the controllers code, as well as in the links generated in the application pages.

If you are using JSP pages or Thymeleaf templates, you can use a tag or utility to use that API to generate the links. In the case of Thymeleaf, you can use the #mvc.url expression object, like in the following example:

public class SampleController {
    @RequestMapping("/sample1")
    public String sample1() {
      return "sample1"
    }

    @RequestMapping("/sample2")
    public String sample2(@RequestParam("param") String param) {
      return "sample2"
    }
}
<a th:href="${(#mvc.url('SC#sample1')).build()}">Go to sample 1</a>
<a th:href="${(#mvc.url('SC#sample2').arg(0,'value')).build()}">Go to sample 2</a>

To get the URL to the controller method you provide a String composed with the name of the Controller plus the # character and the name of the method. The name of the controller is constructed by default in Spring MVC using the capital letters of the controller class. In this sample, the SampleController class name becomes SC. The method name is generated using the java method name, in this case sample1 and sample2.

This is useful and simple, but in most cases it has the following problems:

  • Its very easy to have two controllers which generate the same name. Following the previous example, if we create a ShopController, its name will be also SC, colliding with the SampleController name. This can be avoided by carefully selecting the controller name, which can be painful, or using the name parameter of the @RequestMapping annotation at the class level. This parameter allows to set the name of the controller, avoiding the aforementioned collision. In this case, take into account you will have to use the name parameter also in all the controller methods, as the default naming for methods won’t work.

  • Related to the previous problem, you can’t have two controller methods with the same name, although the method signature is different. You can use the same previous techniques to avoid the name collision.

  • In the case of methods with any @RequestParam annotated parameter, if you don’t provide the value for the parameter, the generated URI will have the parameter added without value. In the example, the following Thymeleaf fragment:

<a th:href="${(#mvc.url('SC#sample2')).build()}">Go to sample 2</a>

Will generate the following HTML code:

<a th:href="/sample2?param}">Go to sample 2</a>

If the link is used, for example, in a form and the param value is sent with a form input tag, the final URL sent to the server will become something like this:

/sample2?param&param=value

In the controller then Spring MVC will try to bind the parameters to the controller parameters. There are two param parameters in the URL, one with a null value and the other with a value of "value". Which one will be used seems not to be clear. Also, if the parameter is a list, you will end up with a null value into the list.

The last problem can’t be avoided and renders the #mvc.url object expression unusable in forms and any URLs generated dinamically in javascript.

TODO

Managing images

Springlets provides some common utilities to manage image files in an Spring MVC project. Usually, to upload an image to the server side, the file is received as a MultipartFile type. After that, the server side should convert this image to the desired type to be saved into the filesystem or the desired type to be saved into the database.

To unify the way as the images are managed in all the projects, Springlets provides an Spring MVC Converter that allows to convert automatically all the received MultipartFile elements to an EmbeddableImage type (Read more about this type into the ).

To register this converter into the Spring MVC context, you could include the following @Bean definition:

@Bean
public SpringletsImageFileConverter springletsImageFileConverter() {
  return new SpringletsImageFileConverter();
}

Spring Mail

To use Springlets for Spring Framework eMail just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-mail</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities for the Spring email support:

Mail receiver service

TODO

Spring JMS

To use Springlets for Spring Framework JMS just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-web</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities for the Spring JMS support:

Sending JMS messages

TODO

10. Springlets for Spring Data features

Springlets for Spring Data provides additional features for the following Spring Data modules:

Spring Data Commons

To use Springlets for the Spring Data Commons module just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-data-commons</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities:

Support for the Datatables javascript component

TODO

Support for the Select2 javascript component

TODO

Support for paging, ordering and filtering in SOAP web services

TODO

Spring Data JPA

To use Springlets for the Spring Data JPA module just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-data-jpa</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities:

Extended support for QueryDSL custom queries

TODO

Support for getting a detached entity

TODO

Support for image management

Springlets JPA support provides an @Embeddable entity to manage images as a field of an entity. To use this embeddable entity as a field of your entity, you could do it easily:

public class MyEntity {

  @Id
  private Long id;

  @Version
  private Integer version;

  /**
   * Image field
   */
  @Embedded
  private EmbeddableImage image;

}

Also, this entity provides some utility methods that will be useful to resize, format and obtain information about the stored image.

public class MyServiceImpl implements MyService {

  @Override
  public MyEntity save(MyEntity entity){

    // Format the image to PNG format and resize it
    // to 150x150 pixels
    EmebddableImage formattedAndResizedImage =
          entity.getImage().formatAndResize("png", 150, 150);

    // Obtain the format of the image
    String format = formattedAndResizedImage.getFormat();

    // Obtain the base64 value of the image
    String base64 = formattedAndResizedImage.getBase64();

    // Obtain the String representation of the
    // image. Combines getFormat() and getBase64()
    // methods.
    String imgString = formattedAndResizedImage.toString();

  }
}

11. Springlets for Spring Security features

Springlets for Spring Security provides additional features:

Springlets for Spring Security authentication

To use the Springlets authentication utilities for Spring Security just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-authentication</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities:

Base implementation for Spring Security authentication based on JPA persistence entities

TODO

12. Springlets for Spring Webflow features

To use the Springlets for Spring Webflow utilities just include the following dependency:

<dependency>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-webflow</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following utilities:

Default configuration for Spring Webflow

TODO

13. Springlets for Spring Boot features

Springlets for Spring Boot provides additional features, autoconfiguration and starters for the Springlets modules as well as other libraries.

The starters provided are the following ones:

Springlets web starter

To use the Springlets web starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-web</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO: Pending

Image management

Including the Springlets web starter, the project will include all the necessary elements to manage images in the view layer. One of these elements are the bootstrap-fileinput jQuery plugin, that will allow developers to select and preview the images that should be uploaded to the server side. This Spring Boot starter includes the following dependencies and versions:

<properties>
  <bootstrap-fileinput.version>4.4.0</bootstrap-fileinput.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.webjars.bower</groupId>
    <artifactId>bootstrap-fileinput</artifactId>
    <version>${bootstrap-fileinput.version}</version>
  </dependency>
</dependencies>

Also, this starter includes the necessary autoconfiguration to register the SpringletsImageFileConverter bean (see ) automatically into the Spring MVC context if the springlets.image.management property has true value.

Springlets Data JPA starter

To use the Springlets Data JPA starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-data-jpa</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO

Springlets Mail starter

To use the Springlets Mail starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-mail</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO

Springlets JMS starter

To use the Springlets JMS starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-jms</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO

Springlets Security Authentication

To use the Springlets Security Authentication starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-authentication</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO

Springlets Webflow starter

To use the Springlets Webflow starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-webflow</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO

Springlets Test starter

To use the Springlets Tests starter just include the following dependency:

<dependencyT>
  <groupId>io.springlets</groupId>
  <artifactId>springlets-boot-starter-test</artifactId>
  <version>{springlets-version}</version>
</dependency>

It provides the following autoconfiguration:

TODO

Appendices

Appendix A: Common application properties

If you use the Springlets for Spring Boot features, various properties can be specified inside your application.properties/application.yml file or as command line switches. This section provides a list of common Springlets for Spring Boot properties and references to the underlying classes that consume them.

This sample file is meant as a guide only. Do not copy/paste the entire content into your application; rather pick only the properties that you need.
# ===================================================================
# COMMON SPRINGLETS PROPERTIES
#
# This sample file is provided as a guideline. Do NOT copy it in its
# entirety to your own application.               ^^^
# ===================================================================

# ----------------------------------------
# SPRINGLETS FRAMEWORK PROPERTIES
# ----------------------------------------

# EMAIL
springlets.mail.receiver.enabled=true # Enable email receiving support
springlets.mail.receiver.host=  # Email server host
springlets.mail.receiver.port=  # Email server port
springlets.mail.receiver.protocol=  # Email server protocol
springlets.mail.receiver.username=  # User to login in the email server
springlets.mail.receiver.password=  # Password to login in the email server
springlets.mail.receiver.starttls-enabled=  # Enables the use of the STARTTLS to connect to the email server
springlets.mail.receiver.jndi-name=  # JNDI name. When set, takes precedence to others mail settings.

# WEB CONTROLLER ADVICES
springlets.mvc.advices.enabled=true # Enable Springlets Spring MVC Controller advices

# Trimeditor advice configuration
springlets.mvc.advices.trimeditor.empty-as-null=true # If an empty parameter value is to be transformed into `null`
springlets.mvc.advices.trimeditor.chars-to-delete= # Set of characters to delete, in addition to trimming the parameter value. Useful for deleting unwanted line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.

# JsonP advice configuration
springlets.mvc.advices.jsonp.query-param-names=callback # Supported list of comma separated Jsonp parameter names

# Image Management
springlets.image.management= # Enable the image Converter

# ----------------------------------------
# SPRINGLETS DATA PROPERTIES
# ----------------------------------------

# ----------------------------------------
# SPRINGLETS SECURITY PROPERTIES
# ----------------------------------------

# IN MEMORY AUTHENTICATION
springlets.security.auth.in-memory.enabled=false # Enable the in memory spring security authentication
springlets.security.auth.in-memory.erase-credentials=false # If authentication credentials must be erased from memory once the authentication process has finished

# ----------------------------------------
# SPRINGLETS WEBFLOW PROPERTIES
# ----------------------------------------