Adding ReactJS to an existing AngularJS app with Grunt workflow

Recently I’ve been seeing a lot of chatter around ReactJS.  Following some research, I’ve boiled it down to this; ReactJS is a library for building reusable components in your web application while leveraging a high performance Virtual DOM diff implementation in order to patch the actual DOM tree upon changes to the underlying state.  This means that when changes to the state do occur, we’re not recreating the entire DOM tree, we’re merely applying changes determined by the virtual DOM.

After reading an article by Todd Motto on Binpress about speeding up AngularJS apps, I started paying closer attention to all those data bindings and uses of ng-repeat, ng-show, etc.  The basic principal in Todd’s article being that any time the model or state of your application changes, Angular runs it’s digest cycle over all the data bindings in your application.  The more data bindings you have, the longer this digest cycle takes.  So if we can reduce or eliminate certain data bindings, then our app should perform better.  This is where React can help.

You could write apps entirely with React from scratch and leave out Angular, but I like what Angular has to offer and since the large majority of the apps I work on are built with Angular, it wasn’t feasible to start from scratch.  I came across an article by Thierry Nicola which talks about speeding up Angular rendering by using React.  The article is pretty straight forward, so I attempted to do it in an existing Angular app I was working on.  This post will attempt to highlight the steps I took before getting things to work.

Install ReactJS into my app

I’m using Bower, so installing React is as simple as the following command.

bower install --save react

Continue reading

How to build a Spring Boot application using IntelliJ IDEA

Welcome back!  This tutorial will be a basic introduction to creating a Spring Boot application using IntelliJ IDEA.  No prior knowledge is expected, the main purpose of this post is to help anyone new to Spring get rolling quickly writing Spring applications with Spring Boot in IntelliJ.  For further reading, be sure to check out Spring’s Guide section on http://spring.io/guides for other tutorials on writing Spring Boot applications.

Create your new project with IntelliJ

Open up IntelliJ and click on the Create New Project option.

Screen Shot 2014-08-14 at 7.28.53 PM

Continue reading

Bootiful Spring apps with Supervisor

Like many other developers, most of the apps I’ve developed ended up running in Tomcat.  This worked out fine for a while, but one of my biggest pain points was with deployment, or redeployment of an updated app.  For some reason, at some point or another, I would run into deployment issues.  These issues ranged from Tomcat not exploding my WAR file when auto deployment was enabled, or the app not wanting to start, or even OutOfMemory errors during deployment.  Often times, restarting Tomcat or even the server was the only solution.  If you have a very small set of apps and a very small set of users accessing those apps, that might seem fine, but as time goes on and you add more apps and more users, restarting Tomcat or the server is no longer feasible.

I had been looking into Spring Boot for a little while and finally decided it was time to migrate an app.  This was a simple app which had some @Scheduled and @Async tasks.  This wasn’t even an app that users would access, but rather it was a stand alone app that read data from a database, created CSV files and FTP’d them.  So it was a simple candidate.  I won’t go into details about migrating the app, I’ll just say in the end I had a much shorter POM.  I used the Spring Boot starter web, jetty, test and actuator dependencies.  I didn’t end up using the Spring Data JPA starter because I prefer EclipseLink to Hibernate.

Running your Spring Boot app in production

Now that I had a functional Spring Boot app (no pun intended), it was time to get it running in production.  I knew immediately that I couldn’t simply execute my JAR and be done with it.  What happens if the process crashes?  What happens if the server is rebooted?  I want my app to keep running.  So I Googled for some solutions and found this Github issue on Spring Boot which lead me to Supervisor.  Supervisor is a simple process control system.  Installation was as simple as easy_install supervisor on my linux server. The documentation on Supervisor’s website is very good, so I recommend you read it if you’re having any trouble.

Once I had Supervisor up and running, I modified the configuration file supervisord.conf which I put in /etc.  Mainly, I changed the last line to include external configuration files for any app I would want to run with Supervisor.

My app configuration file is located at supervisor/conf.d/myapp.conf, relative to the directory where supervisord.conf is located.

These files are simple key=value configuration files.  This configuration file tells Supervisor to run the command listed at the “command” key.  The “autostart” and “autorestart” keys ensure the app starts and restarts automatically.  The “startsecs” says that the app must run for at least 10 seconds to be considered a successful start, otherwise retry the number of times denoted by “startretries”.  The final keys setup logging output.

With that file saved, issuing supervisorctl reload from the command line will force Supervisor to read in that configuration file and know about my app.  It should attempt to start it up automatically.  If everything was successful, then issuing supervisorctl without any arguments, or supervisorctl status will list the apps running along with their status, PID and uptime.  A status of RUNNING means it’s running successfully.  While testing this out, I saw another status of BACKOFF because the value of my command key in the configuration file wasn’t correct.

And that’s pretty much it for getting a Spring Boot app running in production.

Final thoughts

At this point, if this app were a web application that users would access, I would setup a server to act as a reverse proxy to my apps.  I’ve had good experience setting up Nginx in this manner.  You can have multiple instances of your Spring Boot app running and Nginx can load balance between each instance.

I hope this post helps you out :)

Pagination with Spring Data and HATEOAS in an AngularJS app

Most of us have seen pagination used in one form or another for presenting a collection of data to a user that gives them the ability to page through the data.  This is most useful when you’re dealing with large datasets that you don’t want to display all at once on a single page. With Spring Data, a lot of the heavy lifting is done for you and presented in a nice simple interface.  Spring Data comes with the PagingAndSortingRepository interface with extra methods for pagination and also sorting.  If like me you’re using Spring Data JPA, the JpaRepository already extends the PagingAndSortingRepository, so you already have the added benefits.

Getting to know Spring Data’s pagination support

Here is a simple Widget repository with a custom finder that returns a paged result.

As you can see, it’s pretty simple.  Our finder accepts a Pageable argument and returns a Page of Widget entities.  To make this useful from a web application, Spring Data comes with some nice out of the box functionality, using the @EnableSpringDataWebSupport annotation.  Add this annotation to your configuration class and it will add some paging and sorting functionality to your web application that we’ll get into next. Now that we have our repository, we’ll create a controller.

Continue reading

jQuery Simple Forms

GitHub repo: https://github.com/pgrimard/simple-forms

I just published a set of handy jQuery plugins for working with forms!

It includes the following:

  • Function to serialize a form to JSON.
    This is useful if you’re submitting a form via AJAX and need to serialize your form to JSON.  The form serialization will also look for data-default-value attributes on your named form elements and use that value if the input is left blank.  The default value is also verified to see if it’s numeric, in which case the resulting JSON property will be numeric.
  • Function to add new option to an HTML select.
    Adds a button next to your select that when clicked, replaces your select with a text input of the same name, ID and classes.
  • Enable/Disable buttons.
    Simple functions for enabling/disabling buttons.

Spring Security CSRF Protection in a Backbone single page app

Be advised this post has been revised since it’s original writing.  Rob Winch, Spring Security project lead suggested a simpler method of doing what I needed and indeed, it is simpler.

Happy New Year!!  What better way to kick off this new year than to write a new post?  Let’s get to it.  This post will not try to show you best practices for protecting against CSRF (cross-site request forgery).  Instead, I hope to start a discussion on what would be the best way to achieve CSRF protection in a Backbone app using the new Spring Security 3.2.0 release, so that I may better understand it myself.  The source code for this experiment is available at the bottom of this post.

What does Spring Security CSRF protection assume?

In version 3.2.0, CSRF is enabled by default when using Spring Security.  Since I’m building a Backbone app which will be accessed from a browser, I want the added protection.  While reading the documentation, I quickly realized that the way the implementation has been done, the CSRF token needed on your page is stored in a session attribute on the HttpSession.  On the backend, the CSRF token is created using a HttpSessionCsrfTokenRepository.

The token is created automatically when you request the page being protected.  This doesn’t pose any problems if you’re building your app with JSP for example.  If you’re using Spring MVC’s JSP tag libs, or something like Thymeleaf (which I loved using before discovering Backbone) then the CSRF token is available for you as a page attribute when the page is rendered on the server and can be inserted in a form for example or in a meta tag for later use in an AJAX request.  In a Backbone app however, where the  page is rendered primarily in the browser, you need another means to get that CSRF token when you first load the page because we don’t get access to page attributes like we do in JSP.

How about a servlet filter?

One thought I had to retrieve the CSRF token at page load was to create a servlet filter.  This allows me to retrieve the CSRF token from the request and add information about it as response headers.

Continue reading

Cross-Origin Resource Sharing (CORS) requests with Spring MVC

Welcome back!  :)  This will be a brief post to show you how to setup CORS in your Spring MVC application.  The objective here is to keep the code out of my @RequestMapping request handlers so that it can be easily used across the application.

The CORS Filter

The first thing we need is a CORS filter.  When you make an AJAX request from your domain to another domain, the first thing that will happen is an OPTIONS request will be made to the URI in question to determine what requirements are needed to complete this request.  This request is where we need to verify that the origin is actually allowed to make that request and send back a response to the browser permitting it to proceed.  We will retrieve the “Origin” header from the servlet request and verify that it’s one of the origins permitted to to make CORS requests to the application.  Assuming the origin is permitted, we’ll add a “Access-Control-Allow-Origin” header to the servlet response which will contain the value of the incoming “Origin” header.  Let’s extend Spring’s OncePerRequestFilter, verify the origin, then adjust the response headers.

Continue reading