Having JAXB1 and JAXB2 in the same classpath

If you just add JAXB1 and JAXB2 jars into the same classpath you may end up with the following exception:

You are trying to run JAXB 2.0 runtime but you have old JAXB 1.0 
runtime earlier in the classpath.
Please remove the JAXB 1.0 runtime for 2.0 runtime to work correctly.

The ideal solution would be to migrate everything to JAXB2 and remove the JAXB1 dependencies, but if you have certain constrains around this (and there usually are a lot) like: time, legacy systems, too much effort to retest everythig, etc there is an easy solution to have the old code run smooth and in the same time write the new code using the latest version of JAXB.

Here are the steps you need to follow:

  • Download jax1-impl-XXX.jar, where XXX is something like 2.x.x (this can be found in the JAXB2 distribution)
  • Remove your old jaxb-impl.jar (version 1) from the classpath
  • Add the new jaxb1-impl-XXX.jar into the classpath

All done!

How to display images from the database in your jsp pages – the easy way

The easiest and elegant way to read images from the database and display them in the UI is through a servlet that handles the image processing for you. I’ll present below a sample that displays a user avatar in the jsp page. This sample uses Spring 3 and the tip from this article to inject a spring bean into this servlet. This example can easily be adapted to many kinds of situations. Here is the code:

The servlet

package insidecoding.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import insidecoding.service.UserService;

@Component("imageServlet")
public class ImageServlet implements HttpRequestHandler {

    @Autowired
    private UserService UserService;

    @Override
    public void handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // get the thumb from the user entity
        byte[] thumb = userService.getCurrentUserAvatar();

        String name = "userAvatar";
        response.setContentType("image/jpeg");
        response.setContentLength(thumb.length);

        response.setHeader("Content-Disposition", "inline; filename=\"" + name
                + "\"");

        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            input = new BufferedInputStream(new ByteArrayInputStream(thumb));
            output = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[8192];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (IOException e) {
            System.out.println("There are errors in reading/writing image stream "
                    + e.getMessage());
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException ignore) {
                }
            if (input != null)
                try {
                    input.close();
                } catch (IOException ignore) {
                }
        }

    }
}

Map this servlet to the /image path in web.xml

     <servlet>
        <servlet-name>imageServlet</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>imageServlet</servlet-name>
        <url-pattern>/image/*</url-pattern>
    </servlet-mapping>

Usage in JSP Continue reading

How to increase Tomcat heap size in Eclipse

If you get a lot of java.lang.OutOfMemoryErrors while running your web application on Tomcat from Eclipse, it means that you should increase the heap size of your tomcat instance. To do this, follow these steps:

1. Open the Server view and double-click on the Tomcat instance. The server configuration screen will open.

2. Click on the “Open launch configuration” link from the General Information section.

3. Click on the Arguments tab and add the following at the end of the VM arguments: -Xms128m -Xmx512m.

The values for this 2 arguments may vary, depending on your needs or available memory :)

How to inject Spring beans into Servlets

This can be achieved in 3 simple steps:

1. Implement HttpRequestHandler

First of all your servlet class must implement the org.springframework.web.HttpRequestHandlerinterface and provide an implementation for the handleRequest() method just like you would override doPost().

2. Declare the servlet as a Spring Bean

You can do this by either adding the @Component(“myServlet”) annotation to the class, or declaring a bean with a name myServlet in applicationContext.xml.

   @Component("myServlet")
   public class MyServlet implements HttpRequestHandler {
...

3. Declare in web.xml a servlet named exactly as the Spring Bean

The last step is to declare a new servlet in web.xml that will have the same name as the previously declared Spring bean, in our case myServlet. The servlet class must be org.springframework.web.context.support.HttpRequestHandlerServlet.

The Generic DAO pattern in Java with Spring 3 and JPA 2.0

One thing that annoys me the most is code duplication. The DAO layer is the perfect candidate for this kind of situation. Often, developers forget about OOP, polymorphism and design patterns and just copy&paste code, change the name of the class and voila, we have a brand “new” BankDao class. I’ll present you how to implement a generic DAO pattern to avoid code duplication and preserve type safety in the same time. Why would you care about type safety and just don’t go use the EntityManager’s generic methods. Well, for various reasons:

  1. You know for sure which entity objects can be persisted
  2. You avoid a lot of explicit casts which are error prone
  3. The code is cleaner and  very easy to follow
  4.  You actually apply OOP principles like inheritance and polymorphism. ;)

The purpose of this article is not to get you familiar with the DAO pattern, but to show you a better way of using it. You can find a complete reference about DAO here: DataAccessobject.

The Generic DAO interface

Let’s get started. First of all this article assumes you are using Spring 3 (although this can be easily adapted to Spring 2.5) and JPA 2.0 in you project and the initial configuration is in place:  you already have a data sources declared, an entity manager factory, etc.  The application is basically up&running.

The foundation of using a Generic DAO is the CRUD operations that you can perform on each entity. And this is the least you can have. Additional generic methods can be defined like: count all objects of a specific type; execute generic queries based on some parameters, etc. You’ll see a sample bellow for countAll().

The core of this pattern will be an interface called, surprisingly, GenericDao and its implementation Continue reading