Java Object Serialization and Deserialization

In some circumstances, for instance if you want to transfere objects via GWT RPC, it makes sense to assert Objects can be serialized and deserialized without problems. Further there might be some differences between the original object and the deserialized object – for instance some hash tags might have changed and of course the object references.

The following code snippet can be a useful addition to JUnit test cases, which need to test the serialization of complex objects:

http://gist.github.com/650417 

Maven: Compile all projects in eclipse workspace

The Problem:

You have a number of projects in an eclipse workspace. You have had bad expierences with eclipse Maven plugins like m2maven and eclipse IAM.

You usually trigger Maven from the command line but now for convienience you just want one command with which you can compile all the projects in your eclipse workspace.

The Solution (Windows):

This solution is specific to Windows operating systems by providing a simple batch file.

As preperation, you need to find out the parameters, with which Maven is started on your machine. An easy way to go about this is to remove the @echo off statement from the mvn.bat in your Maven \bin directory and call mvn from within your command line. You will be able to see that Maven is called with a statement similar to the following:

 

"C:\Program Files\Java\jre6\bin\java.exe"  -classpath "C:\Users\Max\Documents\Data\Applications\apache-maven-3.0\bin\..\boot\plexus-classworlds-2.2.3.jar" "-Dclassworlds.conf=C:\Users\Max\Documents\Data\Applications\apache-maven-3.0\bin\..\bin\m2.conf" "-Dmaven.home=C:\Users\Max\Documents\Data\Applications\apache-maven-3.0\bin\.." org.codehaus.plexus.classworlds.launcher.Launcher compile

 

Now you can write a simple batch file like the following:

 


M:
cd Eclipse

for /f %%R in ('dir /b') do call :1 %%R
cd ..
goto :eof

:1
%1
cd \Eclipse\%1
[here comes your Maven statement]compile

POJO Persistence

There are surprisingly few frameworks, which allow to persist and query Java objects independent of relational database management systems. To me, at least for implementations not bound to using existing relational databases, storing information in interrelated tables seems an arbitrary step in object-oriented development. Below a few links …

Frameworks/Technologies

db4o

When you use db4o you either need to purchase the commercial license or GPL your product)

JDO (Oracle Specification)

The Java Data Objects standard seems to be supported by the DataNucleus Access Platform. This platform in turn depends on various data stores such as a relational database system or other storage systems.

JOAFIP

An interesting framework, which allows to persist graphs of Java objects to the file system. Allows for ‚lazy loading‘ of Collections if they are too large to be held in memory.

JenaBean

JenaBean persists Pojos using the Jena Semantic Web framework. Therewith, the serializations are in Semantic Web formats. The dependency to Jena is rather complex. JenaBean provides a Maven project file, which handles these dependencies.

ObjectDB

Further Resources

Wikipedia entry on POJOs

Java Code Reusability

The Java world is in movement. After Oracle‘s purchase of Sun there is a great amount of uncertainty regarding the future of this programming language.

How can we deal with this uncertainty? One approach is to understand that Java is not Java. Indeed, the way we write Java code greatly influences, in how far we are bound to a particular vendor or technology.

1. The code can be compiled with/for and/or runs in

2. The resulting objects can be serialized for/with:

  • Objects can be serialized to XML using XStream
  • Objects can be serialized for RPC calls (eg for GWT RPC) (optional since might require to add the Serializable interface)
  1. 3. All dependencies meet the same requirements.

Of course it is highly unlikely that any but the most trivial applications will meet all these requirements for all of their code. However, it is often possible to write significant portions of the application adhering to these requirements. Code which violates these requirements, particularly code, which leverages third party libraries, can be carefully separated from this ‚portable‘ code. One possibility to loosely couple the portable and non-portable code are for instance OSGi declarative services.

Hamcrest GWT

Abstract: The largest parts of the Hamcrest library can be compiled in GWT. Just the IsInstanceOf class needs a bit of tweaking (as well as some other classes depending on reflection). The following provides a brief overview of some of the steps required to compile Hamcrest with GWT.

  1. 1. Download the Hamcrest GWT SVN Branch (Hamcrest GWT subversion branch) and import to eclipse

bildschirmfoto2010-10-08um18-59-38.png

  1. 2. Clean up the build path (remove the generated folders and remove all other source folders but core, library and gwt)
  2. 3. Copy the classes from the gwt folder into the respective packages in the core folder

4. Import a generated CoreMatchers.java from some distribution (eg from hamcrest-all.jar)

Resources

Issue 50: Hamcrest GWT support
Hamcrest GWT subversion branch
Google Group Discussion on Hamcrest GWT version

Restlet HTTPS

Problem

In its 2.0 version, it seems that Restlet has no built in support for HTTPS (see internal connectors). If trying to add a new server with the HTTPS protocol

Server server1 = component.getServers().add(Protocol.HTTPS,
                         
“localhost”, 8183);

A warning will be thrown and the server not started.

No available server connector supports the required protocols: ‘HTTPS’ . Please add the JAR of a matching connector to your classpath.

Solution

Restlet offers connectors, for instance with the Jetty web server (Restlet Wiki Jetty Connector). These in combination with the org.restlet.ext.ssl extension can be used to provide resources via HTTPS. However, it seems that the current version 2.01 does not support to use these connectors (Restlet 2.0 Connectors Wiki Page). Many of these connectors are not part of the downloadable distribution or the maven repository (in version 2.0.1). The apache http client connector, however, is: Restlet Wiki HTTP Client extension.

Resources

Restlet Wiki Configure HTTPS

Create a keystore file
Restlet Wiki SSL extension
Restlet Wiki Jetty Connector

Restlet Wiki Security Package
Blog post how to enable SSL with Restlet (might be a bit outdated)

Configure HTTPs with Jetty

Proof of Concept: GWT, Restlet, OSGi and Maven

After some difficulties I got a project working, which consists of a simple GWT application with a Restlet backend. The application consists of four OSGi bundles, which work inside eclipse PDE. Also, all of these modules and their dependencies are declared using Maven 2.

Overview:

The user interface is based on google‘s standard project from the google eclipse plugin.

bildschirmfoto2010-10-06um12-52-25.png
The button Ping triggers a very simple REST call to the server (based on example from Restlet documentation)

tstBtn.addClickHandler(new ClickHandler() {

                        @Override
                        public void onClick(ClickEvent event) {
                         ClientResource r = new ClientResource(“/ping”);

                         r.setOnResponse(new Uniform() {
                         public void handle(Request request, Response response) {
                         try {
                         tstBtn.setText(response.getEntity().getText());
                         } catch (IOException e) {
                         e.printStackTrace();
                         }
                         }
                         });
                         r.get();
                                
                        }
                        
                });

Clicking this button should result in the caption of the button being filled with a response from the server.

bildschirmfoto2010-10-06um12-55-30.png
The server resource is as following:

public class PingResource extends ServerResource {

@Get(“txt”)
public String toText() {
StringBuilder sb = new StringBuilder(“Restlet server alive. Method: “);
sb.append(getRequest().getMethod());

ChallengeResponse challengeResponse = getRequest()
.getChallengeResponse();
if (challengeResponse != null) {
sb.append(“/ Auth. scheme: “);
sb.append(challengeResponse.getScheme());
}

return sb.toString();
}
}

The send button should work in the same way as in the google example; only that the remote procedure call is facilitated using Restlet.

bildschirmfoto2010-10-06um12-58-54.png

GWT Client:

GreetingServiceAsync r = GWT.create(GreetingServiceAsync.class);
                                r.getClientResource().setReference(“/services/greet”);
                                r.getClientResource().getClientInfo().getAcceptedMediaTypes().add(new
                                                Preference<MediaType>(MediaType.APPLICATION_JAVA_OBJECT_GWT));        
                                
                                r.greetServer(new Name(nameField.getText()), new AsyncCallback<String>() {

                                        @Override
                                        public void onFailure(Throwable caught) {
                                                // Show the RPC error message to the user
                                                dialogBox
                                                                .setText(“Remote Procedure Call – Failure”);
                                                serverResponseLabel
                                                                .addStyleName(“serverResponseLabelError”);
                                                serverResponseLabel.setHTML(SERVER_ERROR+“<br/>”+caught.getMessage());
                                                dialogBox.center();
                                                closeButton.setFocus(true);
                                                
                                        }

                                        @Override
                                        public void onSuccess(String result) {
                                                dialogBox.setText(“Remote Procedure Call”);
                                                serverResponseLabel
                                                                .removeStyleName(“serverResponseLabelError”);
                                                serverResponseLabel.setHTML(result);
                                                dialogBox.center();
                                                closeButton.setFocus(true);
                                                
                                        }
                                        
                                });

Restlet Server:

public class GreetingServiceServerResource extends ServerResource implements GreetingService {

        @Override
        public Representation handle() {
                
                
                 CompositeClassLoader customCL =
new CompositeClassLoader();
                 customCL.addClassLoader(Thread.currentThread().getContextClassLoader());
                 customCL.addClassLoader(Name.
class.getClassLoader());
                
                 ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
                 Thread.currentThread().setContextClassLoader(customCL);
                
                Representation rep =
super.handle();
                
                Thread.currentThread().setContextClassLoader(oldCL);
                
                
return rep;
        }

        @Override
        @Post
        public String greetServer(Name name) throws IllegalArgumentException {
                System.
out.println(“Name submitted: “+name.name);
                
return “Welcome “+name.name+” from Restlet!”;
        }
        

}

OSGi Bundles:

Under equinox, the following modules were required:

id        State Bundle
0        ACTIVE org.eclipse.osgi_3.5.2.R35x_v20100126
         Fragments=2, 3
2        RESOLVED org.eclipse.persistence.jpa.equinox.weaving_1.1.3.v20091002-r5404
         Master=0
3        RESOLVED javax.transaction_1.1.1.v201002111330
         Master=0
17        ACTIVE org.hamcrest.core_1.1.0.v20090501071000
18        ACTIVE thrdGWTUser_0.0.2.SNAPSHOT
19        ACTIVE javax.servlet_2.5.0.v200806031605
21        ACTIVE org.junit4_4.5.0.v20090824
41        ACTIVE org.eclipse.osgi.services_3.2.0.v20090520-1800
49        ACTIVE thrdRestletGWT_0.0.2
50        ACTIVE thrdRestletExtSimple_0.0.2
51        ACTIVE zzSampleGWTClient_0.0.2
52        ACTIVE zzSampleRestletServer_0.0.2

Lessons Learned and Helpful Resources

– org.restlet.ext.simpleframework is deprecated and should not be used
– the current version for the Maven GWT plugin is 1.3-SNAPSHOT or 1.3.1.google. My projects worked with 1.3-SNAPSHOTS at the end.
– Restlet might have problems with transporting String objects. Therefore I encapsulated the String with the username in a Name object.
Classloaders: GWT RPC, OSGi and Restlet
GWT Module XXX not found in project sources or resources.
CLAP Protocol in Restlet and OSGi
GWT + OSGi + Maven
Restlet Server: OSGi and Maven
Deployment of GWT Applications (Part 2)
Maven, GWT and Eclipse Quick start (Part 1)