Enterprise grade Java.
You'll read about Conferences, Java User Groups, Java, Integration, Reactive, Microservices and other technologies.

Friday, February 27, 2015

Developer Interview (#DI15) with Niko Köbler (@dasniko) Java EE and Node.js Performance

13:00 Friday, February 27, 2015 Posted by Test No comments:
, , ,
Developer interview Friday. Today it is my pleasure to welcome Niko Köbler (@dasniko). We meet a couple of times before and I love following his ramblings about JavaScript on the server side. I talked to him about why and how he came in contact with server side JavaScript in general and made him show a little more about his recent performance test, that he ran against RESTFUL backends (WIldFly and node.js). For those interested in more numbers, he has a blog-post up about it High-Performance Microservices - Node.js vs. Wildfly

Niko works as an independant and self-employed software architect, developer and trainer for Java and JavaScript enterprise solutions, integrations and web development. At the moment he is focussing on running Node.js applications in JVM environments and integrating best of both worlds.
He advises and supports clients across industries, conducts workshops, trainings and architecture reviews. Niko is co-lead of a local Java User Group (jug-da.de), writes articles and speaks regularly at international tech conferences.

Find the code he showed on his github account:
a) Wildfly App
b) Node.js App

Friday, February 20, 2015

Plug in Policies Into JBoss Apiman

14:00 Friday, February 20, 2015 Posted by Test No comments:
, ,
The JBoss apiman project did just release 1.0.3.Final this week.  It's mostly a bug fix release, with just a couple of relatively minor improvements. One particular feature, that made it's way into the framework since I last blogged about it is the support for plugins. Those plugins can easily be added to the system in order to provide additional functionality.

Add Policies As Plugins
Currently the only functionality that can be contributed through the plugin framework is new policies. Fortunately policies are also the most important aspect of apiman, as they are responsible for doing all of the important work at runtime.

Creating a Plugin
An apiman plugin is basically a java web archive (WAR) with a little bit of extra sauce. This approach makes it very easy to build using maven, and should be quite familiar to most Java developers. Because a plugin consists of some resources files, compiled java classes, front-end resource such as HTML and javascript, and dependencies in the form of JARs, the WAR format is a natural choice. If you want to give it a try yourself, make sure to dig trough the extensive documentation in the developer guide.
The following video walks you through it quickly:

How To Run Apiman
There is a very handy quickstart available, which allows you to build, deploy and start apiman on WildFly with a single command:

$ mvn clean install -Pinstall-all-wildfly8
$ cd tools/server-all/target/wildfly-8.1.0.Final/
$ ./bin/standalone.sh
Make sure to also read my previous blog posts about API Management with apiman:
You can follow @apiman_io and chat with the team on IRC.

Thursday, February 19, 2015

Marcus Lagergren 20 years of Java In Review

15:00 Thursday, February 19, 2015 Posted by Test No comments:
, ,
We know each other since some years now. And I am very very pleased to see, that we finally could make it happen to have him speaking at JavaLand as a Keynoter. And what would be better for a JVM veteran than talking about this years anniversary: Happy Birthday Java!
Thank you Marcus, for taking the time!

I am looking forward to a beer or two at JavaLand! Follow his rumblings about dynamic languages on the JVM and surgeries on Twitter @lagergren.
But it's obviously best to see him live on stage at JavaLand! So, if you haven't go ahead and register!

Marcus has worked with Java since 1995 and with runtimes since 1999. He started out with JVMs as one of the founders of Appeal Virtual Machines, the company that created the JRockit JVM. His JavaLand keynote will be a historical trip down memory lane - going through 20 years of Java and JVM implementations. This will be partly from Marcus’s own perspective as one of the architects behind JRockit, with plenty of stories from the trenches, like the benchmarking competitions between BEA/Oracle, Sun and IBM. We will see how Java and the JVM turned into the robust high performance server side platform that it is today, partly through personal observations and partly through a more objective “what a long strange trip this has been”. He will take you back to 1995 in a time machine and slowly bring you to 2014, going over the major Java releases and the runtime innovations made in the JVM side to get us here. Finally, we will do a short trip into the future, even though the future is always fuzzy, to explore what might be coming next. With Java 8, the biggest release in Java history, Java is more vibrant and alive than ever before. This is an evolution that won’t be stopped.

Question: "20 Years of Java. Wow! How long do you know Java? And I know, you've been writing the JRockit JVM back in the days .. does writing a JVM actually means knowing the language it is written for? The JVM is written in C/C++, correct?"

Answer: "I first started working with Java when I was a research intern at Ericsson Medialab in 1995-1996. This was Java 1.0 and its betas. Back in those days the JDK fit on one floppy. Yes. Floppy. We had those then.
I first started working with runtimes in 1998-1999, when I joined Appeal Virtual Machines on the JRockit project.
The JVM is written in C++ (and metaprogrammed in Java, and with some hardcoded assembly for different silicons).
I would say that you can get away with a lot of gaps in your language knowledge if you are a runtime implementor for the language in question. Right now, one of the things I am working on is getting the
JVM to run dynamic languages, and even though I am implementing parts of a JavaScript and TypeScript runtime, I don’t know all the details of those languages. When it comes to Java, I have been known to answer programming questions with “I am not a Java programmer” quite frequently. Ironically I am on the Java language team ;-)
Java is also a bit different from, say, C, because it has such a large API library in the JDK. I need an IDE when I program Java to remember what all the library functions are called, and get auto completion and so on. Otherwise, I'm an Emacs dude. So, I wouldn't call myself a Java expert, at least not on the libraries, but I get stuff done. Especially these last three years when the majority of my programming time has been in Java for the first time in my life.
Usually, when I have a Java question in my job, I ask someone else in the Java language team, often my poor colleague Joel Borggren-Franck.
When it comes to C, it's my native language, so there, you won't catch me off guard with anything. When it comes to C++, I don't think anyone fully knows that horror. Not even Bjarne Stroustrup. It's rapidly turning into a Frankenstein’s monster pseudo-runtime language as well, so I hope it will be put out of its misery soon."

Q: "What is your favorite memory about Java? Did you ever meet James Gosling and won an argument against him? Or something else unknown and funny?"

A: "I have indeed met Gosling several times, but I've never had a chance to have a deep, long conversation with him. Usually, we agree on what small issues we have discussed.
My favourite memory of Java has to be either the early JavaOne:s at the end of last century or the beginning of this century, and pushing JRockit there both on the exhibition floor and elsewhere. Otherwise, I'd pick any triumphant moment when we were leading the benchmark wars between 2000-2005, competing in server side performance with Sun HotSpot and IBM J9. Once, we were 30% better than anyone else, and I seem to remember this was due to us being the first to implement
comperssed references. That was an awesome moment. I actually remember that being met with some hostility by some people from Sun then, who were bad sports. But usually, we had a great time and lots of great conversation with our competitors.
All in all, the best job of my life was when I was JIT lead for JRockit and shared an office with equally driven compiler engineers. It’s great now too, but we had something special in the underdog position against Sun and IBM, and the ability to completly reshape our code base whenever we needed to. Those were great days. We listened to massive heavy metal all the time. Now, I work in a
cubicle farm, so it’s headphones instead. Not the same feeling :)

Q: "Looking at JVM technology today compared with the JRockit beginnings: If I'd ask you to name the most significant changes in a couple of sentences, how would that look like?"

A: "If you are talking about JVM technology and not the Java language, I'd say low latency GC technology, invokedynamic and the ability to do in-production monitoring with very low overhead, which Java Mission Control enables. If it's Java, Java 8 is the biggest and most
revolutionary feature... ever... I think. "

Q: "I think it is safe to assume, that working in the language team at Oracle is one of the most amazing places. Surrounded by extremely smart people working on the future of what so many people use on a daily base. Do you personally feel this as pressure?"

A: "No I don't. I feel that it's an asset, and it's the main benefit of my job and the reason that I love it.. There is always someone around who is smarter than me that I can ask for help, and the team I am on is so senior that it's virtually self managing. There is no doubt as to what I should do when I sit down at my desk in the morning, and the competence level of the engineers turns everything into a well oiled machine. I am very blessed to be in such an environment.
I _would_ feel pressure if I were the smartest engineer in a place of low performers, not the other way around. The language team is a place where you continuously learn stuff from your
colleagues, and I love that. Picturing myself as, say, a web frontend consultant, always makes me shudder. (Disclaimer: I don't have anything against web frontend consultants, or think they are stupid - I just don't think I'd get to solve complex algorithmic problems every day there, which is what I live and breathe for)."

Q: "What are you looking forward for in this year of celebrating the 20 year success story?"
A: "I want Java 8 to fully take off, that would be awesome. I would also like to ship a version of our Nashorn runtime that is more language agnostic and can be used as the base for more dynamic languages on the JVM than TypeScript and JavaScript, and start to see it being put to industry use. (I'll also get some serious startup time improvements done, it'll be awesome, hopefully)"

Tuesday, February 17, 2015

JBoss Forge NetBeans integration - Getting Started

12:00 Tuesday, February 17, 2015 Posted by Test No comments:
, ,
JBoss Forge is the Fastest way to build Maven-Based Java EE projects. And as such it already has awesome features to make your life as a developer even easier.
For the most part, people looking at Forge are likely interested in creating web-applications. There are plenty of ways to get started with the Forge basics. You can look at the quickstart section or look at the github repository. Just some short days ago Forge got even more awesome. George Gastaldi (@gegastaldi) created a NetBeans Plugin for Forge which allows you to execute all forge commands via the build in NetBeans quick-search.
  • Run JBoss Forge commands straight from your Netbeans IDE
  • Commands are rendered as native Netbeans Wizards
  • Create your own addon and deploy it inside the Netbeans IDE
Installing The Forge Plugin
To install the plugin just download the latest version from the netbeans plugin portal and unzip the two nbm files to a folder of your choice. Start NetBeans and navigate to "Window>Plugins" select the "Downloaded" tab and click the "add Plugin" button. Navigate to the folder in which you unzipped the two files and select them. Click the "install" button bottom left and click through the wizard. Restart NetBeans and you're ready to go.

The following video gives you a brief overview about what is possible already.

Monday, February 16, 2015

Byteman - a swiss army knife for byte code manipulation

12:00 Monday, February 16, 2015 Posted by Test No comments:
I am working with a bunch of communities in JBoss and there is so much interesting stuff to talk about, that I can't wrap my head around every little bit myself. This is the main reason why I am very thankful to have the opportunity to welcome guest bloggers here from time to time. Today it is Jochen Mader, who  is part of the nerd herd at codecentric. He currently spends his professional time coding Vert.x-based middleware solutions, writing for different publications and talking at conferences. His free time belongs to his family, mtb and tabletop gaming. You can follow him on Twitter @codepitbull.

There are tools you normally don't want to use but are happy enough to know about them when the need arises. At least to me Byteman falls into this category. It's my personal swiss army knife to deal with a Big Ball of Mud or one of those dreaded Heisenbugs. So grab a current Byteman-distribution, unzip it to somewhere on your machine and we are off to some dirty work.

What is it
Byteman is a byte code manipulation and injection tool kit. It allows us to intercept and replace arbitrary parts of Java code to make it behave differently or break it (on purpose):
  •  get all threads stuck in a certain place and let them continue at the same time (hello race condition)
  •  throw Exceptions at unexpected locations
  •  tracing through your code during execution
  •  change return values
and a lot more things.

An example
Let's get right into some code to illustrate what Byteman can do for you.
Here we have a wonderful Singleton and a (sadly) good example of code you might find in many places.

public class BrokenSingleton {

    private static volatile BrokenSingleton instance;

    private BrokenSingleton() {

    public static BrokenSingleton get() {
        if (instance == null) {
            instance = new BrokenSingleton();
        return instance;

Let's pretend we are the poor souls tasked with debugging some legacy code showing weird behaviour in production. After a while we discover this gem and our gut indicates something is wrong here.
At first we might try something like this:

public class BrokenSingletonMain {

    public static void main(String[] args) throws Exception {
        Thread thread1 = new Thread(new SingletonAccessRunnable());
        Thread thread2 = new Thread(new SingletonAccessRunnable());

    public static class SingletonAccessRunnable implements Runnable {
        public void run() {

Running this there is a very small chance to see the actual problem happen. But most likely we won't see anything unusual. The Singleton is initialized once and the application performs as expected. A lot of times people start brute forcing by increasing the number of threads, hoping to make the problem show itself. But I prefer a more structured approach.

Enter Byteman.

Byteman provides a convenient DSL to modify and trace application behaviour. We'll start with tracing calls in my little example. Take a look at this piece of code.

RULE trace entering
CLASS de.codepitbull.byteman.BrokenSingleton
IF true
DO traceln("entered get-Method")

RULE trace read stacks
CLASS de.codepitbull.byteman.BrokenSingleton
AFTER READ BrokenSingleton.instance
IF true
DO traceln("READ:\n" + formatStack())

The core building block of Byteman-scripts is the RULE.

It consists of several components (example shamelessly ripped from the Byteman-Docs:

 # rule skeleton
 RULE <rule name>
 CLASS <class name>
 METHOD <method name>
 BIND <bindings>
 IF <condition>
 DO <actions>

Each RULE needs to have unique __rule name__. The combination of CLASS and METHOD define where we want our modifications to apply. BIND allows us to bind variables to names we can use inside IF and DO. Using IF we can add conditions under which the rule fires. In DO the actual magic happens.

ENDRULE, it ends the rule.

Knwoing this my first rule is easily translated to:

When somebody calls _de.codepitbull.byteman.BrokenSingleton.get()_ I want to print the String "entered get-Method" right before the method body is called (that's what __AT ENTRY__ translates to).

My second rule can be translated to:

After reading (__AFTER READ__) the instance-Member of BrokenSingleton I want to see the current call-Stack.

Grab the code and put it into a file called _check.btm_. Byteman provides a nice tool to verify your scripts. Use __<bytemanhome>/bin/bmcheck.sh -cp folder/containing/compiled/classes/to/test check.btm__ to see if your script compiles. Do this EVERY time you change it, it's very easy to get a detail wrong and spend a long time figuring it out.

Now that the script is saved and tested it's time to use it with our application.

The Agent
Scripts are applied to running code through an agent. Open the run-Configuration for the __BrokenSingletonMain-class__ and add


to your JVM-parameters. This will register the agent and tell it to run _check.btm_.

And while we are at it here are a few more options:
If you ever need to manipulate some core java stuff use


This will add Byteman to the boot classpath and allow us to manipulate classes like _Thread_, _String_ ... I mean, if you ever wanted to such nasty things ...

It's also possible to attach the agent to a running process. Us __jps__ to find the process id you want to attach to and run

__<bytemanhome>/bin/bminstall.sh &ltpid&gt__

to install the agent. Afterwards run

__<bytemanhome>/bin/bmsubmit.sh check.btm__

Back to our problem at hand.

Running our application with the modified run-Configuration should result in output like this

entered get-Method
entered get-Method
Stack trace for thread Thread-0

Stack trace for thread Thread-1

Congratulations you just manipulated byte code. The output isn't very helpful yet but that's something we are going to change.

Messing with threads
With our infrastructure now set up we can start digging deeper. We are quite sure about our problem being related to some multithreading issue. To test our hypothesis we have to get multiple threads into our critical section at the same time. This is close to impossible using pure Java, at least without applying extensive modifications to the code we want to debug.

Using Byteman this is easily achieved.

RULE define rendezvous
CLASS de.codepitbull.byteman.BrokenSingleton
IF NOT isRendezvous("rendezvous", 2)
DO createRendezvous("rendezvous", 2, true);
traceln("rendezvous created");

This rule defines a so called rendezvous. It allows us to specify a place where multiple threads have to arrive until they are allowed to procede (also known as a a barrier).

And here the translation for the rule:

When calling _BrokenSingleton.get()_ create a new rendezvous that will allow progress when 2 threads arrive. Make the rendezvous reusable and create it only if it doesn't exist (the IF NOT part is critical as otherwise we would create a barrier on each call to _BrokenSingleton.get()_).

After defining this barrier we still need to explicitly use it.

RULE catch threads
CLASS de.codepitbull.byteman.BrokenSingleton
AFTER READ BrokenSingleton.instance
IF isRendezvous("rendezvous", 2)
DO rendezvous("rendezvous");

Translation: After reading the _instance_-member inside _BrokenSingleton.get()_ wait at the rendezvous until a second thread arrives and continue together.

We now stop both threads from _BrokenSingletonMain_ in the same lace, after the instance-null-check. That's how to make a race condition reproducible. Both threads will continue thinking _instance_ is null, causing the constructor to fire twice.

I leave the solution to this problem to you ...

Unit tests
Something I discovered while writing this blog post is the possibility to run Byteman-scripts as part of my unit tests. Their JUNit- and TestNG-integration is easily integrated.

Add the following dependency to your _pom.xml_


Now Byteman-scripts can be executed inside your Unit-Tests like this:

public class BrokenSingletonTest
  public void testForRaceCondition() {

Adding such tests to your suits increases the usefulness of Byteman quite a bit. There's no better way preventing others from repeating your mistakes as making these scripts part of the build process.

Closing words
There is only so much room in a blog post and I also don't want to start rewriting their documentation. It was a funny thing writing writing this post as I hadn't used Byteman for quite a while. I don't know how I managed to overlook the unit test integration. That will make me use it a lot more in the future.
And now I suggest to browse their documentation and start injecting, there's a lot to play around with.

Friday, February 13, 2015

Developer Interview (#DI14) Corinne Krych (@corinnekrych) about Swift, AeroGear, OAuth and Keycloak

12:00 Friday, February 13, 2015 Posted by Test No comments:
, , , , ,
Developer interview time again. And today it is my pleasure to welcome Corinne to the series as the first female engineer. She is working in the AeroGear team and in particular on the Swift libraries for iOS. We talked about social authentication via OAuth2 with Swift in iOS and also took a look at securing REST services with Keycloak and how to use the new AeroGear Swift libraries to authenticate against it.

Corinne is a developer for over 15 years now and never go too far from coding. She calls herself open minded and curious and likes to try out new stuff and chat about it. As a polyglot developer she is addicted to clean code. You may have meet her at last years Devoxx or other user group events, because she likes to share and exchange her ideas. Follow her on Twitter @corinnekrych or read her blog to stay up to date with her latest adventures.

Sit back, relax and get a #Coffee+++! Thanks, Corinne for taking the time!

Wednesday, February 11, 2015

Playing with Weld-Probe - See All of your CDI Aspects in One Place

12:00 Wednesday, February 11, 2015 Posted by Test No comments:
, , ,
Weld 3.0.0.Alpha4 was released, while I've been sitting in a conference room at DevConf.CZ. More or less next to Jozef Hartinger (@jozefhartinger) who told me about the new awesome features of this latest release a few minutes before in a shared break. There is one particular feature, that really caught my attention which is the new Weld Probe mechanism.

What Is Weld?
Weld is the reference implementation of CDI: Contexts and Dependency Injection for the Java EE Platform which is the Java standard for dependency injection and contextual lifecycle management and one of the most important and popular parts of the Java EE platform.
Weld is integrated into many Java EE application servers such as WildFly, JBoss Enterprise Application Platform, GlassFish, Oracle WebLogic and others. Weld can also be used in a Servlet-only environment (Tomcat, Jetty) or plain Java SE environment.
Weld 3.x marks the versions in first experimental stages for the next CDI 2.0 version which will be included in Java EE 8. As you already might have guessed, there is no server pre-configured and ready to run any of the upcoming Java EE 8 RIs no matter stage they are in. Particular Weld is way ahead of the crowd and starts to experiment with not even specified features these days. To not disrupt the WildFly 9 team with their improvements, the latest versions are NOT part of it yet.

Test-driving CDI 2.0 with Weld 3.0.0.Alpha4
In order to test Weld today, you need the stable version of WildFly 8.2 and patch it accordingly. If you want to go with latest WildFly 9, there's a patch for that, too. Let's go and download latest WildFly 8.2.0.Final and unzip it to a location of your choice. Next download we need is the Weld 3 Alpha4 Patch for WildFly 8.2. The patch can be applied via the WildFly build in patching mechanism:
$>/WildFly/bin/jboss-cli.bat|sh --command="patch apply /path/to/wildfly-8.2.0.Final-weld-3.0.0.Alph4-patch.zip"
The successful outcome should look like this:
    "outcome" : "success",
    "result" : {}
Now you're ready to start WildFly. Please keep in mind, that this isn't an official patch! So, for now consider this an easy way to update your Weld version. Nothing more. If you want to learn more about patching WildFly take a look at Arun's blog post about patching.
Now it's time to play around with it a bit. A good place to keep an eye on is the new features is the Java EE 8 examples project on GitHub. Still in the very early beginnings, it has at least one new CDI 2.0 example which can be run out of the box. But I am looking at showing you one other new feature of Weld, which is the new Weld-Probe mechanism. So, we need a little web-application first. There are a couple of examples in the weld/core/master branch on Github. One of them is the famous number-guess example.

Weld-Probe Answers All Your CDI Questions 
Why isn’t my field injected? Why isn’t my interceptor triggered? What extensions do third-party libraries register? Have you ever found yourself asking a similar question? Making Weld developer-friendly and helpful in troubleshooting is one of the main goals of the new 3.x version. Today, I am introducing to you a new tool called Weld Probe. Probe is a built-in tool that provides a detailed view into internals of a CDI application. Weld Probe has a web UI and is provided out-of-the-box.

Probe makes it easy to inspect the following CDI aspects. Even more are planned for the future.
  • beans, their properties such as qualifiers, stereotypes and name
  • a graph of bean dependencies
  • observers and producers declared by beans
  • interceptors and decorators bound to a bean
  • extensions
  • information about current contextual instances
  • tracking of invocations and invocation trees
Probe is not meant to replace tools such as a debugger or profiler. It's more about understanding the application and giving a high level view about the inner workings.
Probe consists of a REST API and a default (single-page application) client. Therefore it's only available in a web application. You need to explicitly enable it for development proposes only by adding a servlet initialization parameter org.jboss.weld.development and setting it to true:

Go, build the example and deploy it. Now you can see the number-guess example working. But there's more to it. Just change the application url a bit and add "/weld-probe" to the end of the context: http://localhost:8080/weld-numberguess/weld-probe and you will see this:

Looking over the navigation on top gives you the following areas:

Bean Archives
The initial view shows all the bean archives in your application. You can decide to hide external archives and the accessibility graph gives you a very useful overview for complicated deployments.

Weld can be configured per application through the set of properties. Overview of the Weld configuration properties and their final values (complete reference Weld Configuration).

This view shows all the beans Weld is aware of. Note that  built-in beans and other Java EE specifications that integrate (e.g. for JSR 352: Batch Applications for the Java Platform) are shown as well. There are various filters to find the beans you're interested in. The bean detail shows all important attributes, declared observers and producers, declaring bean for producers, and also dependencies and dependents.

Observer Methods
Discover all the registered observer methods, even those declared on extensions or the ones from other Java EE specifications.

This view lets you inspect the bean instances in application and session contexts.

Invocation Trees
Finally, the invocation tree shows all invocations within the given entry point. Where the entry point is the first business method invocation captured by the monitor in a certain thread.

That was it. If you are missing something or would love to leave comments on existing features, feel free to contribute by filing an issue in the Weld JIRA. Keep in mind, this is still pretty much work in progress and will change and enhance with every new version.

CDI 2.0 Wants You!
But that is not all! CDI 2.0 needs your help and input. There are multiple ways for you to contribute and the specification lead Antoine did a great blog post about what you can do and how to participate. Also feel free to reach out to the Weld community and provide your feedback.

Tuesday, February 10, 2015

NoSQL with Hibernate OGM - Part two: Querying for your data

12:00 Tuesday, February 10, 2015 Posted by Test No comments:
, , ,
After the first final version of Hibernate OGM came out end of January the team has been busy crafting a series of tutorial-style blogs which give you the chance to start over easily with Hibernate OGM. The fist part was all about getting setup and persisting your first entity. In this second part you're going to learn how to query your data. Hibernate OGM will let you get your data in several different ways:
  • using the Java Persistence Query Langage (JP-QL)
  • using the NoSQL native query language of the datastore of your choice (if it has one)
  • using Hibernate Search queries - primarly full-text queries
All of these alternatives will allow you to run a query on the datastore and get the result as a list of managed entities.

Preparing the test class
We are going to add a new class HikeQueryTest. It will populate the datastore with some information about hikes:

    public class HikeQueryTest {

    private static EntityManagerFactory entityManagerFactory;

    public static void setUpEntityManagerFactoryAndPopulateTheDatastore() {
        entityManagerFactory = Persistence.createEntityManagerFactory( "hikePu" );

            EntityManager entityManager = entityManagerFactory.createEntityManager();


            // create a Person
            Person bob = new Person( "Bob", "McRobb" );

            // and two hikes
            Hike cornwall = new Hike(
                "Visiting Land's End", new Date(), new BigDecimal( "5.5" ),
                new HikeSection( "Penzance", "Mousehole" ),
                new HikeSection( "Mousehole", "St. Levan" ),
                new HikeSection( "St. Levan", "Land's End" )
            Hike isleOfWight = new Hike(
                "Exploring Carisbrooke Castle", new Date(), new BigDecimal( "7.5" ),
                new HikeSection( "Freshwater", "Calbourne" ),
                new HikeSection( "Calbourne", "Carisbrooke Castle" )

            // let Bob organize the two hikes
            cornwall.setOrganizer( bob );
            bob.getOrganizedHikes().add( cornwall );

            isleOfWight.setOrganizer( bob );
            bob.getOrganizedHikes().add( isleOfWight );

            // persist organizer (will be cascaded to hikes)
            entityManager.persist( bob );


    public static void closeEntityManagerFactory() {
This methods will make sure that the entity manager factory is created before running the tests and that the datastore contains some data. The data are the same we stored in part 1.
Now that we have some data in place, we can start to write some tests to search for them.

Using the Java Persistence Query Langage (JP-QL)
The JP-QL is a query language defined as part of the Java Persistence API (JPA) specification. It's designed to work with entities and to be database independent.
Taking the entity Hike as an example:
public class Hike {

    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;

    private String description;
    private Date date;
    private BigDecimal difficulty;

    private Person organizer;

    @OrderColumn(name = "sectionNo")
    private List<HikeSection> sections;
      // constructors, getters, setters, ...
A JP-QL query to get the list of available hikes ordered by difficulty looks like this:
SELECT h FROM Hike h ORDER BY h.difficulty ASC
Hibernate OGM will parse this query and transform it into the equivalent one in the native query language of the datastore of your choice. In Neo4j, for example, it creates and execute a Cypher query like the following:
MATCH (h:Hike) RETURN h ORDER BY h.difficulty
In MongoDB, using the MongoDB JavaScript API as a query notation, it looks like this:
db.Hike.find({}, { "difficulty": 1})
If you use JP-QL in your application you will be able to switch between datastore without the need to update the queries.
Now that you have an understanding of what's going on, we can start querying for the data we persisted. We can, for example, get the list of available hikes:

    public void canSearchUsingJPQLQuery() {
        // Get a new entityManager
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        // Start transaction

        // Find all the available hikes ordered by difficulty
        List<Hike> hikes = entityManager
            .createQuery( "SELECT h FROM Hike h ORDER BY h.difficulty ASC" , Hike.class )

        assertThat( hikes.size() ).isEqualTo( 2 );
        assertThat( hikes ).onProperty( "description" ).containsExactly( "Visiting Land's End", "Exploring Carisbrooke Castle" );

If you have used the JPA specification before you will find this code very familiar: it's the same code you would write when working on a relational database using JPA.
You can test this by switching the configuration and dependency between Neo4j and MongoDB: the test will still pass without any change in the code.
The cool thing is that you can use JP-QL queries with datastores which don't have their own query engine. Hibernate OGM's query parser will create full-text queries in this case which are executed via Hibernate Search and Lucene. We will see later how you can do this in more details.
The result of the query is a list of managed entities. This means that changes to the objects will be applied to the data in the database automatically. You also can navigate the resulting object graph, causing lazy associations to be loaded as required.
The support for the JP-QL language is not complete and it might change depending on the backend. We will leave the details to the official Hibernate OGM documentation. At the moment what's supported is:
  • simple comparisons
  • the boolean operators AND, OR, NOT
In case JP-QL is not a good fit for your use case, we will see how you can execute a query using the native language of the backend of your choice.

Using the native backend query language
Sometimes you might decide to sacrifice portablility in favor of the power of the underlying native query language. For example, you might want to benefit from the abilities of Neo4j's Cypher language for running hierarchical/recursive queries. Using MongoDB, let's get the hikes passing through "Penzance":
// Search for the hikes with a section that start from "Penzace" in MongoDB
List<Hike> hikes = entityManager.createNativeQuery("{ $query : { sections : { $elemMatch : { start: 'Penzance' } } } }", Hike.class ).getResultList();
The same code with Neo4j would look like this:
// Search for the hikes with a section that start from "Penzace" in Neo4j
List<Hike> hikes = entityManager.createNativeQuery( "MATCH (h:Hike) -- (:Hike_sections {start: 'Penzance'} ) RETURN h", 
Hike.class ).getResultList();
The important thing to notice is that, like JPA queries, the objects returned by the query are managed entities.
You can also define queries using the annotation javax.persistence.NamedNativeQuery:
name = "PenzanceHikes",
query = "{ $query : { sections : { $elemMatch : { start: 'Penzance' } } } }", resultClass = Hike.class )
public class Hike { ... }
and then execute it like this:
List<Hike> hikes = entityManager.createNamedQuery( "PenzanceHikes" ).getResultList();

Using Hibernate Search queries
Hibernate Search offers a way to index Java objects into Lucene indexes and to execute full-text queries on them. The indexes do live outside your datastore. This means you can have query capabilities even if they are not supported natively. It also offers a few interesting properties in terms of feature set and scalability. In particular, using Hibernate Search, you can off-load query execution to separate nodes and scale it independently from the actual datastore nodes.
For this example we are going to use MongoDB. You first need to add Hibernate Search to your application. In a Maven project, you need to add the following dependency in the pom.xml:
Now, you can select what you want to index:
public class Hike {

    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;

    private String description;

    private Date date;
    private BigDecimal difficulty;

    private Person organizer;

    @OrderColumn(name = "sectionNo")
    private List<HikeSection> sections;
    // constructors, getters, setters, ...
The @Indexed annotation identifies the classes that we want to index, while the @Field annotation specifies which properties of the class we want to index. Every time a new Hike entity is persisted via the entity manager using Hibernate OGM, Hibernate Search will automatically add it to the index and keep track of changes to managed entities. That way, index and datastore are up to date.
You can now look for the hikes to Carisbrooke using Lucene queries. In this example, we will use the query builder provided by Hibernate Search:
public void canSearchUsingFullTextQuery() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();


    //Add full-text superpowers to any EntityManager:
    FullTextEntityManager ftem = Search.getFullTextEntityManager(entityManager);

    // Optionally use the QueryBuilder to simplify Query definition:
    QueryBuilder b = ftem.getSearchFactory().buildQueryBuilder().forEntity( Hike.class ).get();

    // A Lucene query to search for hikes to the Carisbrooke castle:
    Query lq = b.keyword().onField("description").matching("Carisbrooke castle").createQuery();

    //Transform the Lucene Query in a JPA Query:
    FullTextQuery ftQuery = ftem.createFullTextQuery(lq, Hike.class);

    //This is a requirement when using Hibernate OGM instead of ORM:
    ftQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID );

    // List matching hikes
    List<Hike> hikes = ftQuery.getResultList();
    assertThat( hikes ).onProperty( "description" ).containsOnly( "Exploring Carisbrooke Castle" );

The result of the code will be a list of hikes mentioning "Carisbrooke castle" in the description.
Hibernate Search is a very powerful tool with many different options, it would take too long to describe all of them in this tutorial. You can check the reference documentation to learn more about it.

Wrap up
That's all for now. As you have seen, Hibernate OGM provides you with a range of options to run queries against your datastore, which should cover most of your typical query needs: JP-QL, native NoSQL queries and full-text queries via Hibernate Search / Apache Lucene. Even if you have never worked with NoSQL datastores before, you will be able to experiment with them easily.
You can find the complete example code of this blog post (and the previous one) on GitHub. Just fork it and play with it as you like.
Now that you know how to store and find your entities, we will see in the next part of the series how you can put everything inside an application container like WildFly.
We are eager to know your opinion, feel free to comment or contact us, we will answer your questions and hear your feed-back.

Thanks to Gunnar Morling (@gunnarmorling) and Davide D'Alto (@Github: DavidD) for creating this tutorial.

Monday, February 9, 2015

DevConf.CZ Slides and Trip Report

12:00 Monday, February 9, 2015 Posted by Test No comments:
, ,
It's been a short but intense trip. I was invited to speak at the annual DevConf.CZ which happened in Brno, Czech Republic last week. Spanning 3 days, DevConf.cz brings together around 1000 developers, quality engineers, administrators, and users from the Fedora, JBoss, and Red Hat communities. With almost 100 talks and workshops spread over 6 different tracks, DevConf.cz is one of the largest events celebrating free software in the region.
After the keynote by Tim Burke and Mark Little, the attendees had to pick the best from a very wide-spread schedule with many great topics. The fact, that Red Hat has a large office in Brno gives plenty of opportunity to talk to engineers which you normally wouldn't meet in that compilation elsewhere.
If you want to get some more impressions, Google was so nice to compile a story from my trip. Make sure to check it out.

All the talks have been recorded, make sure to check-out the RedHatCzech YouTube Channel. Just for reference, these are the slides of my talks. Thanks to all attendees for your great feedback and attention! Hope to be back next year!

Tuesday, February 3, 2015

Mark Little about Enterprise and IoT

14:00 Tuesday, February 3, 2015 Posted by Test No comments:
, ,
Just a few more weeks to go, until the JavaLand conference is opening it's gates again. The 2015 edition has a packed two-day schedule with awesome speakers and also adds an additional workshop day. Main topic will be "celebrating 20 years of Java" and this is going to be highlighted by two exceptional keynotes. One will be delivered by Oracle's Marcus Lagergren and the other one by Mark Little (@nmcl), who is Red Hat's VP of Engineering and CTO of JBoss Middleware. I got a chance to talk to Mark about his keynote and the general direction about IoT and how everything comes together with enterprise capabilities underneath.

Question: "Mark, you're going to give a keynote at JavaLand this year. Title: 'Enterprise and IoT'. Both well-known buzz words on their own. What made you combine them?"

Answer: "There were a number of things behind this, but I'll concentrate on just one. I'd been doing quite a bit with IoT and constrained devices such as the Raspberry Pi and various Android phones; during that time I'd started to think about how applications more complex than games would do some of the things we take for granted elsewhere, such as reliable messaging, fault tolerance, security, peer-to-peer interactions etc. As the types of applications being developed increase in complexity and importance to people (bank accounts are more important to many people than Flappy Birds), the need for enterprise capabilities will only increase. The IoT developer community is as bright as any developer community, so of course they'd be able to develop solutions to these problems. But I think that if there are perfectly good solutions out there already then we should try to use them first."

Q: "Java EE is bloated and heavyweight. Especially servers are. Many companies are looking at lightweight JVM based solutions. Do we still need Java EE as container models? Why?"

A: "I don't agree that Java EE is bloated and heavyweight. The standard doesn't say you have to build a bloated implementation - that's a design choice. Any container, whether it's something like docker, the JVM or even a Java EE application server, shouldn't really get in your way as a developer but should also offer you the capabilities you need for building and running your applications in a way that is easy to use, understand and manage. If you think about it, your laptop is a container. The operating system is a container. We take these for granted because over the years we've gotten really really good at building them to be unobtrusive. Yet if you look under the covers at your typical operating system, it's doing a lot of hard work for you and offering you capabilities such as process forking and scheduling, that you don't know you need but you do need them. A good Java EE application server should fit into the same category: providing you things such as messaging, transactions, cacheing etc. in an unobtrusive manner and with a minimal footprint."

Q: "Everybody can run anything on IoT hardware these days. The biggest problems are still in other areas, like orchestration and registry and zero configuration. Is there something that you can see in the near future to solve those issues?"

A: "One of the big areas that IoT lacks at the moment is consistency and agreement with the various hardware and software groups involved. I think things such as Project Atomic and Docker could help in some of this with easier packaging of applications, but that doesn't mean much if it only works on a subset of the devices because the industry hasn't agreed on standards. I'm a firm believer that we shouldn't standardise too early, but I also think we should at least recognise the problem and start to think about what it would mean for everyone to come together on an agreed platform. Problems such as orchestration, registry etc. are solvable (we've done it several times in various other waves of technology)."

Q: "How does Security fit into all of the above? I'm afraid, that someday someone can control my house. Isn't it time for a standardized solution? Is Red Hat contributing to any efforts around this already?"

A: "Yes security, or lack thereof, is a worry for many people around IoT. Obviously it's a worry outside of IoT too and we still see examples of security breaches almost on a weekly basis with banks, film companies etc. Security is one of those core features that I think must be in any computing platform, whether it's local or distributed. Standards really help here for similar reasons to what we've previously discussed: if I'm adding new devices to my home network I really want to be sure they're secured together and I also don't want to worry about learning multiple security protocols."

Thank you Mark for taking the time to answer my questions! I'm looking forward to seeing you in JavaLand. And for the fellow visitors: There's still time to register

Monday, February 2, 2015

Developer Interview (#DI13) Vlad Mihalcea (@vlad_mihalcea) about High Performance Hibernate

12:00 Monday, February 2, 2015 Posted by Test No comments:
, ,
I'm happy to announce the availability of the next developer interview. The lucky number 13 was caught by Vlad Mihalcea (@vlad_mihalcea). He is a developer since more than 10 years and been designing and developing software reaching from common enterprise applications to high performance batch and transaction processing systems.
Whenever he finds something interesting, he shares it on his blog. As a strong believer in Open Source Software he advocates for everybody to get involved in supporting it. There are plenty of things to do, ranging from updating documentation, to reporting issues or sending pull-requests.

We talked  about his free Hibernate master class training, that he is continuously publishing on his blog.

Sit back, relax and get a #Coffee+++! Thanks, Vald for taking the time!