Java EE and general Java platforms.
You'll read about Conferences, Java User Groups, Java EE, Integration, AS7, WildFly, EAP and other technologies.

Friday, March 6, 2015

Developer Interview (#DI16) with Veer Muchandi (@VeerMuchandi) Docker, OpenShift Enterprise v3 and Kubernetes

13:00 Friday, March 6, 2015 Posted by Markus Eisele
, , ,
TGIF! And time for a new episode in my developer interview series. With everybody going crazy about containers, Docker and such I decided to talk to someone who once was a middleware/Java EE guy and let him introduce all the latest news and stuff around OpenShift Enterprise v3.

Veer Muchandi is a Senior Middleware Specialist/Architect at RedHat, an open source enthusiast specifically in OpenShift PaaS and Java EE. Veer is also an Enterprise Architect with broad experience with multiple technologies ranging from legacy mainframes to bleeding edge cloud technologies.

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


Some Background:
OpenShift 3.x will incorporate a number of significant model changes to better align the PaaS with the evolving development and operational ecosystems - leveraging the Docker container runtime and image model, the Google container management model, and the Mesos scheduling and execution framework. The upstream project, OpenShift Origin is in master and everybody is waiting for the first beta builds. Please NOTE: OpenShift is in alpha and is not yet intended for production use. However they welcome feedback, suggestions, and testing as we approach our first beta. So, if you get a chance to test-drive it: Go for it!

Architecture Overview:


Wednesday, March 4, 2015

The Road To Awesome - Welcome JBoss Champions Program

09:16 Wednesday, March 4, 2015 Posted by Markus Eisele
,
Today, Arun announced the creation of the JBoss Champions Program in Red Hat. JBoss Champions is a selected group of community members who are passionate advocate of JBoss technologies under a program sponsored by Red Hat. JBoss Champions use a variety of JBoss technologies and actively share their deep technical expertise about it in the community, within their company and their customers or partners. This could be done in forums, blogs, screencasts, tweets, conferences, social media, whitepapers, articles, books, and other means.

I am very happy to see some friends and familiar faces among the founding members:
  1. Adam Bien (@AdamBien)
  2. Alexis Hassler (@alexishassler)
  3. Antonin Stefanutti (@astefanut)
  4. Antonio Goncalves (@agoncal)
  5. Bartosz Majsak (@majson)
  6. Francesco Marchioni (@mastertheboss)
  7. Geert Schuring (@geertshuring)
  8. Guillaume Scheibel (@g_scheibel)
  9. Jaikiran Pai
  10. John Ament (@JohnAment)
  11. Mariano Nicolas De Maio (@marianbuenosayr)
  12. Paris Apostolopoulous (@javapapo)
My congratulations to all of you!

If you want to stay updated with all the latest tweets and rumblings, make sure to subscribe to the @JBossDeveloper/jboss-champions list on twitter.

If you know anyone, who could fit the high profile of a JBoss Champion, don't hesitate to nominate him or her. Find all the requirements and a contact email on the official Champions website.

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 Markus Eisele
, , ,
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 Markus Eisele
, ,
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 Markus Eisele
, ,
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 Markus Eisele
, ,
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 Markus Eisele
,
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());
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }

    public static class SingletonAccessRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println(BrokenSingleton.get());
        }
    }
}

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.

The DSL
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
METHOD get
AT ENTRY
IF true
DO traceln("entered get-Method")
ENDRULE

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

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>
 ENDRULE


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

__-javaagent:<BYTEMAN_HOME>/lib/byteman.jar=script:check.btm__

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

__-javaagent:<BYTEMAN_HOME>/lib/byteman.jar=script:appmain.btm,boot:<BYTEMAN_HOME>/lib/byteman.jar__

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
READ:
Stack trace for thread Thread-0
de.codepitbull.byteman.BrokenSingleton.get(BrokenSingleton.java:14)
de.codepitbull.byteman.BrokenSingletonMain$SingletonAccessRunnable.run(BrokenSingletonMain.java:20)
java.lang.Thread.run(Thread.java:745)

READ:
Stack trace for thread Thread-1
de.codepitbull.byteman.BrokenSingleton.get(BrokenSingleton.java:14)
de.codepitbull.byteman.BrokenSingletonMain$SingletonAccessRunnable.run(BrokenSingletonMain.java:20)
java.lang.Thread.run(Thread.java:745)


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
METHOD get
AT ENTRY
IF NOT isRendezvous("rendezvous", 2)
DO createRendezvous("rendezvous", 2, true);
traceln("rendezvous created");
ENDRULE

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
METHOD get
AFTER READ BrokenSingleton.instance
IF isRendezvous("rendezvous", 2)
DO rendezvous("rendezvous");
ENDRULE

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_

<dependency>
    <groupId>org.jboss.byteman</groupId>   
    <artifactId>byteman-submit</artifactId>
    <scope>test</scope>
    <version>${byteman.version}</version>
</dependency>

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

@RunWith(BMUnitRunner.class)
public class BrokenSingletonTest
{
  @Test
  @BMScript("check.btm")
  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 Markus Eisele
, , , , ,
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 Markus Eisele
, , ,
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.
$>/WildFly/bin/standalone.bat|sh
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:
 <context-param> 
        <param-name>org.jboss.weld.development</param-name> 
        <param-value>true</param-value> 
    </context-param> 

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.

Configuration
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).

Beans
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.

Contexts
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 Markus Eisele
, , ,
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;

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

            EntityManager entityManager = entityManagerFactory.createEntityManager();

            entityManager.getTransaction().begin();

            // 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 );

            entityManager.getTransaction().commit();
           entityManager.close();
    }

    @AfterClass
    public static void closeEntityManagerFactory() {
        entityManagerFactory.close();
    }
}
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:
@Entity
public class Hike {

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

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

    @ManyToOne
    private Person organizer;

    @ElementCollection
    @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:

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

        // Start transaction
        entityManager.getTransaction().begin();

        // 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 )
            .getResultList();

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

        entityManager.getTransaction().commit();
        entityManager.close();
    }
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
  • IS NULL and IS NOT NULL
  • the boolean operators AND, OR, NOT
  • LIKE, IN and BETWEEN
  • ORDER BY
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:
@Entity
@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:
<dependencies>
    ...
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-orm</artifactId>
    </dependency>
    ...
</dependencies>
Now, you can select what you want to index:
@Entity
@Indexed
public class Hike {

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

    @Field
    private String description;

    private Date date;
    private BigDecimal difficulty;

    @ManyToOne
    private Person organizer;

    @ElementCollection
    @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:
@Test
public void canSearchUsingFullTextQuery() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    entityManager.getTransaction().begin();

    //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" );

    entityManager.getTransaction().commit();
    entityManager.close();
}
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.