Archive: October 2012

Adding custom HTML attributes to your AngularJS web app

Posted on by  
Emil van Galen

AngularJS is an excellent JavaScript web framework offering so-called "directives" to 'teach' HTML some new tricks. Examples of built-in AngularJS directives are:

  • "ngView": defines the placeholder for rending views
  • "ngModel": binds scope properties to "input", "select" and "text" elements
  • "ngShow" / "ngDisabled": for showing or disabling an element based on the result of an expressions

Continue reading →

Gradle Goodness: Distribute Custom Gradle in Our Company

Posted on by  
Hubert Klein Ikkink

The Gradle wrapper allows us to let developers use Gradle without the need for every developer to install Gradle. We can add the output of the Gradle wrapper task to version control. Developers only need to checkout the source for a project and invoke the gradlew or gradlew.bat scripts. The scripts will look for a Gradle distribution and download it to the local computer of a developer. We can customize the Gradle wrapper and provide a different source for the Gradle distribution. For example we can add the Gradle distribution ZIP file on our company intranet. We then use the distributionUrl property of the Wrapper task to reference the intranet location where we place the Gradle distribution ZIP file.

In the following sample file we use the distributionUrl property to reference our company intranet:

Continue reading →

Groovy Goodness: Pretty Print XML

Posted on by  
Hubert Klein Ikkink

The easiest way to pretty print an XML structure is with the [XmlUtil](http://groovy.codehaus.org/api/groovy/xml/XmlUtil.html) class. The class has a serialize() method which is overloaded for several parameter types like String, GPathResult and Node. We can pass an OutputSteam or Writer object as argument to write the pretty formatted XML to. If we don't specify these the serialize() method return a String value.

import groovy.xml.*

def prettyXml = '''
<?xml version="1.0" encoding="UTF-8"?>
<languages>
  <language id="1">Groovy</language>
  <language id="2">Java</language>
  <language id="3">Scala</language>
</languages>
'''


// Pretty print a non-formatted XML String.
def xmlString = '<languages><language id="1">Groovy</language><language id="2">Java</language><language id="3">Scala</language></languages>'
assert XmlUtil.serialize(xmlString) == prettyXml

// Use Writer object as extra argument.
def xmlOutput = new StringWriter()
XmlUtil.serialize xmlString, xmlOutput
assert xmlOutput.toString() == prettyXml

// Pretty print a Node.
Node languagesNode = new XmlParser().parseText(xmlString)
assert XmlUtil.serialize(languagesNode) == prettyXml


// Pretty print a GPathResult.
def langagesResult = new XmlSlurper().parseText(xmlString)
assert XmlUtil.serialize(langagesResult) == prettyXml


// Pretty print org.w3c.dom.Element.
org.w3c.dom.Document doc = DOMBuilder.newInstance().parseText(xmlString)
org.w3c.dom.Element root = doc.documentElement
assert XmlUtil.serialize(root) == prettyXml


// Little trick to pretty format
// the result of StreamingMarkupBuilder.bind().
def languagesXml = {
    languages {
        language id: 1, 'Groovy'
        language id: 2, 'Java'
        language id: 3, 'Scala'
    }
}
def languagesBuilder = new StreamingMarkupBuilder()
assert XmlUtil.serialize(languagesBuilder.bind(languagesXml)) == prettyXml

Continue reading →

Gradle Goodness: Task Output Annotations Create Directory Automatically

Posted on by  
Hubert Klein Ikkink

One of the great features of Gradle is incremental build support. With incremental build support a task is only executed if it is really necessary. For example if a task generates files and the files have not changed than Gradle can skip the task. This speeds up the build process, which is good. If we write our own tasks we can use annotations for properties and methods to make them behave correctly for incremental build support. The @OutputDirectory annotation for example can be used for a property or method that defines a directory that is used by the task to put files in. The nice thing is that once we have designated such a directory as the output directory we don't have to write code to create the directory if it doesn't exist. Gradle will automatically create the directory if it doesn't exist yet. If we use the @OutputFile or @OutputFiles annotation the directory part of the file name is created if it doesn't exist.

In the following example build file we create a new task SplitXmlTask with the property destinationDir and we apply the @OutputDirectory annotation. If the directory doesn't exist Gradle will create it when we execute the task.

Continue reading →

Gradle Goodness: Init Script for Adding Extra Plugins to Existing Projects

Posted on by  
Hubert Klein Ikkink

Gradle is very flexible. One of the ways to alter the build configuration is with initialization or init scripts. These are like other Gradle scripts but are executed before the build. We can use different ways to add the init script to a build. For example we can use the command-line option -I or --init-script, place the script in the init.d directory of our GRADLE_HOME directory or USER_HOME/.gradle directory or place a file init.gradle in our USER_HOME/.gradle directory.

We can also use the apply(from:) method to include such a script in our build file. We can reference a file location, but also a URL. Imagine we place an init script on our company intranet to be shared by all developers, then we can include the script with the apply(from:) method. In the following build file we use this syntax to include the script:

Continue reading →

Gradle Goodness: Exclude Transitive Dependency from All Configurations

Posted on by  
Hubert Klein Ikkink

We can exclude transitive dependencies easily from specific configurations. To exclude them from all configurations we can use Groovy's spread-dot operator and invoke the exclude() method on each configuration. We can only define the group, module or both as arguments for the exclude() method.

The following part of a build file shows how we can exclude a dependency from all configurations:

Continue reading →

Gradle Goodness: Running Java Applications from External Dependency

Posted on by  
Hubert Klein Ikkink

With Gradle we can execute Java applications using the JavaExec task or the javaexec() method. If we want to run Java code from an external dependency we must first pull in the dependency with the Java application code. The best way to do this is to create a new dependency configuration. When we configure a task with type JavaExec we can set the classpath to the external dependency. Notice we cannot use the buildscript{} script block to set the classpath. A JavaExec task will fork a new Java process so any classpath settings via buildscript{} are ignored.

In the following example build script we want to execute the Java class org.apache.cxf.tools.wsdlto.WSDLToJava from Apache CXF to generate Java classes from a given WSDL. We define a new dependency configuration with the name cxf and use it to assign the CXF dependencies to it. We use the classpath property of the JavaExec task to assign the configuration dependency.

Continue reading →

A introduction to websockets.

Posted on by  
Richard Rijnberk

To make a long story short websockets allow us to create a pipeline between a web client and a server. Which is great because we can push and pull all kind of data through it. This in turn allows us to create highly responsive web applications that may update information over multiple sessions. Sound awesome doesn’t it. There’s just one catch, and you can probably guess what it is. That’s right, it’s not universally accepted by all browser or containers. Worse yet, most browsers that are currently in use have very poor to no support for it yet. And the same can be said for quite the percentage of web containers out there. Luckily we can use SocksJS. This library actually checks if it is possible to set up a websocket. And, when this is not the case, sets up a default fallback. This means that if a websocket connection cannot be created the SocksJS implementation will fall back to long pulling. Giving us the same behavior as before only at a higher performance cost. The SocksJS api is the same as the one for websockets. This allows us to change from a websockets implementation to a SocksJS implementation with minimal changes. So if you want to create a highly responsive webapp which updates as soon as new information arrives SocksJS is the way to go.

Continue reading →

Day two of the SpringOne 2GX in Washington.

Posted on by  
Richard Rijnberk

It was a full day starting with breakfast and 5 one and a half hour long presentations followed by dinner and a keynote delivered by Adrian Colyer, CTO of SpringSource. The keynote was on how application architecture has evolved over the last 10 years towards what it has become today. We started out with a static frontend client that communicated with a service layer, which in turn persisted to a database. Nowadays we have rich clients, multiple services in our service tier that in turn connect to services, websockets and/or other data sources. He proceeded to show his application, slowly scaling it up from one isolated environment into a cloud solution and from there into a multi cloud solution using brokers for each cloud region. From this he explained the use of auto scaling workers in a message queue and the advantages this mechanism has in relation to bandwith, throughput and latency. During his presentation he used scriptIt, which is a new browser based javascript editor that was released recently. He was enthusiastic about it due to its ability to follow declarations and support for auto completion. Another tool he was adamant about was a REST service console that allows reading and the exercise of calls that alter the state of the service. It is a great tool for seeing what goes on under the hood. For the code featured in this keynote see: github

Continue reading →

Keynote SpringOne 2GX

Posted on by  
Richard Rijnberk

Juergen Hoeller Hoeller begint zijn presentatie met de originele driehoek van spring. Zijn verhaal beschrijft vervolgens de transitie die het framework heeft gemaakt sinds dat model naar een annotation framework. Hij legt de nadruk vooral ook bij de beschrijvende namen van de annotaties, en hoe ze zorgvuldig zijn gekozen om de code leesbaarder te maken. Hierbij gaat hij dieper in op een aantalannotaties zoals stereotypes, injections en ook parameter annotaties. Hierbij geeft hij aan het gevoel te hebben dat de kracht van deze annotaties nog steeds wel onderschat wordt. Hoeller verteld hierna hoe er in de laatste tijd is gewerkt aan de WebApplicationInitialiser om xml configuraties zoals de web.xml iets van het verleden te maken. Hij gaat vervolgens in op de @configuration annotation en de manier waarop in deze configuratie classes gescanned kan worden op het classpath om filters en beans te injecten in de app. Dit soort Java based configuratie zorgt er voor dat xml configuraties zoals de persistance XML niet meer nodig zijn.

Continue reading →

Grassroots Groovy: Parse XML with XmlSlurper from Java

Posted on by  
Hubert Klein Ikkink

We can introduce Groovy into our Java projects at grassroots level. Even if we aren't allowed to run the Groovy compiler we can use other ways to run Groovy code. As long as we can include the Groovy libraries as a compile dependency than we can already use Groovy from Java. In this post we see how we can use the power of XmlSlurper to parse XML from our Java code.

To execute a Groovy script from we can use a GroovyShell object and invoke the evaluate() method. The evaluate() method can parse a Groovy script as File or Reader object. We can also use a String value to be evaluated. The last statement of the script that is evaluated can be assigned to a Java variable. To pass variables to the script we use the Binding object. This is a map of variables and their values. We assign values to the variables in the Java code and in the Groovy script we can use the variable values.

Continue reading →

JAXB class generation using Maven

Posted on by  
Albert van Veen

There is a useful maven plugin to generate all our JAXB classes for us. This plugin can be executed during the generate-sources phase of our maven build. It can be very useful, especially in the first stages of our project when the design of our XSD may change frequently. We can just add the plugin configuration to the pom.xml of our project.

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>

    <configuration>
        <extension>true</extension>
        <args>
            <arg>-Xfluent-api</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>net.java.dev.jaxb2-commons</groupId>
                <artifactId>jaxb-fluent-api</artifactId>
                <version>2.1.8</version>
            </plugin>
        </plugins>
        <bindingDirectory>src/main/resources/</bindingDirectory>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Continue reading →

shadow-left