Daniel’s Weblog


Swing Application Shutdown

After discussing the startup in the last post I continue on the shutdown of a Java application. Typically when the application frame (or window) closes the user is asked if he really wants to exit. If he commits this the application exits while closing the application. In the other case the application might restart or do nothing. How can this be handled with Java Swing?

A common way of shutdown implementation is to add an implementation of WindowListener to the application frame and react on the events. The listener already has a callback windowClosing(WindowEvent) which is called before the window closes. Here the application might ask the user if he really wants to exit or just clicked the wrong button ;-) . In most cases if the user commits a common implementation is to invoke System.exit(0) because this terminates the JVM but the JFrame class provides a more convinient approach. Simply set the default closing operation to JFrame.EXIT_ON_CLOSE will do the same job. If the application requires a callback that the application frame is really closed simply set the closing operation to JFrame.DISPOSE_ON_CLOSE and implement the listeners windowClosed(WindowEvent) method. You even don’t need to invoke System.exit(int) because the EDT exits when no window is active. Which means if the application frame is the only window it also exits the application.

Application Shutdown

This image shows the event invocations when a window is closed. First the user closes the window by pressing the red icon in the top right corner. This causes the EDT to dispatch a window event to the application frame. The event has the type WindowEvent.WINDOW_CLOSING. The application has registered a WindowListener that invokes shutdown in the EDT. In the shutdown method the application asks the user if he really wants to exit. If he aborts the application sets the default close operation to JFrame.DO_NOTHING_ON_CLOSE which continues the application and keeps the frame open. If the user commits the application sets the default close operation to DISPOSE_ON_CLOSE which causes the application frame to be disposed. This again causes the EDT to dispatch a new WindowEvent with the type WindowEvent.CLOSED. Now the application can do some magic in the EDT after the window is closed. If no window exists the EDT exits and the JVM terminates. If the application sets the default close operation to JFrame.EXIT_ON_CLOSE the application will terminate immediately after the windowClosing method is executed (just look at the code of JFrame’s processWindowEvent method).


Swing Application Startup

The startup of an application is one of the based parts where a framework support is very helpful because especially with Java Swing. In Swing there is the Event Dispatch Thread (EDT) which executes any UI related stuff. So anything that is related to UI should be executed in this thread, even the creation of a frame. So how can  a framework support this procedure. One example comes with the Swing AppFramework where a launcher moves the creation and invocation of the startup method into the EDT but than also does a lot of application specific or sometimes unneeded stuff like I18n, session storage.

A really simple approach is shown in the following picture.

Application Startup

The user starts the application either using Web Start, clicking on the JAR or command line. In the applications main-method is one line Launcher.launch(Application.class, args) where the application class and command-line arguments are passed to the launcher. This one creates a new application instance and invokes the startup method in the EDT using SwingUtilities.

Because no window is shown any configured splash screen will be shown until the frame (or window) which is created in startup method is shown to the user. The behavior of startup is application specific but often it can be divided into an initialization part of the platform. Typical services like executor, communication layers, logging, modularization are initialized. After this is completed the application frame is created and shown to the user.


Java 6 Splash-Screen

Working on Java Swing is sometimes not the easiest! Today I came across a problem with the Java6 Splash-Screen feature where you can define the splash screen in the manifest file. I wanted to see when the splash screen gets shown and when it gets disposed. The screen really gets shown when the JVM starts, so its good to use it for showing feedback while initialization. And the screen gets disposed as soon as the first window, may it be a frame or dialog, gets shown.

But nothing comes for free, a problem occured as I added class-path entries to the manifest.  The splash screen was not shown! So I played around with a dozen of combinations in the manifest file. The outcome is that if the Splashscreen-Image entry is after the Class-Path entry no splash screen will be shown! So always keep you entry for the splash screen at the top of the manifest file.


Learning Adobe Flex

With the existing stream of building rich internet applications (RIAs) I also have to look at this technology. So I started learning Adobe Flex because after some talk with collegues and looking around it looks like this is the most stable and widely used technology. JavaFX is just starting and has still a long way to go and Silverlight just only runs on Windows machines with IE installed.

So the first I had to do was browsing the documentation at Adobe Open Source and getting a feeling of Flex. This means mainly downloading the SDK, looking at the examples and fiddling around with them. The concept with declaring the user interface in XML is nice and makes it really easy building simple forms and screens. With the mechanism of having an id-map in the application from where the application code, UI and everything gets and displays the entered/computed text works well. Also with ActionScript which is like JavaScript but with just a little bit more type information makes it also easier for a Java developer to dig into it. One of the biggest points is the extensive API documentation. The structure with having an example available for each UI component and function is quite charming. I hope to see this kind of documentation also in some other projects.

As an example I’d written a small application to calculate the real inflation adjusted return for a one-year cash-investment in a CD.


Web Services with Axis 2, CXF and Maven – Part 2

After the service implementation is implemented and deployed we can start with the service client. For this part I like the way Apache CXF can be integrated in a Spring IoC container, so the service consumer will use Apache CXF for the client implementation.

Again, first we need to set up the Maven project with all required dependencies and build settings. The goal is to generate the client implementation with CXF and write a small test case. So we set up the typical maven project and add the cxf-codegen-plugin to the build settings. This Maven plugin has the goal wsdl2java which must be executed with the configuration pointing to the location of the WSDL of the deployed service. Often it is something like http://localhost:8080/axis2/services/Foo?wsdl. Also the project needs the Spring Framework and Apache CXF as dependency.

The second step is the test case. This one should be written using spring-tests which provides a basis for test cases requiring a Spring IoC container. The configuration file (also known as application-context file) requires the two CXF imports and the service client definition using jaxws:client tag. If the service provider requires authentication one can add the required processors to the output queue using jaxws:outInterceptors and e.g. the WSS4JOutInterceptor as a bean.


Web-Services with Axis 2, CXF and Maven – Part 1

Digging into Web-Services is really complex, there are so many stumbling blocks. First of all one has to understand all the WS-* specifications, or at least the important ones about service. Also important are the guidelines regarding interoperability between Java and .Net. Then the next is the framework one wants to use. Typically everyone talks about Axis2, but sometimes there is also CXF and the new Spring-WS. After that decision the question is about the integration into the development cycle. How can one integrate the generative tasks into the build cycle, e.g. with Maven. This post tries to present one possible solution for these problems in a step to step guide. So lets start.

First of all the project itself is separated into two modules. The first module is for the service implementation and contains the code for the implementation and the service definition in WSDL and XSD files. So lets assume you’ve already wriiten the XSD and WSDL files in your favorite editor. Personally I’m switching between Eclipse and Netbeans. At this point comes the first important hint when using Maven. Put your WSDL and XSD into src/main/resources/META-INF so they are deployed together with the service implementation into the Axis2 runtime.

Then the project descriptor for the service implementation module needs to be updated. Add a property for the Axis2 version, so it can be used at all dependencies and plugin configurations. This makes switching from one version to the other quite charming because it’s just a matter of changing one number. The project dependencies must include the axis2 artifact from org.apache.axis2 and the choosen databinding, e.g. axis2-jaxbri, also from org.apache.axis2. Also add the Maven plugin axis2-wsdl2code-maven-plugin to the build section. This generates the files with source code for the service implementation on the Axis2 runtime. Make sure the plugin executes the goal wsdl2code and the configuration points to the correct WSDL location. Also you should switch on the generation of the server side and services.xml. For a better design it is also a good choice to enable the generation of a server side interface. A hint here is also to include the dependency to the databinding when you’ve not chosen adb.

Now comes the hard part on the console where you simply use mvn compile to generate the files. From these generated files copy the services.xml file from target/generated-sources/axis2/wsdl2code into src/main/resources/META-INF folder. This is the runtime configuration of your service and needed by Axis2.

After this is finished you can package and deploy your service to an Axis2 runtime. But the service will report unchecked exceptions because nothing is implemented. So write a class which either extends the generated skeleton or implements the skeleton interface. This will separate your written code from the generated code. If the implementation extends the skeleton any new service method will report unchecked exceptions after redeployment. Removing a method will give a compile error because of the existing override annotation. Adding a service method when an interface is implemented will create a compile error before the new deployment. As last step change the service-class in the services.xml file to point to your service implementation.


Swing Application on OSGI

I couldn’t continue working on the Java Swing application over the last month because of a major project. After finishing it, I continued working on it in the evening or at weekends and finally it is running on Apache Felix.

The application needed some small fixes at the configuration to include Apache Derby as embedded database and some minor refactorings to make i18n easier. Now it can be downloaded as source-code from SourceForge SVN servers.


Faces and Portal Integration

The integration of Java Server Faces in a portal using Portlets is quite easy. Often a simple Portlet is already provided by the portal server. But this portlet converts the URLs from portal URLs to faces URLs and invokes the JSF lifecycle.

How does one integrate with the portal, so that navigation cases point to different portal sites. One solution I’ve seen is by using a separate service as managed bean. The service bean is often application scoped and a special case for navigation. Another way I can think of is using a special navigation handler. This way there is no new service bean but a slightly different navigation rule which points to another portal site.

The main advantage is the way a developer works with this. He doesn’t need to know that there is a site change. Simply write the code and execute a navigation rule which lets the navigation handler switch portal sites. A simple URL could have a special protocol like „portal:/myRoot/mySite/myPortlet“ instead of „/myRoot/mySite/myPortlet“. In the first case the navigation rule points to a portlet in a portal site and in the second it points to a JSP page in the same portlet.


Abandon Struts tags, use HTML and Dojo

Reading some tutorials and articles about DojoToolkit and thinking about a web application with Struts 2 I can say it is the best to separate the presentation layer and middle layer.

The presentation layer is just about the presentation and therefore a combination of HTML, JavaScript and the DojoToolkit are enough libraries to use. When someone then has to also know the Struts Taglibs for Ajax it’s getting dirty. So my advice is to really separate the presentation layer from the middle layer. This also helps if the correct person is creating the user interface. Because this person often knows nothing about Java, JSP or PHP but is very comfortable with browser technologies like HTML and JavaScript. So for him just learning the API of the DojoToolkit is not too much.

The communication between the presentation layer and facade layer can only be done using HTTP. A typical approach is to use XML or JSON to transfer information. The user interface developer can create a GUI prototype before the real underlying layer is ready by using static files as part of the web application for data. Later on the static files are exchanged with the correct remote invocation.

In the middle layer, if you want to call it facade or service layer, the Struts Actions are used to handle the HTTP-Requests from the presentation layer and return the data in a readable format, which may be JSON or XML. This often implies converting the domain model in data chunks for the presentation layer to display. For data chunks the Data Transfer Object pattern is a good candidate because a DTO represents a single chunk of information which is only needed and assoziations are cutted correctly.

This separation really helps keeping the technologies separated and makes it easier to concentrate on the main tasks. The user interface is developed with HTML, JavaScript and Dojo and the middle layer with Java or PHP. I think this is much better than having a mixture of everything together.


Creating an OSGi bundle with Maven

This article explains the creation of an OSGi bundle with Maven that integrates JPA and TopLink Essentials as library. This is often needed if an application is distributed on top of an OSGi platform like Eclipse Equinox or Apache Felix.

Maven has a plugin that can be used to create OSGi bundles. The most important part about this plugin is the configuration. The next listing contains the complete configuration followed by explanations to important elements especially in conjunction with TopLink Essentials. The plugin configuration is part of the pom files build section.

Beside TopLink Essentials this also integrates the JGoodies libraries (Forms, Binding and Validation) in the bundle.

<plugin>
  <groupId>org.apache.felix</groupId>
  <artifactId>maven-bundle-plugin</artifactId>
  <version>1.4.1</version>
  <extensions>true</extensions>
  <configuration>
    <instructions>
      <Embed-Dependency>
        *;scope=compile|runtime;inline=false;
            groupId=com.jgoodies|toplink.essentials;
            artifactId=forms|binding|validation|toplink-essentials
      </Embed-Dependency>
      <Import-Package>
        !org.apache.tools.ant.*,
        *
      </Import-Package>
      <_exportcontents>com.jgoodies.*,javax.persistence.*</_exportcontents>
      <Export-Package>
        net.sf.daro.core,
        net.sf.daro.core.binding.*,
        net.sf.daro.core.util.*,
        net.sf.daro.core.swing.*,
        net.sf.daro.core.page,
        net.sf.daro.core.form,
      </Export-Package>
      <Private-Package>
        net.sf.daro.core.internal.*,
      </Private-Package>
      <Bundle-Activator>
        net.sf.daro.core.internal.CorePlugin
      </Bundle-Activator>
      <Bundle-Vendor>Daniel Rohe</Bundle-Vendor>
      <Bundle-SymbolicName>${artifactId}</Bundle-SymbolicName>
    </instructions>
  </configuration>
</plugin>

The first important section is the embed-dependency section. This defines the dependencies that should be embedded into the bundle and loaded into the classpath. In this case all dependencies with the scope compile or runtime that match the groupId com.jgoodies or toplink.essentials and the artifactId forms, bindings, validation or toplink-essentials are imported. This filter exactly matches the three JGoodies libraries and the single TopLink Essentials library.

The next section with the name import-package defines the package imports. In this section I excluded all imports to org.apache.tools.ant because they aren’t needed when integrating TopLink Essentials into an application.

The section _exportcontents exports the listed packages which are part of an embedded dependency.