Why directives make AngularJS so pretty cool

Within the last days we (me and another developer) implemented some kind of “generic business entity creation application”. Kind of weird name of course. What it should do, is to provide a web application which allows us to create instances of any business objects (aka Entity) for a business application we´re working on. Of course that kind of problem is already solved if you e.g. go for Grails. But in particular I had that idea to implement it with AngularJS as this framework seems so full of features for client development that it is worth taking a deeper look at it.

It turns out that this is one very complex task to implement with Angular. Why and how we solved it will be described somewhere else but we had some very impressive findings why Angulars architecture makes it is so cool.


First of all: It comes with all features you need to build a full blown client side application. This is a kind of generic sentence, right? But it´s true, you got everything you need.

  • Databinding for simple fields and sets of data
  • Statebinding for html controls
  • Validation support for html forms
  • Built-in support for invoking server-side operations asynchronously
  • An event system to sent messages within your application
  • Dependency injection and custom client side services
  • A programming model for extending Angular for your own MV* components

One could say that also other client side frameworks and toolkits do that. Really? Which ones?

Of course I´m a Java programmer so I´m into client toolkits running on the JVM, e.g. Swing or SWT and none of them has such fatures. It´s the opposite of that: They miss all of those features. E.g Swing: There is no concept for binding (Java) beans holding you business data to widgets. Or something that makes a control visible depending on the state of you business data.

Angular comes with it. You don´t have to take care about implementing any observer patterns for synchronizing model and view as Angular already does, you only have to write down those curly braces and assign values to those variables in your application scope. Or invoking some operations asynchronously. In Swing you have to extend the SwingWorker type and deal with thread synchronization for pushing UI updates back on Swings event dispatcher thread. In Angular you write on line of javascript for that.

The first answer I got while praising Angular was that there are so many fancy server side frameworks like Apache Wicket or at least JSF. Yes, of course. But you always need that server side which creates HTML being displayed. And it´s getting worse once you want to do that what is called “AJAX”, namely extending your page for some dynamic content in Javascript. Because what you do is to spread clients functionality over server and client side code which normally leads to two kinds of programming models: Traditional request/response operations submitting form data and asynchronous operations with Javascript.

For me this is a waste resources cause you got a very powerful runtime environment for rich client applications on your machine that solves so many problems we have with such client runtime environments: Your browser!

But the most mind blowing thing in Angular are directives as they enable something everyone seeks for when building software components:

Reusage with directives

This is the most powerful part of Angular. In once sentence: You can extend HTML for custom tags and attributes adding the functionality you need. From a business application developer point of view this is essential. Our business analysts come up with some kind of component based approach when describing UIs (and I will not raise the question why BAs deal with UIs. Of course they shouldn´t but the truth is: They do!) saying “I have a drop down box here and it should display something on the left, once I choose something from that list”.

You can start to explain them that there is no such thing as a “drop down box”. You can have drop down buttons or combo boxes. But nothing like a drop down box. Or you don´t tell them but developers that they have to create two components – one combo box and another label for describing the thing which is selected from that combo box. Or you simply enhance your componentset for this “drop down box”. BA´s will understand that as they come up with it, developers will understand it, as they read about these components in specifications written by BAs.

To get an idea of it, take a look at this fiddle. Of course it does not explain how to implement a directive in general but it shows how easy it is to hide such a functionality behind a self defined HTML tag like

<div ng-controller="DropDemoController" class="container-fluid">
    <drop-down items="dropDownItems" />

Isn´t that nice? This custom tag encapsulates the logic of selecting something from a combo box and displays additional information in a label on the right. What you got is a fully reusable component. (You can also clone the example from GitHub here which can be run by Grunt.)

What´s left?

A lot of. There is much much more what makes Angular so fancy. E.g.

  • animations which I haven´t worked with yet.
  • The surrounding built-system based on grunt and npm which guarantees a very short code-change-build cycle.
  • The general idea of having a rich client running in your browser accessing server side operations by tiny, self describing REST services.

And so on and so on. Many room for more about Angular.

Spring data for Neo4j and the play framework

I played around with Neo4j and the Play framework. After setting up the application and retrieving the first node objects from Neo4j REST API you (me definitely) directly want to work with domain objects to get rid of mapping nodes to domain objects forth an back. So, the easiest way to do that is using Spring data for Neo4j.

It´s nice. There are tons of features and especially using GraphRepositories is one I like very much. So I coded around a bit while play runs in background and re-compiles my changes dynamically. The demo I created re-creates data each time the application is started by hooking into the start process via a “global” type.

public void beforeStart(Application application) {
    context = new AnnotationConfigApplicationContext(AppConfig.class, DatabaseConfig.class);

An each time I changed something somewhere in the code I got a strange exception saying

[InvalidDataAccessApiUsageException: object is not an instance of declaring class; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class] 

which disappears after stopping the play server and start it up again.

I ask google for that and found this post saying something about a classloading problem and referencing a Spring JIRA ticket.

I use play 2.2.1, Spring data for Neo4j 2.3.3.RELEASE but also after switching to earlier play and Spring data versions the problem still appears. So, I debugged down to Spring.

What I found out is that org.springframework.data.repository.core.support.RepositoryFactorySupport implements a cache for repository information. This cache is a final static HashMap which means that it will survive the play reloading process and the context creation in Global#beforeStart. The problem is that play re-compiles sources every time you change something in the code and it seems that RepositoryInformation stored in the cache are not byte code compatible with that newly compiled version.

After spending some time trying to find out how to configured that within Spring I gave up and do what coder do: I hacked that piece of code. The result can be cloned from here https://github.com/timoe/springdataneo4jext.git. What it does is to implement a custom GraphRepositoryFactoryBean which forces the creation of a non caching instance of GraphRepositoryFactory

Everything else is easy. Just configure your Neo4j config using @EnableNeo4jRepositories#repositoryFactoryBeanClass= NonCachingGraphRepositoryFactoryBean.class and it will work.

@EnableNeo4jRepositories(basePackages = "repo",repositoryFactoryBeanClass = NonCachingGraphRepositoryFactoryBean.class)
public class MyNeo4jConfig extends Neo4jConfiguration{

Update: @olivergierke resolved https://jira.springsource.org/browse/DATACMNS-412 which fixes that bug. The fix was about turning the static Cache to a non static one.

Spring data and Neo4j

I played around with Spring data for Neo4j. Here is how it works.

Setup spring infrastructure

It´s quite easy. Dependencies are

  • org.springframework.data:spring-data-neo4j:2.3.2.RELEASE and
  • org.springframework.data:spring-data-neo4j-rest:2.3.2.RELEASE

(where spring-data-neo4j-rest is needed if neo4j runs as a server and the REST interface should be used).

I introduced a configuration bean that creates an instance of a Neo4j GraphDatabase

@ImportResource(value = {"/datasource-config.xml"})
public class DatabaseConfig {

  @Bean(name = "graphDatabaseService")
  public GraphDatabase graphDatabaseService(){
    return new SpringRestGraphDatabase("http://localhost:7474/db/data");

So, DatabaseConfig#graphDatabaseService creates a SpringRestGraphDatabase instance named “graphDatabaseService”. This bean is references in the application context datasource-config.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd">

    <neo4j:config graphdatabaseservice="graphDatabaseService">


That´s it. Spring data for neo4j is ready to use.

Define entities and repositories

Related to the domain driven design Spring data defines entities and repositories to access them. An entity for tagging something could be

public class Tag {

    private Long id;

the corresponding repository would be defined like that

public interface TagRepository extends GraphRepository<tag> {


This repository has to be added to the Springs datasource-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd">

    <neo4j:config graphdatabaseservice="graphDatabaseService">
    <neo4j:repositories base-package="domain.repo">


TagRepository is an interface?

Yes, it is. There is a bit magic under the hood. CGLib is used for generating repository implementations at runtime. So, no concrete implementations are needed for simple, at least CRUD use cases.h1. Sources
Find the sources at Github here: https://github.com/timoe/neo4jdemo.git.

Currying (with Scala)

What is currying?

I already heard of it at University when talking about functional programming. And during my first steps with scala I read that currying is supported. An example was given I did not understand (this time). Wikipedia says “currying is the technique of transforming a function that takes multiple arguments (or a tuple of arguments) in such a way that it can be called as a chain of functions, each with a single argument”. Ok. This sounds understandable even if I do not have any clue what to do with it. So, hands on.

Adding – without currying

def add (x: Int, y: Int) = x + y;

This is easy, right? Simply define a function add which adds two given Integers.

Adding – with currying

So, let´s re-write the add function to version that supports currying.

def add (x: Int)(y: Int) = x + y;

The only thing I did was to introduce new braces. This notation means:
add is a function that takes an Integer as an argument, returns a function that takes an integer as an argument which returns an Integer.”

Invoking add (39, 3) looks like 39 + 3 is computed and returned. The truth is a bit different from that

val addCurried: (Int) => Int = add(39)
val result = addCurried(3)

It results in two statements. The first one creates a function (here addCurried) that takes one argument. Invoking addCurried then computes the two given numbers. Who needs this piece of code? Well, I guess this particular: No one as it is rather senseless (I guess). Here comes a better one.

A much more better example

Currying becomes very useful when processing lists, e.g. filtering.

def filterList(list: List[Int], filterFunction: Int =>; Boolean): List[Int] = {
  if (list.isEmpty) list
  else if (filterFunction(list.head)) list.head :: filterList(list.tail, filterFunction)
  else filterList(list, filterFunction)

def mod(n: Int)(x: Int) = x % n == 0

filterList(List(1, 2, 3, 4), mod(2))

Nice one. For each element in the given list (traversing recursive by calling head and tail function) the given filter function is being ask, of it matches. If so, the head element of the list is added to the result, otherwise not. (You mentioned it I guess: This is the example from the beginning of this post and it´s very easy to understand, if you got the currying syntax ;))

Ruby and Blocks

This is such a damn cool feature. Of course functional languages like scala or clojure do allow higher order functions. To me this always seems to be a little bit hard to declare and to read. But Ruby? If you ask me: As simple as possible – look at this.

def inc
  update { | count |
    count + 1

def dec
  update { | count |
    count - 1

def update
  # some business logic here
  val = yield someType.someAttribute
  # more business logic

Of course the example is stupid. It declares methods inc and dec which increase resp. decrease a number. It is done by passing a block to the method update which then invoked necessary business logic for increasing or decreasing.
Nice one!

Building a jar including dependencies with Maven

It very simple. Simply add the Maven assembly plugin to your pom

                    <mainClass>[your main class here]</mainClass>

and run

mvn clean compile assembly:single

via command line.

Apache Velocity: How to initialize

Playing around with Apache Velocity was blocked by an Exception when trying to lead a Velocity Template which is located on the classpath of my application.

The code is

VelocityEngine engine = new VelocityEngine();
Template template = engine.getTemplate("/aTemplate.vm");

and it always throws

org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource '/aTemplate.vm'
	at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
	at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
	at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
	at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514)
	at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373)

The solution is really easy. A Resourceloader (here ClasspathResourceLoader) has to be defined before loading the Template:

VelocityEngine engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
Template template = engine.getTemplate("/aTemplate.vm");