Skip to main content


Showing posts from 2011

Enabling JMX in Hibernate, EhCache, Quartz, DBCP and Spring

Continuing our journey with JMX (see: ...JMX for human beings ) we will learn how to enable JMX support (typically statistics and monitoring capabilities) in some popular frameworks. Most of this information can be found on project's home pages, but I decided to collect it with few the addition of some useful tips. Hibernate (with Spring support) Exposing Hibernate statistics with JMX is pretty simple , however some nasty workarounds are requires when JPA API is used to obtain underlying SessionFactory class JmxLocalContainerEntityManagerFactoryBean() extends LocalContainerEntityManagerFactoryBean { override def createNativeEntityManagerFactory() = { val managerFactory = super.createNativeEntityManagerFactory() registerStatisticsMBean(managerFactory) managerFactory } def registerStatisticsMBean(managerFactory: EntityManagerFactory) { managerFactory match { case impl: EntityManagerFactoryImpl => val mBean = new StatisticsService(); mBean.setStatistic

Spring pitfalls: transactional tests considered harmful

One of the Spring killer-features is an in-container integration testing . While EJB lacked this functionality for many years (Java EE 6 finally addresses this, however I haven't, ekhem , tested it), Spring from the very beginning allowed you to test the full stack, starting from web tier, through services all the way down to the database. Database is the problematic part. First you need to use in-memory self-contained database like H2 to decouple your tests from an external database. Spring helps with this to a great degree, especially now with profiles and embedded database support . The second problem is more subtle. While typical Spring application is almost completely stateless (for better or worse), database is inherently stateful. This complicates integration testing since the very first principle of writing tests is that they should be independent on each other and repeatable. If one test writes something to the database, another test may fail; also the same test may

Spring pitfalls: proxying

Being a Spring framework user and enthusiast for many years I came across several misunderstandings and problems with this stack. Also there are places where abstractions leak terribly and to effectively and safely take advantage of all the features developers need to be aware of them. That is why I am starting a Spring pitfalls series . In the first part we will take a closer look at how proxying works. Bean proxying is an essential and one of the most important infrastructure features provided by Spring. It is so important and low-level that for most of the time we don't even realize that it exists. However transactions, aspect-oriented programming, advanced scoping, @Async support and various other domestic use-cases wouldn't be possible without it. So what is proxying ? Here is an example: when you inject DAO into service, Spring takes DAO instances and injects it directly. That's it. However sometimes Spring needs to be aware of each and every call made by s

Logging exceptions root cause first

The 0.9.30 release of Logback logging library brings new awesome feature: logging stack traces starting from root (innermost) exception rather than from the outermost one. Of course my excitement has nothing to do with the fact that I contributed this feature... To paraphrase Cecil B. de Mille: “ The way to make a blog post is to begin with a stack trace and work up to a climax ” - here it goes: The details aren't important yet, but from 100ft view you can see long stack trace with several exceptions wrapping each other ( causing ). We'll go back to this stack trace, but first some basics. If you throw an exception it will be logged in a way showing how the stack was looking in the moment when the exception was from. At the very bottom you will either see static main() or proceeded by methods invoked up to the first stack trace line indicating the place where the actual exception was thrown. This is very convenient since you can see the whole control

The evolution of Spring dependency injection techniques

Looking back at the history of Spring framework you will find out that the number of ways you can implement dependency injection is growing in every release. If you've been working with this framework for more than a month you'll probably find nothing interesting in this retrospective article. Nothing hopefully except the last example in Scala, language that accidentally works great with Spring. First there was XML [ full source ]: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> <bean id="foo" class="com.blogspot.nurkiewicz.Foo"> <property name="bar" ref="bar"/> <property name="j

What features of Java have been dropped in Scala?

Despite more complex and less intuitive syntax compared to Java, Scala actually drops several features of Java, sometimes for good, other times providing replacements on the standard library level. As you will see soon, Scala isn't a superset of Java (like Groovy) and actually removes a lot of noise. Below is a catalogue of the missing features . break and continue in loops Every time I see code like this: while(cond1) { work(); if(cond2) continue; rest(); } I feel as if it has been written by a guy who truly misses the times when goto wasn't yet considered harmful. Hands up who finds this version more readable:

EJB 3.1 Cookbook by Richard Reese review

Recently I received a copy of EJB 3.1 Cookbook (courtesy to Packt Publishing ) with a kind request to prepare a review. And since I have just got my new Kindle reader , this was a great opportunity to test them together. EJB 3.1 Cookbook by Richard Reese aims to provide “ a collection of simple but incredibly effective recipes ” – quoting the subtitle. The book covers expected part of the EJB stack: session and message-driven beans, JPA, security, interceptors, timer service and web services. Contents are organized around so called recipes – short (no more than three pages long) micro-chapters focused on one specific issue. This is the most advantageous feature of this publication: all recipes all self-contained most of the time, so one can jump between them and apply the most suitable in given scenario. This makes the book suitable for both the beginners, which should read it from cover to cover and slightly more experienced developers. However the latter ones will prob

Poor man's CRUD: jqGrid, REST, AJAX, and Spring MVC in one house

More than two years back I wrote an article on how two implement elegant CRUD in Struts2 . Actually I had to devote two articles on that subject because the topic was so broad. Today I have taken much more lightweight and modern approach with a set of popular and well established frameworks and libraries. Namely, we will use Spring MVC on the back-end to provide REST interface to our resources, fabulous jqGrid plugin for jQuery to render tabular grids (and much more!) and we will wire up everything with a pinch of JavaScript and AJAX. Back-end is actually the least interesting part of this showcase, it could have been implemented using any server-side technology capable of handling RESTful requests, probably JAX-RS should now be considered standard in this field. I have chosen Spring MVC without any good reason, but it's also not a bad choice for this task. We will expose CRUD operations over REST interface; the list of best selling books in history will be our domain model (c

Enabling load balancing and failover in Apache CXF

A while ago we've faced the requirement of load-balancing web services clients based on Apache CXF . Also the clients should automatically fail-over when some of the servers are down. To make it even worse, the list of servers target addresses was to be obtained from external service and updated at runtime. Eventually we ended up with home-grown load-balancing micro-library (ESB/UDDI/WS-Addressing seemed like an interesting alternatives, but they were an overkill in our situation). If we only knew Apache CXF already supports all these features (almost) out of the box? Don't blame us though, only reference to this feature points to a very poor documentation page (if you call 404 “poor”). If it's not in official documentation, I would expect to find it in Apache CXF Web Service Development book – unfortunately, bad luck there as well. But hey, isn't exploring such features yourself even greater fun? This is the client configuration we are starting with: <beans xm

MongoDB and recording appenders for Logback

Today I am giving you two new appenders for Logback : one for MongoDB and one which I called recording appender . Just as a reminder, appenders (both in Log4J and Logback) are an abstraction of your application logs destination. The most common are file and console appenders, followed by several others built-in. MongoDB appender is pretty straightforward, so I will start by describing the recording appender. Recording appender As you already know , one of the biggest benefits of using logging frameworks are logging levels. By carefully choosing levels for each logging statement we can easily filter which logs should be present in our log files and which shouldn't. Also we can apply different logging strategies for different environments. This is in theory. In practice we often face the choice between: log everything just in case and handle gigabytes of meaningless log files or log only warnings and errors but when they actually occur, they are meaningless as well, lacking im

Jolokia + Highcharts = JMX for human beings

Java Management Extensions ( JMX ) is a well established, but not widespread technology allowing to monitor and manage every JVM. It provides tons of useful information, like CPU, thread and memory monitoring. Also every application can register its own metrics and operations in so called MBeanServer . Several libraries take advantage of JMX: Hibernate , EhCache and Logback and servers like Tomcat or Mule ESB , to name a few. This way one can monitor ORM performance, HTTP worker threads utilization, but also change logging levels, flush caches, etc. If you are creating your own library or container, JMX is a standard for monitoring, so please don't reinvent a wheel. Also Spring has a wonderful support for JMX . If this standard is so wonderful, why aren't we using it all day long? Well, history of JMX reaches the dark ages of J2EE. Although the specification isn't that complicated, there are at least two disadvantages of JMX effectively discouraging people from using it

Tenfold increase in server throughput with Servlet 3.0 asynchronous processing

It is not a secret that Java servlet containers aren't particularly suited for handling large amount of concurrent users. Commonly established thread-per-request model effectively limits the number of concurrent connections to the number of concurrently running threads JVM can handle. And because every new thread introduces significant increase of memory footprint and CPU utilization (context switches), handling more than 100-200 concurrent connections seems like a ridiculous idea in Java. At least it was in pre-Servlet 3.0 era. In this article we will write scalable and robust file download server with throttled speed limit. Second version, leveraging Servlet 3.0 asynchronous processing feature, will be able to handle ten times bigger load using even less threads . No additional hardware required, just few wise design decisions. Token bucket algorithm Building a file download servers we have to consciously manage are our resources, especially network bandwidth. We don't w

Spring framework without XML... At all!

First, there was EJB 2.1 with countless XML files all over. It won't be such a big exaggeration to say that for every line of business code you had to create at least 10 lines of framework code and two pages of XML. Local and remote interfaces, manual JNDI lookup, triply nested try-catches, checked RemoteExceptions everywhere... this was enterprise . There were even tools to generate some of this boilerplate automatically. Then couple of guys came and created Spring framework . After being forced to cast by obscure PortableRemoteObject.narrow() it was like taking a deep breath of fresh air, like writing poetry after working in coal mine. Time went by (BTW do you remember how many years ago was the last major JRE release?) and Sun learnt their lesson. EJB 3.0 was even simpler compared to Spring, XML-free, annotations, dependency injection. 3.1 was another great step toward simplicity, being more and more often compared to Spring. Logically current state of the art EJB specificat

Activiti processes and executions explained

I was interested in Activiti process engine long before it reached its first stable 5.0 version. Now, when 5.1 was released, I decided to play a bit with this framework, especially paying attention to Spring and JUnit support. But one of the first impediments encountered was the difference between process instance and execution, as well as between sub process and call activity. I am hoping after reading this article you won't encounter the same problems when starting with Activiti. As you know, even a monkey can learn a new Java framework after reading documentation, but the real fun comes when you meet the technology by studying its source code (often tracking bugs and looking for solutions). And I must admit that Activiti code-base was a pleasure to read, nicely structured and designed. For some reason it is not deployed to Alfresco's repository , so to take full advantage of your BPMN journey, start by: svn co c