Rough Book

random musings of just another computer nerd

Category: Web

Heroku template for Spring 4 app with Oracle Java 8 and Tomcat 7.0.54

I’ve been playing around with Heroku at work for the past week or two. Heroku is pretty awesome if you want to get an app up and running quickly. Heroku does support Java and they have a few Java templates. Their current offering for Java uses Spring 3 and Tomcat 7.0.54 with Java 7. However, the version of Spring is somewhat older and they also use OpenJDK’s Java instead of Oracle’s Java. I wanted to try out Java 8 and also use a newer version of Spring so I upgraded the existing template to support both of those (I used a forked version of a custom buildpack for Java 8). I also had to update Heroku’s Web Runner to use Tomcat 7.0.54 (I have a pull-request waiting but I’m not sure if/when it will get approved so I have an artifact on GitHub that Maven can pull).

You can check out the template here.

Comments were broken for a while

Commenting on this blog was disabled for a while… I think it was due to Akismet misbehaving or something. I’m not sure. Either way, you should be able to comment now. I will be slowly adding anti-spam stuff back in.

Setting the content type to text/plain for a JSON response from a Spring controller

I was using a jQuery plugin called a ajaxfileupload to upload a file through AJAX. Technically what the plugin does isn’t AJAX. It creates a hidden form and an iframe, and then submits the form using the iframe as the target. The iframe will then end up with the response from the server. This response is then read-in by the plugin and handled appropriately. In my case I was using a controller action that would return JSON (using the .action extension). The action uses Spring’s MappingJacksonJSONView that returns JSON with a content type of application/json (as it should). This works perfectly in Chrome, however in both Firefox and IE, the user is presented with a dialog box that asks them to download the JSON response. This is obviously not what I wanted. The reason this is happening is because the response is being directly submitted to the iframe (and therefore, the page). That is, it’s not coming through via the XMLHttpRequest object. So IE and FF don’t know what to do with it and assume that it is something the user would want to download. The solution to this problem is to set the content-type to text/plain. This wasn’t as straightforward as I thought it would be.

Initially I was going to call the render(…) method of MappingJacksonJsonView but that didn’t work because the content-type had already been set to application/json. The solution I came up with was to duplicate some of the code (ugh) inside MappingJacksonJsonView to get the JSON as a string and to then write that to the response:


@RequestMapping
public void processFileUpload(HttpServletResponse response, Model model, ...) {

    ...

    //Set the content-type and charset of the response
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    //I need to use another OutputStream here; I cannot use the response's OutputStream because that will cause errors
    //later on when the JSP needs to render its content (recall that getOutputStream() can only be called exactly once
    //on a response). Therefore I'm writing the data to a ByteArrayOutputStream and then writing the byte array from
    //the ByteArrayOutputStream to the response manually.

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectMapper objectMapper = new ObjectMapper();
    JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(byteArrayOutputStream, JsonEncoding.UTF8);

    //Before I can convert the data into JSON, I will need to filter some attributes out of the model (namely BindingResult)
    Map<String, Object> result = new HashMap<String, Object>();

    for(Map.Entry<String, Object> entry : model.asMap().entrySet()) {
        if(!(entry.getValue() instanceof BindingResult)) {
            result.put(entry.getKey(), entry.getValue());
        }
    }

    objectMapper.writeValue(generator, result);
    response.getWriter().write(new String(byteArrayOutputStream.toByteArray(), "UTF8"));
}

This still seems a little hacky to me. A possible improvement is to annotate the action with @ResponseBody and return the JSON as a string without involving the response at all. If anyone has a better solution, I’m all ears!

Popularity Contest WordPress plugin breaks RSS feed

I’m using a somewhat old plugin (it hasn’t been updated since ’09) called Popularity Contest to show the popularity of my posts. However, I noticed that it was breaking my RSS feed. This is due to the fact that the plugin doesn’t properly escape the ampersand character inside an image URL. Instead of &#38; it uses just &. You can fix this by changind line number 2272 to:

$str .= '<img src="'.site_url('?ak_action=api_record_view&#38;id='.$post->ID.'&#38;type=feed').'" alt="" />';

Implementing JSONP in Spring MVC 3.0.x

In Spring 3, it’s very easy to get a view to return JSON. However, there is no built-in mechanism to return JSONP. I was able to find a pretty good tutorial That uses Spring’s DelegatingFilterProxy. I implemented this solution and I got it to work, but I didn’t like the fact that I had to create a separate filter and a bunch of other classes just for that. I also wanted to use a specific extension (.jsonp) for JSONP just to make it more explicit. Spring uses MappingJacksonJsonView to return JSON. I figured that I could extend this view and have it return JSONP instead of JSON.
Read the rest of this entry »

Integrating Regula with Spring 3.0.x MVC

A little less than a year ago, I released Regula, an annotation-based form-validation written in Javascript. The source and documentation are available on GitHub. I started working on the integration on and off throughout most of last year. At the end of the year, I had a pretty good integration going, where you could annotate fields with Hibernate Validator annotations, and the corresponding Regula validation-code would be generated on the client side. Of course, I wasn’t done yet because what I had was simply a demo project and I had to figure out a good way to distribute the whole thing; I was able to finish up the packaging and distribution today. With minimal setup, you should be able to get started with Regula and Spring. You don’t need to go through this post to figure out how to use the integration. This post is mostly about how I accomplished the integration (I don’t go into all the details; just the important bits). As far as actually using it, I will make a blog post about it later.

The source for the integration is also hosted on GitHub. My approach towards translating validation constraints from the server-side to the client-side was two-fold: gather validation constraints from the object and represent it in a canonical form. Using the canonical form, generate Javascript code that uses Regula for validation. To do this, I created a service that examines a domain object and gathers all information regarding its properties and validation constraints. The service returns this information in a canonical form, that I then inserted into the model. On the client-side, I had a tag that used the canonical form and outputted Javascript that uses the Regula framework. Initially, I was calling the service explicitly from an action in the controller. Later, in an effort to make the integration less-invasive and more seamless, I used an aspect-oriented approach with interceptors. In fact, that’s where I’d like to start.
Read the rest of this entry »

Packaging and distributing taglibs in a JAR

This is more of a “note to self” than a “how to”.

If you’re trying to distribute tag files in a JAR, you need to put them under /META-INF/tags. You then need to create a TLD file that you also put under /META-INF/tags. If you have tags or functions that you created in Java, and want to distribute them alongside the tag files, you need to reference them in the TLD and package them in the same JAR (goes without saying).

If you want to do the same thing in maven, the location for the tag files and the tld file is different; you need to put them in src/main/resources/META-INF/tags. Then you can run mvn package and maven will create a JAR with your tags.
Read the rest of this entry »

Regula: An annotation-based form-validator written in Javascript

Regula is an annotation-based form-validation framework written in Javascript. There already exist a few frameworks that address form-validation in Javascript, but I have found them to be somewhat lacking. I have thought about writing one of my own for some time, but I honestly had no idea what form it would or should take. I knew that I wanted to make one that was easy to use, flexible, and easily extensible (custom validation rules). I finally got an idea as to the form my framework should take, when I was looking at Hibernate bean-validation. I like the fact that you can set constraints by using annotations like @NotNull or @NotEmpty. That way, when you look at the bean, you are immediately aware of the constraints attached to it. I wanted to do something similar in HTML.
Read the rest of this entry »

Akismet flagging everything as spam

If you’ve been commenting on posts and now seeing anything, it’s because Akismet as been flagging all comments as spam. I don’t know why. I think it started after I upgraded WordPress. I’ve turned it off for now. Oh well.

JSTL, instanceof, and hasProperty

I’ve been doing a little bit of JSTL over the past week, especially custom tags. I’ve written custom tags in Grails before, and there you use actual Groovy code. I guess this was how custom tags used to be written (in Java), but now you can can build your own custom tags using the standard tag library. The standard tag library is still pretty useful when it comes to building custom tags. Since it’s not straight Java, it forces you think really hard about your logic. You don’t want to put any business or application logic in your tag, and you want to restrict everything to view or presentation logic. A side effect of it not being Java is that if you want to do anything extremely complicated, you’re probably better off writing the tag in Java (making sure that you don’t let any business logic creep in).

While writing my own custom tag, I noticed that although instanceof is a reserved word in the JSTL EL (expression language), it is not supported as an operator. The reason I wanted to use the instanceof operator is that I have an attribute that could either be a List or a Map and depending on the type, I wanted to do different things.

Another thing I was trying to do, was to inspect the incoming object to see if it had a certain property (reflection). JSTL uses reflection so that you can access the properties of an object via dot notation, if they follow the JavaBean naming-convention. However, there was no way for me to see if an object had a certain property. To solve both these problems, I wrote my own JSTL functions.
Read the rest of this entry »

All original content on these pages is fingerprinted and certified by Digiprove
%d bloggers like this: