Fixing issue with Classloader leaks.

We had an issue with a classloader leak. There were three things we had to do before it worked.

  1. Made the mysql connector provided and add mysql-connector jar to the tomcat/libexe/lib directory
    1. Maven block:
      <scope>provided test</scope>
  2. Added the following jvm option to use G1 garbage collection, and enable class unloading and perm gen sweep.
    NOTE: You need all three for this to work. Ignore the warning from java: “Please use CMSClassUnloadingEnabled in place of CMSPermGenSweepingEnabled in the future.” I’ve tried just G1, G1 with class unload, and G1 with perm gen. They are all needed for heap to stay low and for classes to be unloaded.

    -XX:+UseG1GC -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
  3. Added the following library for classloader leak prevention.
    1. Add the following block in your pom.xml of the web module:
    2. Add the following listener to your web.xml:

Once that is all setup, do a clean package on maven, redeploy and restart tomcat

Exclude URL from EhCache Web Cache

You would think that this would be built-in, to easily exclude a URL. Maybe there is a good reason they left it out. Anyway, I recently needed to cache results from webservice hits, so that we could minimize the load on the database. I liked the idea of caching the response to really minimize the execution of code. EhCache Web Cache seemed perfect, until I had to exclude one specific service from the cache. The specs were already given to the customer and the URL could not change. So, I chose to use filters to prevent caching.

First, I created a filter and overrode the doFilter method as seen below.

public class NoCacheFilter implements javax.servlet.Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        /** do nothing **/

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest
            && response instanceof HttpServletResponse) {

            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String requestUri = httpRequest.getRequestURI();
            if(requestUri.contains("/registration/save")) {
                requestUri = requestUri.replace("/vine/", "/vine-nocache/");
                       .forward(request, response);
            } else {
                chain.doFilter(request, response);

    public void destroy() {
        /** do nothing **/

Second, I created another controller for URLs that should not be cached.

public class VineNoCacheController {

    private WebServiceTemplate vineRegisterWsTemplate;

    @RequestMapping(value = "/site/{siteId}/agency/{agencyId}/offender/{subjectId}
                    produces = "application/json")
    public void registerVictim(@PathVariable Integer siteId,
                               @PathVariable Integer agencyId,
                               @PathVariable String subjectId,
                               @RequestParam(required = false) Boolean enableTTY,
                               @RequestParam(required = false) String pin,
                               @RequestParam EnumLanguage language,
                               @RequestParam String uniqueDeviceId,
                               HttpServletResponse response) throws IOException {

// code omitted to save space

Third, I configured the filter in the web.xml. The filters execute in order. So, by putting the no cache filter first, it will execute that doFilter method and if the URI contains the “registration/save”, then forward the request to vine-nocache. If it does not contain that String, then continue down the filter chain(which the next filter is the web cache filter). By using a forward, the end user never knows that it is a different URL.


If there is a better way, please share. But, this is the best way I found in a short period of time.

Editing list using spring JSP input form tag

I recently had to allow the user to edit a list of Strings and was concerned with having to keep track of which Strings were being edited. Spring has made this simple and very clean.

On, there is a

List<String> ipList;

Within the JSP you add a forEach with an input tag as follows:

<c:forEach var="ip" items="${form.ipList}" varStatus="status">
   <div style="clear: both">
      <form:input path="ipList[${status.index}]"/>

Spring Data Repository for MongoDB

First, I have to mention that I am highly impressed with almost everything I find in Spring. So I should not have been so surprised about how amazing Spring Data is and it’s integration with Mongo. Now to the interesting stuff.

I have multiple databases with multiple collections all on the same mongo server. I could not find an example anywhere that accomplished this. Here is how I did it:

To begin, you have to add one dependency. I use maven, so here is the maven dependency:


Now, you need to configure your mongo connection like usual. I like to just put it in the application-context.xml:

<mongo:mongo id="mongoConnection" host="my.mongo.server" port="12345" write-concern="1"/>

One thing to mention here is write-concern. It defaults to 0 which is basically fire and forget, and it will not return an error if one is thrown. Here is the API page with the available values:

Next, configure a template for each database.

    <bean id="imageTemplate" class="">
        <constructor-arg ref="mongoConnection"/>
        <constructor-arg name="databaseName" value="imagedatabase"/>

    <bean id="vehicleTemplate" class="">
        <constructor-arg ref="mongoConnection"/>
        <constructor-arg name="databaseName" value="vehicledatabase"/>

Now, you need to tell Spring where your repositories are so it can inject them. They must all be in the same directory. I tried to have them in different sub-directories, and it did not work correctly. So they are all in the repository directory.

    <mongo:repositories base-package="my.package.repository">
        <mongo:repository id="imageRepository" mongo-template-ref="imageTemplate"/>
        <mongo:repository id="carRepository" mongo-template-ref="vehicleTemplate"/>
        <mongo:repository id="truckRepository" mongo-template-ref="vehicleTemplate"/>

Each repository is an Interface and is written as follows (yes, you can leave them blank):

public interface ImageRepository extends MongoRepository<Image, String> {
public interface TruckRepository extends MongoRepository<Truck, String> {

NOTE: If you have a custom query, here is some crazy magic for you. Just add a method to the interface, spring knows how to interpret it! Here is an example:

public interface CarRepository extends MongoRepository<Car, String> {
    Car findByModelAndYearAndLicensePlate(String model, String year, String licensePlate);

Here is a table with the expected keywords from the Spring documentation:

Keyword Sample Logical Result
GreaterThan findByAgeGreaterThan(int age) {“age” : {“$gt” : age}}
LessThan findByAgeLessThan(int age) {“age” : {“$lt” : age}}
Between findByAgeBetween(int from, int to) {“age” : {“$gt” : from, “$lt” : to}}
IsNotNull, NotNull findByFirstnameNotNull() {“age” : {“$ne” : null}}
IsNull, Null findByFirstnameNull() {“age” : null}
Like findByFirstnameLike(String name) {“age” : age} ( age as regex)
(No keyword) findByFirstname(String name) {“age” : name}
Not findByFirstnameNot(String name) {“age” : {“$ne” : name}}

Here is one of the java objects:

public class Image {

    private String id;

    private Date createTime;
    private Date updateTime;

    @Field(value = "fName")
    private String fileName;
    private byte[] imageData;

    //Getters and setters

    public String toString() {
        return ToStringBuilder.reflectionToString(this);

You do not have to annotate the POJOs with @Document, but it helps with efficiency because it allows the classpath scanner to find and pre-process your domain objects to extract the necessary metadata. Visit this blog for more details:

The @Id annotation will tell spring to make that property an ObjectId and give it the _id name which is a Mongo standard. So you can make it whatever type and name you want in java, but it will convert it back and forth between java and mongo.

The @Field annotation is used if you want to save the name differently in mongo

Now, here is one of the really cool things about Spring Data Mongo. The name of the POJO is the collection! will be saved to the image collection within the imagedb database.

Here is how you can find, insert, and delete records:

public class ImageService {

    private ImageRepository imageRepository;

    public Image findById(String id) {
        return imageRepository.findOne(id);

    public List getList() {
        return imageRepository.findAll();

    public Image insert(Image image) {
        //Make sure id is null, so mongo will generate an id, if it is not null, then mongo will use whatever you set it to, even an empty string

    public Image update(Image image) {
        image.setUpdateTime(new Date());

    public void delete(String id) {

That is all you need. Finally, we do not have to write basic data access code. I love it when code is smart!