Thursday, July 31, 2014

Hibernate Statistics with Hawtio and Jolokia

A huge part of enterprise Java deals with data. Among all the different ways of working with data in enterprise settings, there is still the proven and widely taught approach to use O/R mapping of any kind. The JPA standard makes this comparably easy to use for everybody and it should also be portable. But let's not talk about migration details. The biggest drawback of O/R mapping is, that a developer tend to lose contact with what's happening on the database or even to which exact SQL statements get issued against it. This is the number one reason that those projects run into performance issues. If you're there, you need to analyze the root causes and drill down to the problems. I recently found a nice feature of Hibernate which makes this comparably easy.

Available Statistics And Ways To Get Them.
Hibernate up to 3.5.x ships with a statistics and metrics API that allows you to figure out a lot about what is happening under the covers. All available counters are described in the Statistics interface API, in three categories:
  • Metrics related to the general Session usage, such as number of open sessions, retrieved JDBC connections, etc.
  • Metrics related to the entities, collections, queries, and caches as a whole (aka global metrics).
  • Detailed metrics related to a particular entity, collection, query or cache region.
For example, you can check the cache hit, miss, and put ratio of entities, collections and queries, and the average time a query needs. Be aware that the number of milliseconds is subject to approximation in Java. Hibernate is tied to the JVM precision and on some platforms this might only be accurate to 10 seconds.

Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection, cache region, etc.). You can access the metrics of a particular entity, collection or cache region through its name, and through its HQL or SQL representation for queries. Please refer to the Statistics, EntityStatistics, CollectionStatistics, SecondLevelCacheStatistics, and QueryStatistics API Javadoc for more information.

All you have to do is enable statistics for the session factory you're interested in and retrieve the statistics to analyze them. There are plenty of examples out there how to use this feature with Spring. The reason is pretty simple: Spring comes with a legendary MBeanExporter which exposes JMX MBeans as Java Objects. And guess what: Hibernate Statistics provides an easy way of exposing them through JMX. But there is no need to use Spring if you just put together some more RedHat magic :)
You basically have two different ways of enabling the statistics in your configured setting. The easiest way is to add a property to your persistence-unit configuration:
   <property name="hibernate.generate_statistics" value="true"/>
But it is also possible to enable them manually. More details on how to do that can be found on the community wiki and in the performance-monitoring section in the Hibernate documentation.

Enabling and Exposing Statistics By Example
I created a little example standalone Hibernate application with two entities and a main class which is working with hibernate and initializing everything you need to know. Get your hands on it instantly by forking it on GitHub. Here is the little walk-through:
There are the two mandatory entities (Department and Employee) and the META-INF/persistence.xml. This is the basic setting. There is not much magic in here. You can see where to enable the statistics (potentially) in the persistence.xml. The example enables them in the main class JpaTest. But let's start at the beginning. The main method performs the following steps in order:
  1. Create the EntityManager to use.
  2.  Register the Statistics Mbean we need.
  3. Initialize the Jolokia Server to expose JMX via JSON for Hawtio
  4. Does something with the entities.
The magic starts in step two which is in the registerHibernateMBeans(EntityManager manager) method. It get's hand on the PlatformMBeanServer, registers the relevant Hibernate JMX Mbean, set's the Session Factory in which we're interested in to it and enables the statistics. That is easy. Now you have a JMX MBean "Hibernate" with the attribute "statistics" registered. If you have access to the server via JConsole or Mission Control or VisualVM you can simply connect to the process and browse through the statistics:

Hibernate MBean in JConsole
In production environments this typically isn't possible at all. So you would need to find a way to access this via http/https. This is where I found it handy to try out Hawtio as a a modular web console for managing your Java stuff. Burned down to the basics it is a web-console with plugins. It has a ton of plugins and can be customized and extended to fit your needs. Today we're looking at a very simple plugin, the JMX plugin. It gives you a raw view of the underlying JMX metric data, allowing access to the entire JMX domain tree of MBeans. But in order to make this happen, we first need to find a way to expose the JMX features to Hawtio. This is where Jolokia comes in. There is a JVM agent in it who can expose JMX MBeans via JSON. All you have to do is to init and start the server like this:

JolokiaServerConfig config = new JolokiaServerConfig(new HashMap<String, String>());
JolokiaServer jolokiaServer = new JolokiaServer(config, true);
jolokiaServer.start();

Now you're ready to try out the Hawtio console. Have a look at the quickstart to see what is possible. For this example I just use the Google Chrome Extension which you just have to download and drag into your extensions page in Chrome. This looks like:

Hawtio Extension in Chrome
If you configure "localhost", "8778" and path "jolokia" you're all set to start browsing your results. After you click "connect" you can look through the dashboard or switch to the JMX view and navigate to the Hibernate MBean:

Browsing JMX MBeans with Hawtio
There is a more comprehensive introduction to Hawtio by Stan Lewis from DevNation 2014 waiting for you to watch it:

That was the short example. Go ahead and look at the GitHub source-code and feel free to look into Hawtio a bit more:

Tuesday, July 29, 2014

Getting started with SwitchYard 2.0.0.Alpha1 on WildFly 8.1.0.Final

I've been sticking my head into some hot RedHat technologies lately and among the many interesting parts I found SwitchYard. Without being disrespectful towards everybody wrapping their heads around SOA and service oriented architectures in the past, this has always been kind of weird to me as a Java EE developer.

In the past I've been building component oriented applications with what I had at hand. Mostly driven by the features available in the Java EE standard to be "portable" and easy to use. Looking back this has been a perfect fit for many customers and applications. With an increasing demand for highly integrated applications which use already available services and processes from all over the place (departmental, central or even cloud services) this approach starts to feel more and more outdated. And this feel does not come from a technology perspective but from all the requirements around it. Having this in mind this post is the starting point of a series of how-to's and short tutorials which aim to showcase some more diverse ways of building (Java EE) applications that fit better into today's requirements and landscapes.

What is SwitchYard?
It is a component-based development framework for integration applications using the design principles and best practices of Service Oriented Architecture. If you're expecting kind of a full-blown fancy BPMN/SOA buzz-word suite you're off by a bit. This is for developers and should make it comparably straight forward to use. It's been around for a while now and starting with latest 2.0.0.Alpha1 it is compatible with WildFly 8. Reasons enough for me to get you excited about it.

Installing SwitchYard into latest WildFly 8.1.0.Final
Download both, the switchyard-2.0.0.Alpha1-wildfly bundle and WildFly 8.1.0.Final from the project websites. Install WildFly 8 by unzipping it into a folder of your choice (e.g. D:\wildfly-8.1.0.Final\). Now unzip the SwitchYard bundle into the WildFly folder. Depending on the zip utility in use, you may be prompted whether existing files should be replaced.  Answer yes/all for all files being unzipped.
It's an alpha so you have to tweak the configuration a bit because of SWITCHYARD-2158. Open "JBOSS_HOME/standalone/configuration/standalone.xml" and search for "org.switchyard.component.camel.atom.deploy.CamelRSSComponent" and change the package from "atom" to "rss". Now go ahead and start the server with "JBOSS_HOME/bin/standalone.sh/.bat".
If everything worked correctly you should see a message like this:
09:18:25,857 INFO  [org.jboss.as] (Controller Boot Thread) JBAS015874: WildFly 8.1.0.Final "Kenny" started in 3712ms - Started 210 of 259 services (81 services are lazy, passive or on-demand)

Building and Deploying the Bean Service Quickstart
If you want to get your hands dirty you can easily start with the packaged applications in the "JBOSS_HOME/quickstarts/" directory of the distribution. A simple one is the bean-service example. It makes use of one of the core components of SwitchYard, the Bean Component. It allows Java classes (or beans) to provide and consume services. And therefore you can implement a service by simply annotating a Java class or consume one by injecting a reference directly into your Java class.
And because the Bean Component is a standard CDI Extension, there is no need to learn a new programming model to use it. It's just a standard CDI Bean with a few more annotations.
For existing Java EE applications this means, that you can expose existing CDI-based beans in your application as services to the outside world or consume services within your bean by just adding some more annotations.
First things first. We need to tweak around a bit in the project pom.xml to make this work. Go to the build section and replace the "jboss-as-maven-plugin" with the latest version of the
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>1.0.2.Final</version>
Now run "mvn package" to download all dependencies and execute the tests. It should just work fine and state:
Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
Let's deploy it to our WildFly instance by issuing "mvn -Pdeploy install". The WildFly console finally lets you know about the successful execution:
10:19:44,636 INFO  [org.jboss.as.server] (management-handler-thread - 1) JBAS018559: Deployed "switchyard-bean-service.jar" (runtime-name : "switchyard-bean-service.jar")

Quick Test For The Application
A very quick test is to execute mvn exec:java which will execute the BeanClient class and fire a SOAP request towards the deployed service. The output should be:
SOAP Reply:
<soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><env:header xmlns:env="http://www.w3.org/2003/05/soap-envelope"></env:header><soap:body><ord ers:submitorderresponse="" xmlns:orders="urn:switchyard-quickstart:bean-service:1.0
"><orderack><orderid>PO-19838-XYZ</orderid><accepted>true</accepted><status>Orde
r Accepted [intercepted]</status></orderack></ord></soap:body></soap:envelope>

That is it for today. The next parts will examine the sample application in a bit more detail and install the tooling and introduce you to various other components. If you can't wait, check out:

Wednesday, July 9, 2014

Win a free eBook copy of WildFly Performance Tuning

This is a seriously good start into a new area. I thought you might be interested in winning Packt's latest book about WildFly Performance Tuning. So, this is the contest to make it happen.
I have 2 eBook copies of WildFly Performance Tuning to be given away to two (2) lucky winners.

Here are the Rules
- The contest is running from today (07/09/14, 5:45a UTC) to next Wednesday (07/16/14, 5:45a UTC).
- Answer the three questions below correctly about WildFly and put down a comment on this blog with the answers.
- If more than three correct answers are posted, I will let my daughters draw the two winners.

The Questions to Answer
1) When was WildFly 8.1.0.Final released?
2) What is the name of the Red Hat project, that offers help with Java EE application migration?
3) Who wrote the WildFly Plugin for NetBeans 8?

Content of the Book
Chapter 1, The Science of Performance Tuning, talks about what performance tuning is all about and how it can be applied within an organization.
Chapter 2, Tools of the Tuning Trade, introduces some useful Open Source tools to use when performance tuning anything covered in this book.
Chapter 3, Tuning the Java Virtual Machine, covers what the engine of Java is and how to tune it as well as all other Java-based applications.
Chapter 4, Tuning WildFly, explains what can be tuned in the WildFly
Application Server.
Chapter 5, EJB Tuning in WildFly, talks about how Enterprise JavaBeans can be tuned.
Chapter 6, Tuning the Persistence Layer, covers how to design an effective database as well as how to tune JPA and queries.
Chapter 7, Tuning the Web Container in WildFly, explores Undertow—the blazingly fast, new web container in WildFly—and discusses how it can be tuned to become even better.
Chapter 8, Tuning Web Applications and Services, covers numerous tuning tricks and tips surrounding the web applications and services based on Java EE.
Chapter 9, JMS and HornetQ, explains how JMS works and can be tuned in HornetQ, the JMS provider of WildFly.
Chapter 10, WildFly Clustering, explores tuning in a clustered WildFly, HornetQ, and Java EE components.

About the Author
Anders Welén embraced the object-oriented techniques of the Java language early in life, and later evolved to Java Enterprise specifications. As a true believer and evangelist of Open Source, he naturally discovered the JBoss Application Server,
which led to years of providing expert consultation, training, and support for the JBoss and Java EE infrastructures.

Good Luck everybody!

Friday, July 4, 2014

Farewell msg systems ...

.. and thank you for amazing 14 years. It's true: I've been within the msg group for an incredibly long time  and have been working in the Java/Java EE space almost all of it. Next Friday (07/11/14) will be my last day. Now it is time to move on.
I've been working with customers and internal Java EE projects all over the place, blogged, authored articles and have been speaking at conferences a lot. The passion for Java and mostly Java EE related topics is burning even hotter these days.

I'm more than proud to announce that as of calendar week 29 (7/14/14), I'll be joining Red Hat as Developer Advocate in Arun Gupta's team.
My main topics are technologies related to Red Hat JBoss Middleware including WildFly and the broader JBoss technology stack. So, I will be blogging, speaking and spreading the word about the most important and relevant parts in today's Enterprise Java world. There's no need to be afraid of this blog turning into a sales slide-deck. As you're used to, I'll mostly stick to technology and conference reports. So you don't even have to update your bookmarks as this blog is here to stay.

So, if you have ideas, requests, wishes or if you're just hungry for something new, just give me a ping on @myfear or leave a comment in this blog and I'll be more than happy to respond. Just reach out to me.

Arun and Markus at JavaLand 2014

"Mad Matter: "Have I gone mad?"
Alice: "I'm afraid so. You're entirely bonkers. But I'll tell you a secret. All the best people are.”
Lewis Caroll, Alice no País das Maravilhas

Tuesday, June 24, 2014

Java EE 8 - Deliver More Apps to More Devices

If there's one thing I dislike about summer, it is the fact that there isn't much news to share or talk about. Who ever decided to put the Java Day Tokyo into this boring time of the year did a pretty good job and gave me an opportunity to write a blog post about new and upcoming Java EE 8 specification enriched with some more thoughts and pointers.
As announced on the Java EE 7 EG Mailinglist beginning of June the new EE 8 JSR is going to be filed shortly (before JavaOne).

Contents of EE 8
Unlike the first version of EE 7 which was totally dominated by the word "cloud" and later re-aligned with the hard facts, this new Java EE version will basically stick to three different areas of improvement.

  • HTML 5 / Web Tier Enhancements
  • CDI Alignment / Ease-of-Development
  • Cloud Enablement

All three can be seen as a continued evolution of what EE 7 already delivered and there is no real surprise in it at all. Head over to The Aquarium to read more about the details.

Cameron Purdy about EE 8 at Java Day Tokyo 2014

Hidden Gems - What might come up at JavaOne
The Java Day Tokyo was held recently and with Cameron Purdy as a keynote speaker about Java EE and it's general direction (mp4 download, 363MB) this probably was one of the first chances to see, what will be the overall story for JavaOne with regards to the platform. As Oracle should have learned the Java community isn't interested in big and unpleasant surprises. Strategic directions are communicated and prepared a bit more carefully. We all have seen and heard about the IoT hype and the efforts everybody puts in it. This obviously also seems to have some outreach into Java EE. Beside the general topics and contents of EE 8 the Purdy keynote also contained a slide titled "Powering Java Standard in the Cloud - Deliver Mode Apps to More Devices with Confidence". 

Java Standards in the Cloud.
And yes, you are correct about thinking that this is EE 7 coverage. It actually is. But at least for me it is the first time, that individual features have been isolated from individual technical specifications and put into a complete, strategic picture outlining use-cases in the enterprise. It will be interesting to see, if there is something more like this to be shown at JavaOne and how much IoT we will see in EE 8 when it finally hits the road.