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

5.08.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</attribute>
</mbean>
</server>

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

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

<bean id="scanner" class="component.spring.DirectoryScanner" init-method="start" destroy-method="stop">
<property name="location" value="../../"/>
<property name="extensionList" value="*"/>
</bean>

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">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask" />
</list>
</property>
</bean>

<bean id="scheduledTimerTask"
class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="period" value="3000" />
<property name="timerTask" ref="timer" />
</bean>

<bean id="timer"
class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref="scanner" />
<property name="targetMethod" value="scan" />
</bean>

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="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="assembler" ref="assembler"/>
<property name="namingStrategy" ref="namingStrategy"/>
<property name="autodetect" value="true"/>
<property name="registrationBehaviorName" value="REGISTRATION_REPLACE_EXISTING"/>
</bean>
<bean id="jmxAttributeSource"
class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>

<!-- will create management interface using annotation metadata -->
<bean id="assembler"
class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource" ref="jmxAttributeSource"/>
</bean>

<!-- will pick up the ObjectName from the annotation -->
<bean id="namingStrategy"
class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource" ref="jmxAttributeSource"/>
</bean>

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

Refereces
  1. Source for Directory Scanner - http://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







JavaOne - OSGi Is Huge Here!

If you doubted that OSGi can achieve mass appeal, the list of sessions at J1 proves contrary. Most major tool vendors has either implemented it or have plans to support OSGi bundles:

From small embedded devices, to desktop, to the large application server, OSGi seems to be the component model that the industry is adopting. It will be interesting to see how the corporate developer integrates OSGi in their development rituals.

5.07.2008

JavaOne 2008 - Sun, Lifestyle Company?

On day one of the JavaOne, the theme is clear: JavaFx (http://javafx.com/) is here to stay. The FX story is coalescing into a platform clearly targeting digital lifestyle experiences. It is clear that tremendous of resources are being devoted to bring the FX story together as technology stack with support for rich that stretches from mobile devices, desktop, to the backend.

The Tools
- Continued JavaFX support from NetBeans
- Photoshop/Illustrator plug-in's to export art work as JavaFx artifacts directly

The Features
- JDK 6 update 10 (jdk 6u10) - setting the path for the desktop features envisioned by Sun
- Applets - Sun is going back to the Applets as a way to augment browsing experiences.
- Audio/Video - under the FX unbrella Sun is offereing an HD qualility a/v codec for Java
- FX is slated to target devices such as cellphones and other mobile stacks with a consistent user experience from device to desktop.
- Project Hydrazyne: another Sun initiative to let users easily create rich content and experiences dritributed in a Sun hosted cloud.

I would like to see this effort successeed, for anything elese, just to have competition in the content technology market place. Adobe leads that sector, Microsoft is making inroad with Silverlight, now Sun wants to give Java developer a way into the rich content user exeperience.

You just have to read the blogs around the net to find doubters about this strategy laid out by Sun. However, I think if the company remains on message, provide the tools, continue to share the vision, there will be new convert. Lets see what happens!

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]