Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, April 4, 2016

Spring Boot with JSPs using Undertow

This is a follow-up to my previous post Spring Boot with JSPs in Executable Jars.

Undertow is another alternative for using an embedded container with Spring Boot. You can find general information in the Spring Boot reference guide chapter Use Undertow instead of Tomcat. While I was working on updating the Spring Boot documentation regarding the JSP support for Tomcat, I noticed the following line in the reference guide for Spring Boot 1.3.3:

"Undertow does not support JSPs."

Being a good citizen, I dug a little deeper and discovered the Undertow JSP sample application by Chris Grieger. It turns out that Undertow has indeed JSP support by using jastow, which is a Jasper fork for Undertow. The key was to adapt the Undertow JSP sample application for Spring Boot. Doing so was actually fairly straightforward. The actual Undertow configuration uses Spring Boot`s EmbeddedServletContainerCustomizer:


final UndertowDeploymentInfoCustomizer customizer = new UndertowDeploymentInfoCustomizer() {

  @Override
  public void customize(DeploymentInfo deploymentInfo) {
    deploymentInfo.setClassLoader(JspDemoApplication.class.getClassLoader())
    .setContextPath("/")
    .setDeploymentName("servletContext.war")
    .setResourceManager(new DefaultResourceLoader(JspDemoApplication.class))
    .addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp"));

    final HashMap<String, TagLibraryInfo> tagLibraryInfo = TldLocator.createTldInfos();

    JspServletBuilder.setupDeployment(deploymentInfo, new HashMap<String, JspPropertyGroup>(), tagLibraryInfo, new HackInstanceManager());

  }
};

The full source is available in the JspDemoApplication class. The main issue is more or less the retrieval and configuration of the used Taglibraries. The Undertow JSP sample provides the TldLocator class, which does the heavy lifting. For our example, I am adapting that class so that it works in the context of Spring Boot. In Spring Boot we are dealing with über-Jars, meaning the resulting executable jar file will contain other jar files representing its dependencies.

Spring provides some nifty helpers to retrieve the needed Tag Library Descriptors (TLD) files. In TldLocator#createTldInfos I use a ResourcePatternResolver, specifically a PathMatchingResourcePatternResolver with a location pattern of classpath*:**/*.tld.


final URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();

final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader);
final Resource[] resources;
final String locationPattern = "classpath*:**/*.tld";

try {
 resources = resolver.getResources(locationPattern);
}
catch (IOException e) {
 throw new IllegalStateException(String.format("Error while retrieving resources"
   + "for location pattern '%s'.", locationPattern, e));
}


Important

Don’t forget the asterix right after classpath. The classpath*: allows you to retrieve multiple class path resources with the same name. It will also retrieve resources across multiple jar files. This is an extremely useful feature. For more information please see the relevant JavaDocs for PathMatchingResourcePatternResolver.

Once we have the TLD resources, they will be parsed and ultimately used to create a collection of org.apache.jasper.deploy.TagLibraryInfo. With those at hand, we create a JSP deployment for Undertow using the DeploymentInfo and the TagLibraryInfo collection.


final HashMap<String, TagLibraryInfo> tagLibraryInfo = TldLocator.createTldInfos();
JspServletBuilder.setupDeployment(deploymentInfo, new HashMap<String, JspPropertyGroup>(), tagLibraryInfo, new HackInstanceManager());

And that’s it. Simply build and run the application and you should have a working JSP-based application.


$ mvn clean package
$ java -jar jsp-demo-undertow/target/jsp-demo-undertow-1.0.0-BUILD-SNAPSHOT.jar

In your console you should start seeing how the application starts up.



Once started, open your browser and go to the following Url http://localhost:8080/.


You can find the full source-code for this sample at https://github.com/ghillert/spring-boot-jsp-demo

Thursday, October 1, 2015

AngularJS 1.x and TypeScript

I did a bit of research today on TypeScript. As it is favored (but not required) for the upcoming AngularJS 2.0 release, I wanted to dig a bit deeper. Keep in mind that as of Oct 2015, AngularJS 2.0 is still a pure alpha version and even new projects shall continue using AngularJS 1.4.

Nonetheless, it looks like TypeScript is a viable option even for the latest 1.4 version. In fact, Yeoman now provides an Angular starter (generator-gulp-angular) that gives you the option to use TypeScript as your language of choice.

Here are some resources that I thought were helpful:

http://www.developerhandbook.com/typescript/writing-angularjs-1-x-with-typescript/

I believe, that particularly for Java Developers, TypeScript could be quite interesting - as you have much better type-safety compared to using plain JavaScript. See the following blog entry by Veit Weber:

Why Java Developers might love TypeScript

There is a good presentation by Sander Mak from JavaOne: "TypeScript for Java Developers: Coding JavaScript Without the Pain" on that subject as well:


A longer version:



As you can have a much better OO experience with TypeScript, I think it will be also quite interesting to use rich domain objects with AngularJS rather than using JSON structures directly when retrieving data from your REST endpoints.

There is a great presentation by Gert Hengeveld from NG-NL 2015.



Slides: 

https://docs.google.com/presentation/d/1cbNH2WHO8WzF1XKPxMJ3gJXmfKnWAl3cN77eJJJdAEw/present?slide=id.p

Blog Post:

https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc

Convert JSON Structure to TypeScript Classes

If you create TypeScript classes that need to handle JSON, the follow online tool to generate TypeScript interfaces from JSON might be of interest:

http://json2ts.com/

TypeScript type definitions

I still need to wrap my head around TypeScript type definitions. They basically bolt on type definition for libraries that are not inherently based on TypeScript. There is a repository for them:

https://github.com/borisyankov/DefinitelyTyped


Tuesday, December 2, 2014

Npm, Bower, CI and the Network

Ok, I accepted the reality that building single-page applications (SPA) is better done using the tooling options embraced by the JavaScript community, rather than building those apps using purely Gradle or Maven (and respective plugins). The reason being that building a complete web-UI is rather involved and tools like Yeoman, Grunt (Gulp) and Bower provide quite a bit of useful tooling while also having a much larger user-base than the (less complete) options in the Java world.

So life was good. Everything builds. Of course we still need to integrate the app with our backend that provides the REST endpoints. Personally, I prefer it that developers can build the entire stack at once. Also, can we assume that every (Java) developer has Node/Npm intalled?

Luckily, there are some plugins available for Maven and Gradle that provide useful wrappers around Npm and Node:
Thus, with some trial and error you get a fairly portable build (Linux, Mac and Windows) that not only executes the Grunt build but also downloads and installs Node and its dependencies, Grunt, Bower etc.

You think you finally arrived...Things run mostly okay on the continuous integration (CI) server...mmh, wait... "Mostly" is causing some headaches. This is actually an area where I have some frustrations lately. Looks like the Maven Central in the node world is a tad more volatile than Maven central itself.

In the Java world you have 2 layers of protection that ensure that the CI server build process is fairly resilient to internet hick-ups. Heck, it would even build off-line (assuming no library dependency changes were done). First, you have your local repository of course, which in the case of Maven is typically ${user.home}/.m2/

Second, any serious CI environment would also use a dedicated repository manager that serves as a proxy to the outside world, so that for already retrieved dependencies you would not need to hit Maven Central or other 3rd party repositories.

With NPM you all of a sudden realize you are a tad back into the wild west. Not only do you have to consider NPM (Managing tooling dependencies) but Bower (managing JS/CSS dependencies) as well.

NPM actually provides npm-cache - and you see dependencies being cached in your home directory under ~/.npm/. But try to disable your network card...the eternal spinner is yours. It does not even seem to timeout.

You can go offline - kind of - using “npm install --cache-min 9999999 --no-registry” but it does not seem to support things the way Maven/Gradle does: Check the cache first, and only if the dependency does not exist fetch it remotely. See also: https://github.com/npm/npm/issues/2568

Another issue I encountered is with using Protractor for the E2E testing of my AngularJS application. You will usually use webdriver-manager to retrieve the necessary Selenium files/driver for your targeted Browser, e.g. Chrome. Since, I like to make the build as portable as possible, I do a post-install of the web-driver manager, which requires direct network access in package.json:

"scripts": {
  "postinstall": "node_modules/protractor/bin/webdriver-manager update"
}

Bower unfortunately, does its own caching approach which is configured in .bowerrc, e.g.:

"storage": {
"packages": ".bower_cache"
}

So what about using dedicated repository managers as proxy for NPM and Bower?

Artifactory provides support for NPM but not Bower. There is a feature request to support Bower in Artifactory, though. Nexus also has support for NPM. For Bower an open ticket exists.

Maybe people should start rallying behind web-jars more broadly ;-(



Monday, October 6, 2014

Java Template Engines Revisited Part 1

Over the past week, I spent some time looking at Java based template engines. Typically I need templating support for two areas:

  • View Templates (For rendering views in your browser)
  • Email Templates - with support for both HTML and Text emails

For email templates I had used the usual suspects such as Velocity and Freemarker in the past but both feel a tad heavy and old these days - Velocity's last release was in 2010! Eventually I settled for a simpler option a while back: StringTemplate, which as a library worked fairly okay.

As I had done some client-side templating using Mustache and Handlebars, I was intrigued in seeing Java implementations for both:


The nice thing about Mustache is that implementations are available for almost any programming language imaginable, which could be nice in case you have the need to maintain browser-bound and backend (Java) templates or in case you have multiple Java and non-Java application with templating needs.

For now I have chosen mustache.java. Looks like it is heavily used at Twitter. Depending on how willing you are towards enduring any type of logic in your templates, you may also want to check out Handlebars and the corresponding Java implementation. It is basically a super-set of Mustache, providing additional built-in helpers.

Lastly, for both Mustache and Handlebars there is support available for Spring MVC.


I have not used either support for Spring MVC, yet, though. In case you have used any of the mentioned options, please leave feedback to this blog.


Monday, October 28, 2013

DevNexus 2014 - Atlanta (Feb 24-25) - Call for Papers

The Atlanta Java Users Group is in the middle of organizing its annual developer conference for 2014. 

We are excited to announce that the Call for Papers is active now. Please spread the word among your peers and if your are interested we would love if you submit session proposals for our conference at:


This is what we plan so far:

DevNexus 2014 is on February 24-25 (Monday and Tuesday). We plan on having 1000+ attendees with 10 parallel tracks and 1 workshop track. This equates to:
  • 90+ sessions (75min each)
  • 4 workshops
  • 2 keynotes (60 min each)
Topic-wise we plan to cover the following:
  • Java/JavaEE/Spring
  • HTML5 + JavaScript
  • Data + Integration
  • User Experience
  • Alternative Languages on the JVM
  • Cloud
  • Agile
  • Tools
  • Mobile
Here is a short promo video that we did during DevNexus 2013:



If you have any questions, please ping me or the rest of the organizers at info at ajug dot org.

Wednesday, November 21, 2012

DevNexus 2013 - Feb 18/19 - Registration is Open


The Atlanta Java Users Group is delighted to announce that registration for DevNexus 2013 is now open. In order to reserve your ticket, please go to:


DevNexus 2013 will be held on Monday, February 18th and Tuesday, February 19th at the Cobb Galleria Centre in Atlanta, GA. We have already confirmed many wonderful speakers, representing the who's who in our industry. They will be covering a wide array of crucial technology topics such as:
  • Java and JVM Languages (incl. Clojure + Scala)
  • Cloud, Big Data and NoSQL
  • Web (HTML5, JavaScript)
  • Mobile (Android, Hybrid, Mobile Web)
  • Methodologies, Architecture, Tools and Security
In addition to providing great content for Java/JVM developers, DevNexus is an awesome networking opportunity. This event attracts Java/JVM talent from diverse backgrounds, be it large corporations, consulting organizations or independent technology connoisseurs. You will have an opportunity to discover what other development teams are using as their favorite tools and practices.

Why should you attend DevNexus 2013:
  • Best Value: $195 Early Bird price (until Jan 15) for two full days of technology immersion and camaraderie (group+student discounts available).
  • Ask questions to world-class experts and fellow developers
  • Learn how to move your applications into the cloud 
  • Learn Agile Best Practices & Tools 
  • Learn more about core Java topics as well as other languages on the JVM
  • Learn more about building rich (mobile) web-application applications using HTML5
  • Hear about the latest developments from JBoss, SpringSource and Typesafe
We have already lined-up some impressive speakers, with many more to be announced in the upcoming weeks:
  • Jeremy Deane
  • Hans Dockter
  • Ben Evans
  • Mark Fisher
  • Neil Ford
  • Andrew Fuqua
  • David Geary
  • Wesley Hales
  • Stuart Halloway
  • Ken Kousen
  • Josh Long
  • Matthew McCullough
  • Pratik Patel
  • Reza Rahman
  • Nate Schutta
  • Venkat Subramaniam
  • James Ward
Fore more details regarding speakers please visit:


We would like to welcome 2 new DevNexus sponsors: 

Silver Sponsors

- eHire Labs - http://ehirelabs.com/
- AppDynamics - http://www.appdynamics.com/

Cocktail Hour Sponsor

- eHire Labs - http://ehirelabs.com/

We also would like to thank our other AJUG/DevNexus sponsors for their support in making DevNexus a success. 
We hope to see you all at DevNexus, and please register as soon as possible for this incredibly valuable event at:


(We have sold out early in prior years)

Friday, October 5, 2012

What's New in Spring Integration 2.2 - JPA Support

I have just published a new blog posting, which introduces the new Java Persistence API (JPA) support that is provided with Spring Integration 2.2. This is the third part in a series of blog posts highlighting some of the new features available in Spring Integration 2.2 following the recent release of Release Candidate 1. Please head over to the SpringSource blog to get the details:

http://blog.springsource.org/2012/10/05/whats-new-in-spring-integration-2-2-part-3-jpa-support/

Wednesday, February 15, 2012

DevNexus 2012 - March 21-22 - Schedule Published


DevNexus 2012 is only 5 weeks away and will take place March 21-22. As of late, we have been super-busy organizing and confirming the best minds of our industry. We are happy to announce the preliminary schedule at


Again, this year will mark our biggest DevNexus conference event, yet! Compared to last year, we added 2 more tracks to the conference, bringing the total to 6 tracks. 30+ speakers will deliver 48 sessions equipping you with the critical knowledge to take your career to the next level. And if this is not enough, we have 3 wonderful keynote speakers as well:

  • Patrick Curran, Chair of the Java Community Process organization will present "Java User Groups and the Java Community Process: a winning combination"
  • Barry Hawkins, a veteran in our industry will present "How We Got Here, And What To Do About It", and we also are delighted to have
  • Ben Galbraith, founder of Ajaxian.com and now running mobile architecture and engineering at Walmart.com.

This year we will have an incredible breadth of topics. Besides covering core Java topics (e.g. Java 7+8, Joda Time, Guava) as well as JVM Languages (Groovy and Scala), we will also extensively cover Mobile topics (including HTML5). Furthermore, we will dive into Cloud related topics, covering Platform as a service (PaaS) providers such as Cloud Foundry, Google App Engine and Heroku. Here is a more comprehensive list of covered topics:

  • Core Java (Java 7+8, Joda-Time, Guava)
  • Spring (Spring 3.1, Spring MVC 3.1, Spring Integration)
  • JBoss (DeltaSpike)
  • Mobile (jQuery Mobile, PhoneGap, Android, Appcelerator Titanium)
  • HTML5
  • JavaScript (Node.js, jQuery), 
  • Cloud (Heroku, Cloud Foundry, Google App Engine)
  • Gradle
  • Groovy
  • Git
  • Scala
  • NoSQL (Neo4J, Cassandra)
  • Play Framework
  • Caching (EhCache  and JSR107)
  • REST
  • Continuous deployment
  • Talks on Agile Methodologies and Architecture

With this session line-up on the horizon, attending DevNexus should be a priority - This is also the South-East’s best, yet affordable, developer's conference!

We, the volunteers from the Atlanta Java Users Group would be delighted to see you all at DevNexus! Learn, network and have fun -

Please register today at: http://www.devnexus.com

We would like to thank our Sponsors that help us greatly to keep DevNexus super-affordable ($185 group-ticket / $200 regular ticket). We also welcome two new DevNexus Gold Sponsors:

  • SpringSource, a division of VMware
  • GCA Technology Services and Oracle University 

GCA Technology Services and Oracle University are thrilled to be sponsors of AJUG again this year. GCA specializes in Identity and Access Management (IAM) consulting and education. We partner with Oracle to provide industry leading solutions for user provisioning, role management, rights management, single sign-on, multi-factor authentication, governance and compliance. We deliver training for Oracle Solaris, Java, Oracle Identity and Access Management as well as other Oracle Applications and technologies. We believe that the blended approach by providing expert consultants who also educate our customers in the products we implement, allows us to achieve consistently positive results. Oracle's Java based IAM solutions lead the industry. Let us work with your team to create a training and IAM consulting solution that gets the results you want. Contact us at http://www.gca.net/oracle or 770-643-0443. We look forward to seeing everyone at Devnexus!

The DevNexus Gold Sponsors:

  • Terracotta
  • IntercontinentalExchange (ICE)
  • JBoss
  • The Intersect Group
  • GCA Technology Services and Oracle University
  • SpringSource, a division of VMware

Silver Sponsors:

  • Apex Systems
  • Anteo Group
  • 4t Networks

Cocktail Hour Sponsor:

  • MATRIX Resources

We are looking forward seeing you all in March!!!

Cheers,

Gunnar Hillert
President, Atlanta Java Users Group (AJUG)

PS:

If you have any question let us know at info at ajug.org and please follows us
on Twitter at http://twitter.com/devnexus for news and updates.

Monday, January 30, 2012

DevNexus 2012 Early Bird Ends in 48 Hours!

This is a friendly reminder that the Early Bird pricing for DevNexus 2012 ends in 48 hours on February 1 at 11:59pm. Therefore, please register for DevNexus at http://www.devnexus.com/ in order to secure your ticket for this wonderful conference at the low price of $185.

Date: March 21-22, 2012
Place: Cobb Galleria, Atlanta, GA
Cost: $185 (early bird price), $200 after February 1st.

DevNexus is the South-East's biggest conference for Java developers! We provide the best software professional development content at the lowest possible
price, bringing some of the world's best speakers & most interesting topics to Atlanta!

For 2012, we have an amazing line-up of speakers and sessions. Here is what you can expect:
  • 2 days
  • 6 tracks (2 more than last year!!)
  • 48 sessions
  • 3 keynote presentations
  • Food and beverages will be provided 
  • Cocktail-hour with free sponsored drinks at the end of the first day
  • Raffles and give-aways (e.g. books)
  • Great networking opportunities
  • Ridiculously cost-effective value
  • DevNexus is organized by community volunteers (pro-bono) for the community!
Here is a list of topics that we will cover:
  • Core Java (Java 7+8, Joda-Time, Guava)
  • Mobile (PhoneGap, Android, Titanium Mobile)
  • HTML5
  • JavaScript (Node.js, jQuery)
  • Spring (Spring 3.1, Spring MVC 3.1, Spring Integration)
  • JBoss (Delta Spike, JBoss 7)
  • Cloud (Heroku, Cloud Foundry, Google App Engine)
  • Gradle
  • Groovy
  • Git
  • Scala
  • NoSQL (Neo4J, Cassandra)
  • Play Framework
  • EhCache
  • REST
  • Continuous deployment
  • Talks on Agile Methodologies and Architecture
The DevNexus website already contains 32 session abstracts which you can browse at:

http://www.devnexus.com/s/presentations

More presentation abstracts will be added shortly. We are also super-excited to offer 3 keynote presentations at DevNexus 2012. The opening keynote presenter will be Patrick Curran, Chair of the Java Community Process organization (JCP):

"Java User Groups and the Java Community Process: a winning combination"

Our second keynote presenter will be our very own Barry Hawkins, a veteran in our industry as speaker, developer, and agile coach and mentor.

"How We Got Here, And What To Do About It"

Please find more information about our keynote speakers, including keynote details, on our website at:

http://www.devnexus.com/s/speakers

This is THE conference you must not miss. Therefore, come join us for this incredible event.

Don't hesitate, sign up for DevNexus 2012 today at: http://www.devnexus.com

We would also like to thank our Sponsors that greatly help us to keep DevNexus so affordable:

Gold Sponsors:
  • Terracotta
  • IntercontinentalExchange (ICE)
  • JBoss
  • The Intersect Group
Silver Sponsors:
  • Apex Systems
  • Anteo Group
Lastly, please feel free to send this note to your present & past co-workers in the local software development community. Group discounts of 5 or more apply.

If you have any questions please contact us at:

info at ajug dot org
678-908-9067

See you all at DevNexus 2012!!!!

Friday, January 13, 2012

Sonar and Gradle Multi-Module Projects

I love Sonar. It is a wonderful way to collect some metrics for your Java projects - hassle-free and wrapped in a sweet-looking UI.  For Maven-based projects Sonar literally works out of the box. Just start up your Sonar instance (assuming you are using the default settings running on localhost) and then you simply fire it off using:
$ mvn sonar:sonar 
A few moments later you should have the metrics available at:
http://localhost:9000/
Well, the past few days I was setting up a multi-module Gradle project for Sonar. Let me start by stating that Gradle is awesome. Having the ability to declare dependencies as one-liners and also being able to customize your scripts easily, yet having sensible defaults, is very nice. Kind of the best of both worlds.

Setting up Sonar for a multi module project, though, is unfortunately a bit more complicated, compared to what I am used to in the Maven world. It is not awfully complicated, but it took me a while to collect all the pieces of information.

Getting your Sonar plugin to just doing something is fairly simple. Just follow the basic steps outlined in the plugin documentation at:
One differentiator between the Sonar Plugin for Gradle and Maven is, that the Gradle version does not automatically run code coverage analysis. This needs to be manually setup. This is where the official doc just vaguely refers to Cobertura.

First, I tried using Cobertura for code coverage, but I seemed to run into difficulties for my multi-module projects. The Cobertura Plugin is here:
By chance I realized that the Sonar guys have a GitHub repository with samples on how to setup sonars for various build systems, including Gradle:
In their examples, they are using JaCoCo, which is not mentioned in the original Gradle docs and maybe I could have continued with Cobertura but it seemed that Sonar was preferring JaCoCo and thus I continued with that.

Some Gradle Sonar Plugin Limitations

The Gradle Sonar Plugin has an annoying limitation, where I can run it for the ROOT project OR for the sub-projects individually. See the following Gradle Jira ticket for details:
Furthermore, I hit the minor issue that I cannot set the links in the Sonar dashboard. This seems to be related to the following Sonar Jira issue:
The JaCoCo code coverage plugin is "slightly less" supported by the Gradle Sonar Plugin, e.g. the  Gradle Plugin does not have an explicit setter for the JacocoReportPath and it assumes the "target" folder as the build directory by default. Therefore you must set explicitly:
props["sonar.jacoco.reportPath"]  = "${buildDirName}/jacoco.exec"

Lastly, I deviated a bit from the SonarSource Gradle example, and instead of System properties, I wanted to use Gradle properties to allow for users to provide non-default Sonar configuration settings (databasem url, jdbc parameters etc.). Well, while setting that up I ran into yet another Gradle Jira issue:
But at the the end, I am happily able to run a multi-module Gradle project with Sonar and collecting Code Coverage statistics.  Here is the relavant code from my build.gradle file:

apply plugin: 'sonar'

sonar {

    if (rootProject.hasProperty('sonarHostUrl')) {
        server.url = rootProject.sonarHostUrl
    }

    database {
        if (rootProject.hasProperty('sonarJdbcUrl')) {
            url = rootProject.sonarJdbcUrl
        }
        if (rootProject.hasProperty('sonarJdbcDriver')) {
            driverClassName = rootProject.sonarJdbcDriver
        }
        if (rootProject.hasProperty('sonarJdbcUsername')) {
            username = rootProject.sonarJdbcUsername
        }
        if (rootProject.hasProperty('sonarJdbcPassword')) {
            password = rootProject.sonarJdbcPassword
        }
    }

    project {
        dynamicAnalysis  = "reuseReports"
        withProjectProperties { props ->
            props["sonar.core.codeCoveragePlugin"] = "jacoco"
            props["sonar.jacoco.reportPath"]       = "${buildDirName}/jacoco.exec"
        }
    }

    println("Sonar parameters used: server.url='${server.url}'; database.url='${database.url}'; database.driverClassName='${database.driverClassName}'; database.username='${database.username}'")

}

subprojects { subproject ->

    ...

    // See http://www.gradle.org/docs/current/userguide/dependency_management.html#sub:configurations
    // and http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ConfigurationContainer.html
    configurations {
        jacoco //Configuration Group used by Sonar to provide Code Coverage using JaCoCo
    }

    // dependencies that are common across all java projects
    dependencies {
        ...
        jacoco group: "org.jacoco", name: "org.jacoco.agent", version: "0.5.3.201107060350", classifier: "runtime"
        ...
    }

    test {
        jvmArgs "-javaagent:${configurations.jacoco.asPath}=destfile=${buildDir}/jacoco.exec,includes=org.your.project.*"
    }
    ...
}
I hope this is useful information for all Gradle users out there. 

Friday, December 30, 2011

Method Validation With Spring 3.1 and Hibernate Validator 4.2

JSR 303 and Hibernate Validator have been some awesome additions to the Java ecosystem, giving you a standard way to validate your domain model across application layers. Combined with the annotations of the Java Persistence API (JPA) you have some very nice tools at your disposal to ensure that only valid data enters your database.

However, one piece of missing functionality was the ability to also validate method calls. For example, wouldn't it be nice if you could use normal JSR 303 annotations to safeguard business layer calls as well?

Of course you can enforce constraints programmatically, e.g. prevent the passing of Null parameters. Spring for instance provides the org.springframework.util.Assert class. However, it would be desirable, if constraints placed on input parameters as well as return values were part of the method contract.

Enter Hibernate Validator 4.2, which was released in June of 2011. It provides now method validation and Gunnar Morling, one of the committers, has an excellent write-up on this on his blog at:
Also, check out the Hibernate validator documentation regarding method validation. Gunnar Morling also provides some preliminary Spring support available at GitHub:
But the news for Spring aficionados is getting even better - Direct support for Method Validation With Hibernate Validator is now available in the lastest Spring 3.1 release that went GA just two weeks ago.

Specifically Spring 3.1 provides the following support in regards to method validation:
In order to get started, make sure that you are using Spring 3.1.0.RELEASE and that you have Hibernate Validator 4.2 in your classpath. That's all what you need to begin using JSR 303 annotations on the method level. For example, now you can annotate your methods using e.g.:

@Validated
public interface BusinessService {
    @NotNull String convertToUpperCase(@NotEmpty String input);
}
The @Validated Annotation indicates that the methods in the class are to be included for method validation. Keep in mind that you can specify your own annotation that will be enabling method level validation for the annotated class. Specify your own annotation by calling setValidatedAnnotationType on the MethodValidationPostProcessor.

However, placing the annotations themselves will not enforce the constraints 'automagically'. In fact Spring will be using AOP (Aspect Oriented Programming) Advices under the covers that delegate to Hibernate Validator. The easiest way to enable these advices is to declare a MethodValidationPostProcessor bean in your Spring application context as shown below.
 
<?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:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <context:component-scan base-package="com.hillert.spring.validation" />

    <bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
      
    <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
    
</beans>
 
For more details, I have published a small project over at GitHub that illustrates method level validation using Hibernate Validator:
In order to get get started:
  1. Clone the repository using $ git clone git://github.com/ghillert/spring-hibernate-validator-sample.git 
  2. $ cd spring-hibernate-validator-sample
  3. Build the sample using Maven $ mvn clean package
  4. Run it with $ mvn exec:java 
The command-line based sample provides a simple String conversion service, that converts Strings to upper-case. You can insert those Strings from the command line. The Service layer will enforce the following constraints using method level Hibernate Validator annotations:
  • The input String must not be empty (not null and not an empty String)
  • The conversion service will never return null
In order to trigger validation exceptions you can enter some special strings:
  • Pressing just enter (no string entered) will cause an empty String parameter to be set
  • Submitting "null" (The String), will cause a null parameter to be set
  • When entering "returnnull", the underlying business method will return Null
The Main method will catch the occurring MethodConstraintViolationExceptions and print some details to the command prompt.

Lastly, the current method validator support via Spring is specifically targetting Hibernate Validator. However, there are standardization efforts underway as part of the Bean Validation 1.1 specification (JSR-349). In order to follow the progress, please follow also http://beanvalidation.org/.

Spring will provide support for JSR-349 as soon as the official standard has been ratified. In order to track inclusion into the Spring framework, please follow also Spring Framework Jira ticket SPR-8199 . As of today this feature should be available in the next Spring 3.2 release.

I hope this blog entry and the accompanying sample have showed you how easy it is to get started with  method level validation using Spring and Hibernate Validator. Please let me know if you have further questions or run into issues.

Tuesday, December 27, 2011

Java Print Service Frustrations

This is probably not the most exciting "toy" to play with for the holidays, but I wanted to explore some use-cases that involve printing through Java back-end services. Basically, in an enterprise environment you may run into requirements, where the documents you receive or generate also are required to be printed out for whatever reasons. In all honesty, I never had to deal with Java's print Apis and thus started from scratch.

It turns out, that there are 2 approaches (reminds me of the multitude of Date implementations...). One approach dates back to the 1990s and is called the Java 2 Print API and is tied more to User Interfaces (UI) triggering the printing process. With Java 1.4, the Java Print Service API (JPS) was introduced (JSR 6) which serves as a super-set of the the Java 2 Print Api.

The JPS Api is certainly workable but I ran into some serious trouble. For my initial use-case, I may receive simple text documents, e.g. XML that I want to send to a definable printer as plain text.

I was unable to get that to work on my Mac using Mac OS X 10.6.8. However, on my Windows JVM it worked flawlessly and my text files were printed out without any complaints. On my Mac, though, my little Java test application finishes without any errors but my printer queue states:

Error: pstopdffilter/pstocupsraster failed with err number -31000

Googling did not help much either. There seemed to be some anecdotal evidence that other people might have had trouble with text printing as well but I was unable to uncover definite answers (Many of the information is years old). The question I have is whether this is an issue with:
  • My Printer, which is a Brother HL-4070CDW
  • The Mac JVM (Mine is: build 1.6.0_29-b11-402-10M3527)
  • CUPS
  • something else
If any of the readers has encountered similar issues or is able to shed some more light into this issue, please let me know (THANKS!).

While searching for explanations, I stumbled across the following thread on stackoverflow.com: http://stackoverflow.com/questions/1655297/print-to-specific-printer-ipp-uri-in-java. There they mentioned the following CUPS specific libraries:
Jipsi aparently changed names and moved to Google code:
As I need a generic solution that works not only on Mac using CUPS but also on Windows I have not experimented with any of the libraries above. Nevertheless I wanted to mention them.

I have also tried various other DocFlavors and settings but to no avail. What is interesting, though, is that the printing of PDF files works fine. Printing image files such as PNG or JPG fails as well.

Here is the trivial application that I am using:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;

public class PrintPS {

  public static void main(String args[]) throws FileNotFoundException, PrintException {
    FileInputStream textStream = new FileInputStream(args[0]); 
    DocFlavor myFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc myDoc = new SimpleDoc(textStream, myFormat, null); 
  
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 
  
    aset.add(new Copies(1)); 
    aset.add(Sides.ONE_SIDED); 
  
    PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
  
    System.out.println("Printing to default printer: " + printService.getName());
  
    DocPrintJob job = printService.createPrintJob(); 
    job.print(myDoc, aset); 

  }
}

Furthermore, I looked at the follwing Java-based Text editors to see how they accomplish printing (Which works fine on my Mac as well):
RTEXT uses the DocFlavor: DocFlavor.SERVICE_FORMATTED.PRINTABLE which in turn uses a component that implements the java.awt.print.Printable Interface. 

I guess, as a next step I have two options...go down into the trenches of Java2D or have some fun generating PDF files...And all I wanted was to print some simple text that works across Operating Systems. 

Wednesday, December 7, 2011

DevNexus 2012 - Registration is Open

The Atlanta Java Users Group is delighted to announce that registration for DevNexus 2012 is now open. In order to reserve your ticket, please go to:
DevNexus 2012 will be held on Wednesday, March 21st and Thursday, March 22nd at the Cobb Galleria Centre in Atlanta, GA. We already confirmed many amazing presenters covering a wide array of crucial technology topics.

In addition to providing great content for Java developers, DevNexus is a very valuable networking opportunity. This event attracts Java/JVM talent from diverse backgrounds, be it large corporations, consulting organizations or independent technology connoisseurs. You will have an opportunity to discover what other development teams are using as their favorite tools and practices.

Why should you attend DevNexus 2012:
  • Best Value: $185 Early Bird price (until Feb 1) for two full days of technology immersion and comaraderie.
  • Ask questions to world-class experts and fellow developers
  • Learn how to move your applications into the cloud (covering Cloud Foundry, Heroku, Google App Engine, OpenShift)
  • Learn Agile Best Practices & Tools
  • Learn more about core Java topics as well as other languages on the JVM
  • Learn more about building rich (mobile) web-application applications, e.g. using HTML5
  • Hear about the latest developments from JBoss and SpringSource
We have already lined-up some impressive speakers, with many more to be announced in the upcoming weeks:
  • Tim Berglund - Covering NoSQL topics
  • Patrick Curran - Chairman of the JCP, keynote speaker
  • Hans Dockter  - Founder of Gradle
  • Ben Evans - Covering various core Java topics including Java 8
  • Mark Fisher - Spring Integration Lead, covering Enterprise Integration Patterns (EIP) and Cloud Foundry
  • Barry Hawkins - Covering Agile Methodologies
  • Josh Long - Spring Developer Advocate
  • Pratik Patel - Mobile/Web, Java
  • Rossen Stoyanchev - Spring MVC Lead
  • James Ward - Covering Heroku and Play framework
Fore more details on speakers please visit:

http://www.devnexus.com/s/speakers

We also would like to thank our sponsors for their support in making DevNexus a success:

Gold Sponsors
Silver Sponsor
We hope to see you all at DevNexus, and please register for this incredibly valuable event at:


Thursday, December 1, 2011

Cloud Foundry for Spring Developers - Slides

Yesterday, I presented "Cloud Foundry for Spring Developers", at the Atlanta Spring User Group. I finally got around to upload the presentation slides to Slideshare:

http://www.slideshare.net/hillert/cloud-foundry-for-spring-developers

I would like to thank everyone for coming to the presentation! Cloud Foundry rocks!

Tuesday, November 29, 2011

Cloud Foundry for Spring Developers


I will be presenting at the Atlanta Spring User Group tonight (Nov 29, 2011) at 6:30pm. For more details, including directions, please visit:

http://www.meetup.com/AtlantaSpring/


Title: Cloud Foundry for Spring Developers

Session abstract:

This session provides an overview of how to build and deploy Spring-based applications to the Cloud Foundry platform.
The session will cover application configuration parameters, binding services to your application, deployment options using using STS, the vmc command tool, as well as the new Apache Maven plugin for Cloud Foundry. Gunnar will demonstrate how to deploy applications to both micro and public Cloud Foundry and will also show how debugging works with Cloud Foundry and how you can inspect services remotely using Caldecott.

Gunnar will also show various options to keep your War-files deployable to both Cloud Foundry and stand-alone Servlet Containers using Auto-Reconfiguration, the Cloud namespace, and Spring 3.1 profiles.

Lastly, he will give a high-level overview how you can use Cloud Foundry together with Spring Integration in order to create scalable Spring applications.

Wednesday, November 2, 2011

DevNexus 2012 - Call For Papers Now Open


The DevNexus™ 2012 developer conference is taking place March 21-22. We are delighted to announce the Call for Papers is now open. We are looking forward to receiving your amazing proposals covering one of the following topics:
  • Java and JVM Languages
  • Cloud
  • NoSQL
  • Web (incl. Mobile Development, HTML5, JavaScript)
  • Methodologies and Tools
We do not encourage overt marketing pitches. Sessions are 75 minutes long and we encourage breakout sessions, work-shops and case studies. Please include the following information:
  • Name
  • Job Title
  • Email
  • Twiter id
  • Company
  • Presentation Title
  • Audience Level (General, Beginner, Intermediate, Advanced)
  • Presentation Abstract
  • Your Bio
Please submit your proposals as soon as possible to info at ajug.org. The Call for Papers closes January 15, 2012.
The planning committee will carefully review your proposals, and you will get a confirmation whether your talks are selected or not for the DevNexus™ conference.
For more information, please visit: http://www.devnexus.com/

Thursday, September 22, 2011

Maven and Cloud Foundry - The plugin is here!

It has been an amazing time so far for me working at SpringSource for the past couple of months and today I have finally published my first blog post for the official SpringSource blog. The blog post also marks the Milestone 1 (M1) release of the Cloud Foundry Maven Plugin which will make it much easier for Maven users to deploy their applications to Cloud Foundry.

Thus, checkout the blog post, use the plugin and follow the project over at GitHub. Please provide plenty of feedback - it is highly appreciated!

Friday, July 29, 2011

OSCON 2011 - Mission Accomplished


OSCON 2011 - Mission Accomplished and a week of amazing learning and networking is finally coming to an end. I had flown in not only for OSCON Java but also for the Community Leadership Summit, that took place last Saturday and Sunday (but Sunday, I attended the JVM languages day instead, which was wonderful as well).

I was super-impressed with the variety of people from all over the planet, not only the US but also Europe and the Americas. E.g. if you saw somebody wrapped in a flag…that was Bruno Souza, the man that has put Brazil on the map for Java developers. Furthermore, all the cool open-source companies that you could ever think of were present as well. Just an awesome level of energy there.

Also, I was able to connect with a ton of VMware/SpringSource folks at the event that I hadn’t met personally before, yet. Just to give you an idea of how awesome the open-source community is: On Tuesday we went out for some great food at McMenamins Kennedy School. It is housed in an old school with everything left intact/restored (incl. the showers in the rest rooms). That place has 5 bars, restaurant and excellent outdoor seating.

Anyway, our group included Dan Allen from JBoss (member of the Seam, Weld and Arquillian projects), Peter Neubauer from Neo4J (Founder, good chance for me to speak some German ;-), William  Rowe from SpringSource (Apache Foundation Vice President, HTTP Server), David Blevins from IBM (Co-founder of Geronimo and OpenEJB), Mark Johnson from SpringSource  (President of NEJUG),  Bruce Snyder from SpringSource (ActiveMQ comitter), Josh Long from SpringSource (Developer advocate and author), Steve Mayzak from SpringSource (Author). Seriously, to me, this was like being backstage! Thanks for having the chance to meet you all!

Back to OSCON here are the sessions I was able to attend:

Monday

  • Theory of Caching (Greg Luck)
  • Java Puzzlers – Scraping the Bottom of the Barrel (Josh Bloch, Bob Lee)
  • The Ghost in the VM: A Reference to References (Bob Lee)

Tuesday

  • Everything You Wanted to Know about Open Source that Nobody Told You (Jeff Genender)
  • Managing Thousands of Cloud Instances with Java (Patrick Lightbody)
  • ActiveMQ in Action – Common Problems and Solutions (Bruce Snyder)
  • The Evolution of Java: Past, Present, and Future (Josh Bloch)
  • From Ruby on Rails to Java: The Gory Details (Steve Jenson) 
  • A Giant Hop Forward with Spring Roo (Steve Mayzak and Josh Long

Thursday, July 21, 2011

Priority Channels in Spring Integration

As somebody was asking about a Priority Channel example for Spring Integration in the forums today, I went ahead and created a simple example. You can grab the source code over at GitHub:

https://github.com/ghillert/spring-integration-examples/tree/master/priority-channel-example

For some additional information check out the related forum entry:

http://forum.springsource.org/showthread.php?112368-PriorityQueue-example-needed

Monday, July 4, 2011

HTML5 WebSockets for JVM Developers

Anything related around HTML5 seems to be a hot button topic these days and lucky for me that I got an opportunity to take a deep dive into WebSockets. Thus, I will use this blog to post my findings over the next few days and I will present some simple code examples as well.

Anyway, WebSockets allow Servers to basically "push" data back to subscribed Browser clients in an effective manner instead of using workarounds such as long-polling. The WebSockets API is being standardized by the W3C (http://dev.w3.org/html5/websockets/) and the actual protocol is being defined by the Hypertext-Bidirectional (HyBi) working group (Part of IETF) - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09.

For further reading and to learn more about WebSockets in general, please also check out the following resources:
It turns out, though, that the only browsers, that support WebSockets out of the box right now, are Safari and Chrome. Wait - Firefox is not supported? Well, Firefox does support WebSockets but it is disabled by default due to security issues with the implemented draft version of the WebSocket protocol (Firefox 4+5). You can find more information about this here:
Nonetheless, if you're interested, you can re-activate WebSockets in Firefox 4 and 5 quite easily. Take a look at the following link for more information on how to do this:
Firefox 6 is supposed to bring back websockets support, albeit using a newer draft of the websocket protocol (hybi-07), which is not backwards compatible.

What about Web Servers?

Okay, so WebSockets look cool, yet with limited browser support. Furthermore, different webservers have varying stages of support for asynchronous messaging, with Jetty and Glassfish being the best options currently a provide native websocket support. It looks like Resin also has direct websocket support. See also:
Tomcat 7 currently does not support WebSockets, yet. Check out the following issue tracker entry to learn more about the current state of affairs in Tomcat 7:
What's next?

So, essentially what we want is some kind of framework that supports "graceful degradation": when available a suitable framework shall use websockets, but if not available, the framework should fall back to more traditional push work-arounds such as long-polling.

On the server-side, I am running Java, and therefore, I need a respective implementation on that platform. Choices, though, seem to be rather limited and I came up with the following list of options:
Just for reference, there seems to be quite some activity going on outside of Java:
My choice for now

Socket.IO looks like it has quite some traction but the default implementation is for Node.JS. There are Java implementations available but they did not seem to have much traction. jWebSocket actually looks promising but its licensing (LGPL) is too restrictive to me (My choice needs to be Apache license compatible ;-).

Out of the list above, I chose Atmosphere (http://atmosphere.java.net/). Atmosphere has pretty much all the features you would like to have incl. detecting server-side capabilities and using the best possible approach transparently. Atmosphere comes with a jQuery plugin that abstracts away the implementation details (same Api for using long-polling vs. websockets)

While Atmosphere comes with quite a few examples, they are interestingly mostly for JAX-RS and there are no examples for Spring MVC. Also, the documentations is rather limited but luckily you get very swift and helpful responses from Atmosphere mailing list.

In my next posting, I will provide a little example integrating Spring MVC and Atmosphere. So stay tuned.

Nevertheless, if you have other WebSocket recommendations and/or thoughts, please leave comments!

PS:

A funny thing, I just realized that Burr Sutter, a friend of mine and fellow AJUG board member wrote down his WebSockets research experiences as well. It is a small world. Go check it out at: