Kohei Nozaki's blog 

Jersey 1.x ExceptionMapper examples


Posted on Saturday Oct 29, 2016 at 12:42PM in Technology


CAUTION: this posting is about Jersey 1.x which is obsoleted. If you use more modern JAX-RS implementation such as Jersey 2.x or above, please check if there are any better approaches.

JAX-RS (Jersey) provides a mechanism called ExceptionMapper which is an universal way to map an exception that thrown by a JAX-RS implementation itself or application code, to any HTTP response. In this posting, I’ll introduce some basic but useful usages of it that I have found.

ExceptionMapper for RuntimeException

When your resource method throw an Exception, say, an unintentional NullPointerException which caused by a bug or something, typically this produces a 500 Error page which created by your application container. You can catch, log those exceptions and produce a customer-friendly response with an ExceptionMapper which is something like following:

@Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {

    private static final Logger LOGGER = Logger.getLogger(RuntimeExceptionMapper.class.getName());

    @Override
    public Response toResponse(final RuntimeException e) {
        // taken from http://stackoverflow.com/questions/13716793/jersey-how-to-register-a-exceptionmapper-that-omits-some-subclasses
        if (e instanceof WebApplicationException) {
            return ((WebApplicationException) e).getResponse();
        }

        LOGGER.log(Level.WARNING, "RuntimeException occurred", e);

        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("Sorry, something went wrong")
                .build();
    }
}

ExceptionMapper for NotFoundException

When your app receive a request which has no corresponding resource method, typically this produces a 404 Error page created by your container as well as an uncaught Exception. You can handle this situation with an ExceptionMapper as follows:

@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {

    private static final Logger LOGGER = Logger.getLogger(NotFoundExceptionMapper.class.getName());

    @Override
    public Response toResponse(final NotFoundException e) {
        LOGGER.log(Level.FINE, "NotFoundException occurred", e);

        return Response.status(Response.Status.NOT_FOUND)
                .entity("Check the destination path of your request - we have no API here")
                .build();
    }
}

ExceptionMapper for ParamExceptionMapper

Let’s say you have a value class which is something like following:

public class EmployeeId {

    private final long value;

    public EmployeeId(final long value) {
        if (value < 1) {
            throw new IllegalArgumentException("EmployeeId must be larger than zero");
        }

        this.value = value;
    }

    public EmployeeId(final String value) {
        this(Long.parseLong(value));
    }

    // getter and toString omitted
}

And you have a resource method which receives an EmployeeId as follows:

@Path("myresource")
public class MyResource {

    @GET
    @Path("emp")
    @Produces(MediaType.TEXT_PLAIN)
    public String emp(@QueryParam("id") EmployeeId id) {
        ...
    }
}

When the resource method receives a valid id, say 123, Jersey automatically constructs an EmployeeId instance and passes it to the application code. That’s fine, but consider if a malicious user has sent an invalid value, say -1. Typically this produces an error page which created by your container as well. You may want to return a more informational response with HTTP status code 400 with an ExceptionMapper which is something like:

@Provider
public class ParamExceptionMapper implements ExceptionMapper<ParamException> {

    private static final Logger LOGGER = Logger.getLogger(ParamExceptionMapper.class.getName());

    @Override
    public Response toResponse(final ParamException e) {
        LOGGER.log(Level.FINE, "ParamException occurred", e);

        final StringBuilder sb = new StringBuilder("Your parameter '" + e.getParameterName() + "' is invalid");

        final Throwable cause = e.getCause();
        if (cause instanceof IllegalArgumentException) {
            final String message = cause.getMessage();
            if (message != null && !message.isEmpty()) {
                sb.append(": ").append(message);
            }
        }

        return Response.status(Response.Status.BAD_REQUEST)
                .entity(sb.toString())
                .build();
    }
}

Conclusion

ExceptionMapper helps making error responses of your REST APIs more helpful. And it reduces repetitive exception handling code in your resource classes that tend to be tons of boilarplate.

You can obtain complete code based on Jersey 1.x and testcases that powered by Arquillian, Embedded Tomcat and Apache HttpClient, from my GitHub repository.


JPA Builder Pattern


Posted on Sunday Oct 16, 2016 at 06:07PM in Technology


Thanks to JPA, creating an entity which has tons of fields and complex relations has become much easier than the plain old JDBC era. but there are still some difficulties with it. for example, consider that you have a database schema which is something like following diagram:

829fc6f6 cccb 44c2 816a b7f397e83309

With those entities, let’s say you have to write some code for creating an employee. this would be something like:

public class EmployeeService {

    private final EntityManager em;

    EmployeeService(final EntityManager em) {
        this.em = em;
    }

    public long create(long deptId,
                       String name,
                       boolean temporary,
                       Set<Long> projectIds,
                       Set<String> phoneNumbers) {

        // instantiating and setting attributes of employee
        final Employee employee = new Employee();
        employee.setName(name);
        employee.setTemporary(temporary);
        employee.setProjects(new HashSet<>());
        employee.setPhones(new HashSet<>());

        // making a relation between employee and dept
        final Dept dept = em.find(Dept.class, deptId);
        employee.setDept(dept);
        em.persist(employee);
        dept.getEmployees().add(employee);

        // making relations between employee and projects
        for (final Long projectId : projectIds) {
            final Project project = em.find(Project.class, projectId);
            project.getEmployees().add(employee);
            employee.getProjects().add(project);
        }

        // creating phones
        for (final String phoneNumber : phoneNumbers) {
            final Phone phone = new Phone();
            phone.setNumber(phoneNumber);
            phone.setEmployee(employee);
            em.persist(phone);
            employee.getPhones().add(phone);
        }

        em.flush(); // making sure a generated id is present

        return employee.getId();
    }
}

And you will use the method create() as follows:

final Set<Long> projectIds = new HashSet<>();
Collections.addAll(projectIds, project1Id, project2Id);
final Set<String> phoneNumbers = new HashSet<>();
Collections.addAll(phoneNumbers, "000-0000-0001", "000-0000-0002", "000-0000-0003");

final long savedEmployeeId = service.create(
        engineeringDeptId,
        "Jane Doe",
        true,
        projectIds,
        phoneNumbers);

Not so bad, but think about if there are more complex relations or attributes that may be optional. the arguments of the method will be much longer, and hard to maintain.

In such a case, a pattern which I call "JPA builder pattern" would be nice. you create a non-static nested builder class and a method which creates a builder, into the class EmployeeService, as follows:

...

public Builder builder(long deptId, String name) {
    return new Builder(deptId, name);
}

public final class Builder { // non-static
    private final long deptId;
    private final String name;
    private boolean temporary;
    private Set<Long> projectIds = new HashSet<>();
    private Set<String> phoneNumbers = new HashSet<>();

    private Builder(final long deptId, final String name) {
        this.deptId = deptId;
        this.name = name;
    }

    public Builder temporary(boolean temporary) {
        this.temporary = temporary;
        return this;
    }

    public Builder projectIds(Long... ids) {
        Collections.addAll(projectIds, ids);
        return this;
    }

    public Builder phoneNumbers(String... numbers) {
        Collections.addAll(phoneNumbers, numbers);
        return this;
    }

    public long build() {
        // In reality, passing "this" instead of actual values (deptId, name, ...) is recommended
        return EmployeeService.this.create(deptId, name, temporary, projectIds, phoneNumbers);
    }
}

And you will use the builder as follows:

final long savedEmployeeId = service.builder(engineeringDeptId, "Jane Doe")
        .temporary(true)
        .projectIds(project1Id, project2Id)
        .phoneNumbers("000-0000-0001", "000-0000-0002", "000-0000-0003")
        .build();

It doesn’t make much sense if relations or attributes that may be optional are not that many as this example, but in reality, entities likely to have those much more. in such a case, I believe this pattern makes your code much clean, readable and maintainable.

You can obtain the entire project which contains entities, the service class and executable tests that run with an embedded database, from my GitHub repo.