Showing posts with label Eclipse. Show all posts
Showing posts with label Eclipse. Show all posts

Sunday, March 28, 2010

Running JavaDoc/JUnit/Emma on Hudson using Buckminster

Last week I wrote about "Building Products with Buckminster/Hudson", today I want to share some of my experience about my JavaDoc job, running JUnit tests and Emma code coverage.

JavaDoc

My goal was to generate JavaDoc for our framework softmodeler and the server/client application.

A short overview about the checkout sources:
${workspace}/source/softmodeler/plugins
${workspace}/source/scodi-server/plugins
${workspace}/source/scodi-rcp/plugins

To prevent errors (some errors prevent JavaDoc from creating the index.html and related files) it's important to set the classpath, in my case the target platform. So I pass the location of the target platform and use a fileset to get all the jars together. This path is then referred using classpathref="files-classpath" in the javadoc call.

If you get errors about too long filenames and such, make sure you use useexternalfile="true", more information on that here.
For the actual Javadoc task I use a bunch of filesets, excluding some unwanted packages.

Here the ant "create.javadoc" target:

<target name="create.javadoc" description="Generate the JavaDoc for the sources">
<echo message="javadoc source ${source}"></echo>
<echo message="javadoc destination ${javadoc.output}"></echo>
<echo message="target platform ${target.platform}"></echo>


<!-- set target platform as classpath -->
<path id="files-classpath">
<fileset dir="${target.platform}">
<include name="*.jar"/>
</fileset>
</path>


<!-- clean and create output location -->
<delete dir="${javadoc.output}"/>
<mkdir dir="${javadoc.output}"/>


<!-- generate the javadoc -->
<javadoc
destdir="${javadoc.output}"
classpathref="files-classpath"
maxmemory="1024m"
source="1.6"
useexternalfile="true"
author="true"
version="true"
use="true"
windowtitle="Scodi/Softmodeler Documentation">
<!-- link external APIs -->
<link offline="false" href="http://java.sun.com/javase/6/docs/api/"/>
<link offline="false" href="http://www.osgi.org/javadoc/r4v42/"/>
<link offline="false" href="http://help.eclipse.org/galileo/topic/org.eclipse.platform.doc.isv/reference/api/"/>
<link offline="false" href="http://download.eclipse.org/modeling/emf/emf/javadoc/2.5.0/"/>
<link offline="false" href="http://docs.huihoo.com/javadoc/jboss/jbpm/4.1/"/>
<link offline="false" href="http://technology-related.com/javaee/5/docs/api/"/>
<link offline="false" href="http://docs.jboss.org/hibernate/stable/core/api/"/>
<link offline="false" href="http://docs.jboss.org/hibernate/stable/annotations/api/"/>
<link offline="false" href="http://docs.jboss.org/hibernate/stable/entitymanager/api/"/>
<link offline="false" href="http://jackrabbit.apache.org/api/1.4/"/>
<link offline="false" href="http://www.day.com/maven/jsr170/javadocs/jcr-1.0/"/>

<!-- softmodeler sources -->
<fileset dir="${source}/softmodeler/plugins/" defaultexcludes="true">
<include name="**/*.java"/>
<exclude name="**/org/**"/>
<exclude name="**/net/**"/>
<exclude name="**/test/**"/>
</fileset>

<!-- scodi sources -->
<fileset dir="${source}/scodi-server/plugins/">
<include name="**/*.java"/>
<exclude name="**/test/**"/>
</fileset>
<fileset dir="${source}/scodi-rcp/plugins/">
<include name="**/*.java"/>
<exclude name="**/test/**"/>
<exclude name="ch.scodi.mig/**"/>
</fileset>

<bottom><![CDATA[<i>Copyright © 2007 henzler informatik gmbh, CH-4106 Therwil</i>]]></bottom>
</javadoc>
</target>

To be able to launch the ant task from Buckminster I had to add the following action to buckminster.cspex:

<cs:public name="create.javadoc" actor="ant">
<cs:actorproperties>
<cs:property key="buildFile" value="build/javadoc.ant">
<cs:property key="targets" value="create.javadoc">
</cs:property>
<cs:properties>
<cs:property key="source" value="${workspace}source">
<cs:property key="javadoc.output" value="${workspace}javadoc">
</cs:property>
</cs:property>

The Hudson job then needs to checkout the source and run a build step "Run Buckminster":

import '${WORKSPACE}source/scodi-rcp/features/ch.scodi.client.site/site.cquery'

perform -D workspace=${WORKSPACE} -D target.platform=${WORKSPACE}../../target.platform/workspace/.metadata/.plugins/org.eclipse.pde.core/.bundle_pool/plugins/ ch.scodi.client.site#create.javadoc

I know the target.platform path is ugly, didn't find a pre-defined variable. Tried ${targetPlatformPath} but that somehow didn't work, any hints?

You then can publish the JavaDoc using the "Post-Build-Action".


Junit & Emma

Buckminster provides the command "junit" which allows you to launch "JUnit Plug-In Tests". This is a really great feature, because you can run tests in your eclipse environment very easy.
I ran into some problems because my launch file was not found, the launch needs to be within your workspace (not your checkout sources).
I imported my product site.query and did not realize that my test feature (containing the launch file) was not part of that. So additionally I had to import my test feature (see below) and it worked.

import '${WORKSPACE}source/scodi-server/features/ch.scodi.server.site/site.cquery'
import '${WORKSPACE}source/scodi-server/features/ch.scodi.server.test.site/site.cquery'

build

perform -D target.os=* -D target.ws=* -D target.arch=* -D qualifier.replacement.*=${version} ch.scodi.server.site#site.p2
perform -D target.os=win32 -D target.ws=win32 -D target.arch=x86 ch.scodi.server.site#create.product.zip

junit -l '/ch.scodi.server.test.site/ScodiServerTest.launch' -o '${WORKSPACE}output/junit_result.xml'


There is a "Post-Build-Action" to publish JUnit results. It somehow does not work with the generated output and caused my build to fail.
A great alternative is the "Performance Plugin", which publishes your result and also performance trends.

Martin Taal, founder and lead of the EMF Teneo project, wrote a very useful wiki article about Teneo building with Buckminster and Hudson.
Interesting for me was the Emma part.
To get Emma coverage reports do the following:
- Install the Emma Plug-In
- Install org.eclipse.buckminster.emma.headless.feature.feature.group to the Buckminster installation
- change the "junit" command to "emma"
- add an additional paramter for the coverage report
- Your done. Awesome!!!

emma -l '/ch.scodi.server.test.site/ScodiServerTest.launch' -o '${WORKSPACE}output/junit_result.xml' --xml '${WORKSPACE}/output/coverage_report.xml' --flatXML

The Emma "Post-Build-Action" then publishes your coverage report.

Buckminster and Hudson, a great combination which makes releng of eclipse based products so much easier. Thanks to the Buckminster team!!!

Friday, March 26, 2010

Building Products with Buckminster/Hudson

I just finished setting up our Buckminster/Hudson build server. Due to lack of documentation it was a real struggle, sharing some of my experience may help other developers.

I used Ralf's tutorial to get an good overview about the topic, great blog.

First up some information about the project I'm working on. It's a server-client application (two separated products) called scodi, which is based on our framework softmodeler. For a more detailed overview you can read my previous post, if your interested.

Target Platform

How to setup Hudson and Buckminster can be read in Ralf's tutorial. Little tip, to prevent OutOfMemoryErrors, add -Xmx1024m to the "additional parameters" of your Buckminster installation (see troubleshooting tip Hudson out of memory).

I have a separated free style job to publish my target platform for other jobs. In the "Source-Code-Management" section I checkout the feature which contains my target defintion (in my case ch.scodi.client.site).
To actually resolve the target definition, I added a build step "Run Buckminster" with the following command:
importtargetdefinition -A '${WORKSPACE}ch.scodi.client.site/TargetDefinition.target'

In the "Post-Build-Action" checked "Archive and publish an Eclipse Target Platform" and added ".metadata/.plugins/org.eclipse.pde.core/.bundle_pool" as path.

Consider that the TargetDefinition can not resolve directory locations. My target definition used to have a directory location containing bundles from the springsource repository.
I tried using the rmap file to get the bundles during materialization but had some trouble with that, so I decided to create an own update site for those bundles and add this site to the target definition. More on that can be found here: http://www.eclipse.org/forums/index.php?t=msg&th=164508&start=0&

Building the Product

After the target definition job is run, we can start building the products.
This is pretty straight forward, see Ralf's tutorial on how to checkout your source from SVN.
I have three different builds for each, server and client product: Integration, Nightly and Release.
For each build the plug-in qualifier should be different (e.g. I20100326-2, N20100326, R20100326-01).
To accomplish this I installed the flowing plug-in: http://wiki.hudson-ci.org/display/HUDSON/Version+Number+Plugin
In the integration job I choose "Create a formatted version number" name it "version" and use something like this "I${BUILD_YEAR, XXXX}${BUILD_MONTH, XX}${BUILD_DAY, XX}-${BUILDS_TODAY}" as format.

To finally build the client product I added a Buckminster build step, selected the previously published target platform and used the following as commands:
import '${WORKSPACE}source/scodi-rcp/features/ch.scodi.client.site/site.cquery'

build

perform -D target.os=* -D target.ws=* -D target.arch=* -D qualifier.replacement.*=${version} ch.scodi.client.site#site.p2.zip
perform -D target.os=win32 -D target.ws=win32 -D target.arch=x86 ch.scodi.client.site#create.product.zip
perform -D target.os=win32 -D target.ws=win32 -D target.arch=x86_64 ch.scodi.client.site#create.product.zip

Notice qualifier.replacement.*=${version}, this tells Buckminster/Eclipse to use my formated version as qualifier and results in plug-ins named like this "com.softmodeler.model_1.0.0.I20100325-3.jar", requires that Bundle-Version: 1.0.0.qualifier is defined in the bundle manifest.

Ok this post is getting long and I'm tired.
I will post some more next week about my JavaDoc build and running JUnit Tests.

Thursday, December 24, 2009

Override Eclipse Key Binding

A few weeks back is was struggling with an Eclipse key binding problem. I had to override the CTRL+S binding. Since I had my own "org.eclipse.ui.bindings" extension, I keept on getting conflict messages (no wonder).
So I thought I'll make a post as personal reference and maybe it helps some other developer.

This is what I did in ApplicationActionBarAdvisor.makeActions().

IBindingService bindingService = (IBindingService) window.getService(IBindingService.class);
bindingService.addBindingManagerListener(new IBindingManagerListener() {
@Override
public void bindingManagerChanged(BindingManagerEvent event) {
BindingManager manager = event.getManager();
for (Binding binding : manager.getBindings()) {
ParameterizedCommand command = binding.getParameterizedCommand();
if (command != null && ActionFactory.SAVE.getCommandId().equals(command.getId())) {
manager.removeBinding(binding);
}
}
}
});

IWorkbenchAction saveDocumentAction = ActionFactory.SAVE.create(window);
saveDocumentAction.setId("saveDocument");
saveDocumentAction.setActionDefinitionId(SAVE_DOCUMENT_COMMAND);

register(saveDocumentAction);

Monday, December 21, 2009

SWT instead of AWT packages

Today I got annoyed using eclipse code completion to add a KeyAdapter on a SWT component. Instead of adding the SWT KeyAdapter (since it's a SWT widget), eclipse suggests the AWT KeyAdapter before the SWT KeyAdapter. The result of this is that I often choose the wrong one.
Same thing with other classes like KeyListener, MouseListener...

So I was looking for a solution, eclipse should ignore the java.awt package.
I have not found a way to handle this for the whole workspace using preferences.
I now exclude the java.awt package in all my UI bundles from their Java Build Path.

Maybe you have had the same "trouble" and never thought about getting rid of it :-)

Wednesday, July 8, 2009

Migrate oAW projects to Eclipse Galileo

As we all know, oAW moved into the Eclipse Galileo release.
More information on that here.

The new projects can be found here:
Modeling Workflow (MWE)
Model to Text (M2T)
Textual Modeling Framework (TMF)

In the project I'm working on, we use EMF to generate the model objects and oAW to generate services for the generated objects, which then are published using Eclipse Riena.
After the Galileo release, I had to update my current oAW workflow using the new workflow components and dependencies.

First I downloaded the required bundles for my target platform and IDE, you can get them from the Galileo update site.

Galileo - http://download.eclipse.org/releases/galileo/

> Modeling
  • MWE SDK
  • Xpand SDK
  • Xtext SDK
My generator plug-in now has the following dependencies:

Bundles
  • org.eclipse.emf.mwe.core;bundle-version="0.7.0",
  • org.eclipse.emf.mwe.utils;bundle-version="0.7.0",
  • org.eclipse.xtend;bundle-version="0.7.0",
  • org.eclipse.xpand;bundle-version="0.7.0"
Packages
  • com.ibm.icu.text;version="4.0.1",
  • org.antlr.runtime;version="3.0.0",
  • org.eclipse.jdt.core,
  • org.osgi.framework,
  • org.slf4j;version="1.5.6"
Done that I renamed my workflow file from generator.oaw to generator.mwe.
Now finally the changes I made on the file itself:

old generator.oaw

<?xml version="1.0"?>
<workflow>
<property file="workflow/settings.properties"/>

<!-- properties set through the generator -->
<property name="ecoreFile" value=""/>
<property name="outputLocation" value=""/>

<!-- set up EMF for standalone execution -->
<bean class="org.eclipse.mwe.emf.StandaloneSetup" >
<platformUri value=".."/>
</bean>

<!-- load basic model and store it in slot 'model' -->
<component class="org.eclipse.mwe.emf.Reader">
<uri value="${ecoreFile}" />
<modelSlot value="model" />
</component>


<!-- Service Interfaces -->
<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Service::interface FOREACH model.eClassifiers" />
<globalVarDef name="productName" value="'${productName}'"/>
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<outlet path="${outputLocation}${serviceInterfaceSrc}" >
<postprocessor class="org.openarchitectureware.xpand2.output.JavaBeautifier" />
</outlet>
</component>

<!-- Service Objects -->
<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Service::javaClass FOREACH model.eClassifiers" />
<globalVarDef name="productName" value="'${productName}'"/>
<globalVarDef name="serviceInternalPackage" value="'${serviceInternalPackage}'"/>
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<outlet path="${outputLocation}${serviceInternalSrc}">
<postprocessor class="org.openarchitectureware.xpand2.output.JavaBeautifier" />
</outlet>
</component>

<!-- Service Properties File -->
<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Service::properties FOR model" />
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<globalVarDef name="serviceInternalPackage" value="'${serviceInternalPackage}'"/>
<outlet path="${outputLocation}${serviceInternal}/META-INF/spring/">
<postprocessor class="com.softmodeler.generator.postprocessor.XmlBeautifier" />
</outlet>
</component>

<!-- Test Cases -->
<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Test::javaClass FOREACH model.eClassifiers" />
<globalVarDef name="productName" value="'${productName}'"/>
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<globalVarDef name="testPackage" value="'${testPackage}'"/>
<outlet path="${outputLocation}${testSrc}">
<postprocessor class="org.openarchitectureware.xpand2.output.JavaBeautifier" />
</outlet>
</component>

<!-- All Tests Suite -->
<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Test::allTests FOR model" />
<globalVarDef name="testPackage" value="'${testPackage}'"/>
<globalVarDef name="productName" value="'${productName}'"/>
<outlet path="${outputLocation}${testSrc}">
<postprocessor class="org.openarchitectureware.xpand2.output.JavaBeautifier" />
</outlet>
</component>
</workflow>




new generator.mwe

<?xml version="1.0"?>
<workflow>
<property file="workflow/settings.properties"/>

<!-- properties set through the generator -->
<property name="ecoreFile" value=""/>
<property name="outputLocation" value=""/>

<!-- set up EMF for standalone execution -->
<bean class="org.eclipse.emf.mwe.utils.StandaloneSetup" >
<platformUri value=".."/>
</bean>

<!-- load model and store it in slot 'model' -->
<component class="org.eclipse.emf.mwe.utils.Reader" uri="${ecoreFile}">
<modelSlot value="model" />
</component>

<!-- first do some cleanup -->
<component class="org.eclipse.emf.mwe.utils.DirectoryCleaner" directory="${outputLocation}${serviceInterfaceSrc}" />
<component class="org.eclipse.emf.mwe.utils.DirectoryCleaner" directory="${outputLocation}${serviceInternalSrc}" />
<component class="org.eclipse.emf.mwe.utils.DirectoryCleaner" directory="${outputLocation}${serviceInternal}" />
<component class="org.eclipse.emf.mwe.utils.DirectoryCleaner" directory="${outputLocation}${testSrc}" />

<!-- Service Interfaces -->
<component class="org.eclipse.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel"/>
<expand value="template::Service::interface FOREACH model.eClassifiers" />
<globalVarDef name="productName" value="'${productName}'"/>
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<outlet path="${outputLocation}${serviceInterfaceSrc}" >
<postprocessor class="org.eclipse.xpand2.output.JavaBeautifier" />
</outlet>
</component>

<!-- Service Objects -->
<component class="org.eclipse.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel"/>
<expand value="template::Service::javaClass FOREACH model.eClassifiers" />
<globalVarDef name="productName" value="'${productName}'"/>
<globalVarDef name="serviceInternalPackage" value="'${serviceInternalPackage}'"/>
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<outlet path="${outputLocation}${serviceInternalSrc}">
<postprocessor class="org.eclipse.xpand2.output.JavaBeautifier" />
</outlet>
</component>

<!-- Service Properties File -->
<component class="org.eclipse.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel"/>
<expand value="template::Service::properties FOR model" />
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<globalVarDef name="serviceInternalPackage" value="'${serviceInternalPackage}'"/>
<outlet path="${outputLocation}${serviceInternal}/META-INF/spring/">
<postprocessor class="com.softmodeler.generator.postprocessor.XmlBeautifier" />
</outlet>
</component>

<!-- Test Cases -->
<component class="org.eclipse.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel"/>
<expand value="template::Test::javaClass FOREACH model.eClassifiers" />
<globalVarDef name="productName" value="'${productName}'"/>
<globalVarDef name="serviceInterfacePackage" value="'${serviceInterfacePackage}'"/>
<globalVarDef name="testPackage" value="'${testPackage}'"/>
<outlet path="${outputLocation}${testSrc}">
<postprocessor class="org.eclipse.xpand2.output.JavaBeautifier" />
</outlet>
</component>

<!-- All Tests Suite -->
<component class="org.eclipse.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel"/>
<expand value="template::Test::allTests FOR model" />
<globalVarDef name="testPackage" value="'${testPackage}'"/>
<globalVarDef name="productName" value="'${productName}'"/>
<outlet path="${outputLocation}${testSrc}">
<postprocessor class="org.eclipse.xpand2.output.JavaBeautifier" />
</outlet>
</component>
</workflow>



Basically only the namespace of the component classes changed.

Ending the whole story I have to say that I launch the workflow in my application using the org.eclipse.emf.mwe.core.WorkflowRunner.run(...) which works fine.
If I launch the workflow by itself "Run As -> MWE Workflow" I get an strange
"java.lang.ClassNotFoundException: org.eclipse.jface.text.BadLocationException" Exception, strange because I don't get why there should be an dependency on jface.

Monday, March 16, 2009

Use EMF and Riena

EMF, Teneo and Riena are great Eclipse projects. Use EMF to model your business objects and generate the Java code, use Teneo to persist through Hibernate and Riena to transfer your objects to the Eclipse RCP client and back. Isn't that sexy!

Nevertheless As I tried to use that setup, I ran into a few problems.
  • Transferring a 0...* reference causes an Exception: java.util.ArrayList ([...]) cannot be assigned to org.eclipse.emf.common.util.EList
  • Registered Adapters (EObjectImpl:eAdapters) can not be passed over the wire and causes Exception
  • In some cases I had trouble transferring the EObjectImpl:eProperties attribute
The way I figured to solve those issues, is the AbstractSerializerFactory.

Through extension points I can register my own EObjectSerializerFactory which uses my Deserialiser/Serializer for all EObjects.
My classes need to be in a "common" plug-in which is active on the server and client.
Both the EObjectSerializer and EObjectDeserializer are based on the JavaSerializer/JavaDeserializer provided by Caucho.

Basiclly all I do, is serializing the content of the EStructuralFeatures instead of serializing the Java fields.
So this way eFlags, eAdapters, eContainer, eContainerFeatureID and eProperties (EObjectImpl fields) are not passed over the wire.
I my case this works since I don't need the eContainer on the server.

Here the classes, maybe they help you to use the same combination:
EObjectSerializerFactory.java


/*******************************************************************************
* $URL: $
*
* Copyright (c) 2007 henzler informatik gmbh, CH-4106 Therwil
*******************************************************************************/
package com.softmodeler.service.communication;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;

import com.caucho.hessian.io.AbstractSerializerFactory;
import com.caucho.hessian.io.Deserializer;
import com.caucho.hessian.io.HessianProtocolException;
import com.caucho.hessian.io.Serializer;

/**
* EObjectSerializerFactory, provides a serializer and deserializer for EObjects
*
* @see EObjectSerializer
* @see EObjectDeserializer
* @author created by Author: fdo, last update by $Author: fdo $
* @version $Revision: 1236 $, $Date: 2009-03-03 22:51:32 +0100 (Di, 03 Mrz 2009) $
*/
public class EObjectSerializerFactory extends AbstractSerializerFactory {
/** class name suffix for implemented EClassifiers */
private static final String CLASS_SUFFIX = "Impl"; //$NON-NLS-1$
/** packages that should be excluded from reading */
private static final String[] EXCLUDE_PACKAGE_NS_URI = new String[] { "http://www.eclipse.org/emf/2002/Ecore" }; //$NON-NLS-1$

/** internal cache of all EClassifiers existing in the system, ClassifierName=>EClassifier */
private Map allClassifiers = null;

/**
* Returns a map with all relevant EClassifiers
*
* @return map ClassifierName=>EClassifier
*/
private Map getAllClassifiers() {
if (allClassifiers == null) {
allClassifiers = new HashMap();

// iterate the EPackages and place all classifiers in the allClassifiers map
for (Object value : EPackage.Registry.INSTANCE.values()) {
if (value instanceof EPackage) {
EPackage ePackage = (EPackage) value;
if (isValidPackage(ePackage.getNsURI())) {
for (EClassifier eClassifier : ePackage.getEClassifiers()) {
allClassifiers.put(eClassifier.getName(), eClassifier);
}
}
}
}
}
return allClassifiers;
}

/**
* Returns true if the package is valid (not in the EXCLUDE_PACKAGE_NS_URI list)
*
* @param nsURI the package NameSpace URI
* @return true if valid
*/
private boolean isValidPackage(String nsURI) {
for (String excludePackage : EXCLUDE_PACKAGE_NS_URI) {
if (excludePackage.equals(nsURI)) {
return false;
}
}
return true;
}

/**
* Returns the EClassifier for the passed Class
*
* @param cl
* @return returns null if the class is not an EObject or not found in the EPackages
*/
@SuppressWarnings("unchecked")
private EClass getClassifier(Class cl) {
if (EObject.class.isAssignableFrom(cl)) {
String name = cl.getSimpleName();
if (name.endsWith(CLASS_SUFFIX)) {
EClassifier classifier = getAllClassifiers().get(name.substring(0, name.indexOf(CLASS_SUFFIX)));
if (classifier instanceof EClass) {
return (EClass) classifier;
}
}
}
return null;
}

@SuppressWarnings("unchecked")
@Override
public Deserializer getDeserializer(Class cl) throws HessianProtocolException {
EClass classifier = getClassifier(cl);
if (classifier != null) {
return new EObjectDeserializer(classifier);
}
return null;
}

@SuppressWarnings("unchecked")
@Override
public Serializer getSerializer(Class cl) throws HessianProtocolException {
EClass classifier = getClassifier(cl);
if (classifier != null) {
return new EObjectSerializer(classifier);
}
return null;
}
}




EObjectSerializer.java


/*******************************************************************************
* $URL: $
*
* Copyright (c) 2007 henzler informatik gmbh, CH-4106 Therwil
*******************************************************************************/
package com.softmodeler.service.communication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.impl.EObjectImpl;

import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.AbstractSerializer;
import com.caucho.hessian.io.JavaSerializer;

/**
* Serializes EObjects, this class is based on the {@link JavaSerializer} instead of working with java fields,
* {@link EStructuralFeature} are used to serialize the 'data' values of the {@link EObject}.

* Java fields of the {@link EObjectImpl}; eAdapters, eFlags, eContainer, eContainerFeatureID and eProperties are
* ignored
*
* @see JavaSerializer
* @author created by Author: fdo, last update by $Author: fdo $
* @version $Revision: 1151 $, $Date: 2009-02-25 22:47:19 +0100 (Mi, 25 Feb 2009) $
*/
public class EObjectSerializer extends AbstractSerializer {
private List fieldSerializers;
private List fields;

/**
* constructor
*
* @param classifier
*/
@SuppressWarnings("unchecked")
public EObjectSerializer(EClass classifier) {
fields = classifier.getEAllStructuralFeatures();
fieldSerializers = new ArrayList();

for (EStructuralFeature feature : fields) {
if (!feature.isMany()) {
EClassifier eDataType = feature.getEType();
Class type = eDataType.getInstanceClass();
fieldSerializers.add(getFieldSerializer(type));
} else {
fieldSerializers.add(ListFieldSerializer.SER);
}
}
}

@SuppressWarnings("unchecked")
@Override
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
if (out.addRef(obj)) {
return;
}

Class cl = obj.getClass();

int ref = out.writeObjectBegin(cl.getName());

if (ref < -1) { writeObject10((EObject) obj, out); } else { if (ref == -1) { writeDefinition20(out); out.writeObjectBegin(cl.getName()); } writeInstance((EObject) obj, out); } } private void writeObject10(EObject obj, AbstractHessianOutput out) throws IOException { for (int i = 0; i < feature =" fields.get(i);" i =" 0;" feature =" fields.get(i);" ser =" new" value =" null;" value =" obj.eGet(feature);" ser =" new" value =" false;" value =" (Boolean)" ser =" new" value =" 0;" value =" (Integer)" ser =" new" value =" 0;" value =" (Long)" ser =" new" value =" 0;" value =" (Double)" ser =" new" value =" null;" value =" (String)" ser =" new" value =" null;" objvalue =" (List)" value =" new">



EObjectDeserializer.java


/*******************************************************************************
* $URL: $
*
* Copyright (c) 2007 henzler informatik gmbh, CH-4106 Therwil
*******************************************************************************/
package com.softmodeler.service.communication;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;

import com.caucho.hessian.io.AbstractHessianInput;
import com.caucho.hessian.io.AbstractMapDeserializer;
import com.caucho.hessian.io.HessianFieldException;
import com.caucho.hessian.io.IOExceptionWrapper;
import com.caucho.hessian.io.JavaDeserializer;

/**
* Deserializes EObjects, this class is based on the {@link JavaDeserializer} instead of working with java fields,
* {@link EStructuralFeature} are used to deserialize the 'data' values of the {@link EObject}.

* Java fields of the {@link EObjectImpl}; eAdapters, eFlags, eContainer, eContainerFeatureID and eProperties are
* ignored
*
* @see JavaDeserializer
* @author created by Author: fdo, last update by $Author: fdo $
* @version $Revision: 1236 $, $Date: 2009-03-03 22:51:32 +0100 (Di, 03 Mrz 2009) $
*/
public class EObjectDeserializer extends AbstractMapDeserializer {
private Map fieldMap;
private EClass classifier;

/**
* constructor
*
* @param classifier
*/
public EObjectDeserializer(EClass classifier) {
this.classifier = classifier;
fieldMap = getFieldMap(classifier);
}

@SuppressWarnings("unchecked")
@Override
public Class getType() {
return classifier.getInstanceClass();
}

@Override
public Object readMap(AbstractHessianInput in) throws IOException {
try {
EObject obj = instantiate();

return readMap(in, obj);
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(classifier.getName() + ":" + e.getMessage(), e); //$NON-NLS-1$
}
}

@Override
public Object readObject(AbstractHessianInput in, String[] fieldNames) throws IOException {
try {
Object obj = instantiate();
return readObject(in, (EObject) obj, fieldNames);
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(classifier.getName() + ":" + e.getMessage(), e); //$NON-NLS-1$
}
}

public Object readMap(AbstractHessianInput in, EObject obj) throws IOException {
try {
int ref = in.addRef(obj);

while (!in.isEnd()) {
Object key = in.readObject();

FieldDeserializer deser = fieldMap.get(key);

if (deser != null) {
deser.deserialize(in, obj);
} else {
in.readObject();
}
}

in.readMapEnd();

in.setRef(ref, obj);
return obj;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}

public Object readObject(AbstractHessianInput in, EObject obj, String[] fieldNames) throws IOException {
try {
int ref = in.addRef(obj);

for (String name : fieldNames) {
FieldDeserializer deser = fieldMap.get(name);

if (deser != null) {
deser.deserialize(in, obj);
} else {
in.readObject();
}
}

in.setRef(ref, obj);
return obj;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(obj.getClass().getName() + ":" + e, e); //$NON-NLS-1$
}
}

/**
* create an instance of the passed classifier
*
* @return
* @throws Exception
*/
protected EObject instantiate() throws Exception {
return EcoreUtil.create(classifier);
}

/**
* Creates a map featureName=>FieldDeserializer.
*/
@SuppressWarnings("unchecked")
protected Map getFieldMap(EClass classifier) {
Map fieldMap = new HashMap();

for (EStructuralFeature feature : classifier.getEAllStructuralFeatures()) {
if (feature.isTransient() || fieldMap.containsKey(feature.getName())) {
continue;
}
FieldDeserializer deser;

EClassifier eDataType = feature.getEType();
Class type = eDataType.getInstanceClass();

if (String.class.equals(type)) {
deser = new StringFieldDeserializer(feature);
} else if (byte.class.equals(type)) {
deser = new ByteFieldDeserializer(feature);
} else if (short.class.equals(type)) {
deser = new ShortFieldDeserializer(feature);
} else if (int.class.equals(type)) {
deser = new IntFieldDeserializer(feature);
} else if (long.class.equals(type)) {
deser = new LongFieldDeserializer(feature);
} else if (float.class.equals(type)) {
deser = new FloatFieldDeserializer(feature);
} else if (double.class.equals(type)) {
deser = new DoubleFieldDeserializer(feature);
} else if (boolean.class.equals(type)) {
deser = new BooleanFieldDeserializer(feature);
} else if (feature.isMany()) {
deser = new EListDeserializer(feature);
} else {
deser = new ObjectFieldDeserializer(feature);
}

fieldMap.put(feature.getName(), deser);
}
return fieldMap;
}

abstract static class FieldDeserializer {
protected EStructuralFeature feature;

public FieldDeserializer(EStructuralFeature feature) {
this.feature = feature;
}

abstract void deserialize(AbstractHessianInput in, EObject obj) throws IOException;

}

static class EListDeserializer extends FieldDeserializer {

EListDeserializer(EStructuralFeature feature) {
super(feature);
}

@SuppressWarnings("unchecked")
@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
List value = null;

try {
value = (List) in.readObject(List.class);
if (value.size() > 0) {
obj.eSet(feature, value);
}
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class ObjectFieldDeserializer extends FieldDeserializer {

ObjectFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
Object value = null;

try {
value = in.readObject(feature.getEType().getInstanceClass());

if (value != null) {
obj.eSet(feature, value);
}
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class BooleanFieldDeserializer extends FieldDeserializer {
BooleanFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
boolean value = false;

try {
value = in.readBoolean();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class ByteFieldDeserializer extends FieldDeserializer {
ByteFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
int value = 0;

try {
value = in.readInt();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class ShortFieldDeserializer extends FieldDeserializer {
ShortFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
int value = 0;

try {
value = in.readInt();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class IntFieldDeserializer extends FieldDeserializer {
IntFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
int value = 0;

try {
value = in.readInt();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class LongFieldDeserializer extends FieldDeserializer {
LongFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
long value = 0;

try {
value = in.readLong();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class FloatFieldDeserializer extends FieldDeserializer {
FloatFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
double value = 0;

try {
value = in.readDouble();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class DoubleFieldDeserializer extends FieldDeserializer {
DoubleFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
double value = 0;

try {
value = in.readDouble();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static class StringFieldDeserializer extends FieldDeserializer {
StringFieldDeserializer(EStructuralFeature feature) {
super(feature);
}

@Override
void deserialize(AbstractHessianInput in, EObject obj) throws IOException {
String value = null;

try {
value = in.readString();

obj.eSet(feature, value);
} catch (Exception e) {
logDeserializeError(feature, obj, value, e);
}
}
}

static void logDeserializeError(EStructuralFeature feature, Object obj, Object value, Throwable e)
throws IOException {
String fieldName = (feature.getContainerClass().getName() + "." + feature.getName()); //$NON-NLS-1$

if (e instanceof HessianFieldException) {
throw (HessianFieldException) e;
} else if (e instanceof IOException) {
throw new HessianFieldException(fieldName + ": " + e.getMessage(), e); //$NON-NLS-1$
}

if (value != null) {
throw new HessianFieldException(fieldName + ": " + value.getClass().getName() + " (" + value + ")" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ " cannot be assigned to " + feature.getEType().getName()); //$NON-NLS-1$
} else {
throw new HessianFieldException(fieldName + ": " + feature.getEType().getName() //$NON-NLS-1$
+ " cannot be assigned from null", e); //$NON-NLS-1$
}
}
}

Monday, December 1, 2008

Eclipse Nebula

I was searching for a better SWT DateTime widget, since the standard widget isn't really "done" yet.
Durring my search I stumbled over the Eclipse Nebula project, which provides a few real nice widgets that extend the SWT widget collection.

Currently the widgets are in Alpha and Beta status. Right now I'm using the DateChooserCombo in a CellEditor, I found and reported a Bug and hope the widgets will be stabilzed soon.

http://www.eclipse.org/nebula/

Thursday, August 21, 2008

oaw Output Postprocessor (Beautifier)

I'm working on a project using oaw to generate java classes, spring definitions, ecore models and a lot more.

There is a pretty nice JavaBeautifier to clean up my generated classes. The problem was the XmlBeautifier, it didn't remove white spaces. This resulted in some pretty ugly xml files.

So I searched the web for some alternative, didn't find one so I modified the original for my own needs.
Here is the code if someone approaches the same problem.



/*
*
*
* Copyright (c) 2005-2006 Sven Efftinge (http://www.efftinge.de) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sven Efftinge (http://www.efftinge.de) - Initial API and implementation
*
*

*/
package com.softmodeler.generator.postprocessor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openarchitectureware.util.EncodingDetector;
import org.openarchitectureware.xpand2.output.FileHandle;
import org.openarchitectureware.xpand2.output.PostProcessor;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
* *
*
* @author Sven Efftinge (http://www.efftinge.de)
* @author Bernd Kolb
*/
public class XmlBeautifier implements PostProcessor {

private final Log log = LogFactory.getLog(getClass());

private String[] fileExtensions = new String[] { ".xml", ".xsl", ".xsd", ".wsdd", ".wsdl", ".ecore" };

public void setFileExtensions(final String[] fileExtensions) {
this.fileExtensions = fileExtensions;
}

public void beforeWriteAndClose(final FileHandle info) {
if (isXmlFile(info.getTargetFile().getAbsolutePath())) {
try {
// TODO this is only a heuristic, but it should work for most cases. This really is the beginning of reimplementing
// the XML parser just because we do RAM rather then file based beautification...
final String bufferedString = info.getBuffer().toString().trim();
final int indEncoding = bufferedString.indexOf("encoding");
final int indEndHeader = bufferedString.indexOf("?>");
String readEncoding = null;
Document doc = null;
if (bufferedString.startsWith(" 0 && indEncoding < readencoding =" info.getFileEncoding();" doc =" parseDocument(bufferedString," doc =" parseDocument(bufferedString," tfactory =" TransformerFactory.newInstance();" threadid="562510&tstart="90" showtopic="788" serializer =" tfactory.newTransformer();" systemvalue =" doc.getDoctype().getSystemId();" publicid =" doc.getDoctype().getPublicId();" bytearrayoutputstream =" new" string =" byteArrayOutputStream.toString(info.getFileEncoding());" nodelist =" node.getChildNodes();" i =" 0;" child =" nodeList.item(i);"> encodingsToTry = new ArrayList();
if (encoding != null) {
encodingsToTry.add(encoding);
} else {
byte[] sampleBytes = bufferedString.substring(0, Math.min(64, bufferedString.length())).getBytes();
encodingsToTry.add(EncodingDetector.detectEncoding(sampleBytes).displayName());
encodingsToTry.add("ISO-8859-1");
encodingsToTry.add("UTF-8");
encodingsToTry.add("MacRoman");
encodingsToTry.add("UTF-16");
encodingsToTry.add("UTF-16BE");
encodingsToTry.add("UTF-16LE");
}
encodingsToTry.add(System.getProperty("file.encoding"));

Document doc = null;
Exception lastException = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);
factory.setValidating(false);

DocumentBuilder builder = factory.newDocumentBuilder();

builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
builder.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException exception) throws SAXException {
log.warn(exception.getMessage());
}

public void fatalError(SAXParseException exception) throws SAXException {
if (exception.getMessage() != null && exception.getMessage().startsWith("Invalid byte")) {
// ignore, since we try other encodings
} else {
log.warn(exception.getMessage());
}
}

public void warning(SAXParseException exception) throws SAXException {
log.debug(exception.getMessage());
}
});

for (Iterator it = encodingsToTry.iterator(); it.hasNext();) {
String enc = it.next();
try {
doc = builder.parse(new ByteArrayInputStream(bufferedString.getBytes(enc)));
// if no error exit here
break;
} catch (Exception e) {
lastException = e;
}
}
if (doc == null && lastException != null) {
throw lastException;
} else {
return doc;
}
}

public boolean isXmlFile(final String absolutePath) {
for (int i = 0; i <>



The only difference to the original Beautifier is the removeWhiteSpaces method and it's call.

If you want to use this class or make your own for any other job, place the class in your generator plug-in and add the following config in your oaw workflow file:

<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Nls::modelEcoreFile FOR model" />
<outlet path="${model-ecore}">
<postprocessor class="com.softmodeler.generator.postprocessor.XmlBeautifier"/>
</outlet>
</component>

Wednesday, June 11, 2008

Spring Dynamic Modules and Hibernate

I'm currently working on a Sourceforge project.
On the server side I want to use Spring DM and Hibernate.
Eclipse RCP and Spring DM builds the client.

I spent the last few evenings trying and searching for a working Spring DM/Hibernate example. I had a lot of classloading issues.
Yesterday I got it to work, you can download the plug-in here.

It's a simple application handling a User object and using HSQL as database.

I added all the dependent jars in the /lib directory. You can create separated plug-ins for them if you want.
Here a list of all the jar files, because thats where I had my problems:
  • cglib-nodep-2.1_3.jar
  • commons-collections.jar
  • commons-dbcp.jar
  • commons-pool.jar
  • dom4j-1.6.1.jar
  • hibernate3.jar
  • hsqldb.jar
  • jta.jar
  • spring-core.jar
  • spring-jdbc.jar
  • spring-orm.jar
  • spring-tx.jar // why is the org.springframework.dao package in this jar?

You can access the service in the Test class:

package com.blogspot.swissdev.springservice;

import org.osgi.framework.BundleContext;

/**
*
* @author Flavio Donze
*/
public class Test {

private BundleContext context = Activator.getDefault().getContext();

public void start() {
System.out.println("starting the test...");

UserService service = (UserService) context.getService(context.getServiceReference(UserService.class.getName()));

User user = (User) context.getService(context.getServiceReference(User.class.getName()));
user.setPassword("pass");
user.setUsername("user");
service.store(user);

for (User u : service.findAll())
{
System.out.println("User: "+u.getId() + ", " + u.getUsername() + ", " + u.getPassword());
}
}
}


And here is my Spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="META-INF/spring/database.properties"/>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>

<bean id="test" init-method="start" class="com.blogspot.swissdev.springservice.Test"/>

<!-- USER beans, POJO, DAO, Service -->
<bean id="user" class="com.blogspot.swissdev.springservice.UserImpl" scope="prototype">
</bean>

<bean id="userDao" class="com.blogspot.swissdev.springservice.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

<bean id="userService" class="com.blogspot.swissdev.springservice.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>

</beans>
Since I just wanted to get Spring DM and Hibernate to work, I didn't really test the rest, just in case you encounter some bugs.

To setup your workspace with Spring DM read the first part of my previous post.

For this example I used:
Eclipse 3.4 RC3
Spring Dynamic Modules for OSGi(tm) 1.0.2

Wednesday, June 4, 2008

Eclipse RCP Application using Spring DM

Last week I was searching the web for some example of Spring DM running on a Eclipse RCP application.
Didn't find one, so I thought I could write a post.

Download:
Eclipse 3.4 RC3
Spring Dynamic Modules for OSGi(tm) 1.0.2

Now create a new Plug-in-Project, using the settings below:
























As a next step you have to import the Spring DM Plug-ins.
File->Import->Plug-in Development->Plug-ins and Fragments.
Point the plug-in location to the extracted "spring-osgi-1.0.2/dist" directory.



On the next page, add the following plug-ins:
  • org.springframework.bundle.osgi.core
  • org.springframework.bundle.osgi.extender
  • org.springframework.bundle.osgi.io
You just imported the Spring DM OSGi part, you also need the actual Spring framework.
Do the same as above, but instead of the "dist" directory select the "spring-osgi-1.0.2/lib" dir and select those plugins:
  • org.springframework.bundle.spring.aop
  • org.springframework.bundle.spring.beans
  • org.springframework.bundle.spring.context
  • org.springframework.bundle.spring.core
  • org.springframework.osgi.aopalliance.osgi
We have to manually create a apache commons logging plugin.
Spring DM has some classloading problems with the existing plugin contained in the eclipse platform.
New->Plug-in Development->Plug-in from existing JAR archives.
Add External...
Now if you have the Spring framework including dependencies on your machine select the commons-logging.jar located at "spring-framework-2.5.x/lib/jakarta-commons", otherwise download the jar here.
Name the plugin "org.apache.commons.logging

Ok, so now your workspace is ready.
Let's create a Spring service.

package swissdev.springdm;

public interface IMyService {

String getSomething();
}


package swissdev.springdm;

public class MyService implements IMyService {

@Override
public String getSomething() {
return "something";
}

public void start() {
System.out.print("start service");
}

public void stop() {
System.out.print("stop service");
}
}

META-INF/spring/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="myService"
class="swissdev.springdm.MyService"
init-method="start"
destroy-method="stop"/>

</beans>


META-INF/spring/applicationContext-osgi.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:osgi="http://www.springframework.org/schema/osgi"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd">

<osgi:service id="myServiceOsgi" ref="myService" interface="swissdev.springdm.IMyService"/>

</beans>


Our application is basically ready to launch, so lets do that.
Right click on the swissdev.springdm plug-in: Run-As -> Eclipse Application.
A simple window containing a view is launched, nothing special.

Open the run configuration: Run -> Run Configurations...
Select your "swissdev.springdm.application" launch config and change to the "Arguments" tab.
Add "-console" to the Program arguments.
Switch to the Plug-ins tab and select all the "Workspace" plug-ins, hit the "Add Required Plug-ins" button and run again.
Type ss in the console, you will get the following output:



So our Spring plug-ins are not active.
Open the run configurations again and switch to the "Configurations" tab, change the Configurations File option to "Use existing config.ini file as a template" and enter ${workspace_loc}/swissdev.springdm/config.ini.
We can get the default generated config.ini in our workspace.
It's located at /.metadata/.plugins/org.eclipse.pde.core/swissdev.springdm.application/config.ini, copy it to your plug-in.
Right click on the ini file and select Open With -> Text Editor.
Ctrl+f Find: extender
You should find ....org.springframework.bundle.osgi.extender add @start at the end:
org.springframework.bundle.osgi.extender@start
Do the same with the swissdev.springdm plugin.

Launch again, you will see a lot of output and somewhere between "start service", thats the output we defined in the MyService class.
Spring DM is working!

To use our service we first need to modify our Activator:

private BundleContext context;

public BundleContext getContext() {
return context;
}

public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
this.context = context;
}



Open the generated View class and edit the createPartControl method:

public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(getViewSite());
viewer.addDoubleClickListener(new IDoubleClickListener() {

@Override
public void doubleClick(DoubleClickEvent event) {
ServiceTracker tracker = new ServiceTracker(Activator.getDefault().getContext(), IMyService.class.getName(),null);
tracker.open();
IMyService service = (IMyService) tracker.getService();
System.out.println(service.getSomething());
}
});
}


Launch again and double click one of the itms in the window, in the console there should appear an "something" output.

That was it....