Archive for ‘Uncategorized’

April 12, 2009

Introducing JmxLogger – Real-time Application Log Monitoring with JMX

For past month, I have been working (on/off) on JmxLogger, a logging API which lets you monitor your Java Logging or Log4J application log events in real-time using JMX. I have had the idea for a while, but decided to finally capture it as project. So, here it is.

http://code.google.com/p/jmx-logger/

JmxLogger
JmxLogger makes it easy to broadcast your Java Logging or your Log4J log events as JMX notifications. As such, you can easily monitor your application’s activity logs in real-time. Using familiar logging API and configuration mechanism (i.e. log4j.xml or Java Logging properties file), developers can quickly integrate realtime application log monitoring into their existing deployed code. All it takes is a logging configuration change.

The JmxLogger API provides a Java Logging Handler and a Log4J Appender which can be used to integrate between your favorite logging framework and JMX. JmxLogger hides the complexity of dealing with JMX. You simply configure your logging framework as you normally do, and that’s it. You are ready to broadcast your logging events as JMX notification events.

Features

  • Support for Java Util Logging API
  • Support for the Log4J logging API
  • Easy integration with your favorite logging framework
  • No coding required, simply configure your logging framework to get started.
  • Specify and control the level of event to broadcast
  • Monitor event through a console or listener scripts
  • Realtime monitoring of your application activity logging via JMX.

Getting Started

  • Download the jar (generic or with log4j support)
  • Add jar to your classpath (in case of Log4J, you will need log4j.jar on your classpath)
  • Configure your favorite logging framework
  • Use JMX console (JConsole or VisualVM) to monitor your log actvities.

JmxLogger Events

When you log your application events using either Java Logging or Log4J (see project site for more detail), your log events will get routed to the JmxLogger Java Logging Handler or Log4J Appender defined in your application’s logging configuration file.

Below you can see a configuration that sends log messages to the Console and a JmxLogger Logging Handler.

Using a command-line Console you can see your log message messages as they are logged in your application.

The same log events are also emitted as JMX notifications. Using JConsole, you can see these events as they are logged in your application in real-time.

That’s it! You have seen how JmxLogger can effortlessly integrate JMX and the two standard logging API’s available (Java Logging and Log4J).

March 30, 2009

Why Modularity Matters

In my previous blog, I provided a summarized view of what OSGi is and how it impacts Java developers. I got some interesting feedback. So, in this blog entry, I want to take a detour to examine modularity itself and its importance in creating robust systems that can scale in size and functionality. This blog post does not discuss any specific Java technologies or platform directly. However, it looks at how modular design has affected industries as diverse as manufacturing to software engineering. Future posts will continue to look at OSGi and other modularization technologies.

Modularity
In the Merriam-Webster dictionary, being modular is defined as “… composed of standardized, self-contained units for easy construction and flexible use …” The notion of modularity is universal and has found usage in process (policy), manufacturing, business, finance, engineering, etc. Those who study the natural sciences have presented arguments about the modularity of nature. Biological studies have shown that the evolution of complex organisms are due in part to functional modularity (composition of smaller independent components with clear bound & functions) and behavioral modularity (having traits and attributes that can evolve independently). To stay closer to the discernible realms, let’s examine how contemporary usage of modularity and has affected our modern lives.

Product manufacturers figured out the way to increase output, increase quality, and reduce cost pressures was in modularity. At the turn of last century, industrialist Henry Ford introduced the notion of modularity in his assembly line with standardized and interchangeable automobile parts. He was able to reduce his production cycles and costs to achieve mass production of his Model-T automobiles.

The adoption of modular architecture, not processor speed, has been argued to be the quintessential force behind rapid growth and adoption of computing technologies. Today’s hardware, while ever decreasing in size, offers cheap information processing power that has permeated through all industries. Achieving such complex and powerful systems has been possible through the use of modularity. Manufacturers independently create standardized, interchangeable subsystems (microprocessor, memory chips, input/output devices, etc) that can function together to create complex devices. They have been able to build systems with high level of complexity by combining hardware modules (subsystems) into innumerable configurations.

In term of longevity, Unix is arguably one of the most successful operating system today. Created in 1969, Unix has been used in all conceivable computing environment from small embedded to research class supercomputers and everything in between. Unix’s success is attributed to its flexibility and depth made possible by its simple, clean, and orthogonal design. As complex an operating system as Unix is, it is composed of simple, distinct, interacting modules (small programs) with clean interfaces that do one thing and does it well (and nothing more).

In the world of Java, there are numerous examples of successful modular designs. One of the earliest and most popular was the JBoss application server. The JBoss designers realized early on the power of modularity. They were one of the first to build a modular architecture on the top of the JMX (though JMX was designed for management, not a general purpose lightweight component server, its standardized API provided the tools needed to build a modular systems). Other examples of well-known, successful modular systems include the Eclipse and the NetBeans desktop platforms. Both frameworks let developers build complex desktop applications (including IDE’s) using small pluggable modules that interact at runtime.

Modularity in Software
So, the question remains: how does one develop modular code? In disciplines such as engineering and manufacturing, for example, there is a natural affinity to design modularity along the physical attributes of materials. In software development, however, there are little or no affordances to provide guidance to shape code into standardized modules. As such, developers tend to take the path of least resistance and write software systems organically (i.e. monolithic) where the code produced has little or no clear boundaries. The next few paragraphs review provide some points on creating modular software. If you already create your software as modules great, otherwise, you can use the following text as guidelines for your next projects.

Logical Modularity
Generally in software, modularity can be categorized as logical or physical. Logical Modularity is associated with the internal organization of code into logically-related units. In modern high level languages, logical modularity usually starts with the class, the smallest code group that can be defined. In languages such as Java and C#, classes can be further aggregated into packages (namespace in C#) which allows developers to organize code into group of related classes (languages such as Ruby, Scala, Smalltak, Java7 support similar organizational structure with additional semantics for managed components) .

In the Art of Unix Programming, author Eric S. Raymond provides an iconic rule for modularity that states “… write simple parts connected by clean interfaces.” Depending on the context, a module can be implemented as a single class, several classes in a package, or an entire API (a collection of packages). Regardless of the implementation scale of your module, you should be able to describe its functionality in a single sentence (i.e. this module calculates tax per zip code). Your module should expose its functionality as simple interfaces that shield callers from all implementation details. The functionality of a module should be accessible through a published interface that allows the module to expose its functionalities to the outside world while hiding its implementation details (it is way beyond the scope of this blog entry to provide a comprehensive treatments of design patterns and rules for modularity in software).

Physical Modularity

Physical Modularity, is probably the earliest form of modularity introduced in software creation. Physical modularity is comprised of two main components 1) a file that contains compiled code and other resources 2) an executing environment that understand how to execute the file. Developers build and assemble their modules into compiled assets that can be distributed as single or multiple files. In Java for instance, the jar file is the unit of physical modularity for code distribution (.Net has the assembly). The file and its associated meta data is designed to be loaded and executed by the run time environment that understands how run the compiled code.

Physical modularity can also be affected by the context and scale of abstraction. Within Java, for instance, the developer community has created and adopted several physical modularity strategies to address different aspects of enterprise development 1) WAR for web components 2) EJB for distributed enterprise components 3) EAR for enterprise application components 4) vendor specific modules such as JBoss Service Archive (SAR). These are usually a variation of the JAR file format with special meta data to target the intended runtime environment. The current trend of adoption seems to be pointing to OSGi as a generic physical module format (see previous post). OSGi provides the Java environment with additional functionalties that should allow developers to model their modules to scale from small emddeable to complex enterprise components (a lofty goal in deed).

Why Be Modular?
We have seen numerous disciplines have benefited by adopting modularity in process and development efforts. So, why should you invest time in implementing a modular architecture for your next project? After all, adopting a modular design introduces new overhead such as change in design practices, module files management as project grows, design- and build-time dependency management, and each group working on a module has a narrow knowledge of the code. The following is a list of benefits that you gain that outweigh the headaches you may encounter in modular design.

  • Scalable Development: a modular design allows a project to be naturally subdivided along the lines of its modules. A developer (or groups of developers) can be assigned a module to implement independently which can produce an asynchronous project flow.
  • Testable Code Unit: when your code is partition into functionally-related chunks, it facilitates the testing of each module independently. With the proper testing framework, developers can exercise each module (and its constituencies) without having to bring up the entire project.
  • Build Robust System: in the monolithic software design, as your system grows in complexity so does its propensity to be brittle (changes in one section causes failure in another). Modularity lets you build complex system composed of smaller parts that can be independently managed and maintained. Fixes in one portion of the code does not necessarily affect the entire system.
  • Easier Modification & Maintenance: post-production system maintenance is another crucial benefit of modular design. Developers have the ability to fix and make non-infrastructural changes to module without affecting other modules. The updated module can independently go through the build and release cycle without the need to re-build and redeploy the entire system.
  • Functionally Scalable: depending on the level of sophistication of your modular design, it’s possible to introduce new functionalities with little or no change to existing modules. This allows your software system to scale in functionality without becoming brittle and a burden on developers.

Conclusion
In this post, I wanted to provide a broad overview of modularity as a concept and its effect on software system. We have seen how modularity is intrinsically entrenched in non-computing disciplines and how they all benefit from the practice. Software is no different, complex systems from desktop applications to enterprise behemoth such as application servers benefit from modularity in design. It is not the intent of this entry to insinuate that modular design means an end to buggy code. On the contrary, developers will always write buggy code as long there’s code to be written. However, it is the intent of this entry to show that modularity is a step toward making software development, deployment, and management easier to scale and maintain.

References
1. Merriam-Webster, http://www.merriam-webster.com/dictionary/Modular
2. Mark Dodgson, David Gann and Ammon Salter, Think, Play, Do: Innovation, Technology, and Organization
4. Carliss Young Baldwin and Kim B. Clark, Design Rules: the Power of Modularity
4. Werner Callebaut, Diego Rasskin-Gutman, Herbert A. Simon, Modularity: understanding the development and evolution of natural complex systems
5. Eric S. Raymond, The Art of Unix Programming, 1999
6. Mark Fleury, Juha Lindfors, Enabling Component Architectures with JMX, http://www.onjava.com/pub/a/onjava/2001/02/01/jmx.html, 2001
7. P. Jalote, An Integrated Approach to Software Engineering, 1997
8. Tim Boudreau, Jaroslav Tulach, Geertjan Wielenga Rich Client Programming: Plugin into the NetBeans Platform

March 8, 2009

Java Modularity with OSGi (1)

I am excited: the notion of modularity is once again taking center stage in Java land.

All technology platforms (OS’s, languages, applications, etc) eventually face the struggle of providing an adequate level of abstraction to encapsulate modular code unit. On the MS Windows platform, for instance, there is myriad of technologies including VCL, VBX, OCX, ActiveX, COM, DLL, etc, that emerged over the years designed to provide modular, sharable, and distributable code units for specific domains.

On the Java platform, the story is similar. From the beginning, the JAR file format provided the means to physically package Java code and resources as modules. The file format has served its original purpose well giving the means to distribute and reuse the large number of Java API’s that is available today. However, while the JAR file format works great for physical modularity, it falls short, however, of supporting a logical component model. (NOTE: vendors have developed their own component models to address their specific needs, for instance SpringSource’s Spring Framework, JBoss SAR, Geronimo GBean, JMX MBeans, EJB’s, etc).

OSGi
You have probably heard about OSGi and wonder how it fits in the Java landscape. In short, OSGi extends JAR’s physical modularity into a logical component model (known as bundle). In OSGi, the bundle can be a living entity that provides services, not a mere container for code API. As such, OSGi affords system developers the following capabilities:

  • A Framework: This is an execution environment for bundles at run-time. Bundles are loaded, executed, and managed (see OSGi Frameworks below).
  • Service Registry: OSGi provides a container where bundles are deployed and can expose services to other registered bundles.
  • Life-cycle Services and Events: Allows addition, removal, and update of bundles dynamically at run-time. The framework publish lifecycle events as notifications that can be captured for appropriate reactions.
  • Service Model: Ability to expose and discover service interfaces at run-time.
  • Bundle Isolation: OSGi adheres to strict isolation rules. Each bundle gets its own class loader. Visibility of a bundle is specified at the package level, not class. A Bundles can export its internal packages or indicate its dependency on existing packages hosted by other bundles running in the framework.
  • Version Dependency: Expressive and flexible bundle versioning semantics with automatic dependency resolution.
  • Multi-version Coexistence: Multiple versions of same bundle can co-exists without any shadowing effect. Client A can have a dependency on bundle X.1 while client B has a dependency on a different version of bundle X.2 with no risks of class path collisions (commonly known as Jar Hell).
  • Dynamic Availability: part of OSGi’s component model is the notion of bundle dynamic availability. A bundle is not guaranteed to be available. This is good because you can remove/reload/restart a bundle at runt time (without restarting the framework). This is not so good because your bundle has to have mechanism to handle dynamic availability of bundles it depends on.

The OSGi Bundle
Because OSGi was designed (from the ground up) to be a component-based platform, an OSGi application is a collection of interacting bundles running within the framework. As stated earlier, an OSGi bundle is based on the traditional JAR file. However, OSGi uses special meta-data in the META-INF/MANIFEST.MF file of the bundle to specify configuration information used by the OSGi framework at runtime. Below is an example of a MANIFES.MF file for a bundle

Bundle-ManifestVersion: 2
Bundle-SymbolicName: com.services.demo
Bundle-Version: 1.0.0
Bundle-Activator: com.services.Activator
Bundle-ClassPath: .,com/services/api.jar
Import-Package:
com.other.services; version=“[1.0.0,2.0.0)”;
Export-Package:
com.services.sei; version=1.1;

Some important items to notice in the manifest meta data:

  • Bundle-Activator: specifies a class that will react to bundle life-cycle events (when the bundle starts and when the bundle stops). You can use this event as a starting point for functionalities implemented by your bundle (sort of a main() for your OSGi application).
  • Bundle-ClassPath: establishes a classpath for your bundle’s internal library of classes (and jar files).
  • Import-Package: this entry specifies the name of a package that the bundle depends on (and expected to be available on the platform). Notice the version directive specified in the Import-Package declaration. It uses an interval notation to express dependency on versions 1.0.0 <= X < 2.0.0
  • Export-Package: declares a package in the bundle that should be made available at runtime. When the bundle is installed in a framework, package will be visible to other installed packages running.

OSGi Frameworks
You may be wondering where/how do I run an OSGi bundle? You will need a framework. A framework is an implementation of the OSGi service platform specifications that has the ability to execute bundles. The framework itself is a small core with system level logic to load bundles. All of the framework’s functionalities come from installed bundles on the framework. There are several framework implementations available today, the three most popular (and open source) are:

  • Apache Felix – A small embeddable, developer friendly port of OSGi service platform. It’s the basis for many popular projects including Glassfish and JOnAS App Servers.
  • Eclipse Equinox – This is the base for Eclipse IDE (which a collection of bundles known as plugins in Eclipse parlance). It’s used in many popular products such as SpringSource DM Server and IBM’s WebSphere.
  • KnopflerfishKnopflerfish is one of the earliest implementations from the commercial side (gone open source) with presence in automotive, telecom, and home automation.

Why Should I Care?
You will certainly wonder how OSGi impacts you. Well, if you spend most of your day writing enterprise applications, then OSGi will mean little to you. As a matter of fact, vendors are working hard to keep developers away from OSGi-specific concerns. You will continue to use enterprise semantics that you are already familiar with and produce enterprise artifacts (EJB, WAR, EAR, etc) that you produce today. Life is good, keep coding!

However, if you are system level developer or simply interested in component-based development, OSGi may be of great value. Already, many vendors are decomposing their products into OSGi-ready jars to allow developers easy deployment on OSGi runtimes. There’s also a movement of porting commonly used API’s to OSGi by creating a bundle repository (i.e. Felix Commons and Equinox Orbit).

Another approach to OSGi integartion is to embed an OSGi framwork into your own development to create a component model. Eclipse has become the posterchild for this approach using OSGi to provide a plugin architecture for the IDE. Felix, however, has become the favorite embeddable OSGi framework because of its relative small size, easy licensing, and easy API. One great example of embedded Felix is the SIP-Communicator desktop application which uses OSGi-bundles as plugins to extend the application (I am sure there are others).

Conclusion
I hope this entry got you, at least, interested in OSGi. I think OSGi is a great start toward a unified component model for Java. It will certainly get developers to (hopefully) start viewing their systems in terms of components and not just classes. In future posts, I will look at how to use OSGi practically and integrate into your development efforts.

Even if you don’t plan to adopt OSGi right away, at least check it out .

References
About OSGihttp://en.wikipedia.org/wiki/OSGi
OSGi Alliance – http://osgi.org/
OSGi Articles – http://www.osgi.org/Links/HomePage
OSGi on InfoQhttp://www.infoq.com/osgi
Free OSGi Book By Neil Barlertt (PDF) – http://neilbartlett.name/downloads/osgibook_preview_20090110.pdf
EclipseCon Presentation by Richard S. Hall (PDF) – http://felix.apache.org/site/presentations.data/osgiapachecon-2005121…
Eclipse Equinox – http://www.eclipse.org/equinox/
Apache Felix – http://felix.apache.org/
Knopflerfishhttp://www.knopflerfish.org/
SpringSource OSGihttp://www.springsource.org/osgi
Sip-Communicator Presenation – http://archive.fosdem.org/2007/slides/lightningtalks/SIPcommunicator.pdf

December 22, 2008

JmxBuilder Finds New Home

JmxBuilder has been officially incorporated in Groovy for the 1.6 RC-1 release. I am delighted that the Groovy team thought highly of JmxBuilder to make it an addition to the language. JmxBuilder will have much more features in 2009. Special thanks to Guillame Laforge and the rest of the Groovy team for all their help in integrating the two projects.

Because of this change, JmxBuilder will be moved from its current Google code location once everything is migrated to codehaus.

December 14, 2008

JmxBuilder (Groovy DSL for JMX) Released

JmxBuilder 0.5 (beta) has been released. After some constructive feedback (see previous post about JmxBuilder in April on Dzone), I redesigned the DSL to be more robust, compact, and added new features to help export and programmatically manage MBeans at runtime. The new features focus on building JMX agents, Jmx clients, and participate in the JMX event model. So, here it is:

Full description at http://code.google.com/p/groovy-jmx-builder/

JmxBuilder is a Groovy-based domain specific language for the Java Management Extension (JMX) API. It uses the builder pattern to create an internal DSL that facilitates the exposure of Java and Groovy beans for runtime control and management via the MBean server.The Groovy JMX Builder DSL hides the complexity of creating and exporting management beans via the JMX API and provides a set of natural constructs to interact with the JMX infrastructure.

Features

Learn More
Here is where you can get more information about JmxBuilder

Check it out.

December 4, 2008

JavaFx Is Here! Could Sun Be on the Right Path?

When I saw JavaFax at last’s and this year’s at JavaOne, I did walked out of the presentations a bit skeptical “… yeah right, how is Sun’s going to compete with the deadly Adobe Flex/Flash combination … it’s marketing gimmic” . Well today (and if you been following JavaFx, for a while) Sun finally made good on its promise of delivering a Rich Media platform by officially releasing the SDK for JavaFx (at http://javafx.com, the site is being slammed, everything is slow now).

I must say that I am less skeptical now and cautiously optimistic on the future of Java as a rich media platform. This could actually work.

Java as viable rich medium
Using JDK 6 update 10 (released earlier) as a base, you now can see how applets are positioning themselves to be a formidable option to the Flex/Flash combo.

1. Applets load gracefully

2. Online streaming videos with Applets
Here is something you have never done/seen before with Java applets. Online videos, cool!

3. Rich Applet
Look at the skinning, the rich interaction options provided by this applet, yes this not flash, it’s a Java applet

JavaFx.Com
The site has been redesigned and contains tons of examples and code for you to get started. I have already dowloaded the SDK today and will start playing around with the technology. You may encounter heavy traffic.

I hope that this is just a start and Sun and the Java community continues to support this effort that I think all Java developer will benefit from.

November 25, 2008

Processing Applets on the new JDK 6 U 10

I finally downloaded the latest JDK 6 u 10 (download) recently. This is a significant release for the (once again battle front) Desktop. At this year’s JavaOne, Sun made it known that it has all intentions of going back to the desktop. Update 10 is one of many shots, that, the hardware-originated organization plans to take at its competitors as it transforms itself (i think) into a media/content company (see Project Hydrazine and JavaFx).

Anyway, after I downloaded update 10, I headed to the one location where I know I will find plenty of applets: http://processing.org/

Processing is an interesting project that started at MIT where Java is used as the center piece for teaching interactive art. It comes with an IDE and its sole purpose is to quickly create compelling visualization interactive Applets. The project has, since, expanded to include a hardware platform (hardware.processing.org) and even a Java ME port (mobile.processing.org). Click above to explore other aspect of processing (go directly to the showcases or links)

Back to the applets. With the latest update, all of the applets that I looked at so far took seconds to render (on my 2 yrs old machine). Once the JRE is loaded, applets rendered in seconds, some near instantaneously. Applets that manage the download process cleverly (with a splash screen or spinning wheel, etc) provides the sort of rich media experiences that you come to expect now a day online.

I won’t say that Java applets will dethrone the king of online rich media (rhymes with Flash). But, if these improvements keep up, Adobe will certainly have welcome competition in this arena. This is certainly good news for developers (choice is good) and will be a boon for the end users.

Resources
http://java.sun.com/javase/downloads/index.jsp
http://java.sun.com/javase/6/webnotes/6u10.html
http://processing.org/

June 30, 2008

Official Groovy/Grails Support in NetBeans 6.5

Judging from the list of features that will be included in NetBeans 6.5, Groovy and Grails will be officially supported by the NB team. From the wiki text, Groovy and Grails will be first-class citizen in NB65 with features that will include:
- Editor support (code completion, color highlights, etc)
- Two-way Java / Groovy class integration
- Seamless Grail project support (support for all Grails artifacts and commands)
- Jetty integration for development-time deployment/testing.

It remains to be seen if NB65 Groovy support will be as comprehensive as IntelliJ which currently has the most extensive support for Groovy / Grails development.

For more, go to:
http://wiki.netbeans.org/NewAndNoteWorthyMilestone1NB65#section-NewAndNoteWorthyMilestone1NB65-Groovy

May 9, 2008

JavaOne 2008 – Last Day Notables

The last day of JavaOne 2008 was heralded by the final General Session where Sun showcased several cool projects. Here are a few you maybe interested in. Some are useful others just plain cool:

1. VisualVM – This is a great (and seems to be indispensable) tool to do VM runtime monitoring and profiling. It runs outside of the an IDE and lets you look deep into the VM and your runninig application at runtime. The profiler is the same that is found in NetBeans and provides a hierarchical navigation and snapshot of all activities of a running application. Check it out at https://visualvm.dev.java.net/.

2. NetBeans 6.1 JavaScript Support – if you do a lot of JavaScript, then the NetBeans is for you. In the demo shown on stage, Netbeans manages to make JavaScript development as well-supported as regular Java. The IDE provides Javadoc-like support, code completion, data structure navigation, on-the-fly documentation, even code hints, etc, etc. While other IDE such as Intellij has had support for JavaScript for a while, this is the first glimpse of it on the NetBeans platform.

3. LiveScribe (http://livescribe.com) – this is not a developer tool, but rather a pen-base computing platform based on the Java Micro Edition. It records pen stroke and voice as you write. Describing it here does not do it justice, but the one demo that caught my attention was a translating demo where the presenter wrote words in one language and the pen automatically translates it into different language…

4. Sentilla, Pervasive Computing Device: Sentilla sells small computing devices meant to be used in sensor networks. Pervasive computing is the notion that everything around us will (some day) have a microchip. Companies such as sells a platform to build and deploy these devices everywhere.

5. JFugue, Music Processing Software – this open source software lets you programmatically build music players in Java. It uses a simple text base language to describe music timing, rythm, notes, sound bank, etc. With the JFugue API, you can create music in several ways including direct notation and pattern inference.

May 9, 2008

Integrating Spring and JBoss SAR Components

Integrating Spring and JBoss SAR Components
Last time I wrote about JBoss, it was a discussion on how to create a JBoss service component (SAR). However, in many cases, a SAR component has to be integrated with other component-based technologies. In this article, I will discuss how to accomplish this by integrating the JBoss with the Spring component model and how to expose Spring components to receive management services from within JBoss JMX Console.

Integration
The architecture and implementation of the JBoss service component system differ vastly from the Spring Framework‘s component model. JBoss (version 4.x and below) implements its internal kernel, for its component container, completely on the Java Management Extension API. As such, when you build a JBoss components, you automatically inherits all the management facilities exposed by JMX. The Spring container, on the other hand, is designed to be a lightweight and portable container and has the ability to host POJO’s as components. Therefore, Spring has become the container of choice for many system designers because of its simplicity and portability to be hosted in any environment.


As you can see, integrating Spring in another container requires some sort of adapter that controls how and when the Spring context is created and destroyed. As we will see later in this document, this can be easily accomplished using a few API calls.

Motivation
Why would I want to integrate Spring and JBoss you ask? Well, there is an application domain that is not suited to be implemented as web-based apps. Inevitably, at some point in your career, you will need to implement headless services that expose functionalities without a GUI. These type of services are temporally durable and operate without any human intervention. When creating these types of GUI-less services, you may decide to use the Spring container as your core operating environment for POJO components. Since Spring exposes a uniform abstraction layer for the Enterprise Java API’s, it makes sense to code around Spring so that your implementation is portable to any environment that can host enterprise services (JBoss container, ServiceMix, Mule, EJB’s, etc). Then, your Spring components can leverage services offered by that enterprise environment (database, timers, messaging, adapters, management, etc).

Integration Points
The portability and programmability of the Spring container makes it an attractive platform for developers to create POJO component-driven apps. For web-based apps, Spring provides ready-made adapters to easily integrate your Spring context within the servlet container. However, for non-web system, Spring does not readily provide specific hooks for integration (this is a good thing, it keeps things simple). On the other hand, the Spring API exposes a simple API that makes programming the integration, of Spring in your environment, a seamless effort.

The picture above shows how Spring integration with the JBoss Application Server can be easily achieved. You create a JBoss service component that serves as an adapter to the Spring container. As the JBoss service object receives lifecycle events from the application server, event-handling logic can be inserted in the adapter to control the creation and management of the Spring context. Once booted and running, the Spring container takes over and mounts its internal POJO components and registers them with the available MBean Server for management.

The Spring Directory Scanner
Extending on the example presented in the previous blog on JBoss components, this example demonstrates how to create a Spring-based directory scanner that gets hosted within the JBoss application container. The previous example, all of the logic of the scanner was implemented directly into the JBoss service component. While there’s nothing wrong with that approach, it tightly couples your code with JBoss and make it far less portable. In this version of the scanner, the logic is encapsulated in POJO’s hosted within a Spring context.

A JBoss service component serves as a Spring adapter and manages the creation and destruction of the Spring context from within the JBoss container. The spring context is booted up by the JBoss service component through life cycle event hooks from the server. Upon initialization, Spring mounts its POJO’s and exposes the Directory Scanner component for runtime management and control through JMX. Using the JConsole or JBoss’ Jmx-Console, these components can be managed at runtime locally or remotely.

The Code
The code itself is simple and self explanatory. The JBoss service component responds to JBoss application server’s life cycle events. These events are used to manage the creation and management of the Spring context. The Directory Scanner Spring component is driven by a Timer Task object mounted in Spring. Every time the timer expires, it executes the scan() method on the Directory Scanner instance.

The JBoss Service Spring Adapter
The JBoss service component is a a plain Java class with life cycle methods named create, destroy, start, stop. It implements a management interface which exposes these methods for JMX control. The component deployer will automatically execute methods create() then start() upon instantiation of the service component.

public interface JBossSpringAdapterMBean {
void create();
void destroy();
long getErrorCount();
long getSpringComponentCount();
String[] getSpringComponents();
String getSpringConfigPath();
boolean isSpringLoaded();
boolean isStarted();
void setSpringConfigPath(String path);
void start() throws Exception;
void stop();
}

Besides the life cycle methods, there are other management methods that are added for convenience. For instance, there’s a method that returns the error count or one that returns the list components loaded in the spring context.

During the deployment of the JBoss Spring adapter (implemented as JBoss service component), the create(), destroy(), and start() methods of the adapter will be invoked by the JBoss service archive deployer. This provides an opportunity to instantiate and manage the Spring context at key points during the lifetime of the adapter.

Booting Spring
The create() method is called after all the setters are injected with values from the JBoss service descriptor.

public class JBossSpringAdapter implements JBossSpringAdapterMBean {
private ClassPathXmlApplicationContext spring;

...

public void create(){
log.info("**** CYCLE: CREATE ****");
if(!created){
try{
spring = new ClassPathXmlApplicationContext(springConfigPath);
spring.registerShutdownHook();
created = true;
}catch(Exception ex){
errorCount++;
created=false;
log.error("Unable to start Spring Context", ex);
}
}
}

...

The create() method is used to instantiate the Spring context. In the code snippet, the path to the Spring context is injected during deployment from the deployment descriptor using the setSpringConfigPath() method. The registerShutdownHook() method registers Spring to listens to VM shutdown signal so the context can properly deactivate all of its registered components.

Shutting Down the Context
On the other hand, when your JBoss adapter class receives a shutdown signal (say, the server is shutting down for instance), you wan to have your Spring context gracefully go down as well. By providing a destroy() method, the JBoss deployer invoke that method when the server sends out a shutdown signal.

public void destroy() {
log.info("**** CYCLE: DESTROY ****");
if(created){
try{
stop();
if(spring.isActive()){
spring.close();
  spring.destroy();
spring = null;
}
created = false;
}catch(Throwable ex){
log.error(" Failed to destroy component. ", ex);
}
}
}

Controlling the Spring Context
Another desirable aspect of the adapter is the ability to control the Spring context with a start / stop functionality. While it is not a necessary, it affords a runtime convenience where the Spring context can be controlled and managed from a JMX console.

...
public void start() throws Exception {
log.info("**** CYCLE: START ****");
if(!started){
try{
if(!spring.isActive()){
spring.refresh();
spring.start();
}
started = true;
log.info("**** Spring context started OK.****");
}catch(Throwable ex){
errorCount++;
started = false;
log.error("**** Failed to start Spring context:", ex);
}
}
}

...

public void stop() {
log.info("**** CYCLE: STOP ****");
if(started){
try{
spring.close();
started = false;
log.info("**** Spring context stopped OK.****");
}catch(Throwable ex){
errorCount++;
started = false;
log.error("**** Failed to stop Spring context:", ex);
}
}
}

...

The JBoss Service Component Descriptor
The last part of creating the JBoss Spring Adapter, is to create a JBoss Service Descriptor file (jboss-service.xml). Using this file, you can inject runtime values, and point to a descriptive xmbean descriptor file that is used to export your service archive component as an JMX MBean.

<?xml version=”1.0″ encoding=”UTF-8″?>
<server>
<mbean code=”integration.jboss.JBossSpringAdapter”
name=”demo.integration:name=JBossSpringAdapter,type=Adapter”
xmbean-dd=”META-INF/spring-adapter-xmbean.xml”>
<attribute name="SpringConfigPath“>/META-INF/spring.xml
</mbean>

For details about creating a JBoss service component and how to format jboss-service.xml and the Xmbean descriptor file, visit the JBoss 4 User Guide.


Deploying the JBoss Spring Service Adapter
Without going into the implementation of the Spring Directory Scanner component, let’s see what happens when the JBoss service archive is deployed. We expect the JBoss SAR deployer to recognize our JBoss Spring Adapter component as a valid JBoss service archive component and deploy it. Once deployed, we can validate the deployment through the log and through the JMX Console.

JBoss SAR Starting

During deployment, we see the JBossSpringAdapter service component being deployed by the application server. We can also see that the Spring context is being instantiated.

JBoss JMX Console shows the JBoss service component JMX management interface.

The JMX operations for the Spring service adapter are shown above. Notice that you can start and stop the spring container at runtime. That gives you the ability to conrol the lifescyle of your Spring container at runtime without redployment of the application . This maybe useful if you want to make a configuration change in production without redeployment of the entire application.

The Directory Scanner Spring Component
The scanner is a simple Java object which uses the standard java.io.File package to get filtered list of files in a given directory. You will notice that there are some annotations around the class. These are Spring-specific annotations used to expose the Directory Scanner class as a managed JMX MBean (this is not covered in this writeup). I also introduce an interface called Controllable for good form (not necessary).

The Controllable Interface

public interface Controllable {
public void start();
public void stop();
}

This interface shows control points that can be implemented in the Directory Scanner. This is not necessary, but added for completion.

The Directory Scanner Class
The class that implements the logic for scanning the directory is divided into three distinct sections

  • The properties (getter/setters) for the component
  • The life cycle control methods
  • The scanning method which is invoked to do a sweep of a a directory

@ManagedResource(description="Directory Scanner Component.",
objectName="demo.integration:name=DirectoryScanner,type=SpringComponent")
public class DirectoryScanner implements Controllable{

...

@ManagedAttribute(description="Comma separated list ....")
public String getExtensionList() {
return (fileFilter != null) ? fileFilter.toString() : null;
}

@ManagedAttribute
public void setExtensionList(String extensionList) {
fileFilter = new FileListFilter(extensionList);
}

@ManagedAttribute(description="The directory location to scan.")
public String getLocation() {
return (location != null) ? location.getPath() : null;
}

@ManagedAttribute
public void setLocation(String location) {
this.location = new File(location);
}

...

@ManagedOperation(description="Lifecycle to start component.")
public void start() {
started = true;
log.info("**** Directory Scanner Compoennt started OK.");
}

@ManagedOperation(description="Lifecycle to stop component.")
public void stop() {
started = false;
log.info("**** Directory Scanner Compoennt stopped OK.");
}

...

public void scan() throws RuntimeException {
if (started) {
if (location != null && location.isDirectory()) {
File[] list = location.listFiles(fileFilter);
log.info("Scanned files with extensions [ " + fileFilter.toString() + "]" +
" from [" + location.getAbsolutePath() + "]");
} else {
log.warn("Unable to scan location Make sure it's valid.");
}
}
}

}

As you can see, this is a simple class. The thing to notice is the Spring-specific annotations that decorate the class. They are used to export and describe the class as a JMX MBean server. It’s beyond the scope of this write up to go into the details of how to do this in Spring. However the next section shows the Spring file that describes and wire it all together.

The Spring Configuration File
The configuration of this component is simple and straight forward.

Above, we see the DirectoryScanner being configured to scan two directory up from where the application is invoked. Also, we set the list of files to scan.

<bean id="timerFactory"
class="org.springframework.scheduling.timer.TimerFactoryBean">

<bean id="scheduledTimerTask"
class="org.springframework.scheduling.timer.ScheduledTimerTask">

<bean id="timer"
class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">

The stuff above is boiler plate for setting up timer services from Spring. Here we are declaratively setting the timer to invoke the scan() method on the DirectoryScanner POJO wired above.

<bean id="jmxAttributeSource"
class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>


<bean id="assembler"
class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">


<bean id="namingStrategy"
class="org.springframework.jmx.export.naming.MetadataNamingStrategy">

Finally, the code snippet above sets up the POJO to be exported as an MBean into the running MBeanServer. This configuration relies on the annotation embedded in the class to derive the meta data used to describe the class inside the MBeanServer.

Download Source
You can download the application sample application to get the code source.

Observations

  • Think in Componentcomponent-based development is incredibly easy to get into and understand. It facilitates the separation of concerns and promotes forces you into better coding practices (testing, loose coupling, re-usability, etc).
  • JBoss Service Component Evolving – Starting with version 4.x, JBoss components can now be annoted (instead of using the descriptor file) to describe its meta characteristics for JMX. Starting with version 5, JBoss will switch to OSGi as the executable unit for its components.
  • Exception ManagementWhen deploying components into a container (such as JBoss app server), great care must be taken to handle exceptions properly. In JBoss (version 4.x), when a component throws an unhandled exception, that component is immediately disabled and shutdown. You must catch all exceptions and handle them properly. In DirectoryScanner, for instance, if the scan() method throws an exception during a scanning request, the entire component is deactivated.
  • (OSGi) Components Are Here to StayAll major containers including JBoss AS, SpringSource App Platform, IBM WebSphere, Glassfish, and JOnAs support OSGi bundles as their coarse component model.

Refereces

  1. Source for Directory Scannerhttp://vladimirvivien.com.s3.amazonaws.com/jBoss-spring-integration.zip
  2. JBoss Server Microkernel – http://docs.jboss.org/jbossas/jboss4guide/r4/html/ch2.chapter.html
  3. Spring Documentation – http://static.springframework.org/spring/docs/2.5.x/reference/index.html
  4. Spring JMX Documentation – http://static.springframework.org/spring/docs/2.5.x/reference/jmx.html
  5. OSGi – http://en.wikipedia.org/wiki/OSGi
  6. OSGi and Spring – http://www.infoq.com/interviews/osgi-adrian-colyer
Follow

Get every new post delivered to your Inbox.

Join 154 other followers