Head first ES6 with React, Browserify and Babel

Recently I hopped over to the React blog and in their latest article, they announced they were deprecating react-tools.  This had been a great tool for me, making use of it via gulp-react which has served me well to transform my JSX into plain JS.  In React’s post though, they mentioned about migrating to Babel which supports converting JSX to vanilla JS.  Babel’s website has some documentation on using Babel with various build systems.  In my case, I was using Gulp with Browserify.  For a complete working example head on over to Github.  This sample runs a Spark web application with embedded Jetty server.

React ES6 Modules

Traditionally, I would write modules in the following way and then use gulp-react to transform the JSX into plain JS.  Then pass the result through Browserify to bundle up all of my components and scripts.

var React = require('react');

var HelloWorld = React.createClass({
  render: function() {
    return <h1>Hello World!</h1>;
  }
});

module.exports = HelloWorld;

Moving to ES6 module syntax and using Babel, there’s no longer a need for gulp-react.  This is the same module written in ES6.  The Babel team has written the Babelify transformer for Browserify, so in a single task, this code is transformed to plain JS and bundled up with all my other scripts.  You’ll need to keep in mind that React only supports ES6 classes as of version 0.13 which was recently released.

import React from 'react';

export default class HelloWorld extends React.Component {
  render() {
    return <h1>Hello World!</h1>;
  }
}

Continue reading “Head first ES6 with React, Browserify and Babel”

Creating ReactJS mixin factories

If you do anything with ReactJS, chances are you’ve come across mixins in some form or another.  In a ReactJS app, mixins provide a way to compose your components out of building blocks, allowing you to reuse common logic.  The ReactJS documentation defines this as cross-cutting concerns.

Recently I started using RefluxJS, which provides mixins in the form of factories.  Why do you need a mixin factory?  Well that depends on your use case.  The benefit of using a mixin factory is that it allows you to pass information to the factory which constructs a mixin based on that information.    This way the mixin remains generic enough to be used in other ReactJS components while maintaining some flexibility as to what you can do with it.  Here’s an example of using RefluxJS mixin factories:

mixins: [Reflux.connect(MyStore, 'stateProp')]

The Reflux.connect method is a factory method that accepts a RefluxJS store as the first parameter, and accepts an optional second parameter for the state property name to bind data to.  If the second parameter is left out, the data returned from the store gets bound to the entire state of the component.  RefluxJS also has a “listenTo” factory method which allows you to specify a callback function to call instead of simply updating the state of the component.
Continue reading “Creating ReactJS mixin factories”

Evolving apps from AngularJS to ReactJS

In a previous post, I talked about adding ReactJS to an existing AngularJS app using directives.  Over the course of my app development since then, I’ve replaced the need for directives with ReactJS entirely, but I still used AngularJS for it’s routing capabilities, built in ajax support using $http and for it’s dependency injection.  This post is about how my use of ReactJS has paved the way to removing AngularJS entirely.  My main motivation behind this was that working with ReactJS is just a lot of fun.  It’s the way I felt when I first started learning Angular.  Moving on…

Framework reliance

It should come as no surprise that extracting AngularJS out of an existing app can be a fairly involved feat, especially if the app is written in such a way that it relies heavily on the framework.  Things I had to worry about the most were routing and dependency injection.  You cannot simply rip out these framework features without having a good alternative.

While starting to use ReactJS in my Angular app, my alternative to ngRoute was react-router.  However, simply rebuilding my simple routes with react-router wasn’t going to suffice.  When building an Angular app, chances are you’re going to use it’s built in module system.  So removing ngRoute in favour of react-router wasn’t going to be as easy as I first thought.  React-router has it’s own way of doing things:

var routes = (
  <Route path="/" handler={App}>
    <DefaultRoute name="dashboard" handler={Dashboard}/>
    <Route name="logout" handler={Logout}/>
  </Route>
);

Router.run(routes, function(Handler) {
  React.render(<Handler/>, document.getElementById('app'));
});

In this snippet, the call to Router.run is what bootstraps the application.  Compare this to how ngRoute is setup, and you’ll see how we quickly lose Angular’s module system and inherent dependency injection.  It’s possible there is a way to get this working with ngRoute, but this post isn’t about making Angular and React play nice, it’s about embracing ReactJS :)

But wait, I still want my app to be modular!

Yes, at this stage, I still want my app to be modular, but I’ve been relying on Angular’s module system for so long.  I need to find alternative means.  This point proved to be slightly more involved than replacing ngRoute because it pulled me right down into my build system, Grunt.  Up until now, I hadn’t invested a whole lot of time into learning how all the tasks in my Grunt build worked, I was more focused on building features into my apps.  I had basically been using Yeoman and built my apps using the AngularJS generator.  So the result was a pre-baked Gruntfile.js build script.

At this stage in my development career, I had read a lot of buzz about other build tools and libraries out there, so I decided if I’m going to learn something, might as well try something new.  This is where I started looking a bit closer at Browserify for modularization and Gulp for building my app.  I had read about them on multiple occasions and just told myself I would find the time to learn them one day.  Unfortunately, as most things go, this wouldn’t happen until I really needed them.

At first the idea of replacing my existing Grunt build with Gulp and introducing Browserify seemed a little daunting and I was working on 2 apps at the time.  One for my day job and one for a personal client.  Between day and night, I was flipping back and forth between the two apps and some things that worked in one Gulp build, didn’t necessarily work in the other, and I’m still trying to figure out why.  Mostly, I’m having issues with gulp-usemin not liking it when I want to update more than 1 HTML file.  Over the course of about a week, I managed to write my own gulpfile.js which produced pretty much the same result as my Grunt build, but now also using Browserify to bundle up all of my modules.  This also meant I had to learn how to write my modules differently since I was no longer relying on Angular’s dependency injection.  Browserify expects your modules to be written in CommonJS style.

Conclusion

I didn’t devote an entire section of this post to how I replaced Angular’s ajax support with $http.  Quite simply, I reverted back to using simple old jQuery.  I was initially going to try to find some cool new library that did the same thing, but since some of the NPM modules I was already depending on were depending on jQuery, I figured I might as well just use it.

Moving forward, I’ve been reading up on Flux and seeing how it might benefit my ReactJS apps.  I’ve started using it in one of the apps I’m working on where I have views that need to know about the currently logged in user.  So I’ve created a CurrentUserStore and a CurrentUser mixin.

The mixin ensures that any component that needs to know about the current user, always has the current user information on it’s state.  This allows me to render the view based on the user’s authorities.  The mixin is also responsible for fetching the user’s information from the server if the CurrentUserStore indicates that it doesn’t have the user’s information populated, using a simple boolean.  The result is if the user refreshes the page, the CurrentUserStore is always re-populated, but if the user is merely clicking around through the app, we’re not re-fetching the user’s information every time.

All that being said, I’m really impressed with ReactJS so far.  Using react-router has changed how I write apps from the ground up, and the introduction of Flux gives me a nice way of communicating data throughout my app.

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 “Adding ReactJS to an existing AngularJS app with Grunt workflow”

How to build a Spring Boot application using IntelliJ IDEA

Update 2015-08-26: This tutorial has been updated with the latest version of IntelliJ 15 EAP at the time of writing and describes building an app with IntelliJ’s built in support for Spring Initializr.

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.

IntelliJ IDEA New Project

Continue reading “How to build a Spring Boot application using IntelliJ IDEA”

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 “Pagination with Spring Data and HATEOAS in an AngularJS app”