Quantcast
Channel: Baeldung
Viewing all 4735 articles
Browse latest View live

File Upload with Spring MVC

$
0
0

I usually post about Dev stuff on Twitter - you can follow me there:

1. Overview

In previous articles, we introduced the basics of form handling and explored the form tag library in Spring MVC.

In this article, we focus on what Spring offers for multipart (file upload) support in web applications.

Spring allows us to enable this multipart support with pluggable MultipartResolver objects. The framework provides one MultipartResolver implementation for use with Commons FileUpload and another for use with Servlet 3.0 multipart request parsing.

After configuring the MultipartResolver we’ll see how to upload single file and multiple files.

2. Commons FileUpload

To use CommonsMultipartResolver to handle the file upload, we need to add the following dependency:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

Now we can define the CommonsMultipartResolver bean into our Spring configuration.

This MultipartResolver comes with a series of set method to define properties such as the maximum size for uploads:

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);
    return new CommonsMultipartResolver();
}

3. With Servlet 3.0

In order to use Servlet 3.0 multipart parsing, we need configure a couple pieces of the application. First, we need to set a MultipartConfigElement in our DispatcherServlet registration:

public class MainWebAppInitializer implements WebApplicationInitializer {

    private String TMP_FOLDER = "/tmp"; 
    private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; 
    
    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        
        ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(
          new GenericWebApplicationContext()));

        appServlet.setLoadOnStartup(1);
        
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, 
          MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
        
        appServlet.setMultipartConfig(multipartConfigElement);
    }
}

In the MultipartConfigElement object, we have configured the storage location, maximum individual file size, maximum request size (in case of multiple files in a single request), and the size at which the file upload progress is flushed to the storage location.

These settings must be applied at the servlet registration level, as Servlet 3.0 does not allow them to be registered in the MultipartResolver as is the case with CommonsMultipartResolver.

Once this is done, we can add the StandardServletMultipartResolver to our Spring configuration:

@Bean
public StandardServletMultipartResolver multipartResolver() {
    return new StandardServletMultipartResolver();
}

4. Uploading a File

To upload our file, we can build a simple form in which we use an HTML input tag with type=’file’.

Regardless of the upload handling configuration we have chosen, we need to set the encoding attribute of the form to multipart/form-data. This lets the browser know how to encode the form:

<form:form method="POST" action="/spring-mvc-xml/uploadFile" enctype="multipart/form-data">
    <table>
        <tr>
            <td><form:label path="file">Select a file to upload</form:label></td>
            <td><input type="file" name="file" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form>

To store the uploaded file we can use a MultipartFile variable. We can retrieve this variable from the request parameter inside our controller’s method:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") MultipartFile file, ModelMap modelMap) {
    modelMap.addAttribute("file", file);
    return "fileUploadView";
}

The MultipartFile class provides access to details about the uploaded file, including file name, file type, and so on. We can use a simple HTML page to display this information:

<h2>Submitted File</h2>
<table>
    <tr>
        <td>OriginalFileName:</td>
        <td>${file.originalFilename}</td>
    </tr>
    <tr>
        <td>Type:</td>
        <td>${file.contentType}</td>
    </tr>
</table>

5. Uploading Multiple Files

To upload multiple files in a single request, we simply put multiple input file fields inside the form:

<form:form method="POST" action="/spring-mvc-java/uploadMultiFile" enctype="multipart/form-data">
    <table>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form:form>

We need to take care that each input field has the same name, so that it can be accessed as an array of MultipartFile:

@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public String submit(@RequestParam("files") MultipartFile[] files, ModelMap modelMap) {
    modelMap.addAttribute("files", files);
    return "fileUploadView";
}

Now, we can simply iterate over that array to display files informations:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Spring MVC File Upload</title>
    </head>
    <body>
        <h2>Submitted Files</h2>
	    <table>
            <c:forEach items="${files}" var="file">    
                <tr>
                    <td>OriginalFileName:</td>
                    <td>${file.originalFilename}</td>
                </tr>
                <tr>
                    <td>Type:</td>
                    <td>${file.contentType}</td>
                </tr>
            </c:forEach>
	    </table>
    </body>
</html>

6. Conclusion

In this article we looked at different ways to configure multipart support in Spring. Using these, we can support file uploads in our web applications.

The implementation of this tutorial can be found in a GitHub project. When the project runs locally, the form example can be accessed at: http://localhost:8080/spring-mvc-java/fileUpload

I usually post about Dev stuff on Twitter - you can follow me there:



Entity Validation, Optimistic Locking, and Query Consistency in Spring Data Couchbase

$
0
0

1. Introduction

After our introduction to Spring Data Couchbase, in this second tutorial we focus on the support for entity validation (JSR-303), optimistic locking, and different levels of query consistency for a Couchbase document database.

2. Entity Validation

Spring Data Couchbase provides support for JSR-303 entity validation annotations. In order to take advantage of this feature, first we add the JSR-303 library to the dependencies section of our Maven project:

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

Then we add an implementation of JSR-303. We will use the Hibernate implementation:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

Finally, we add a validator factory bean and corresponding Couchbase event listener to our Couchbase configuration:

@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean() {
    return new LocalValidatorFactoryBean();
}

@Bean
public ValidatingCouchbaseEventListener validatingCouchbaseEventListener() {
    return new ValidatingCouchbaseEventListener(localValidatorFactoryBean());
}

The equivalent XML configuration looks like this:

<bean id="validator"
  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

<bean id="validatingEventListener" 
  class="org.springframework.data.couchbase.core.mapping.event.ValidatingCouchbaseEventListener"/>

Now we add JSR-303 annotations to our entity classes. When a constraint violation is encountered during a persistence operation, the operation will fail, throwing a ConstraintViolationException.

Here is a sample of the constraints that we can enforce involving our Student entities:

@Field
@NotNull
@Size(min=1, max=20)
@Pattern(regexp="^[a-zA-Z .'-]+$")
private String firstName;

...
@Field
@Past
private DateTime dateOfBirth;

3. Optimistic Locking

Spring Data Couchbase does not support multi-document transactions similar to those you can achieve in other Spring Data modules such as Spring Data JPA (via the @Transactional annotation), nor does it provide a rollback feature.

However it does support optimistic locking in much the same way as other Spring Data modules through the use of the @Version annotation:

@Version
private long version;

Under the covers, Couchbase uses what is known as a “compare and swap” (CAS) mechanism to achieve optimistic locking at the datastore level.

Each document in Couchbase has an associated CAS value that is modified automatically any time the document’s metadata or contents are altered. The use of the @Version annotation on a field causes that field to be populated with the current CAS value whenever a document is retrieved from Couchbase.

When you attempt to save the document back to Couchbase, this field is checked against the current CAS value in Couchbase. If the values do not match, the persistence operation will fail with an OptimisticLockingException.

It is extremely important to note that you should never attempt to access or modify this field in your code.

4. Query Consistency

When implementing a persistence layer over Couchbase, you have to consider the possibility of stale reads and writes. This is because when documents are inserted, updated, or deleted, it may take some time before the backing views and indexes are updated to reflect these changes.

And if you have a large dataset backed by a cluster of Couchbase nodes, this can become a significant problem, especially for a OLTP system.

Spring Data provides a robust level of consistency for some repository and template operations, plus a couple of options that let you determine the level of read and write consistency that is acceptable for your application.

4.1. Levels of Consistency

Spring Data allows you to specify various levels of query consistency and staleness for your application via the Consistency enum found in the org.springframework.data.couchbase.core.query package.

This enum defines the following levels of query consistency and staleness, from least to most strict:

  • EVENTUALLY_CONSISTENT
    • stale reads are allowed
    • indexes are updated according to Couchbase standard algorithm
  • UPDATE_AFTER
    • stale reads are allowed
    • indexes are updated after each request
  • DEFAULT_CONSISTENCY (same as READ_YOUR_OWN_WRITES)
  • READ_YOUR_OWN_WRITES
    • stale reads are not allowed
    • indexes are updated after each request
  • STRONGLY_CONSISTENT
    • stale reads are not allowed
    • indexes are updated after each statement

4.2. Default Behavior

Consider the case where you have documents that have been deleted from Couchbase, and the backing views and indexes have not been fully updated.

The CouchbaseRepository built-in method deleteAll() safely ignores documents that were found by the backing view but whose deletion is not yet reflected by the view.

Likewise, the CouchbaseTemplate built-in methods findByView and findBySpatialView offer a similar level of consistency by not returning documents that were initially found by the backing view but which have since been deleted.

For all other template methods, built-in repository methods, and derived repository query methods, according to the official Spring Data Couchbase 2.1.x documentation as of this writing, Spring Data uses a default consistency level of Consistency.READ_YOUR_OWN_WRITES.

It is worth noting that earlier versions of the library used a default of Consistency.UPDATE_AFTER.

Whichever version you are using, if you have any reservations about blindly accepting the default consistency level being provided, Spring offers two methods by which you can declaratively control the consistency level(s) being used, as the following subsections will describe.

4.3. Global Consistency Setting

If you are using Couchbase repositories and your application calls for a stronger level of consistency, or if it can tolerate a weaker level, then you may override the default consistency setting for all repositories by overriding the getDefaultConsistency() method in your Couchbase configuration.

Here is how you can override global consistency level in your Couchbase configuration class:

@Override
public Consistency getDefaultConsistency() {
    return Consistency.STRONGLY_CONSISTENT;
}

Here is the equivalent XML configuration:

<couchbase:template consistency="STRONGLY_CONSISTENT"/>

Note that the price of stricter levels of consistency is increased latency at query time, so be sure to tailor this setting based on the needs of your application.

For example, a data warehouse or reporting application in which data is often appended or updated only in batch would be a good candidate for EVENTUALLY_CONSISTENT, whereas an OLTP application should probably tend towards the more strict levels such as READ_YOUR_OWN_WRITES or STRONGLY_CONSISTENT.

4.4. Custom Consistency Implementation

If you need more finely tuned consistency settings, you can override the default consistency level on a query-by-query basis by providing your own repository implementation for any queries whose consistency level you want to control independently and making use of the queryView and/or queryN1QL methods provided by CouchbaseTemplate.

Let’s implement a custom repository method called findByFirstNameStartsWith for our Student entity for which we do not want to allow stale reads.

First, create an interface containing the custom method declaration:

public interface CustomStudentRepository {
    List<Student> findByFirstNameStartsWith(String s);
}

Next, implement the interface, setting the Stale setting from the underlying Couchbase Java SDK to the desired level:

public class CustomStudentRepositoryImpl implements CustomStudentRepository {

    @Autowired
    private CouchbaseTemplate template;

    public List<Student> findByFirstNameStartsWith(String s) {
        return template.findByView(ViewQuery.from("student", "byFirstName")
          .startKey(s)
          .stale(Stale.FALSE),
          Student.class);
    }
}

Finally, by having your standard repository interface extend both the generic CrudRepository interface and your custom repository interface, clients will have access to all the built-in and derived methods of your standard repository interface, plus any custom methods you implemented in your custom repository class:

public interface StudentRepository extends CrudRepository<Student, String>,
  CustomStudentRepository {
    ...
}

5. Conclusion

In this tutorial, we showed how to implement JSR-303 entity validation and achieve optimistic locking capability when using the Spring Data Couchbase community project.

We also discussed the need for understanding query consistency in Couchbase, and we introduced the different levels of consistency provided by Spring Data Couchbase.

Finally, we explained the default consistency levels used by Spring Data Couchbase globally and for a few specific methods, and we demonstrated ways to override the global default consistency setting as well as how to override consistency settings on a query-by-query basis by providing your own custom repository implementations.

You can view the complete source code for this tutorial in the github project.

To learn more about Spring Data Couchbase, visit the official Spring Data Couchbase project site.

XStream User Guide: JSON

$
0
0

I usually post about Dev stuff on Twitter - you can follow me there:

1. Overview

This is the third article in a series about XStream. If you want to learn about its basic use in converting Java objects to XML and vice versa, please refer to the previous articles.

Beyond its XML-handling capabilities, XStream can also convert Java objects to and from JSON. In this tutorial, we will learn about these features.

2. Prerequisites

Before reading this tutorial, please go through the first article in this series, in which we explain the basics of the library.

3. Dependencies

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.5</version>
</dependency>

4. JSON Drivers

In the previous articles, we learned how to set up an XStream instance and to select an XML driver. Similarly, there are two drivers available to convert objects to and from JSON: JsonHierarchicalStreamDriver and JettisonMappedXmlDriver.

4.1. JsonHierarchicalStreamDriver

This driver class can serialize objects to JSON, but is not capable of deserializing back to objects. It does not require any extra dependencies, and its driver class is self-contained.

4.2. JettisonMappedXmlDriver

This driver class is capable of converting JSON to and from objects. Using this driver class, we need to add an extra dependency for jettison.

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.3.7</version>
</dependency>

5. Serializing an Object to JSON

Let’s create a Customer class:

public class Customer {

    private String firstName;
    private String lastName;
    private Date dob;
    private String age;
    private List<ContactDetails> contactDetailsList;
       
    // getters and setters
}

Note that we have (perhaps unexpectedly) created age as a String. We will explain this choice later.

5.1. Using JsonHierarchicalStreamDriver

We will pass a JsonHierarchicalStreamDriver to create an XStream instance.

xstream = new XStream(new JsonHierarchicalStreamDriver());
dataJson = xstream.toXML(customer);

This generates the following JSON:

{
  "com.baeldung.pojo.Customer": {
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1986-02-14 16:22:18.186 UTC",
    "age": "30",
    "contactDetailsList": [
      {
        "mobile": "6673543265",
        "landline": "0124-2460311"
      },
      {
        "mobile": "4676543565",
        "landline": "0120-223312"
      }
    ]
  }
}

5.2. JettisonMappedXmlDriver Implementation

We will pass a JettisonMappedXmlDriver class to create an instance.

xstream = new XStream(new JettisonMappedXmlDriver());
dataJson = xstream.toXML(customer);

This generates the following JSON:

{
  "com.baeldung.pojo.Customer": {
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1986-02-14 16:25:50.745 UTC",
    "age": 30,
    "contactDetailsList": [
      {
        "com.baeldung.pojo.ContactDetails": [
          {
            "mobile": 6673543265,
            "landline": "0124-2460311"
          },
          {
            "mobile": 4676543565,
            "landline": "0120-223312"
          }
        ]
      }
    ]
  }
}

5.3. Analysis

Based on the output from the two drivers, we can clearly see that there are some slight differences in the generated JSON. For example, JettisonMappedXmlDriver omits the double quotes for numeric values despite the data type being java.lang.String:

"mobile": 4676543565,
"age": 30,

JsonHierarchicalStreamDriver, on the other hand, retains the double quotes.

6. Deserializing JSON to an Object

Let’s take the following JSON to convert it back to a Customer object:

{
  "customer": {
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1986-02-14 16:41:01.987 UTC",
    "age": 30,
    "contactDetailsList": [
      {
        "com.baeldung.pojo.ContactDetails": [
          {
            "mobile": 6673543265,
            "landline": "0124-2460311"
          },
          {
            "mobile": 4676543565,
            "landline": "0120-223312"
          }
        ]
      }
    ]
  }
}

Recall that only one of the drivers (JettisonMappedXMLDriver) can deserialize JSON. Attempting to use JsonHierarchicalStreamDriver for this purpose will result in an UnsupportedOperationException.

Using the Jettison driver, we can deserialize the Customer object:

customer = (Customer) xstream.fromXML(dataJson);

7. Conclusion

In this article we have covered the JSON handling capabilities XStream, converting objects to and from JSON. We also looked at how we can tweak our JSON output, making it shorter, simpler and more readable.

As with XStream’s XML processing, there are other ways we can further customize the way JSON is serialized by configuring the instance, using either annotations or programmatic configuration. For more details and examples, please refer to the first article in this series.

The complete source code with examples can be downloaded from the linked GitHub repository.

I usually post about Dev stuff on Twitter - you can follow me there:


Java Web Weekly, Issue 120

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

At the very beginning of last year, I decided to track my reading habits and share the best stuff here, on Baeldung. Haven’t missed a review since.

Here we go…

1. Spring and Java

>> How to Replace Rules in JUnit 5 [codeaffine.com]

I find deep-dives into the upcoming JUnit 5 very interesting.

But, if you’re using rules in JUnit 4 and know they’re going away in version 5 – you’ll find this one particularly useful.

>> Overriding Dependency Versions with Spring Boot [spring.io]

Gone are the days where you have to painstakingly lay out each Spring dependency and versions manually. There are now – and have been for a while – much easier ways to get your dependency tree in working order.

>> Hibernate 5: How to persist LocalDateTime & Co with Hibernate [thoughts-on-java.org]

I remember struggling with this a few years back – I’m glad Hibernate finally supports the new Date classes well.

>> Would We Still Criticise Checked Exceptions, If Java had a Better try-catch Syntax? [jooq.org]

As always, interesting ruminations on improving the Java syntax – this time with better try-catch syntax.

>> JUnit 5 – Extension Model [codefx.org]

Working with JUnit 5 is going to be fun, and extending it is going to be even more so.

Libraries (and IDEs) won’t have to hack around the API any more – which is bound to lead to some good things coming on top of the new JUnit.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical

>> How to run database integration tests 20 times faster [vladmihalcea.com]

I haven’t seen a ram disk in a while 🙂

This writeup is practical and chock full of solid advice if you want to speed up your builds and don’t mind getting your hands a bit dirty with some low level tools.

>> Eric Evans — Tackling Complexity in the Heart of Software [dddeurope.com]

Yeah. Good talk.

Also worth reading:

3. Musings

>> Are Your Arguments Falsifiable? [daedtech.com]

A fun read in general, but particularly if you regularly put your work out there and get feedback on it.

>> How I’ve Avoided Burnout During More Than 3 Decades As A Programmer [thecodist.com]

Interesting advice from someone who’s been doing this stick for a whole lot longer then most of us.

Also worth reading:

4. Comics

And my favorite Dilberts of the week:

>> Why does your agreeing sound like mocking? [dilbert.com]

>> And it’s free? [dilbert.com]

>> Pictures of people who were attacked by bears [dilbert.com]

5. Pick of the Week

Instead of picking something, this week I’m going to ask you a question:

Do you like the new Baeldung design?

Let me know in the comments – and have a great weekend.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Spring Expression Language Guide

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

The Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used with XML or annotation-based Spring configurations.

There are several operators available in the language:

Type Operators
Arithmetic +, -, *, /, %, ^, div, mod
Relational <, >, ==, !=, <=, >=, lt, gt, eq, ne, le, ge
Logical and, or, not, &&, ||, !
Conditional ?:
Regex matches

2. Operators

For these examples, we will use annotation-based configuration. More details about XML configuration can be found in later sections of this article.

SpEL expressions begin with the # symbol, and are wrapped in braces: #{expression}. Properties can be referenced in a similar fashion, starting with a $ symbol, and wrapped in braces: ${property.name}. Property placeholders cannot contain SpEL expressions, but expressions can contain property references:

#{${someProperty} + 2}

In the example above, assume someProperty has value 2, so resulting expression would be 2 + 2, which would be evaluated to 4.

2.1. Arithmetic Operators

All basic arithmetic operators are supported.

@Value("#{19 + 1}") // Will inject 20
private double add; 

@Value("#{'String1 ' + 'string2'}") // Will inject "String1 string2"
private String addString; 

@Value("#{20 - 1}") // Will inject 19
private double subtract;

@Value("#{10 * 2}") // Will inject 20
private double multiply;

@Value("#{36 / 2}") // Will inject 19
private double divide;

@Value("#{36 div 2}") // Will inject 18, the same as for / operator
private double divideAlphabetic; 

@Value("#{37 % 10}") // Will inject 7
private double modulo;

@Value("#{37 mod 10}") // Will inject 7, the same as for % operator
private double moduloAlphabetic; 

@Value("#{2 ^ 9}") // Will inject 512
private double powerOf;

@Value("#{(2 + 2) * 2 + 9}") // Will inject 17
private double brackets;

Divide and modulo operations have alphabetic aliases, div for / and mod for %. The + operator can also be used to concatenate strings.

2.2. Relational and Logical Operators

All basic relational and logical operations are also supported.

@Value("#{1 == 1}") // Will inject true
private boolean equal;

@Value("#{1 eq 1}") // Will inject true
private boolean equalAlphabetic;

@Value("#{1 != 1}") // Will inject false
private boolean notEqual;

@Value("#{1 ne 1}") // Will inject false
private boolean notEqualAlphabetic;

@Value("#{1 < 1}") // Will inject false
private boolean lessThan;

@Value("#{1 lt 1}") // Will inject false
private boolean lessThanAlphabetic;

@Value("#{1 <= 1}") // Will inject true
private boolean lessThanOrEqual;

@Value("#{1 le 1}") // Will inject true
private boolean lessThanOrEqualAlphabetic;

@Value("#{1 > 1}") // Will inject false
private boolean greaterThan;

@Value("#{1 gt 1}") // Will inject 7
private boolean greaterThanAlphabetic;

@Value("#{1 >= 1}") // Will inject true
private boolean greaterThanOrEqual;

@Value("#{1 ge 1}") // Will inject true
private boolean greaterThanOrEqualAlphabetic;

All relational operators have alphabetic aliases, as well. For example, in XML-based configs we can’t use operators containing angle brackets (<, <=, >, >=). Instead, we can use lt (less than), le (less than or equal), gt (greater than), or ge (greater than or equal).

2.3. Logical Operators

SpEL supports all basic logical operations:

@Value("#{250 > 200 && 200 < 4000}") // Will inject true
private boolean and; 

@Value("#{250 > 200 and 200 < 4000}") // Will inject true
private boolean andAlphabetic;

@Value("#{400 > 300 || 150 < 100}") // Will inject true
private boolean or;

@Value("#{400 > 300 or 150 < 100}") // Will inject true
private boolean orAlphabetic;

@Value("#{!true}") // Will inject false
private boolean not;

@Value("#{not true}") // Will inject false
private boolean notAlphabetic;

As with arithmetic and relational operators, all logical operators also have alphabetic clones.

2.4. Conditional Operators

Conditional operators are used to inject different values depending on some condition:

@Value("#{2 > 1 ? 'a' : 'b'}") // Will inject "b"
private String ternary;

The ternary operator is used for performing compact if-then-else conditional logic inside the expression. In this example we trying to check if there was true value or not.

Another common use for ternary operator is to check if some variable is null and then return the variable value or a default:

@Value("#{someBean.someProperty != null ? someBean.someProperty : 'default'}")
private String ternary;

The Elvis operator is a way of shortening of the ternary operator syntax for the case above used in the Groovy language. It is also available in SpEL. The code below is equivalent to the code above:

@Value("#{someBean.someProperty ?: 'default'}") // Will inject provided string if someProperty is null
private String elvis;

2.5. Using Regex in SpEL

The matches operator can be used to check whether or not a string matches a given regular expression.

@Value("#{'100' matches '\\d+' }") // Will inject true
private boolean validNumericStringResult;

@Value("#{'100fghdjf' matches '\\d+' }") // Will inject false
private boolean invalidNumericStringResult;

@Value("#{'valid alphabetic string' matches '[a-zA-Z\\s]+' }") // Will inject true
private boolean validAlphabeticStringResult;

@Value("#{'invalid alphabetic string #$1' matches '[a-zA-Z\\s]+' }") // Will inject false
private boolean invalidAlphabeticStringResult;

@Value("#{someBean.someValue matches '\d+'}") // Will inject true if someValue contains only digits
private boolean validNumericValue;

2.6. Accessing List and Map Objects

With help of SpEL, we can access the contents of any Map or List in the context. We will create new bean workersHolder that will store information about some workers and their salaries in a List and a Map:

@Component("workersHolder")
public class WorkersHolder {
    private List<String> workers = new LinkedList<>();
    private Map<String, Integer> salaryByWorkers = new HashMap<>();

    public WorkersHolder() {
        workers.add("John");
        workers.add("Susie");
        workers.add("Alex");
        workers.add("George");

        salaryByWorkers.put("John", 35000);
        salaryByWorkers.put("Susie", 47000);
        salaryByWorkers.put("Alex", 12000);
        salaryByWorkers.put("George", 14000);
    }

    //Getters and setters
}

Now we can access the values inside the collections using SpEL:

@Value("#{workersHolder.salaryByWorkers['John']}") // Will inject 35000
private Integer johnSalary;

@Value("#{workersHolder.salaryByWorkers['George']}") // Will inject 14000
private Integer georgeSalary;

@Value("#{workersHolder.salaryByWorkers['Susie']}") // Will inject 47000
private Integer susieSalary;

@Value("#{workersHolder.workers[0]}") // Will inject John
private String firstWorker;

@Value("#{workersHolder.workers[3]}") // Will inject George
private String lastWorker;

@Value("#{workersHolder.workers.size()}") // Will inject 4
private Integer numberOfWorkers;

3. Use in Spring Configuration

3.1. Referencing a Bean

In this example we will look at how to use SpEL in XML-based configuration. Expressions can be used to reference beans or bean fields/methods. For example, suppose we have the following classes:

public class Engine {
    private int capacity;
    private int horsePower;
    private int numberOfCylinders;

   // Getters and setters
}

public class Car {
    private String make;
    private int model;
    private Engine engine;
    private int horsePower;

   // Getters and setters
}

Now we create an application context in which expressions are used to inject values:

<bean id="engine" class="com.baeldung.spring.spel.Engine">
   <property name="capacity" value="3200"/>
   <property name="horsePower" value="250"/>
   <property name="numberOfCylinders" value="6"/>
</bean>
<bean id="someCar" class="com.baeldung.spring.spel.Car">
   <property name="make" value="Some make"/>
   <property name="model" value="Some model"/>
   <property name="engine" value="#{engine}"/>
   <property name="horsePower" value="#{engine.horsePower}"/>
</bean>

Take a look at the someCar bean. The engine and horsePower fields of someCar use expressions that are bean references to the engine bean and horsePower field respectively.

To do the same with annotation-based configurations, use the @Value(“#{expression}”) annotation.

3.2. Using Operators in Configuration

Each operator from the first section of this article can be used in XML and annotation-based configurations. However, remember that in XML-based configuration, we can’t use angle bracket operators. Instead, we should use their alphabetic aliases, such as lt (less than) or le (less than or equals). For annotation-based configurations, there are no such restrictions.

public class SpelOperators {
    private boolean equal;
    private boolean notEqual;
    private boolean greaterThanOrEqual;
    private boolean and;
    private boolean or;
    private String addString;
    
    // Getters and setters
    @Override
    public String toString() {
        // toString which include all fields
    }

Now we will add a spelOperators bean to the application context:

<bean id="spelOperators" class="com.baeldung.spring.spel.SpelOperators">
   <property name="equal" value="#{1 == 1}"/>
   <property name="notEqual" value="#{1 lt 1}"/>
   <property name="greaterThanOrEqual" value="#{someCar.engine.numberOfCylinders >= 6}"/>
   <property name="and" value="#{someCar.horsePower == 250 and someCar.engine.capacity lt 4000}"/>
   <property name="or" value="#{someCar.horsePower > 300 or someCar.engine.capacity > 3000}"/>
   <property name="addString" value="#{someCar.model + ' manufactured by ' + someCar.make}"/>
</bean>

Retrieving that bean from the context, we can then verify that values were injected properly:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
SpelOperators spelOperators = (SpelOperators) context.getBean("spelOperators");

Here we can see the output of the toString method of spelOperators bean:

[equal=true, notEqual=false, greaterThanOrEqual=true, and=true, 
or=true, addString=Some model manufactured by Some make]

4. Parsing Expressions Programmatically

At times, we may want to parse expressions outside the context of configuration. Fortunately, this is possible, using SpelExpressionParser. We can use all operators that we saw in previous examples, but should use them without braces and hash symbol. That is, if we want to use an expression with the operator, when used in Spring configuration, the syntax is #{1 + 1}; when used outside of configuration, the syntax is simply 1 + 1.

In the following examples, we will use the Car and Engine beans defined in the previous section.

4.1. Using ExpressionParser

Let’s look at a simple example:

ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression("'Any string'");
String result = (String) expression.getValue();

ExpressionParser is responsible for parsing expression strings. In this example SpEL parser will simply evaluate the string ‘Any String’ as an expression. Unsurprisingly, the result will be ‘Any String’.

As with using SpEL in configuration, we can use it to call methods, access properties, or call constructors.

Expression expression = expressionParser.parseExpression("'Any string'.length()");
Integer result = (Integer) expression.getValue();

Additionally, instead of directly operating on the literal, we could call the constructor:

Expression expression = expressionParser.parseExpression("new String('Any string').length()");

We can also access the bytes property of String class in the same way, resulting in the byte[] representation of the string:

Expression expression = expressionParser.parseExpression("'Any string'.bytes");
byte[] result = (byte[]) expression.getValue();

We can chain method calls, just as in normal Java code:

Expression expression = expressionParser.parseExpression("'Any string'.replace(\" \", \"\").length()");
Integer result = (Integer) expression.getValue();

In this case, the result will be 9, because we have replaced whitespace with the empty string. If we don’t wish to cast the expression result, we can use the generic method T getValue(Class<T> desiredResultType), in which we can provide the desired type of class that we want to be returned. Note that EvaluationException will be thrown if the returned value cannot be cast to desiredResultType:

Integer result = expression.getValue(Integer.class);

The most common usage is to provide an expression string that is evaluated against a specific object instance:

Car car = new Car();
car.setMake("Good manufacturer");
car.setModel("Model 3");
car.setYearOfProduction(2014);

ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression("model");

EvaluationContext context = new StandardEvaluationContext(car);
String result = (String) expression.getValue(context);

In this case, the result will be equal to value of the model field of the car object, “Model 3“. The StandardEvaluationContext class specifies which object the expression will be evaluated against. It cannot be changed after the context object is created. StandardEvaluationContext is expensive to construct, and during repeated usage it builds up cached state that enables subsequent expression evaluations to be performed more quickly. Because of caching it is good practice to reuse StandardEvaluationContext where it possible, if the root object does not change.

However, if the root object is changed repeatedly, we can use the mechanism shown in example below:

Expression expression = expressionParser.parseExpression("model");
String result = (String) expression.getValue(car);

Here, we call the getValue method with an argument that represents the object to which we want to apply a SpEL expression. We can also use the generic getValue method, just as before:

Expression expression = expressionParser.parseExpression("yearOfProduction > 2005");
boolean result = expression.getValue(car, Boolean.class);

4.2. Using ExpressionParser to Set a Value

Using the setValue method on the Expression object returned by parsing an expression, we can set values on objects. SpEL will take care of type conversion. By default, SpEL uses org.springframework.core.convert.ConversionService. We can create our own custom convertor between types. ConversionService is generics aware, so it can be used with generics. Let’s take a look how we can use it in practice:

Car car = new Car();
car.setMake("Good manufacturer");
car.setModel("Model 3");
car.setYearOfProduction(2014);

CarPark carPark = new CarPark();
carPark.getCars().add(car);

StandardEvaluationContext context = new StandardEvaluationContext(carPark);

ExpressionParser expressionParser = new SpelExpressionParser();
expressionParser.parseExpression("cars[0].model").setValue(context, "Other model");

The resulting car object will have modelOther model” which was changed from “Model 3“.

4.3. Parser Configuration

In the following example, we will use the following class:

public class CarPark {
    private List<Car> cars = new ArrayList<>();

    // Getter and setter
}

It is possible to configure ExpressionParser by calling the constructor with a SpelParserConfiguration object. For example, if we try to add car object into the cars array of CarPark class without configuring the parser, we will get an error like this:

EL1025E:(pos 4): The collection has '0' elements, index '0' is invalid

We can change the behavior of the parser, to allow it to automatically create elements if the specified index is null (autoGrowNullReferences, the first parameter to the constructor), or to automatically grow an array or list to accommodate elements beyond its initial size (autoGrowCollections, the second parameter).

SpelParserConfiguration config = new SpelParserConfiguration(true, true);
StandardEvaluationContext context = new StandardEvaluationContext(carPark);

ExpressionParser expressionParser = new SpelExpressionParser(config);
expressionParser.parseExpression("cars[0]").setValue(context, car);

Car result = carPark.getCars().get(0);

The resulting car object will be equal to the car object which was set as the first element of the cars array of carPark object from the previous example.

5. Conclusion

SpEL is a powerful, well-supported expression language that can be used across all the products in the Spring portfolio. It can be used to configure Spring applications or to write parsers to perform more general tasks in any application.

The code samples in this article are available in the linked GitHub repository.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

An Intro to Spring HATEOAS

$
0
0

I just announced the Master Class of my "REST With Spring" Course:

>> THE "REST WITH SPRING" CLASSES

1. Overview

This article explains the process of creating hypermedia-driven REST web service using Spring HATEOAS project.

2. Spring-HATEOAS

The Spring HATEOAS project is a library of APIs that we can use to easily create REST representations that follow the principle of HATEOAS (Hypertext as the Engine of Application State).

Generally speaking, the principle implies that the API should guide the client through the through the application by returning relevant information about the next potential steps, along with each response.

In this article we are going to build an example using Spring HATEOAS with the goal of decoupling the client and server, and theoretically allowing the API to change its URI scheme without breaking clients.

3. Preparation

First, let’s add Spring HATEOAS dependency:

<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>0.19.0.RELEASE</version>
</dependency>

Next, we have the Customer resource without Spring HATEOAS support:

public class Customer {

    private String customerId;
    private String customerName;
    private String companyName;

    // standard getters and setters
}

And we have a controller class without Spring HATEOAS support:

@RestController
@RequestMapping(value = "/customers")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/{customerId}", method = RequestMethod.GET)
    public Customer getCustomerById(@PathVariable String customerId) {
        return customerService.getCustomerDetail(customerId);
    }
}

Finally, the customer resource representation:

{
    "customerId": "10A",
    "customerName": "Jane",
    "customerCompany": "ABC Company"
}

4. Adding HATEOAS Support

In a Spring HATEOAS project, we don’t need to either look up the Servlet context nor concatenate the path variable to the base URI. Spring HATEOAS offers three abstractions for creating the URI – ResourceSupport, Link and ControllerLinkBuilder. These are used to create the metadata and associate it to the resource representation.

4.1. Adding Hypermedia Support to a Resource

Spring HATEOAS project provides a base class called ResourceSupport to inherit from when creating resource representation.

public class Customer extends ResourceSupport {
    private String customerId;
    private String customerName;
    private String companyName;
 
    // standard getters and setters
}

The Customer resource extends from ResourseSupport class to inherit the add() method. So once we create a link, we can easily set that value to the resource representation without adding any new fields to it.

Spring HATEOAS provides a Link object to store the metadata (location or URI of the resource).

We’ll first create a simple link manually:

Link link = new Link("http://localhost:8080/spring-security-rest/api/customers/10A");

The Link object follows the Atom link syntax and consists of a rel which identifies relation to the resource and href attribute which is the actual link itself.

Here’s how the Customer resource looks now that it contains the new link:

{
    "links": [{
        "rel": "self",
        "href": "http://localhost:8080/spring-security-rest/api/customers/10A"
    }],
    "customerId": "10A",
    "customerName": "Jane",
    "customerCompany": "ABC Company"
}

The URI associated with the response is qualified as a self link. The semantics of the self relation is clear – it’s simply the canonical location the Resource can be accessed at.

Another very important abstraction offered by the library is the ControllerLinkBuilder – which simplifies building URIs by avoiding hard-coded the links.

The following snippet shows building the customer self-link using the ControllerLinkBuilder class:

linkTo(CustomerController.class).slash(customer.getCustomerId()).withSelfRel();

Let’s have a look:

  • the linkTo() method inspects the controller class and obtains its root mapping
  • the slash() method adds the customerId value as the path variable of the link
  • finally, the withSelfMethod() qualifies the relation as a self-link

5. Relations

In the previous section we’ve shown a self-referencing relation. More complex systems may involve other relations as well.

For example, a customer can have a relationship to orders. The Order class will be modeled as a resource as well:

public class Order extends ResourceSupport {
    private String orderId;
    private double price;
    private int quantity;

    // standard getters and setters
}

At this point, the CustomerController controller can be extended with a method that return all orders of a particular customer:

@RequestMapping(value = "/{customerId}/orders", method = RequestMethod.GET)
public List getOrdersForCustomer(@PathVariable String customerId) {
    return orderService.getAllOrdersForCustomer(customerId);
}

An important thing to notice here, is that the hyperlink for the customer orders depends on the mapping of getOrdersForCustomer() method. We’ll refer to this types of links as method links and show how the ControllerLinkBuilder can assist in their creation.

The ControllerLinkBuilder offers rich support for Spring MVC Controllers. The following example shows how to build HATEOAS hyperlinks based on the getOrdersForCustomer() method of the CustomerController class.

List<Order> methodLinkBuilder = 
  methodOn(CustomerController.class).getOrdersForCustomer(customer.getCustomerId());
Link ordersLink = linkTo(methodLinkBuilder).withRel("allOrders");

The methodOn() obtains the method mapping by making dummy invocation of the target method on the proxy controller, and sets the customerId as the path variable of the URI.

7. Spring HATEOAS in Action

Let’s put the self-link and method link creation all together in a getAllCustomers() method.

@RequestMapping(method = RequestMethod.GET)
public List getAllCustomers() {
    List allCustomers = customerService.allCustomers();
    for (Customer customer : allCustomers) {
        Link selfLink = linkTo(CustomerController.class).slash(customer.getCustomerId()).withSelfRel();
        customer.add(selfLink);
        
        if (orderService.getAllOrdersForCustomer(customer.getCustomerId()).size() > 0) {
            List<Order> methodLinkBuilder = 
              methodOn(CustomerController.class).getOrdersForCustomer(customer.getCustomerId());
            Link ordersLink = linkTo(methodLinkBuilder).withRel("allOrders");
            customer.add(ordersLink);
        }
    }
    return allCustomers;
}

Let’s invoke the getAllCustomers() method:

curl http://localhost:8080/spring-security-rest/api/customers

And examine the result:

[{
    "links": [{
        "rel": "self",
        "href": "http://localhost:8080/spring-security-rest/api/customers/10A"
    }, {
        "rel": "allOrders",
        "href": "http://localhost:8080/spring-security-rest/api/customers/10A/orders"
    }],
    "customerId": "10A",
    "customerName": "Jane",
    "companyName": "ABC Company"
}, {
    "links": [{
        "rel": "self",
        "href": "http://localhost:8080/spring-security-rest/api/customers/20B"
    }, {
        "rel": "allOrders",
        "href": "http://localhost:8080/spring-security-rest/api/customers/20B/orders"
    }],
    "customerId": "20B",
    "customerName": "Bob",
    "companyName": "XYZ Company"
}, {
    "links": [{
        "rel": "self",
        "href": "http://localhost:8080/spring-security-rest/api/customers/30C"
    }],
    "customerId": "30C",
    "customerName": "Tim",
    "companyName": "CKV Company"
}]

Within each resource representation, there is a self  link and the allOrders link to extract all orders of a customer. If a customer does not have orders, then the link for orders will not appear.

This example demonstrates how Spring HATEOAS fosters API discoverability in a rest web service. If the link exists, the client can follow it and get all orders for a customer:

curl http://localhost:8080/spring-security-rest/api/customers/10A/orders
[{
    "links": [{
        "rel": "self",
        "href": "http://localhost:8080/spring-security-rest/api/customers/10A/001A"
    }],
    "orderId": "001A",
    "price": 150.0,
    "quantity": 25
}, {
    "links": [{
        "rel": "self",
        "href": "http://localhost:8080/spring-security-rest/api/customers/10A/002A"
    }],
    "orderId": "002A",
    "price": 250.0,
    "quantity": 15
}]

8. Conclusion

In this tutorial, we have discussed how to build a hypermedia-driven Spring REST web service using Spring HATEOAS project.

In the example, we see that client can have a single entry point to the application and further actions can be taken based on the metadata in the response representation. This allows the server to change its URI scheme without breaking the client. Also, the application can advertise new capabilities by putting new links or URIs in the representation.

The full implementation of this article can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

The Master Class of my "REST With Spring" Course is finally out:

>> CHECK OUT THE CLASSES

Java Web Weekly, Issue 121

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

At the very beginning of last year, I decided to track my reading habits and share the best stuff here, on Baeldung. Haven’t missed a review since.

Here we go…

1. Spring and Java

>> Understanding Reactive types [spring.io]

Even more insight into reactive types and semantics, and of course into the upcoming Spring 5 work that’s happening behind the scenes.

>> String Compaction [javaspecialists.eu]

Interesting as as always, this one is an low level exploration of how the JVM deals with memory and Strings.

>> Testing improvements in Spring Boot 1.4 [spring.io]

Testing in a Spring Boot project is getting simpler and more streamlined – especially when it comes to mocking and handling of complex JSON.

>> The Parameterless Generic Method Antipattern [jooq.org]

A very interesting piece on how the Java compiler doesn’t always do the right thing when it comes to using generics.

>> Java EE vs Java SE: Has Oracle Given up on Enterprise Software? [takipi.com]

A well researched and insightful writeup about the state of Java EE today.

>> Most popular Java EE servers: 2016 edition [plumbr.eu]

And continuing the Java EE thread, some real-world data about the popularity of existing Java EE servers.

>> Exercises in Kotlin: Part 1 – Getting Started [dhananjaynene.com]

>> Exercises in Kotlin: Part 2 – High level syntax and Variables [dhananjaynene.com]

>> Exercises in Kotlin: Part 3 – Functions [dhananjaynene.com]

If you’re curious about Kotlin – this looks like a great place to start.

I haven’t yet gone through the exercises myself, but they’re on my weekend todo list.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical

>> Ideal HTTP Performance [mnot.net]

We’re all working with HTTP one way or another, so it really doesn’t hurt understanding the protocol well. This is a great writeup to get us there.

>> Boost Your REST API with HTTP Caching [kennethlange.com]

A quick and practical intro to using caching headers with a REST API.

>> A Beginner’s Guide to Addressing Concurrency Issues [techblog.bozho.net]

Taking a step back before diving head first into a complex architecture problem is fantastic advice.

There is a time when analyzing the transactional semantics of your system and improving them is the right thing to do. And then there are all the other times when it just seems like it is.

Also worth reading:

3. Musings

>> Join me at GeeCON [code-cop.org]

GeeCON is going to be a blast, can’t wait to get there – if you’re coming, make sure you say hi.

>> A Taxonomy of Software Consultants [daedtech.com]

Getting some clarity around the terms we’re using when talking about our work we do and about ourselves is definitely a useful thing to spend some time on.

>> The powerful hacker culture [lemire.me]

The hacker culture and the drive to tinker, experiment and simply do – is one of the things I like most about our ecosystem, and probably one of the top reasons we’re all in it.

Also worth reading:

4. Comics

And my favorite Dilberts of the week:

>> Feel as if you have a strategy [dilbert.com]

>> Must. not. cry. on. the. outside [dilbert.com]

>> I see what you’re doing [dilbert.com]

5. Pick of the Week

>> I’m a boring programmer (and proud of it) [m.signalvnoise.com]

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Guide to the Fork/Join Framework in Java

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

The fork/join framework was presented in Java 7. It provides tools to help speed up parallel processing by attempting to use all available processor cores – which is accomplished through a divide and conquer approach.

In practice, this means that the framework first “forks”, recursively breaking the task into smaller independent subtasks, until they are simple enough to be executed asynchronously.

After that, the “join” part begins, in which results of all subtasks are recursively joined into a single result, or in the case of a task which returns void, the program simply waits until every subtask is executed.

To provide effective parallel execution, the fork/join framework uses a pool of threads called the ForkJoinPool, which manages worker threads of type ForkJoinWorkerThread. 

2. ForkJoinPool

The ForkJoinPool is the heart of the framework. It is an implementation of the ExecutorService that manages worker threads and provides us with tools to get information about the thread pool state and performance.

Worker threads can execute only one task at the time, but the ForkJoinPool doesn’t create a separate thread for every single subtask. Instead, each thread in the pool has its own double-ended queue (or deque, pronounced deck) which stores tasks.

This architecture is vital for balancing the thread’s workload with the help of the work stealing algorithm.

2.1. Work Stealing Algorithm

Simply put – free threads try to “steal” work from deques of busy threads.

By default, a worker thread gets tasks from the head of its own deque. When it is empty, the thread takes a task from the tail of the deque of another busy thread or from the global entry queue, since this is where the biggest pieces of work are likely to be located.

This approach minimizes the possibility that threads will compete for tasks. It also reduces the number of times the thread will have to go looking for work, as it works on the biggest available chunks of work first.

2.2. ForkJoinPool Instantiation

In Java 8, the most convenient way to get access to the instance of the ForkJoinPool is to use its static method commonPool(). As its name suggests, this will provide a reference to the common pool, which is a default thread pool for every ForkJoinTask.

According to Oracle’s documentation, using the predefined common pool reduces resource consumption, since this discourages the creation of a separate thread pool per task.

ForkJoinPool commonPool = ForkJoinPool.commonPool();

The same behavior can be achieved in Java 7 by creating a ForkJoinPool and assigning it to a public static field of a utility class:

public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);

Now it can be easily accessed:

ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;

With ForkJoinPool’s constructors, it is possible to create a custom thread pool with a specific level of parallelism, thread factory, and exception handler. In the example above, the pool has a parallelism level of 2. This means that pool will use 2 processor cores.

3. ForkJoinTask<V>

ForkJoinTask is the base type for tasks executed inside ForkJoinPool. In practice, one of its two subclasses should be extended: the RecursiveAction for void tasks and the RecursiveTask<V> for tasks that return a value. They both have an abstract method compute() in which the task’s logic is defined.

3.1. RecursiveAction – An Example

In the example below, the unit of work to be processed is represented by a String called workload. For demonstration purposes, the task is a nonsensical one: it simply uppercases its input and logs it.

To demonstrate the forking behavior of the framework, the example splits the task if workload.length() is larger than a specified threshold using the createSubtask() method.

The String is recursively divided into substrings, creating CustomRecursiveTask instances which are based on these substrings.

As a result, the method returns a List<CustomRecursiveAction>.  

The list is submitted to the ForkJoinPool using the invokeAll() method:

public class CustomRecursiveAction extends RecursiveAction {

    private String workload = "";
    private static final int THRESHOLD = 4;

    private static Logger logger = 
      Logger.getAnonymousLogger();

    public CustomRecursiveAction(String workload) {
        this.workload = workload;
    }

    @Override
    protected void compute() {
        if (workload.length() > THRESHOLD) {
            ForkJoinTask.invokeAll(createSubtasks());
        } else {
           processing(workload);
        }
    }

    private List<CustomRecursiveAction> createSubtasks() {
        List<CustomRecursiveAction> subtasks = new ArrayList<>();

        String partOne = workload.substring(0, workload.length() / 2);
        String partTwo = workload.substring(workload.length() / 2, workload.length());

        subtasks.add(new CustomRecursiveAction(partOne));
        subtasks.add(new CustomRecursiveAction(partTwo));

        return subtasks;
    }

    private void processing(String work) {
        String result = work.toUpperCase();
        logger.info("This result - (" + result + ") - was processed by " 
          + Thread.currentThread().getName());
    }
}

This pattern can be used to develop your own RecursiveAction classes. To do this, create an object which represents the total amount of work, chose suitable threshold, define a method to divide the work, and define a method to do the work.

3.2. RecursiveTask<V>

For tasks that return a value, the logic here is similar, except that result for each subtask is united in a single result:

public class CustomRecursiveTask extends RecursiveTask<Integer> {
    private int[] arr;

    private static final int THRESHOLD = 20;

    public CustomRecursiveTask(int[] arr) {
        this.arr = arr;
    }

    @Override
    protected Integer compute() {
        if (arr.length > THRESHOLD) {
            return ForkJoinTask.invokeAll(createSubtasks())
              .stream()
              .mapToInt(ForkJoinTask::join)
              .sum();
        } else {
            return processing(arr);
        }
    }

    private Collection<CustomRecursiveTask> createSubtasks() {
        List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
        dividedTasks.add(new CustomRecursiveTask(
          Arrays.copyOfRange(arr, 0, arr.length / 2)));
        dividedTasks.add(new CustomRecursiveTask(
          Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
        return dividedTasks;
    }

    private Integer processing(int[] arr) {
        return Arrays.stream(arr)
          .filter(a -> a > 10 && a < 27)
          .map(a -> a * 10)
          .sum();
    }
}

In this example, the work is represented by an array stored in the arr field of the CustomRecursiveTask class. The createSubtask() method recursively divides the task into smaller pieces of work until each piece is smaller than the threshold. Then, the invokeAll() method submits subtasks to the common pull and returns a list of Future.

To trigger execution, the join() method called for each subtask.

In this example, this is accomplished using Java 8’s Stream API; the sum() method is used as a representation of combining subresults into the final result.

4. Submitting Tasks to the ForkJoinPool

To submit tasks to the thread pool, few approaches can be used.

The submit() or execute() method (their usecases are the same):

forkJoinPool.execute(customRecursiveTask);
int result = customRecursiveTask.join();

The invoke() method forks the task and waits for the result, and doesn’t need any manual joining:

int result = forkJoinPool.invoke(customRecursiveTask);

The invokeAll() method is the most convenient way to submit a sequence of ForkJoinTasks to the ForkJoinPool. It takes tasks as parameters (two tasks, varargs, or a collection), forks them returns a collection of Future objects in the order in which they were produced.

Alternatively, you can use separate fork() and join() methods. The fork() method submits a task to a pool, but it doesn’t trigger its execution. The join() method is be used for this purpose. In the case of RecursiveAction, the join() returns nothing but null; for RecursiveTask<V>, it returns the result of the task’s execution:

customRecursiveTaskFirst.fork();
result = customRecursiveTaskLast.join();

In our RecursiveTask<V> example we used the invokeAll() method to submit a sequence of subtasks to the pool. The same job can be done with fork() and join(), though this has consequences for the ordering of the results.

To avoid confusion, it is generally a good idea to use invokeAll() method to submit more than one task to the ForkJoinPool.

5. Conclusions

Using the fork/join framework can speed up processing of large tasks, but to achieve this outcome, some guidelines should be followed:

  • Use as few thread pools as possible – in most cases the best decision is to use one thread pool per application or system
  • Use the default common thread pool, if no specific tuning is needed
  • Use a reasonable threshold for splitting ForkJoingTask into subtasks
  • Avoid any blocking in your ForkJoingTasks

The examples used in this article are available in the linked GitHub repository.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Introduction to PowerMock

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

Unit testing with the help of a mocking framework has been recognized as a useful practice for a long time, and the Mockito framework, in particular, has dominated this market in recent years.

And in order to facilitate decent code designs and make the public API simple, some desired features have been intentionally left out. In some cases, however, these shortcomings force testers to write cumbersome code just to make the creation of mocks feasible.

This is where the PowerMock framework comes into play.

PowerMockito is a PowerMock’s extension API to support Mockito. It provides capabilities to work with the Java Reflection API in a simple way to overcome the problems of Mockito, such as the lack of ability to mock final, static or private methods.

This tutorial will give an introduction to the PowerMockito API and how it is applied in tests.

2. Preparing for Testing with PowerMockito

The first step to integrate PowerMock support for Mockito is to include the following two dependencies in the Maven POM file:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>

Next, we need to prepare our test cases for working with PowerMockito by applying the following two annotations:

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.*")

The fullyQualifiedNames element in the @PrepareForTest annotation represents an array of fully qualified names of types we want to mock. In this case, we use a package name with a wildcard to tell PowerMockito to prepare all types within the com.baeldung.powermockito.introduction package for mocking.

Now we are ready to exploit the power of PowerMockito.

3. Mocking Constructors and Final Methods

In this section, we will demonstrate the ways to get a mock instance instead of a real one when instantiating a class with the new operator, and then use that object to mock a final method. The collaborating class, whose constructors and final methods will be mocked, is defined as follows:

public class CollaboratorWithFinalMethods {
    public final String helloMethod() {
        return "Hello World!";
    }
}

First, we create a mock object using the PowerMockito API:

CollaboratorWithFinalMethods mock = mock(CollaboratorWithFinalMethods.class);

Next, set an expectation telling that whenever the no-arg constructor of that class is invoked, a mock instance should be returned rather than a real one:

whenNew(CollaboratorWithFinalMethods.class).withNoArguments().thenReturn(mock);

Let’s see how this construction mocking works in action by instantiating the CollaboratorWithFinalMethods class using its default constructor, and then verify the behaviors of PowerMock:

CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();
verifyNew(CollaboratorWithFinalMethods.class).withNoArguments();

In the next step, an expectation is set to the final method:

when(collaborator.helloMethod()).thenReturn("Hello Baeldung!");

This method is then executed:

String welcome = collaborator.helloMethod();

The following assertions confirm that the helloMethod method has been called on the collaborator object, and returns the value set by the mocking expectation:

Mockito.verify(collaborator).helloMethod();
assertEquals("Hello Baeldung!", welcome);

If we want to mock a specific final method rather than all the final ones inside an object, the Mockito.spy(T object) method may come in handy. This is illustrated in section 5.

4. Mocking Static Methods

Suppose that we want to mock static methods of a class named CollaboratorWithStaticMethods. This class is declared as follows:

public class CollaboratorWithStaticMethods {
    public static String firstMethod(String name) {
        return "Hello " + name + " !";
    }

    public static String secondMethod() {
        return "Hello no one!";
    }

    public static String thirdMethod() {
        return "Hello no one again!";
    }
}

In order to mock these static methods, we need to register the enclosing class with the PowerMockito API:

mockStatic(CollaboratorWithStaticMethods.class);

Alternatively, we may use the Mockito.spy(Class<T> class) method to mock a specific one as demonstrated in the following section.

Next, expectations can be set to define the values methods should return when invoked:

when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString()))
  .thenReturn("Hello Baeldung!");
when(CollaboratorWithStaticMethods.secondMethod()).thenReturn("Nothing special");

Or an exception may be set to be thrown when calling the thirdMethod method:

doThrow(new RuntimeException()).when(CollaboratorWithStaticMethods.class);
CollaboratorWithStaticMethods.thirdMethod();

Now, it is time for executing the first two methods:

String firstWelcome = CollaboratorWithStaticMethods.firstMethod("Whoever");
String secondWelcome = CollaboratorWithStaticMethods.firstMethod("Whatever");

Instead of calling members of the real class, the above invocations are delegated to the mock’s methods. The following assertions prove that the mock has come into effect:

assertEquals("Hello Baeldung!", firstWelcome);
assertEquals("Hello Baeldung!", secondWelcome);

We are also able to verify behaviors of the mock’s methods, including how many times a method is invoked. In this case, the firstMethod has been called twice, while the secondMethod has never:

verifyStatic(Mockito.times(2));
CollaboratorWithStaticMethods.firstMethod(Mockito.anyString());
        
verifyStatic(Mockito.never());
CollaboratorWithStaticMethods.secondMethod();

Note: The verifyStatic method must be called right before any static method verification for PowerMockito to know that the successive method invocation is what needs to be verified.

Lastly, the static thirdMethod method should throw a RuntimeException as declared on the mock before. It is validated by the expected element of the @Test annotation:

@Test(expected = RuntimeException.class)
public void givenStaticMethods_whenUsingPowerMockito_thenCorrect() {
    // other methods   
       
    CollaboratorWithStaticMethods.thirdMethod();
}

5. Partial Mocking

Instead of mocking an entire class, the PowerMockito API allows for mocking part of it using the spy method. The following class will be used as the collaborator to illustrate the PowerMock support for partial mocking:

public class CollaboratorForPartialMocking {
    public static String staticMethod() {
        return "Hello Baeldung!";
    }

    public final String finalMethod() {
        return "Hello Baeldung!";
    }

    private String privateMethod() {
        return "Hello Baeldung!";
    }

    public String privateMethodCaller() {
        return privateMethod() + " Welcome to the Java world.";
    }
}

Let’s begin with mocking a static method, which is named staticMethod in the above class definition. First, use the PowerMockito API to partially mock the CollaboratorForPartialMocking class and set an expectation for its static method:

spy(CollaboratorForPartialMocking.class);
when(CollaboratorForPartialMocking.staticMethod()).thenReturn("I am a static mock method.");

The static method is then executed:

returnValue = CollaboratorForPartialMocking.staticMethod();

The mocking behavior is verified as follows:

verifyStatic();
CollaboratorForPartialMocking.staticMethod();

The following assertion confirms that the mock method has actually been called by comparing the return value against the expectation:

assertEquals("I am a static mock method.", returnValue);

Now it is time to move on to the final and private methods. In order to illustrate the partial mocking of these methods, we need to instantiate the class and tell the PowerMockito API to spy it:

CollaboratorForPartialMocking collaborator = new CollaboratorForPartialMocking();
CollaboratorForPartialMocking mock = spy(collaborator);

The objects created above are used to demonstrating the mocking of both the final and private methods. We will deal with the final method now by setting an expectation and invoke the method:

when(mock.finalMethod()).thenReturn("I am a final mock method.");
returnValue = mock.finalMethod();

The behavior of partially mocking that method is proved:

Mockito.verify(mock).finalMethod();

A test verifies that calling the finalMethod method will return a value that matches the expectation:

assertEquals("I am a final mock method.", returnValue);

A similar process is applied to the private method. The main difference is that we cannot directly invoke this method from the test case. Basically, a private method is to be called by other ones from the same class. In the CollaboratorForPartialMocking class, the privateMethod method is to be invoked by the privateMethodCaller method and we will use the latter as a delegate. Let’s start with the expectation and invocation:

when(mock, "privateMethod").thenReturn("I am a private mock method.");
returnValue = mock.privateMethodCaller();

The mocking of the private method is confirmed:

verifyPrivate(mock).invoke("privateMethod");

The following test makes sure that the return value from invocation of the private method is the same as the expectation:

assertEquals("I am a private mock method. Welcome to the Java world.", returnValue);

6. Conclusion

This tutorial has provided an introduction to the PowerMockito API, demonstrating its use in solving some of the problems developers encounter when using the Mockito framework. The implementation of these examples and code snippets can be found in the linked GitHub project.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Java Web Weekly, Issue 122

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

At the very beginning of last year, I decided to track my reading habits and share the best stuff here, on Baeldung. Haven’t missed a review since.

Here we go…

1. Spring and Java

>> Event Sourcing in Microservices Using Spring Cloud and Reactor [kennybastani.com]

All the cool kids of doing microservices – and most are left with a complex and hard to manage mess on their hands.

But there are ways to avoid that – and Event Sourcing is one of the best ways I found to get there.

>> How to verify equality without equals method [lkrnac.net]

A cool deep-dive into testing the implementation of the equals method using reflection.

>> Exploring CQRS with Axon Framework: Closing thoughts [geekabyte.blogspot.com]

The end of a long running series I’ve been following closely, all about one of my favorite topics – Event Sourcing and CQRS.

CQRS is definitely not the holy grail, but it sure comes close in some scenarios 🙂

>> How to join unrelated entities with JPA and Hibernate [thoughts-on-java.org]

A cool addition to Hibernate I wasn’t aware of.

>> Java EE 8 MVC: Global exception handling [mscharhag.com]

A very quick and to the point intro to handling exceptions if you’re doing work with Java EE.

>> Save Time by Writing Less Test Code [petrikainulainen.net]

Some initial details about a course I’m really excited about (check out this week’s pick for more on that).

 

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical and Musings

>> Why You Should Do Periodic Reviews of Legacy Code [daedtech.com]

Solid advice for keeping your less visited code for rotting and getting out of sync with the parts of the system you’re actively working on.

>> Evaluating Delusional Startups [zachholman.com]

A funny read if you’re out of that game, and hopefully a helpful one is you’re not.

Also worth reading:

3. Comics

And my favorite Dilberts of the week:

>> Bury something in the woods [dilbert.com]

>> Can’t you find meaning in your personal life? [dilbert.com]

>> That could work [dilbert.com]

4. Pick of the Week

Almost a year ago, when I started to work on my first course, I wrote that we have so few solid courses in our ecosystem. I know from experience that it takes a long time to put together a good, high quality course – around 6 months of ongoing work – which explains why there are so few of these out there.

 

That’s slowly changing – Petri’s newly announced testing course is definitely going to be reference material:

>> TEST WITH SPRING

 

The packages have been at 50% off all week (ending today) – so if you’re into testing, pick this one up. If you’re not really into testing, then definitely pick this one up.

I’m excited about this one, not just because it’s about testing, but also about Spring (which is very cool).

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Conferences in May

$
0
0

After reading the enthusiastic Join me at GeeCON article I was inspired to do a quick writeup about the conferences that are coming up in the month of May.

I’m super excited about May; first off, there’s GeeCON, starting on the 11th and wrapping up on the 13th and then SpringIO in Barcelona, on the 19 and the 20th.

Both of these are fantastic events with a lot of cool talks. But, beyond the talks, it’s the hallway track that I’m psyched about even more. Reading about “the community” in general simply doesn’t compare to being in a room with so many passionate developers.

So, if you’re planning to attend – and I definitely recommend you do – grab me and say hi.

 

Now, here are the talks I’m most excited about – first, from GeeCON:

– Cloud Native Java

– MDD: Metrics Driven Development

– Microservices. Stairway to heaven or highway to hell?

– Microservices tracing with Spring Cloud and Zipkin

– Beyond lambdas – the aftermath

– PrivateEye

– Creating Jenkins pipelines with groovy-based DSL

– Take me on a journey – the next step in automated testing practices

– Building multiplayer game using Reactive Streams

– How to Think, in RxJava, Before Reacting

– Twelve BDD Antipatterns – stories from the trenches about how NOT to do BDD

– Every millisecond counts

– Better living through pull requests

 

And from SpringIO:

– From Spring Framework 4.3 to 5.0

– Designing Applications: The Reactive Way

– 10 ways to get super-productive with Spring Boot

– JUnit 5 – Shaping the Future of Testing on the JVM

– Understanding Microservice Performance

– Testing Spring Boot Applications

– What’s new in Spring Data?

– From Imperative To Reactive

– Test-driven documentation with Spring REST Docs

– Extending Spring Data

– Securing RESTful services with Spring HATEOAS and HDIV

 

A lot of cool stuff that’s going to have an impact over the work I’m going to be doing in 2016.

And of course I’m excited about my own presentations, so definitely join me for that as well.

Yeah, May is going to be fun.

Mockito’s Mock Methods

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

This tutorial illustrates various uses of the standard static mock methods of the Mockito API.

As with other articles focused on the Mockito framework (like Mockito Verify or Mockito When/Then), the MyList class shown below will be used as the collaborator to be mocked in test cases:

public class MyList extends AbstractList<String> {
    @Override
    public String get(int index) {
        return null;
    }

    @Override
    public int size() {
        return 1;
    }
}

2. Simple Mocking

The simplest overloaded variant of the mock method is the one with a single parameter for the class to be mocked:

public static <T> T mock(Class<T> classToMock)

We will use this method to mock a class and set an expectation:

MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);

Then execute a method on the mock:

boolean added = listMock.add(randomAlphabetic(6));

The following code confirms that the add method has been invoked on the mock, and that the invocation returns a value which matches the expectation we set before:

verify(listMock).add(anyString());
assertThat(added, is(false));

3. Mocking with Mock’s Name

In this section, we will cover another variant of the mock method which is provided with an argument specifying the name of the mock:

public static <T> T mock(Class<T> classToMock, String name)

Generally speaking, the name of a mock has nothing to do with working code, but may be helpful when it comes to debugging, where the mock’s name is used to track down verification errors.

To make sure that the provided name of a mock is included in the message of an exception thrown from an unsuccessful verification, we will rely on a JUnit implementation of the TestRule interface, called ExpectedException, and include it in a test class:

@Rule
public ExpectedException thrown = ExpectedException.none();

This rule will be used to handle exceptions thrown from test methods.

In the following code, we create a mock for the MyList class and name it myMock:

MyList listMock = mock(MyList.class, "myMock");

Afterwards, set an expectation on a method of the mock and execute it:

when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));

We will create an intentionally failed verification that should throw an exception with the message containing information about the mock. In order to do it, expectations on the exception need to be set first:

thrown.expect(TooLittleActualInvocations.class);
thrown.expectMessage(containsString("myMock.add"));

The following verification should fail and throw an exception matching what were expected:

verify(listMock, times(2)).add(anyString());

Here is the thrown exception’s message:

org.mockito.exceptions.verification.TooLittleActualInvocations:
myMock.add(<any>);
Wanted 2 times:
at com.baeldung.mockito.MockitoMockTest
  .whenUsingMockWithName_thenCorrect(MockitoMockTest.java:...)
but was 1 time:
at com.baeldung.mockito.MockitoMockTest
  .whenUsingMockWithName_thenCorrect(MockitoMockTest.java:...)

As we can see, the mock’s name has been included in the exception message, which will be useful to find the failure point in case of an unsuccessful verification.

4. Mocking with Answer

Here, we will demonstrate the use of a mock variant in which the strategy for the mock’s answers to interaction is configured at creation time. This mock method’s signature in the Mockito documentation looks like the following:

public static <T> T mock(Class<T> classToMock, Answer defaultAnswer)

Let’s start with the definition of an implementation of the Answer interface:

class CustomAnswer implements Answer<Boolean> {
    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
        return false;
    }
}

The CustomAnswer class above is used for the generation of a mock:

MyList listMock = mock(MyList.class, new CustomAnswer());

If we do not set an expectation on a method, the default answer, which was configured by the CustomAnswer type, will come into play. In order to prove it, we will skip over the expectation setting step and jump to the method execution:

boolean added = listMock.add(randomAlphabetic(6));

The following verification and assertion confirm that the mock method with an Answer argument has worked as expected:

verify(listMock).add(anyString());
assertThat(added, is(false));

5. Mocking with MockSettings

The final mock method that is covered within this article is the variant with a parameter of the MockSettings type. This overloaded method is use to provide a non-standard mock.

There are several custom settings that are supported by methods of the MockSettings interface, such as registering a listener for method invocations on the current mock with invocationListeners, configuring serialization with serializable, specifying the instance to spy on with spiedInstance, configuring Mockito to attempt to use a constructor when instantiating a mock with useConstructor, and some others.

For the convenience, we will reuse the CustomAnswer class introduced in the previous section to create a MockSettings implementation that defines a default answer.

A MockSettings object is instantiated by a factory method as follows:

MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());

That setting object will be used in the creation of a new mock:

MyList listMock = mock(MyList.class, customSettings);

Similar to the preceding section, we will invoke the add method of a MyList instance and verify that a mock method with a MockSettings argument works as it is meant to by using the following code snippet:

boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));

6. Conclusion

This tutorial has covered the mock method of Mockito in detail. The implementation of these examples and code snippets can be found in a GitHub project.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Java Web Weekly, Issue 123

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

At the very beginning of last year, I decided to track my reading habits and share the best stuff here, on Baeldung. Haven’t missed a review since.

Here we go…

1. Spring and Java

>> FizzBuzz Kata With Java Streams [securesoftwaredev.com]

“Practicing means slowing down” – very nicely put.

This is a step by step Kata of a well known problem, using some Java 8 goodness.

>> The best way of logging JDBC statements [vladmihalcea.com]

Some cool techniques to set up logging in a Hibernate system or right around the data source.

This one falls in the category – “didn’t know you could do that”.

>> What’s new in Spring Data Hopper? [spring.io]

Some really cool stuff in this latest Spring Data release.

I’m especially interested in the Querydsl stuff – looks like I have something to play with this weekend.

Projections also look like they’re going to really come in handy in some scenarios.

>> Using Java Generics to express variance of Collections and Functions [advancedweb.hu]

Playing with generics is always fun, especially when you sprinkle some Java 8 syntax on top.

>> Laziness at extreme: developing JAX-RS services with Spring Boot [aredko.com]

A quick and fun way of using Boot outside the core Spring ecosystem.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical

>> The Benefits of Hypermedia APIs [olivergierke.de]

If you’ve been following Baeldung for any amount of time, you know Hypermedia APIs are one of my favorite topics. So I was excited to see this writeup pop up in my RSS feed.

Yeah – go read this one.

>> Locating Common Micro Service Performance Anti-Patterns [infoq.com]

A solid overview of the common things that can go wrong in a microservice architecture.

Some of these aren’t microservice specific, but the ones that are definitely paint a clear picture of the extra complexity in this kind of system.

>> Microservices are about applying a group of Best Practices [vanillajava.blogspot.com]

Moving an existing codebase to a microservice architecture is no small feat. And that’s not even taking into account the non-technical challenges.

We definitely need more nuanced strategies based on actual production experience with microservices to help drive these architectural decisions.

Also worth reading:

3. Musings

>> Hiring is Broken… And It Isn’t Worth Fixing [daedtech.com]

An insightful read on how the hiring process isn’t looking at the right things.

It’s also long enough to fit three cool cartoons 🙂

The interesting thing is that I’ve read about at least two companies trying to take on the challenge just this week – both with non-traditional, depth vs width approaches. So maybe there’s hope.

>> Breach concealment is not a security strategy [troyhunt.com]

If you find security news and musings about the right way to handle a data breach interesting – then this is certainly worth reading.

>> Email: how to be polite and efficient [lemire.me]

The more email I get, the more I think that writing good email is a black art. This quick writeup has some useful rules to live by when writing that email.

>> Applied Consultant Taxonomy to Prevent Confusion [daedtech.com]

More nuanced and practical examples of how scoping and defining different roles is important, and “consultant” really isn’t enough.

Also worth reading:

4. Comics

And my favorite Dilberts of the week:

>> I’ll sweet your dumb tweets off to the side [dilbert.com]

>> Buy our monthly subscription or I’ll send your browser history to your contacts [dilbert.com]

>> Should have kept that thought bottled up [dilbert.com]

5. Pick of the Week

>> Hacking is Important [medium.com]

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Spring HTTP/HTTPS Channel Security

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

This tutorial shows how to use HTTPS to protect your application’s login page using Spring’s Channel Security feature.

Using HTTPS for authentication is crucial to protect the integrity of sensitive data when in transport.

The article builds on top of the Spring Security Login tutorial by adding an additional layer of security. We highlight the steps needed to secure the authentication data by serving the login page through the encoded HTTPS channel.

2. Initial Setup Without Channel Security

Let’s start out with the security configuration explained in the aforementioned article.

The web-app allows users to access:

  1. /anonymous.html without authentication,
  2. /login.html, and
  3. other pages (/homepage.html) after a successful login.

The access is controlled by the following configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests() 
      .antMatchers("/anonymous*")
      .anonymous();

    http.authorizeRequests()
      .antMatchers("/login*")
      .permitAll();

    http.authorizeRequests()
      .anyRequest()
      .authenticated();

Or via XML:

<http use-expressions="true">
    <intercept-url pattern="/anonymous*" access="isAnonymous()"/>
    <intercept-url pattern="/login*" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
</http>

At this point, the login page is available at:

http://localhost:8080/spring-security-login/login.html

Users are able to authenticate themselves through HTTP, however this is insecure as passwords will be sent in plain text.

3. HTTPS Server Configuration

To only deliver the login page over HTTPS your web-server must be able to serve HTTPS pages. This requires that SSL/TLS support is enabled.

Note that you can either use a valid certificate or, for testing purposes, you can generate your own.

Let’s say we’re using Tomcat and rolling our own certificate. We’ll first need to create a keystore with a self-signed certificate.

Generating the keystore can be done issuing the following command in the terminal:

keytool -genkey -alias tomcat -keyalg RSA -storepass changeit -keypass changeit -dname 'CN=tomcat'

This will create a private a key and a self-signed certificate in the default keystore for your user profile, in your home folder.

The next step is to edit conf/server.xml to make it look like this:

<Connector port="8080" protocol="HTTP/1.1"
   connectionTimeout="20000"
   redirectPort="8443" />

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
   maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
   clientAuth="false" sslProtocol="TLS"
   keystoreFile="${user.home}/.keystore" keystorePass="changeit" />

The second SSL/TLS <Connector> tag is usually commented out in the config file so uncommenting and adding keystore information is all that is needed. Further information is available in Tomcat’s related documentation.

With the HTTPS configuration in place, the login page can now be served under the following URL as well:

https://localhost:8443/spring-security-login/login.html

Web-servers other than Tomcat would require different but likely similar configuration.

4. Configuring Channel Security

At this point, we are able to serve the login page both under HTTP and HTTPS. This section explains how to mandate the usage of HTTPS.

To require HTTPS for the login page modify your security configuration by adding the following:

http.requiresChannel()
  .antMatchers("/login*").requiresSecure();

Or add the requires-channel=”https” attribute to your XML config:

<intercept-url pattern="/login*" access="permitAll" requires-channel="https"/>

After this point users could login only via HTTPS. All relative links e.g. a forward to /homepage.html will inherit the protocol of the original request and will be served under HTTPS.

When mixing HTTP and HTTPS request inside a single web app, there are additional aspects to be aware of and that require further configuration.

5. Mixing HTTP and HTTPS

From the security perspective, serving all requests under HTTPS is considered a best practice.

When using HTTPS exclusively is not an option, we can configure Spring to use HTTP by appending the following to the config:

http.requiresChannel()
  .anyRequest().requiresInsecure();

Or add requires-channel=”http” attributes to the XML:

<intercept‐url pattern="/**" access="isAuthenticated()" requires‐channel="http"/>

This instructs Spring to use HTTP for all requests that are not explicitely configured to use HTTPS, but at the same time it breaks the original login mechanism. The following sections explain the underlying cause.

5.1. A Custom Login Processing URL over HTTPS

The security configuration in the original security tutorial contains the following:

<form-login login-processing-url="/perform_login"/>

Without forcing /perform_login to use HTTPS a redirect would happen to the HTTP variant of it, losing the login information sent with the original request.

To overcome this we need to configure Spring to use HTTPS for the processing URL:

http.requiresChannel()
  .antMatchers("/login*", "/perform_login");

Notice the extra argument /perform_login passed to the antMatchers method.

The equivalent in the XML configuration requires adding a new <intercept-url> element to the config:

<intercept-url pattern="/perform_login" requires-channel="https"/>

If your own application is using the default login-processing-url (which is /login) you don’t need to configure this explicitly as the /login* pattern already covers that.

With the configuration in place, users are able to login, but are not able access authenticated pages e.g. /homepage.html under the HTTP protocol, because of Spring’s session fixation protection feature.

5.2. Disabling session-fixation-protection

Session fixation is a problem which can’t be avoided when switching between HTTP and HTTPS.

By default Spring creates a new session-id after a successful login. When a user loads the HTTPS login page the user’s session-id cookie will be marked as secure. After logging in, the context will switch to HTTP and the cookie will be lost as HTTP is insecure.

To avoid this setting session-fixation-protection to none is required.

http.sessionManagement()
  .sessionFixation()
  .none();

Or via XML:

<session-management session-fixation-protection="none"/>

Disabling session fixation protection might have security implications, therefore you need to weigh the pros and cons if you’re concerned about session fixation based attacks.

6. Test

After applying all these configuration changes accessing /anonymous.html without logging in (using either http:// or https://) will forward you to the page through HTTP.

Opening other pages directly like /homepage.html should get you forwarded to the login page via HTTPS and after login you will be forwarded back to /homepage.html using HTTP.

7. Conclusion

In this tutorial we’ve taken a look on how to configure a Spring web-application which communicates through HTTP except for the login mechanism. However new modern web-applications should almost always use HTTPS exclusively as their communication protocol. Lowering security levels or turning off security features (like session-fixation-protection) is never a good idea.

This tutorial and the one it is based on shares the same codebase which is available at GitHub. The channel security configuration can be enabled by listing https as an active Spring profile.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Java Web Weekly, Issue 124

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

At the very beginning of last year, I decided to track my reading habits and share the best stuff here, on Baeldung. Haven’t missed a review since.

Here we go…

1. Spring and Java

>> JUnit 5 – Conditions [codefx.org]

Conditions and better control over the execution of tests are solid steps forward in the JUnit ecosystem – can’t wait to get my hands on the new syntax.

>> Reducing boilerplate code with Project Lombok [codecentric.de]

A quick intro to the foundations of Lombock to get rid of some of the more verbose parts of Java.

>> java.util.Optional – Short Tutorial By Example [javaspecialists.eu]

We’ve seen many introductions to Optional since it came out. I’ve covered some in these weekly reviews over that time. This one is as good as any and it has a solid video as well – so if you’re not yet using Optional well, have a look.

>> The Top 100 Java Libraries in 2016 – After Analyzing 47,251 Dependencies [takipi.com]

A very cool breakdown and high level view of what’s going with the libraries in the Java ecosystem.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical

>> 5 Ways to NOT F**K Up Your Microservices in Production [takipi.com]

More practical and realistic writeups about working in a microservice architecture are getting published than before.

This one is simple and to the point, but it does a good job illustrating a clear fact – microservices do come with a real cost and extra complexity.

Also worth reading:

3. Musings

>> A Manager’s Guide to Legacy Code [daedtech.com]

Working with legacy code is a necessary evil – and this writeup tries to frame what that works entails for the developer tasked to do it.

>> Github and Code Review: A Quiet Revolution [daedtech.com]

Sometimes it’s important to take a step back and have a look at broad strokes of the industry. Especially if you’re heads down in that industry and most of these new workflows are second nature to you.

That’s the direction of this writeup – a step back and a look at what’s been happening.

>> The New 10-Year Vesting Schedule [zachholman.com]

Some realities that are well worth understanding before taking a job at a startup.

Also worth reading:

4. Comics

And my favorite Dilberts of the week:

>> I feel good about next year [dilbert.com]

>> All I could get is fake buy-in [dilbert.com]

>> This stain is fudge [dilbert.com]

5. Pick of the Week

Some fun with giraffes:

>> 5 mètres 80 (video) [vimeo.com]

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Intro to WebSockets with Spring

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

In this article we will create a simple web application that implements messaging using the new WebSocket capabilities introduced with Spring Framework 4.0.

WebSockets are a bi-directional, full-duplex, persistent connection between a web browser and a server. Once a WebSocket connection is established the connection stays open until the client or server decides to close this connection.

A typical use case could be when an app involves multiple users communicating with each other, like in a chat. We will build a simple chat client in our example.

2. Maven Dependencies

Since this is a Maven-based project, we first add the required dependencies to the pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

In addition, as we’ll use JSON to build the body of our messages, we need to add the Jackson dependencies. This allow Spring to convert our Java object to / from JSON:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.3</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId> 
    <version>2.7.3</version>
</dependency>

If you want to get the newest version of the libraries above, look for them on Maven Central.

3. Enable WebSocket in Spring

The first thing to do is to enable the WebSocket capabilities. To do this we need to add a configuration to our application and annotate this class with @EnableWebSocketMessageBroker. As its name suggests, it enables WebSocket message handling, backed by a message broker:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/chat").withSockJS();
    }
}

Here can we see that the method configureMessageBroker is used to configure the message broker. First, we enable an in-memory message broker to carry the messages back to the client on destinations prefixed with “/topic”.

We complete our simple configuration by designating the “/app” prefix to filter destinations targeting application annotated methods (via @MessageMapping).

The registerStompEndpoints method registers the “/chat” endpoint, enabling Spring’s STOMP support.

This endpoint, when prefixed with “/app”, is the endpoint that the ChatController.send() method is mapped to handle.

It also enables the SockJS fallback options, so that alternative messaging options may be used if WebSockets are not available. This is useful since WebSocket is not supported in all browsers yet and may be precluded by restrictive network proxies. The fallbacks let the applications use a WebSocket API, but gracefully degrade to non-WebSocket alternatives when necessary at runtime.

4. Create the Message Model

Now that we’ve set up the project and configured the WebSocket capabilities, we need to create a message to send.

The endpoint will accept messages containing the sender name and a text in a STOMP message whose body is a JSON object. The message might look like this:

{
    "from": "John",
    "text": "Hello!"
}

To model the message carrying the text,  we can create a simple Java object with from and text properties:

public class Message {

    private String from;
    private String text;

    // getters and setters
}

By default, Spring will use the Jackson library to convert our model object to and from JSON.

5. Create a Message-Handling Controller

As we’ve seen, Spring’s approach to working with STOMP messaging is to associate a controller method to the configured endpoint. This is made possible through the @MessageMapping annotation.

The association between the endpoint and the controller gives us the ability to handle the message, if needed:

@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
    String time = new SimpleDateFormat("HH:mm").format(new Date());
    return new OutputMessage(message.getFrom(), message.getText(), time);
}

For the purposes of our example, we’ll create another model object named OutputMessage to represent the output message sent to the configured destination. We populate our object with the sender and the message text taken from the incoming message and enrich it with a timestamp.

After handling our message, we send it to the appropriate destination defined with the @SendTo annotation. All subscribers to the “/topic/messages” destination will receive the message.

6. Create a Browser Client

After making our configurations in the server-side, we’ll use the sockjs-client library to build a simple HTML page that interact with our messaging system.

First of all, we need to import the sockjs and stomp Javascript client libraries. Next, we can create a connect() function to open the communication with our endpoint, a sendMessage() function to send our STOMP message and a disconnect() function to close the communication:

<html>
    <head>
        <title>Chat WebSocket</title>
        <script src="./js/sockjs-0.3.4.js"></script>
        <script src="./js/stomp.js"></script>
        <script type="text/javascript">
            var stompClient = null;
            
            function setConnected(connected) {
                document.getElementById('connect').disabled = connected;
                document.getElementById('disconnect').disabled = !connected;
                document.getElementById('conversationDiv').style.visibility 
                  = connected ? 'visible' : 'hidden';
                document.getElementById('response').innerHTML = '';
            }
            
            function connect() {
                var socket = new SockJS('/spring-mvc-java/chat');
                stompClient = Stomp.over(socket);  
                stompClient.connect({}, function(frame) {
                    setConnected(true);
                    console.log('Connected: ' + frame);
                    stompClient.subscribe('/topic/messages', function(messageOutput) {
                        showMessageOutput(JSON.parse(messageOutput.body));
                    });
                });
            }
            
            function disconnect() {
                if(stompClient != null) {
                    stompClient.disconnect();
                }
                setConnected(false);
                console.log("Disconnected");
            }
            
            function sendMessage() {
                var from = document.getElementById('from').value;
                var text = document.getElementById('text').value;
                stompClient.send("/app/chat", {}, 
                  JSON.stringify({'from':from, 'text':text}));
            }
            
            function showMessageOutput(messageOutput) {
                var response = document.getElementById('response');
                var p = document.createElement('p');
                p.style.wordWrap = 'break-word';
                p.appendChild(document.createTextNode(messageOutput.from + ": " 
                  + messageOutput.text + " (" + messageOutput.time + ")"));
                response.appendChild(p);
            }
        </script>
    </head>
    <body onload="disconnect()">
        <div>
            <div>
                <input type="text" id="from" placeholder="Choose a nickname"/>
            </div>
            <br />
            <div>
                <button id="connect" onclick="connect();">Connect</button>
                <button id="disconnect" disabled="disabled" onclick="disconnect();">
                    Disconnect
                </button>
            </div>
            <br />
            <div id="conversationDiv">
                <input type="text" id="text" placeholder="Write a message..."/>
                <button id="sendMessage" onclick="sendMessage();">Send</button>
                <p id="response"></p>
            </div>
        </div>

    </body>
</html>

7. Testing the Example

To test our example, we can open a couple of browser windows and access the chat page at:

http://localhost:8080/spring-mvc-java/resources/chat.html

Once this is done, we can join the chat by entering a nickname and hitting the connect button. If we compose and send a message we can see it in all browser sessions that have joined the chat.

Take a look at the screenshot to see an example:

screenshot

8. Conclusion

In this tutorial we have explored Spring’s WebSocket support. We have seen its server side configuration and built a simple client side counterpart with the use of sockjs and stomp Javascript libraries.

The example code can be found in the GitHub project.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Returning Image/Media Data with Spring MVC

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll illustrate how to return images and other media using the Spring MVC framework.

We will discuss several approaches, starting from directly manipulating HttpServletResponse than moving to approaches that benefit from Message ConversionContent Negotiation and Spring’s Resource abstraction. We’ll take a closer look on each of them and discuss their advantages and disadvantages.

2. Using the HttpServletResponse

The most basic approach of the image download is to directly work against a response object and mimic a pure Servlet implementation, and its demonstrated using the following snippet:

@RequestMapping(value = "/image-manual-response", method = RequestMethod.GET)
public void getImageAsByteArray(HttpServletResponse response) throws IOException {
    InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    IOUtils.copy(in, response.getOutputStream());
}

Issuing the following request will render the image in a browser:

http://localhost:8080/spring-mvc-xml/image-manual-response.jpg

The implementation is fairly straightforward and simple owing to IOUtils from the org.apache.commons.io package. However, the disadvantage of the approach is that its not robust against the potential changes. The mime type is hard-coded and the change of the conversion logic or externalizing the image location requires changes to the code.

The following section discusses a more flexible approach.

3. Using the HttpMessageConverter

The previous section discussed a basic approach that does not take advantage of the Message Conversion and Content Negotiation features of the Spring MVC Framework. To bootstrap these feature we need to:

  • Annotate the controller method with the @ResponseBody annotation
  • Register an appropriate message converter based on the return type of the controller method (ByteArrayHttpMessageConverter for example needed for correct conversion of bytes array to an image file)

3.1. Configuration

For showcasing the configuration of the converters, we will use the built-in ByteArrayHttpMessageConverter that converts a message whenever a method returns the byte[] type.

The ByteArrayHttpMessageConverter is registered by default, but the configuration is analogous for any other built-in or custom converter.

Applying the message converter bean requires registering an appropriate MessageConverter bean inside Spring MVC context and setting up media types that it should handle. You can define it via XML, using <mvc:message-converters> tag.

This tag should be defined inside <mvc:annotation-driven> tag, like in the following example:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>image/jpeg</value>
                    <value>image/png</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Aforementioned configuration part will register ByteArrayHttpMessageConverter for image/jpeg and image/png response content types. If <mvc:message-converters> tag is not present in the mvc configuration, then the default set of converters will be registered.

Also, you can register the message converter using Java configuration:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(byteArrayHttpMessageConverter());
}

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
    return arrayHttpMessageConverter;
}

private List<MediaType> getSupportedMediaTypes() {
    List<MediaType> list = new ArrayList<MediaType>();
    list.add(MediaType.IMAGE_JPEG);
    list.add(MediaType.IMAGE_PNG);
    list.add(MediaType.APPLICATION_OCTET_STREAM);
    return list;
}

3.2. Implementation

Now we can implement our method that will handle requests for media. As it was mentioned above, you need to mark your controller method with the @ResponseBody annotation and use byte[] as the returning type:

@RequestMapping(value = "/image-byte-array", method = RequestMethod.GET)
public @ResponseBody byte[] getImageAsByteArray() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
    return IOUtils.toByteArray(in);
}

To test the method, issue the following request in your browser:

http://localhost:8080/spring-mvc-xml/image-byte-array.jpg

On the advantage side, the method knows nothing about the HttpServletResponse, the conversion process is highly configurable, ranging from using the available converters to specifying a custom one. The content type of the response does not have to be hard-coded rather it will be negotiated based on the request path suffix .jpg.

The disadvantage of this approach is that you need to explicitly implement the logic for retrieving image from a data source (local file, external storage, etc.) and you don’t have a control over the headers or the status code of the response.

4. Using the ResponseEntity Class

You can return an image as byte[] wrapped in the Response Entity. Spring MVC ResponseEntity enables control not only over the body of the HTTP Response but also the header and the respose status code. Following this approach, you need to define the return type of the method as ResponseEntity<byte[]> and create returning ResponseEntity object in the method body.

@RequestMapping(value = "/image-response-entity", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageAsResponseEntity() {
    HttpHeaders headers = new HttpHeaders();
    InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
    byte[] media = IOUtils.toByteArray(in);
    headers.setCacheControl(CacheControl.noCache().getHeaderValue());
    
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK);
    return responseEntity;
}

Using the ResponseEntity allows you to configure a response code for a given request.

Explicitly setting the response code is especially useful in the face of an exceptional event e.g. if the image was not found (FileNotFoundException) or is corrupted (IOException). In these cases all that is needed is setting the response code e.g. new ResponseEntity<>(null, headers, HttpStatus.NOT_FOUND), in an adequate catch block.

In addition, if you need to set some specific headers in your response, this approach is more straightforward than setting headers by means of HttpServletResponse object that is accepted by the method as a parameter. It makes the method signature clear and focused.

5. Returning Image Using the Resource Class

Finally, you can return an image in the form of the Resource object.

The Resource interface is an interface for abstracting access to low-level resources. It is introduced in Spring as more capable replacement for the standard java.net.URL class. It allows an easy access to different types of resources (local files, remote files, classpath resources) without need to write a code that explicitly retrieve them.

To use this approach the return type of the method should be set to Resource and you need to annotate the method with the @ResponseBody annotation.

5.1. Implementation

@ResponseBody
@RequestMapping(value = "/image-resource", method = RequestMethod.GET)
public Resource getImageAsResource() {
   return new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg");
}

or, if we want more control over the response headers:

@RequestMapping(value = "/image-resource", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resource> getImageAsResource() {
    HttpHeaders headers = new HttpHeaders();
    Resource resource = 
      new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg");
    return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}

Using this approach, you treat images as resources that can be loaded using the ResourceLoader interface implementation. In such case, you abstract from the exact location of your image and ResourceLoader decides where from it is loaded.

It provides a common approach to control the location of images using the configuration, and eliminate the need for writting file loading code.

6. Conclusion

Among the aforementioned approaches, we started from the basic approach, than using the approach that benefits from message conversion feature of the framework. We also discussed how to get the set the response code and response headers without handing the response object directly.

Finally, we added flexibility from the image locations point of view, because where to retrieve an image from, is defined in the configuration that is easier to change on the fly.

The sample code following the tutorial is available at GitHub.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Spring Security – Run-As Authentication

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll illustrate how to use Run-As authentication in Spring Security with a simple scenario.

The very high level explanation about Run-As is as follows: a user can execute some piece of logic as another principal with different privileges.

2. The RunAsManager

The first thing we’ll need to do is set up our GlobalMethodSecurity and inject a RunAsManager.

This is responsible for providing the temporary Authentication object with extra privileges:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected RunAsManager runAsManager() {
        RunAsManagerImpl runAsManager = new RunAsManagerImpl();
        runAsManager.setKey("MyRunAsKey");
        return runAsManager;
    }
}

By overriding runAsManager, we’re replacing the default implementation in the base class – which simply returns a null.

Also notice the key property – the framework uses that to secure/verify temporary Authentication objects (created via this manager).

Finally – the resulting Authentication object is a RunAsUserToken.

3. Security Configuration

To authenticate our temporary Authentication object, we’ll set up a RunAsImplAuthenticationProvider:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    ...
    auth.authenticationProvider(runAsAuthenticationProvider());
}

@Bean
public AuthenticationProvider runAsAuthenticationProvider() {
    RunAsImplAuthenticationProvider authProvider = new RunAsImplAuthenticationProvider();
    authProvider.setKey("MyRunAsKey");
    return authProvider;
}

We’re of course setting this up with the same key we used in the manager – so that the provider can check that the RunAsUserToken authentication object is created using the same key.

4. The Controller With @Secured

Now – let’s see how to use Run-As Authentication replacement:

@Controller
@RequestMapping("/runas")
class RunAsController {

    @Secured({ "ROLE_USER", "RUN_AS_REPORTER" })
    @RequestMapping
    @ResponseBody
    public String tryRunAs() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return "Current User Authorities inside this RunAS method only " + 
          auth.getAuthorities().toString();
    }

}

The core thing here is the new role – RUN_AS_REPORTER. This is the trigger of the Run-As functionality – as the framework deals with it differently because of the prefix.

When a request executes through this logic, we’ll have:

 

  • The current user authorities before tryRunAs() method are [ROLE_USER]
  • The current user authorities inside tryRunAs() method are [ROLE_USER, ROLE_RUN_AS_REPORTER]
  • The temporary Authentication object replaces the existing Authentication object for the duration of the tryRunAS() method invocation only

 

5. The Service

Finally, let’s implement the actual logic – a simple service layer that’s also secured:

@Service
public class RunAsService {

    @Secured({ "ROLE_RUN_AS_REPORTER" })
    public Authentication getCurrentUser() {
        Authentication authentication = 
          SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }
}

Note that:

  • To access getCurrentUser() method, we need to ROLE_RUN_AS_REPORTER
  • So we can only call getCurrentUser() method inside our tryRunAs() controller method

6. The Front-End

Next, we will use a simple front-end to test our Run-As feature:

<html>
<body>
Current user authorities: 
    <span sec:authentication="principal.authorities">user</span>
<br/>
<span id="temp"></span>
<a href="#" onclick="tryRunAs()">Generate Report As Super User</a>
             
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function tryRunAs(){
    $.get( "/runas" , function( data ) {
         $("#temp").html(data);
    });
}
</script>
</body>
</html>

So now, when a user triggers the “Generate Report As Super User” action – they’ll obtain the temporary ROLE_RUN_AS_REPORTER authority.

7. Conclusion

In this quick tutorial, we explored a simple example using the Spring Security Run-As authentication replacement feature.

This tutorial is based on the codebase available on GitHub.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

Java Web Weekly, Issue 125

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

A bit of a quicker one this week, as I’m writing it in between Spring IO sessions.

Here we go…

1. Spring and Java

>> Thymeleaf 3 – Get Started Quickly with Thymeleaf 3 and Spring MVC [codeleak.pl]

A quick and to the point intro to using Thymeleaf with Spring, hopefully getting the industry one step closer to never touching a JSP file ever again.

>> How to Split JUnit Tests in a Continuous Integration Environment [semaphoreci.com]

A solid, thorough writeup focused on intelligently separating the way different tests run in a CI pipeline. Very useful stuff.

>> 13 Decks Java Developers Must See to Stay Updated [takipi.com]

Some very interesting slide-decks worth going over. Not only for the subject matter, but also to see what the cadence of a good talk looks like.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical

>> Cleanup Temp Files [techblog.bozho.net]

This is a quick writeup that I was thinking would make the “Also word reading” section below.

But, temporary files and applications that just keep growing and growing is such a common and overlooked problem that I think it’s really worth thinking about if you’re writing that kind of app.

Also worth reading:

3. Musings

>> Dirty Hacks Are OK [techblog.bozho.net]

I know this is not the best advice I’ve given” – that cracked me up.

But, in all seriousness, once you know the rules, yes, sometimes it’s definitely OK to break them.

>> CodeFX Leveled Up [codefx.org]

I thoroughly enjoyed reading this piece, from so many points of view.

First, it’s a clear, ambitious plan that I’m sure Nicolai is going to execute on well.

But more importantly – it represents forward movement in a space where so many people sit still for years and years – blogging. It’s quite easy to find yourself settle in a rhythm and doing the things that you’ve always been doing.

Shake things up!

>> The Gravitational Force of Wage Labor [daedtech.com]

An interesting read on the dynamics of longer term consulting engagements.

>> DDD Is Expensive Is A Myth [sapiensworks.com]

Like all the other DDs, Domain Driven Design may look like it’s more work at the beginning, but overall, the level of clarity that it brings into a system dwarfs the time it takes to understand and implement.

>> Simple Asynchronous Microservices using Lambda Architecture [vanillajava.blogspot.com]

A good first step towards understanding the Lambda architecture.

>> Lessons learned from delivering a test automation workshop [ontestautomation.com]

I’m doing more workshops this year, so I enjoyed going through this one. Have a look if you’re interested in either side of the workshop experience.

Also worth reading:

4. Comics

And my favorite Dilberts of the week:

>> I won’t bother using real words [dilbert.com]

>> OK, let’s begin wasting our time [dilbert.com]

>> Take your time. I’m good either way [dilbert.com]

5. Pick of the Week

>> Who wants to live in The Real World? [m.signalvnoise.com]

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE

XML Serialization and Deserialization with Jackson

$
0
0

1. Overview

In this article, we are going to look at how to serialize a Java object to XML data using Jackson 2.x and deserialize it back to a POJO.

We’ll focus on the basic operation that don’t require a lot of complexity or customization.

2. XmlMapper Object

XmlMapper is the main class from Jackson 2.x that helps us in serialization, so we shall need to create an instance of it:

XmlMapper mapper = new XmlMapper();

XmlMapper is available in jackson-dataformat-xml jar, so we have to add it as a dependency in our pom.xml. In this tutorial we use the version 2.7.4, but you should always check for the latest version:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.7.4</version>
</dependency>

3. Serialize Java to XML

XmlMapper is a subclass of ObjectMapper which is used in JSON serialization. However it adds some XML specific tweaks to the parent class.

We can now look at how to use it to do actual serialization. Let’s create the java class whose object to serialize:

class SimpleBean {
    private int x = 1;
    private int y = 2;
    //standard setters and getters
}

3.1. Serialize to XML String

We can serialize the Java object into an XML string:

@Test
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException {
    XmlMapper xmlMapper = new XmlMapper();
    String xml = xmlMapper.writeValueAsString(new SimpleBean());
    assertNotNull(xml);
}

Resulting XML string (formatted for readability):

<SimpleBean>
    <x>1</x>
    <y>2</y>
</SimpleBean>

3.2. Serialize to XML file

We can also serialize the Java object to an XML file for later use:

@Test
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.writeValue(new File("simple_bean.xml"), new SimpleBean());
    File file = new File("simple_bean.xml");
    assertNotNull(file);
}

The content of the resulting file simple_bean.xml :

<SimpleBean>
    <x>1</x>
    <y>2</y>
</SimpleBean>

4. Deserialize XML to Java

In this section, we shall look at how to obtain java objects from XML.

4.1. Deserialize From XML String

As with serialization, we can also deserialize an XML String back to a Java object like so:

@Test
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    SimpleBean value = 
      xmlMapper.readValue("<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
    assertTrue(value.getX() == 1 && value.getY() == 2);
}

4.2. Deserialize From XML File

Likewise, if we have an XML file, this section shows how to convert it back to a Java object.

Here we first read the file into an input stream and then convert the input stream to a string with a simple utility method.

The rest of the code is similar to that in section 4.1 above:

@Test
public void whenJavaGotFromXmlFile_thenCorrect() throws IOException {
    File file = new File("simple_bean.xml");
    XmlMapper xmlMapper = new XmlMapper();
    String xml = inputStreamToString(new FileInputStream(file));
    SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class);
    assertTrue(value.getX() == 1 && value.getY() == 2);
}

The utility method:

public static String inputStreamToString(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder();
    String line;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    return sb.toString();
}

5. Conclusion

This simple article illustrated how to serialize a simple POJO to XML and obtain a POJO from basic XML data.

The source code that accompanies this article is available on GitHub.

Viewing all 4735 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>