<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TechJava&#187; TechJava &#8211; Articles on java</title>
	<atom:link href="http://www.techjava.de/topics/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.techjava.de</link>
	<description>Journal on Java Technology</description>
	<lastBuildDate>Thu, 17 Jun 2010 10:41:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Extending Xtext Build Participants</title>
		<link>http://www.techjava.de/topics/2010/06/extending-xtext-build-participants/</link>
		<comments>http://www.techjava.de/topics/2010/06/extending-xtext-build-participants/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:41:21 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mdsd]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[builder]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[oaw]]></category>
		<category><![CDATA[xpand]]></category>
		<category><![CDATA[xtend]]></category>
		<category><![CDATA[xtext]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=674</guid>
		<description><![CDATA[
You&#8217;ve definitely heard about 
Xtext, the famous text modeling framework, 
community award winner . We are all looking forward to the new project management wonder: the 
release of Helios, upcoming on June the 23rd, which will include Xtext 1.0.0. In this article, I want do describe some aspects of integration of Xtext-based languages into IDE.
Introduction
Creating [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.techjava.de/wp-content/uploads/builder_hands.jpg" alt="" title="builder_hands" width="150" height="99" style="margin:10px; float: right;" /><br />
You&#8217;ve definitely heard about 
<a  href="http://www.eclipse.org/Xtext/" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/Xtext/');" >Xtext</a>, the famous text modeling framework, 
<a  href="http://www.eclipse.org/org/press-release/20100322_awardswinners.php" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/org/press-release/20100322_awardswinners.php');" >community award winner </a>. We are all looking forward to the new project management wonder: the 
<a  href="http://www.eclipse.org/helios/" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/helios/');" >release of Helios</a>, upcoming on June the 23rd, which will include Xtext 1.0.0. In this article, I want do describe some aspects of integration of Xtext-based languages into IDE.<span id="more-674"></span></p>
<h3>Introduction</h3>
<p>Creating your own domain-specific textual languages in Xtext is really easy, and the authors in 
<a  href="http://xtext.itemis.com/" onclick="javascript:pageTracker._trackPageview('/external/xtext.itemis.com/');" >Northern Germany</a> are doing a good job to make it even easier. Once you have a language, you want to process it and this means usually to transform your model into another representation. The facility responsible for this transformation is called generator and consists of a bunch of transformation templates (e.G. XPand) and some code executing them. On some event, the model is read in and the transformations are applied to produce code. Currently, there are two ways of triggering the transformation: you can put the calling infrastructure in a Modeling Workflow Engine file, which is a kind of batch script or you can write a build-participant, which react on the changes in the model. In this article I want to describe my experiences with the builder approach.</p>
<h3>Examining initial builder</h3>
<p>The base idea behind the builder approach is the fact, that Xtext provides an project builder, which watches for all Xtext resource changes (Xtext-based DSL models) and notifies the so-called XtextBuilderParticipants. These are registered using Eclipse extension point <code>org.eclipse.xtext.builder.participant</code> and implement the <code>IXtextBuilderParticipant</code> interface:</p>
<pre class="brush: java;">
...
public interface IXtextBuilderParticipant {
    void build(IBuildContext context, IProgressMonitor monitor) throws CoreException;
}

public interface IBuildContext {
    IProject getBuiltProject();
    List&lt;IResourceDescription.Delta&gt; getDeltas();
    ResourceSet getResourceSet();
    void needRebuild();
}
</pre>
<p>In order not to start completely from scratch, let us examine the builder provided in the Domain-Model-Example, delivered with Xtext. In the build method the example builder processes as follows:</p>
<ul>
<li>checks that the project is a Java project</li>
<li>finds the generation folder</li>
<li>creates an Output</li>
<li>creates an Outlet and registers it in the Output</li>
<li>registers a post-processor managing Java imports on the outlet</li>
<li>creates the Xpand execution context</li>
<li>registers the Java Beans version of the metamodel</li>
<li>processes the changes and analyses if the files have to be deleted or not prior re-generation</li>
<li>for all changed model elements re-generates</li>
</ul>
<p>Quite a lot of tasks, so there is a good reason, why 
<a  href="http://wiki.eclipse.org/Modeling_Workflow_Engine_%28MWE%29" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/Modeling_Workflow_Engine_%28MWE%29');" >MWE</a> scripts are used for generation. </p>
<h3>Using Project natures</h3>
<p>The first improvement I created for the builder is the ability to distinguish DSLs. The problem of triggering <strong>all</strong> XtextBuildParticipants on the change of <strong>any</strong> Xtext-based resource is that the entire Workspace gets re-generated. In my scenario, we used three DSLs and a random change caused three builders to run, even if the change has been made in another project of workspace. In order to solve this problem I used the standard Eclipse way to distinguish projects: Project Natures. </p>
<p>The nature I created is used as a marker for the builder and is emtpy:</p>
<pre class="brush: java;">
public class UiNature implements IProjectNature {
	public static final String NATURE_ID = &quot;de.techjava.dsl.uiNature&quot;;
	private IProject project;

	public void configure() throws CoreException {
        }

	public void deconfigure() throws CoreException {
	}
	public IProject getProject() {
		return project;
	}
	public void setProject(IProject project) {
		this.project = project;
	}
}
</pre>
<p>Don&#8217;t forget to register it in the plugin.xml:</p>
<pre class="brush: xml;">
   &lt;extension point=&quot;org.eclipse.core.resources.natures&quot;
         id=&quot;de.techjava.dsl.uiNature&quot;
         name=&quot;User Interface DSL Project Nature&quot;&gt;
      &lt;runtime&gt;
         &lt;run class=&quot;de.techjava.dsl.userinterface.builder.UiNature&quot; /&gt;
      &lt;/runtime&gt;
   &lt;/extension&gt;
</pre>
<p>As the first line in my builder I check the presence of the nature in the current project and stop building if the nature is not present:</p>
<pre class="brush: java;">
if (!context.getBuiltProject().hasNature(UiNature.NATURE_ID)) {
	// skip projects without UI DSL nature
	return;
}
</pre>
<p>Now, what is missing is the ability to add and remove the nature to/from the project. I liked the way how Xpand/Xtend Natures are configured (using toggle action in configure menu of the project pop-up menu). What you need is a ToggleAction that can be switched on, if the nature is not present and switched off, if the nature is installed. </p>
<pre class="brush: java;">
public class ToggleNatureAction implements IObjectActionDelegate {
	private ISelection selection;
	@SuppressWarnings(&quot;unchecked&quot;)
	public void run(IAction action) {
		if (selection instanceof IStructuredSelection) {
			for (Iterator it = ((IStructuredSelection) selection).iterator(); it.hasNext();) {
				Object element = it.next();
				IProject project = null;
				if (element instanceof IProject) {
					project = (IProject) element;
				} else if (element instanceof IAdaptable) {
					project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
				}
				if (project != null) {
					toggleNature(project);
				}
			}
		}
	}

	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}

	/**
	 * Toggles sample nature on a project
	 * @param project to have sample nature added or removed
	 */
	private void toggleNature(IProject project) {
	// implemetation of toggle nature ...
	}
}
</pre>
<p>In order to make an action to a toggle-action the 
<a  href="http://wiki.eclipse.org/index.php/Platform_Command_Framework" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/index.php/Platform_Command_Framework');" >Eclipse Command Framework</a>, 
<a  href="http://wiki.eclipse.org/Menu_Contributions" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/Menu_Contributions');" >Object Contributions</a> and the 
<a  href="http://wiki.eclipse.org/Command_Core_Expressions" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/Command_Core_Expressions');" >Command Core Expressions</a> are needed. The idea is to register two actions as object contributions on the IProject using the <code>org.eclipse.ui.popupMenus</code> extension point and define visibility of those to be complement to each other (if one is visible the other is not) based on the object state, which is the presence of a project nature. The actions used point to the same implementation class but have different labels. The menu path to pop-up menu <strong>Project &gt; Configure</strong> is <strong>org.eclipse.ui.projectConfigure/additions</strong>. The visibility is defined based on the objectState:</p>
<pre class="brush: xml;">
  &lt;extension point=&quot;org.eclipse.ui.popupMenus&quot;&gt;
      &lt;objectContribution adaptable=&quot;true&quot;
            id=&quot;de.techjava.dsl.userinterface.ui.addNature&quot;
            objectClass=&quot;org.eclipse.core.resources.IProject&quot;&gt;
         &lt;action
               class=&quot;de.techjava.dsl.userinterface.ui.action.ToggleNatureAction&quot;
               id=&quot;de.techjava.dsl.userinterface.ui.AddNatureAction&quot;
               label=&quot;Add User Interface DSL Nature&quot;
               menubarPath=&quot;org.eclipse.ui.projectConfigure/additions&quot;&gt;
         &lt;/action&gt;
         &lt;visibility&gt;
            &lt;not&gt;&lt;objectState name=&quot;nature&quot; value=&quot;de.techjava.dsl.uiNature&quot; /&gt;&lt;/not&gt;
         &lt;/visibility&gt;
      &lt;/objectContribution&gt;
      &lt;objectContribution adaptable=&quot;true&quot;
            id=&quot;de.techjava.dsl.userinterface.ui.removeNature&quot;
            objectClass=&quot;org.eclipse.core.resources.IProject&quot;&gt;
         &lt;action
               class=&quot;de.techjava.dsl.userinterface.ui.action.ToggleNatureAction&quot;
               id=&quot;de.techjava.dsl.userinterface.ui.AddNatureAction&quot;
               label=&quot;Remove User Interface DSL Nature&quot;
               menubarPath=&quot;org.eclipse.ui.projectConfigure/additions&quot;&gt;
         &lt;/action&gt;
         &lt;visibility&gt;
            &lt;objectState name=&quot;nature&quot; value=&quot;de.techjava.dsl.uiNature&quot; /&gt;
         &lt;/visibility&gt;
      &lt;/objectContribution&gt;
   &lt;/extension&gt;
</pre>
<p>Please note, that the nature is implemented and registered inside of the generator project and the toggle action is implemented in the UI project. Finally, the code of the toggleNature method, which is the standard code for the project nature installation and removal:</p>
<pre class="brush: java;">
...
	IProjectDescription description = project.getDescription();
	String[] natures = description.getNatureIds();

	// remove the nature
	for (int i = 0; i &lt; natures.length; ++i) {
		// if nature exists
		if (NATURE_ID.equals(natures[i])) {
			// Remove the nature
			String[] newNatures = new String[natures.length - 1];
			System.arraycopy(natures, 0, newNatures, 0, i);
			System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1);
			description.setNatureIds(newNatures);
			project.setDescription(description, null);
			return;
		}
	}

	// Add the nature
	String[] newNatures = new String[natures.length + 1];
	System.arraycopy(natures, 0, newNatures, 0, natures.length);
	newNatures[natures.length] = NATURE_ID;
	description.setNatureIds(newNatures);
	project.setDescription(description, null);
...
</pre>
<p>That&#8217;s it, run and right-click on the Project and then go to the Configure Menu (pretty low in the pop-up) and you will see the result:<br />
<img src="http://www.techjava.de/wp-content/uploads/both-features.png" alt="" title="both-features" width="507" height="145" style="margin:10px; float:left" /></p>
<h3>Parameterizing generator</h3>
<p>Domain-specific languages should cover only the real requirements and incorporate the specific decision made in the project. So far the theory, but in fact it is a trade-off and a compromise, what is a part of the language and what is too specific to be covered. The same holds for the generator: on the one hand you want the generator to solve exactly your problem, on the other hand you want to make it generic enough to cover a class of similar problems. </p>
<p>I faced the problem of using the generator for two teams in a big project, where the langage could be reused, but the generation infrastructure need to be slightly modified. For example, the information about the generation target folder, package prefix and the fact which artifact should be generated differred between the teams. In the same time the teams were able to agree on the same language. In order not to develop two generators, I decided to parameterize the generator and the templates. </p>
<p>The Xpand2/Xtend developers provided a way of parameterization of the templates using the so-called Global Variables, using the GLOBALVAR keyword. My favorite way of using it is to create a cached extension for reading the variable:</p>
<pre class="brush: bash;">
/*
 * Retrieves the boolean value of the global variable set from outside of the template
 */
cached Boolean generateService() :
    GLOBALVAR generateService == &quot;true&quot;
;
</pre>
<p>In order to set global variables from the build participant the XPand execution context constructor takes a <code>Map&lt;String, Variable&gt;</code> argument. The nice story about the global variables, that you can provide any objects as values. So the advantage over the usage of MWE workflow with property files read-in during processing is the big flexibility in providing the object-graphs or even statefull objects as global variable values. A good example of usage of global variable is provided in Domain-Example with Java Import Tool:</p>
<pre class="brush: java; highlight: [4,5];">
JavaImportsTool importsTool = new JavaImportsTool();
...
ctx = new XpandExecutionContextImpl(output, null,
    Collections.singletonMap(JavaImportsTool.VAR_NAME,
    new Variable(JavaImportsTool.VAR_NAME,importsTool)),
    null, null);
...
</pre>
<p>In the same time it is important to be able to load simple properties from file in the generation project. For example you could implement your own ModelProperties container, which reads properties from the file located in the generation project. For example:</p>
<pre class="brush: java;">
public class ModelProperties extends Properties {
	/**
	 * Indicates that no timestamp is available
	 */
	private static final long NO_TIMESTAMP = -1;

	private long lastModified = NO_TIMESTAMP;
	private final IFile propertyFile;
	private final HashMap&lt;String, Variable&gt; globalVars;

	/**
	 * Creates a valid model properties instance
	 *
	 * @param aProject reference to the current project
	 * @param name of the property file
	 * @throws CoreException on errors
	 */
	public ModelProperties(final IProject aProject, String filename) throws CoreException {
		if (aProject == null) {
			ErrorHelper.throwCoreException(&quot;project must be not null&quot;);
		}
		if (filename == null) {
			ErrorHelper.throwCoreException(&quot;filename must be not null&quot;);
		}
		this.globalVars = new HashMap&lt;String, Variable&gt;();
		this.propertyFile = (IFile) aProject.findMember(filename);
	}

	public IFile getPropertyFile() {
		return propertyFile;
	}

	/**
	 * Returns the global variables.
	 * @return global variables.
	 */
	public Map&lt;String, Variable&gt; getGlobalVars() {
		updateProperties();
		return globalVars;
	}

	@Override
	public String getProperty(String key) {
		updateProperties();
		return super.getProperty(key);
	}

	/**
	 * Updates the properties and the global variables if the property file has
	 * been modified.
	 */
	public void updateProperties() {
		if (this.propertyFile != null &amp;&amp; lastModified != this.propertyFile.getModificationStamp()) {
			loadProperties();
			globalVars.clear();
			for (Map.Entry&lt;Object, Object&gt; entry : entrySet()) {
				final String propertyName = (String) entry.getKey();
				globalVars.put(propertyName, new Variable(propertyName, entry.getValue()));
			}
		}
	}

	/**
	 * Loads the properties from the model file
	 */
	private void loadProperties() {

		try {
			if (propertyFile != null &amp;&amp; propertyFile.exists()) {
				super.load(propertyFile.getContents());
				this.lastModified = propertyFile.getModificationStamp();
				handleSpecialProperties();
			}
		} catch (CoreException e) {
			// no model property file isn't a problem but clear the properties:
			super.clear();
			this.lastModified = NO_TIMESTAMP;
		} catch (IOException e) {
			super.clear();
			this.lastModified = NO_TIMESTAMP;
		}
	}

	protected void handleSpecialProperties() {

	}
}
</pre>
<p>Using this class you can simple initialize the XPandExecutionContext with properties read from the file system. So in build-Method of your Generator put something like:</p>
<pre class="brush: java;">
         ModelProperties structureProperties = new ModelProperties(context.getBuiltProject(), &quot;structure.properties&quot;);
         XpandExecutionContextImpl ctx = new XpandExecutionContextImpl(output, null, structureProperties null, null);
</pre>
<p>Now you can resolve the values from the property files directly from the Templates and Extensions using the built-in GLOBAL VAR feature.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/06/extending-xtext-build-participants/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parameterized classes, arrays and varargs</title>
		<link>http://www.techjava.de/topics/2010/06/parameterized-classes-arrays-and-varargs/</link>
		<comments>http://www.techjava.de/topics/2010/06/parameterized-classes-arrays-and-varargs/#comments</comments>
		<pubDate>Wed, 02 Jun 2010 14:30:00 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[limitation]]></category>
		<category><![CDATA[parametrized]]></category>
		<category><![CDATA[varargs]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=668</guid>
		<description><![CDATA[Yesterday, I discovered a funny nuance in Java programming language, which I didn&#8217;t know before and decided to share it with you. I was designing an API for transport of changes in relationships between two DTO types. Since I wanted to support batch changes, I created the class for carrying these:

class ManyToManyDelta&#60;S extends BaseDto&#60;?&#62;, T [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I discovered a funny nuance in Java programming language, which I didn&#8217;t know before and decided to share it with you. I was designing an API for transport of changes in relationships between two DTO types. Since I wanted to support batch changes, I created the class for carrying these:</p>
<pre class="brush: java;">
class ManyToManyDelta&lt;S extends BaseDto&lt;?&gt;, T extends BaseDto&lt;?&gt;&gt; {

  List&lt;SimpleRelationship&lt;S,T&gt;&gt; relationshipsToAdd;
  List&lt;SimpleRelationship&lt;S,T&gt;&gt; relationshipsToRemove;
  ...
}

class SimpleRelationship&lt;V extends BaseDto&lt;?&gt;, W extends BaseDto&lt;?&gt;&gt; {

  // BaseDto classes are identified by the parameterized Id
  Id&lt;V&gt; left;
  Id&lt;W&gt; right;

  SimpleRelationship(BaseDto&lt;V&gt; one, BaseDto&lt;W&gt; another) {
    left = one.getId();
    right = another.getId();
  }
}
</pre>
<p>Having this structure, you can model the relationship between two instances of types A and B by an instance of <code>SimpleRelationship&lt;A&gt;</code>. If you want to communicate the creation of a relationship you would put the latter into the <code>relatioshipToAdd</code> list, if you want to model the deletion, you would put it into the <code>relatioshipToRemove</code> list.</p>
<p>Now I it was time to develop methods for access of the relationship lists inside of the <code>ManyToManyDelta</code>:</p>
<pre class="brush: java;">
class ManyToManyDelta&lt;S extends BaseDto&lt;?&gt;, T extends BaseDto&lt;?&gt;&gt; {
  ...
  public void add(SimpleRelationship&lt;S, T&gt; toAdd) {
    if (toAdd == null) { /* react */}
    this.relatioshipToAdd.add(toAdd);
  }
  ...
}
</pre>
<p>You could think that you have a batch update (e.g. an <code>Array</code> or <code>List</code>) of <code>SimpleRelatioship</code> objects you would like to add them by one invocation instead of a series of invocation. e.G:</p>
<pre class="brush: java;">
class ManyToManyDelta&lt;S extends BaseDto&lt;?&gt;, T extends BaseDto&lt;?&gt;&gt; {
  ...
  public void add(SimpleRelationship&lt;S, T&gt;[] toAdd) {
    if (toAdd == null) { /* react */}
    this.relatioshipToAdd.addAll(Arrays.asList(toAdd));
  }
  public void add(SimpleRelationship&lt;S, T&gt; toAdd) {
    if (toAdd == null) { /* react */}
    this.relatioshipToAdd.add(toAdd);
  }
  ...
}
</pre>
<p>Using the 
<a  href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" onclick="javascript:pageTracker._trackPageview('/external/java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html');" >varargs</a> feature of Java you could also write equivalent:</p>
<pre class="brush: java;">
class ManyToManyDelta&lt;S extends BaseDto&lt;?&gt;, T extends BaseDto&lt;?&gt;&gt; {
  ...
  public void add(SimpleRelationship&lt;S, T&gt;... toAdd) {
    if (toAdd == null) { /* react */}
    this.relatioshipToAdd.addAll(Arrays.asList(toAdd));
  }
  ...
}
</pre>
<p>That would be nice, right? By the way, it is a good idea, to write some client code, during the development of API. This discovers potential problems:</p>
<pre class="brush: java;">
  ...
  A entityA = ...;
  B entityB = ...;
  ManyToManyDelta&lt;A, B&gt; delta = new ManyToManyDelta&lt;A,B&gt;();
  delta.add(new SimpleRelationship&lt;A,B&gt;(entityA, entityB));
</pre>
<p>Coding this result in a type safety warning: A generic array of SimpleRelationship<a> is created for a varargs parameter. Which reveals a problem in a Java language: you can not create an array of parameterized types. And resulting from this fact, you can not use that as varargs argument.</p>
<p>Finally, if you want to create convenience methods for one and many items, you have to do it in a old-fashined way, by providing overloaded methods.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/06/parameterized-classes-arrays-and-varargs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JSF 2.0 Reality Check</title>
		<link>http://www.techjava.de/topics/2010/02/jsf-2-reality-check/</link>
		<comments>http://www.techjava.de/topics/2010/02/jsf-2-reality-check/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 21:50:42 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[enterprise systems]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[bean]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[jsf 2.0]]></category>
		<category><![CDATA[jsr 303]]></category>
		<category><![CDATA[jsr 330]]></category>
		<category><![CDATA[managed baen]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=632</guid>
		<description><![CDATA[
Abstract
The JavaServer Faces (JSF) 2.0 is the newest Java presentation technology that is covered in JSR-314 and was publicly released on July 01, 2009. It became a part of the JEE6 standard and can be comfortably used in conjunction with other JEE frameworks, with Spring or just on its own. This article reveals the possible [...]]]></description>
			<content:encoded><![CDATA[<p><img style="float: right; margin-left:5px;" title="check" src="http://www.techjava.de/wp-content/uploads/check-150x150.jpg" alt="" width="150" height="150" /></p>
<h2>Abstract</h2>
<p>The JavaServer Faces (JSF) 2.0 is the newest Java presentation technology that is covered in JSR-314 and was publicly released on July 01, 2009. It became a part of the JEE6 standard and can be comfortably used in conjunction with other JEE frameworks, with Spring or just on its own. This article reveals the possible scenarios and shows the required configuration for the usage of JSF 2.0 with EJB 3.1 and with Spring 3.0. It also discusses several auxilary technologies which can be used along with JSF 2.0. <span id="more-632"></span></p>
<h2>Management Summary</h2>
<p>There are many presentation frameworks available, so why JSF 2.0? The short answer is simple: it has an extensible component-oriented presentation layer and event-driven programming model, which both abstract from HTML/JS and leverage the developement. In more detail, the most important features are:</p>
<ul>
<li>Facelet Support</li>
<li>Validation &amp; Conversion Mechanisms</li>
<li>Resources Support</li>
<li>Templating</li>
<li>Expression Language</li>
<li>Annotation Support</li>
</ul>
<p>JSF 2.0 makes strong use of the SoC (Separation of Concerns) principle, promoting the MVC (Model View Controller) design pattern. Its declarative view is based on facelets: the view documents can be defined using XHTML. These documents build their own component tree from the core or third-party components. The use of special composition elements allows effective templating. The model or/and the controller are realized using so called backing beans / managed beans. A backing bean is an annotated POJO (Plain Old Java Object). The access from the view to the backing beans is possible using the expression language. The navigation can be influenced directly from the view or from the backing beans, by pointing to the logical names of the pages. JSF offers a flexible validation model, which suports Bean Validation (JSR 303) out of the box.</p>
<h2>Presentation with JSF 2.0</h2>
<p>This chapter discusses the model of the presentation used in JSF 2.0.</p>
<h3>Initial setup</h3>
<p>A JSF project is an ordinary Java Web project. The result of it runs inside of a web container, like Tomcat or Jetty. A characteristical descriptor has to contain the servlet definitions/mappings of the JSF servlet and third-party component servlets.  Here is an exammple for JSF 2.0 and Prime Faces, an open-source component library.</p>
<pre class="brush: xml;">
&lt;web-app xmlns=&quot;.../javaee&quot; xmlns:xsi=&quot;...&quot;
	xsi:schemaLocation=&quot;.../web-app_2_5.xsd&quot; version=&quot;2.5&quot;&gt;
...
	&lt;!-- Activating the Expression Language --&gt;
	&lt;context-param&gt;
		&lt;param-name&gt;com.sun.faces.expressionFactory&lt;/param-name&gt;
		&lt;param-value&gt;com.sun.el.ExpressionFactoryImpl&lt;/param-value&gt;
	&lt;/context-param&gt;

	&lt;!-- Java Server Faces Servlet --&gt;
	&lt;servlet&gt;
		&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
	&lt;!--  Prime Faces Resource loading --&gt;
	&lt;servlet&gt;
		&lt;servlet-name&gt;Resource Servlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;org.primefaces.resource.ResourceServlet&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
	&lt;!-- Java Server Faces Servlet Mapping --&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;*.jsf&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;!--  Prime Faces Resource loading --&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;Resource Servlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/primefaces_resource/*&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
...
&lt;/web&gt;
</pre>
<h3>The View</h3>
<p>The definition of a JSF presentation is relatevely simple. Just create a simple XHTML document and import the JSF namespaces in the header.</p>
<pre class="brush: xml;">
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:p=&quot;http://primefaces.prime.com.tr/ui&quot;&gt;
	 &lt;f:loadBundle var= &quot;msgs&quot; basename= &quot;ViewMessages&quot; /&gt;
	 &lt;h:head&gt;
		 &lt;title&gt;#{msgs.welcomeTitle}&lt;/title&gt;
		 &lt;h:outputStylesheet library=&quot;css&quot; name=&quot;default.css&quot; target=&quot;head&quot;/&gt;
	 &lt;/h:head&gt;
	 &lt;h:body&gt;
		 &lt;p:dataTable id= &quot;customers&quot; value=&quot;#{cusomterProvider.customer}&quot; var=&quot;customer&quot;&gt;
			 &lt;p:column&gt;
				 &lt;h:outputText id=&quot;customerName&quot; value=&quot;#{customer.name}&quot; /&gt;
			 &lt;/p:column&gt;
			...
		 &lt;/p:dataTable&gt;
	 &lt;/h:body&gt;
&lt;/html&gt;
</pre>
<p>Please note, that along with the JSF core components, the PrimeFaces component <code>dataTable</code> is used. At runtime the components will be transformed into the corresponding HTML elements.</p>
<h3>The Backing Bean</h3>
<p>In the previos example, special strings have been used <code>#{customerProvider.customers}</code> and <code>#{customer.name}</code>. Both of them are expressions specified in the Expression Language. This language allows to address elements known inside the application. The <code>customer.name</code> accesses the property <code>name</code> of the variable defined inside the iteration over the elements delivered from the <code>customerProvider.getCustomers()</code>. The <code>customerProvider</code> is a Java Object that delivers data to the view and is called Backing Bean. A Backing Bean is a serializeable POJO, that is attached to the view. It can be declared using JSF Annotation <code>javax.faces.ManagedBean</code>, using the <code>ManagedBean</code> element of the <strong>faces-config.xml</strong> or by other mechanisms compatible with the Expression Language resolvers.</p>
<pre class="brush: java;">
@ManagedBean
@SessionScope
public class CustomerProvider
{
	public List &lt;Customer &gt; getCustomers()
	{
		...
	}
}
</pre>
<h3>Internationalization</h3>
<p>Internationalization is an important requirement for the presentation layer. In the previous example, a special string has been used <code>#{msgs.welcomeTitle}</code> to provide a message. The <code>msgs</code> variable is bound to a resource file, containing the localized messages, so the <code>#{msgs.welcomeTitle}</code> is pointing to the key <code>welcomeTitle</code> inside the property file.</p>
<h3>Validation</h3>
<p>Input validation is another important requirement for web applications. Especially, the ability to validate parts of the input using technologies like AJAX has to be supported in order to deliver the state-of-the-art technology. JSF fosters numerous different validation approaches. For example:</p>
<pre class="brush: xml;">
...
 &lt;h:inputText id=&quot;customerName&quot; value=&quot;#{customerService.current.name}&quot; required= &quot;true&quot; /&gt;
	 &lt;f:validateLength minimum=&quot;7 &quot;/&gt;
 &lt;/h:inputText&gt;
 &lt;h:message for=&quot;customerName&quot;/&gt;
...
</pre>
<p>Please note, that in the example above, the input of the customer name is mandatory and the minimum length is seven.</p>
<p>Another validation approach is defined in the Bean Validation Standard (JSR 303) and is supported if the components are deployed and available. According to JSR 303, the data container can define format constraints which can be used for purposes of validation. There is a set of predefined constraints available, which can be extended by custom constraints. For example:</p>
<pre class="brush: java;">
public class Customer
{
	@Size(min=2, max=50, message= &quot;Customer name must be at least 2 and at most 50 characters long. &quot;)
	private String name;
	// getters and setters
	...
}
</pre>
<p>This example shows that the customer name has to be at least two and at most fifty characters long and defines a custom error message which is displayed on violation. Remember the previous section Internationalization? Yes, the validation error message can be localized too, by suppliying EL-expressions instead of the message description:</p>
<pre class="brush: java;">
public class Customer
{
	@Size(min=2, max=50, message= &quot;{customerNameError} &quot;)
	private String name;
	// getters and setters
	...
}
</pre>
<p>Thus, the value of <code>{customerNameError}</code> (without a #) is a key in the file which must be named <strong>ValidationMessages.properties</strong> and must be available on classpath.</p>
<h2>JSF 2.0 with other frameworks</h2>
<p>The use of JSF fosters comfort in implementing the presentation tier. The presentation-tier is usually built on top of the business logic layer. The latter can be implemented using different technolgies.</p>
<h3>JSF 2.0 and EJB 3.1</h3>
<p>Enterprise Java Beans is a standard way to implement business logic inside JEE applications. The current EJB 3.1 specification fosters the usage of Stateless and Statefull Session Beans for this purpose. Since JEE6-compliant servers support Context and Dependency Injection (CDI) and the EJB and Resource Injection, the session beans can be directly referenced from the backing beans. JSF 2.0 is also a part of the JEE 6, every JEE-compliant server will support JSF out-of-the-box, too.</p>
<pre class="brush: java;">
@ManagedBean
public class CustomerProvider
{
	@EJB
	private CustomerService service;
	...
}
</pre>
<h3>JSF 2.0 and Spring 3.0</h3>
<p>If you don&#8217;t want to run a full-blown JEE server, but a web-container only, you have to include some libraries into your application deployment.</p>
<ul>
<li>JSF 2.0 API and Implementation: e.g. Mojarra 2.0.2 (
<a  href="https://javaserverfaces.dev.java.net/files/documents/1866/146040/mojarra-2.0.2-FCS-binary.zip" onclick="javascript:pageTracker._trackPageview('/external/javaserverfaces.dev.java.net/files/documents/1866/146040/mojarra-2.0.2-FCS-binary.zip');" >mojarra-2.0.2-FCS-binary.zip</a>)</li>
<li>Expression Language 2.2 API and Implementation: 
<a  href="http://download.java.net/maven/glassfish/javax/el/el-api/2.2.0-SNAPSHOT/el-api-2.2.0-SNAPSHOT.jar" onclick="javascript:pageTracker._trackPageview('/external/download.java.net/maven/glassfish/javax/el/el-api/2.2.0-SNAPSHOT/el-api-2.2.0-SNAPSHOT.jar');" >el-api-2.2.jar</a>, 
<a  href="http://download.java.net/maven/glassfish/org/glassfish/web/el-impl/2.2.0-SNAPSHOT/el-impl-2.2.0-SNAPSHOT.jar" onclick="javascript:pageTracker._trackPageview('/external/download.java.net/maven/glassfish/org/glassfish/web/el-impl/2.2.0-SNAPSHOT/el-impl-2.2.0-SNAPSHOT.jar');" >el-impl-2.2.jar</a></li>
<li>Content and Dependency Injection (CDI, JSR 330) API and Implementation: 
<a  href="http://atinject.googlecode.com/files/javax.inject.zip" onclick="javascript:pageTracker._trackPageview('/external/atinject.googlecode.com/files/javax.inject.zip');" >javax.inject.zip</a></li>
<li>Bean Validation (JSR 303) API and Implementation: e.g. Hibernate Validator (
<a  href="http://sourceforge.net/projects/hibernate/files/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA-dist.zip/download" onclick="javascript:pageTracker._trackPageview('/external/sourceforge.net/projects/hibernate/files/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA-dist.zip/download');" >hibernate-validator-4.0.2.GA-dist.zip</a>)</li>
</ul>
<p>This list will be extended by libraries required to run the Spring framework. In order to activate Spring, the context listeners have to be activated. The application context parameter can be provided as a context parameter.</p>
<pre class="brush: xml;">
 &lt;!-- Spring Activation --&gt;
 &lt;listener&gt;
	 &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
 &lt;/listener&gt;
 &lt;listener&gt;
	 &lt;listener-class&gt;org.springframework.web.context.request.RequestContextListener&lt;/listener-class&gt;
 &lt;/listener&gt;
 &lt;context-param&gt;
	 &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
	 &lt;param-value&gt;/WEB-INF/spring-config.xml&lt;/param-value&gt;
 &lt;/context-param&gt;
</pre>
<p>In addition, the Expression Language variable resolvers of JSF should be replaced by those from Spring. This is configured in the <code>faces-config.xml</code></p>
<pre class="brush: xml;">
&lt;faces-config xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd&quot;
	version=&quot;2.0&quot;&gt;
	&lt;application&gt;
		&lt;el-resolver&gt;org.springframework.web.jsf.el.SpringBeanFacesELResolver&lt;/el-resolver&gt;
	&lt;/application&gt;
&lt;/faces-config&gt;
</pre>
<p>In order to enable the Spring&#8217;s IoC (Inversion of Control), we need to activate the component scan in the application-context configuration file:</p>
<pre class="brush: xml;">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;...&quot; xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xsi:schemaLocation=&quot;...&quot;&gt;

	&lt;context:component-scan base-package=&quot;de.techjava&quot;&gt;
		&lt;context:include-filter type=&quot;annotation&quot;
			expression=&quot;org.springframework.stereotype.Service&quot; /&gt;
	&lt;/context:component-scan&gt;
&lt;/beans&gt;
</pre>
<p>Instead of using JSF for resolving the backing beans, the Spring framework can be used. The backing bean is annotated with the Spring annotation <code>Controller</code>. The controller is a special kind of Spring component, which is used in the presentation layer. The Spring&#8217;s way of implementing business logic is to provide Spring services. Spring service has to be annotated with <code>Service</code> annotation.</p>
<pre class="brush: java;">
@Controller
@Scope( &quot;session &quot;)
public class CustomerProvider implements Serializable
{
	@Inject
	private CustomerService customerService;
	...
}

@Service
@Scope( &quot;singleton &quot;)
public class CustomerServiceImpl implements CustomerService
{
	...
}
</pre>
<p>This is not as elegant as inside the JEE server, but it will work.</p>
<h3>References</h3>
<ul>
<li>
<a  href="http://jcp.org/en/jsr/detail?id=303" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/jcp.org/en/jsr/detail');" >JSR 303: Bean Validation</a></li>
<li>
<a  href="http://jcp.org/en/jsr/detail?id=330" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/jcp.org/en/jsr/detail');" >JSR 330: Dependency Injection for Java</a></li>
<li>
<a  href="http://blog.ralscha.ch/?p=652" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/blog.ralscha.ch/');" >JSR 330 with Spring (in German)</a></li>
<li>
<a  href="https://javaserverfaces.dev.java.net/" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/javaserverfaces.dev.java.net/');" >Mojarra Project</a></li>
<li>
<a  href="http://download.java.net/maven/glassfish/javax/el/el-api/2.2.0-SNAPSHOT/" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/download.java.net/maven/glassfish/javax/el/el-api/2.2.0-SNAPSHOT/');" >Expression Language API</a></li>
<li>
<a  href="http://download.java.net/maven/glassfish/org/glassfish/web/el-impl/2.2.0-SNAPSHOT/" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/download.java.net/maven/glassfish/org/glassfish/web/el-impl/2.2.0-SNAPSHOT/');" >Expression Language Implementation</a></li>
<li>
<a  href="https://www.hibernate.org/412.html" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/www.hibernate.org/412.html');" >Hibernate Validator (JSR 303 Implementation)</a></li>
<li>
<a  href="http://code.google.com/p/atinject/" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/code.google.com/p/atinject/');" >AtInject (JSR 330 Implementation)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/02/jsf-2-reality-check/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Real World Java EE Practices &#8211; Rethinking Best Practices by Adam Bien</title>
		<link>http://www.techjava.de/topics/2010/02/rethinking-best-practices/</link>
		<comments>http://www.techjava.de/topics/2010/02/rethinking-best-practices/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 23:21:43 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[enterprise systems]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[adam bien]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[enterprise]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=594</guid>
		<description><![CDATA[
I just returned from the furious event given by Adam Bien on 
Real World Java EE Practices. The presentation has been held in Lehmanns Bookstore in Hamburg in co-operation with the JUGHH. It was a full success with no space left in the bookstore. I think, I got the last seat and there were some [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.techjava.de/wp-content/uploads/adambien-225x300.jpg" alt="" title="adambien" width="225" height="300" style="float:right; margin:5px;" /><br />
I just returned from the furious event given by Adam Bien on 
<a  href="http://www.adam-bien.com/roller/abien/entry/free_jug_session_in_hamburg" onclick="javascript:pageTracker._trackPageview('/external/www.adam-bien.com/roller/abien/entry/free_jug_session_in_hamburg');" >Real World Java EE Practices</a>. The presentation has been held in Lehmanns Bookstore in Hamburg in co-operation with the JUGHH. It was a full success with no space left in the bookstore. I think, I got the last seat and there were some people standing. </p>
<p>Adam made it in an hour and presented many interesting topics. He started with new subjects introduces in JEE6, like optional local interfaces, cronjob-like Timer Service and other nice goodies. Then he covered new stuff from JEE like REST and CDI (Context and Dependency Injection). Finally, he moved to the best practices, patterns and anti-pattern. As usual, it was quick and precise &#8211; Adam answered many questions and gave a good overview of the technology.</p>
<p>After the presentation, JUGHH / Lehmanns offer a glass of sparkling wine for the smaller audience and Adam spoke about the possibility to speak about JavaFX next time. This time I left my camera at home and only had my phone with me, so sorry for the low-resolutioned picture&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/02/rethinking-best-practices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exposing Functionality using Web Services and JEE</title>
		<link>http://www.techjava.de/topics/2010/01/functionality-web-services-jee/</link>
		<comments>http://www.techjava.de/topics/2010/01/functionality-web-services-jee/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 11:11:22 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[enterprise systems]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[bean]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[ejb]]></category>
		<category><![CDATA[ejb3]]></category>
		<category><![CDATA[java 5]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[web service]]></category>
		<category><![CDATA[wsdl]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=554</guid>
		<description><![CDATA[
Abstract
About two years ago, I published an 
article about Exposing the Functionality implemented in Stateless Session Beans (EJB 2.1) using Web Services. J2EE 1.4 times are over and the new version of the Java Enterprise framework, called Java Enterprise Edition 5 (JavaEE 5, or simply JEE) has emerged. In this article the same business scenario [...]]]></description>
			<content:encoded><![CDATA[<h2>
<a  href="http://www.techjava.de/wp-content/uploads/valve.jpg" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/valve.jpg');" ><img style="float: right; margin: 5px;" title="valve" src="http://www.techjava.de/wp-content/uploads/valve-150x150.jpg" alt="" width="150" height="150" /></a>Abstract</h2>
<p>About two years ago, I published an 
<a  href="http://www.techjava.de/topics/2008/02/ws4j2ee14/">article</a> about Exposing the Functionality implemented in Stateless Session Beans (EJB 2.1) using Web Services. J2EE 1.4 times are over and the new version of the Java Enterprise framework, called Java Enterprise Edition 5 (JavaEE 5, or simply JEE) has emerged. In this article the same business scenario is repeated in the new framework. </p>
<h2>Requirements</h2>
<p>Before we dive into code examples, some software is required. The good news about the software is, that it also evolved over time. Here is what we use:</p>
<ul>
<li>Sun&#8217;s Java 6 SDK</li>
<li>JBoss AS 5.1.0 GA for JDK6</li>
<li>Eclipse Galileo 3.5.1 for JEE development</li>
</ul>
<p><span id="more-554"></span><br />
Some words about the used software. It is important to get the JDK6-compiled version of the JBoss Application Server. There are some issues with running the version compiled with Java 5 on JDK6, since JDK6 has its own JAX-WS implementation which causes problems with JBoss (affected should be all versions of JBoss &lt; 5.2. Currently it seems like version 5.2 will be compiled with JDK6 by default.) If you launch JBoss from Eclipse, make sure to add the <code>-Djava.endorsed.dirs=PATH_TO_JBOSS/jboss-5.1.0.GA/lib/endorsed</code> as a VM argument, if launched from the command line, please add it as an option inside of the <code>run.conf.bat</code> file:</p>
<pre class="brush: bash;">
set &quot;JAVA_OPTS=%JAVA_OPTS% -Djava.endorsed.dirs=$JBOSS_HOME/lib/endorsed&quot;
</pre>
<p>Otherwise you will get the following exception:</p>
<pre class="brush: java;">java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage</pre>
<p>After installation (unpacking) of Eclipse, make sure to configure the JDK (under <strong>Preferences &gt; Java &gt; Installed JREs</strong>) and the JBoss instance (<strong>Preferences &gt; Server &gt; Runtime Environment</strong>).</p>
<h2>Use Case</h2>
<p>In order to demonstrate the technology by example, imagine the following use case. The system under construction is capable of providing measurements of some sensors. The sensors are identified by numbers and can be queried by the user by providing the timespan of measurements. As a result, the systems delivers the set of measurements for the given timespan with one measurement per minute but at most sixty measurements. Every measurement contains the id of sensor from which it has been recorded, the timestamp, the value as a byte array, the measurement unit and finally a flag whether the measurement exceeds the limits or specified alarm values.</p>
<h2>Implementation</h2>
<p>We start the implementation with the creation of a JEE Session Bean and then expose the functionality using a second Facade bean. In doing so we follow the EJB 3 specification.</p>
<h3>Eclipse for Java EE development</h3>
<p>The plugins in Eclipse for Java EE provide massive support and foster the development by deep integration withe JEE servers. Instead of a simple Java Project, start with an <strong>Enterprise Application Project</strong>. Then, create a new <strong>EJB Project</strong> and add it to the created Enterprise Application Project. In order to deploy the resulting application to the server, right-click on the enterprise project and select <strong>Run As &gt; Run on Server </strong>.</p>
<p>To check the deployment on the application server, use the JBoss Consoles. These can be accessed via 
<a  href="http://localhost:8080/" onclick="javascript:pageTracker._trackPageview('/external/localhost/');" >http://localhost:8080/</a> for the locally installed JBoss. An additional Web Service Console is accessible via 
<a  href="http://localhost:8080/jbossws/" onclick="javascript:pageTracker._trackPageview('/external/localhost/jbossws/');" >http://localhost:8080/jbossws/</a>.</p>
<h3>Implementing the Functionality</h3>
<p>In order to implement the functionality in a stateless session bean, we start with the creation of the business interface.</p>
<pre class="brush: java;">
/**
 * Defines the sensor manager functionality
 */
public interface SensorManager
{
	/**
	 * Retrieve sensor data
	 * @param sensorId id of the sensor
	 * @param timespan the measurement period
	 * @return a list of measurements in the given period
	 * @throws SensorManagerException on any kinds of errors
	 */
	public List&lt;Measurement&gt; getSensorData(SensorID sensorId, Timespan timespan) throws SensorManagerException;
}
</pre>
<p>The POJOs <code>Measurement</code>, <code>SensorID</code> and <code>Timespan</code> are used to show the usage of custom user types:</p>
<pre class="brush: java;">
public class Measurement
{
	private SensorID sensorID;
	private Date timestamp;
	private boolean critical;
	private byte[] value;
	private String unit;
...
// getters and setters
}
....
public class SensorID
{
	private long sensorId;
...
// getters and setters
}

public class Timespan
{
	private Date start;
	private Date end;
...
// getters and setters
}
</pre>
<p>After the creation of the business interface, let us create the actual Session Bean. The class is annotated with the <code>@javax.ejb.Stateless</code> annotation in order to indicate that the bean is a Stateless Session Bean. Since it implements the business interface (and only it), the container will be able to deduce that the given interface is the Local Business interface: this is just one of many examples of the Configurations by Exception in EJB 3. In order to be able to reference the bean from other beans, we annotate the binding of the local interface to a specific JNDI name using the vendor-specific annotation <code>org.jboss.ejb3.LocalBinding</code>.</p>
<pre class="brush: java;">
@Stateless
@LocalBinding(jndiBinding=&quot;de.techjava.sensor/SensorManager&quot;)
public class SensorManagerBean implements SensorManager
{
	/** Logging facility */
	protected static Logger LOG = Logger.getLogger(SensorManagerBean.class);
	/** Max number of returned values */
	private static final long MAX_DURATION = 60;

	/**
	 * Implementation of the business method
	 */
	public List&lt;Measurement&gt; getSensorData(SensorID sensorId, Timespan timespan) throws SensorManagerException
	{
		LOG.debug(&quot;Entering getSensorData()&quot;);
		if (sensorId == null || timespan == null || timespan.getStart() == null || timespan.getStart() == null)
		{
			throw new SensorManagerException(&quot;Missing a mandatory parameter, that was null (not set)&quot;);
		} else if (!timespan.getStart().before(timespan.getEnd()))
		{
			throw new SensorManagerException(&quot;The timespan is defined by the start that should be before end&quot;);
		}

		List&lt;Measurement&gt; measurements = new LinkedList&lt;Measurement&gt;();
		for (long i = 0; i &lt; getNumberOfElements(timespan); i++)
		{
			Date date = new Date();
			date.setTime(timespan.getStart().getTime() + i * 1000 * 60);
			if (date.after(timespan.getEnd()))
				break;
			Measurement measurement = createMeasurement(sensorId, date, i);
			measurements.add(measurement);
		}

		LOG.debug(&quot;Leaving getSensorData(). Returning &quot; + measurements.size() + &quot; values.&quot;);
		return measurements;
	}

	/**
	 * Retrieves the number of measurements in timespan
	 */
	private long getNumberOfElements(Timespan timespan) { ... }

	/**
	 * Creates a measurement instance, a dummy implementation
	 */
	private Measurement createMeasurement(SensorID sensorId, Date timestamp, long number) { ... }
}
</pre>
<h2>Web Service Definition</h2>
<p>The quality of the web service interface is an important design consideration. As described in 
<a  href="http://www.techjava.de/topics/2008/02/ws4j2ee14/">the previous post</a>, in many cases it is a good idea to create it by hand instead of generation by a tool. In this particular case, we create another annotated Stateless Session Bean, which is used as a Facade and contains all Web Service-specific settings. From this Bean we generate the WSDL and then tune it in order to show the capability of the customization. In doing so we try to match the WSDL from the previous example as close as possible.</p>
<p>Firstly, we create the business interface and the bean class, then annotate it and finally add the code delegating the Web Service request to the SensorManager.</p>
<pre class="brush: java;">
public interface MeasurementProviderFacade
{
	public List&lt;Measurement&gt; getSensorData(SensorID id, Timespan timespan) throws SensorDataOperationFault;
}

...

@Stateless
public class MeasurementProviderFacadeBean implements MeasurementProviderFacade
{
	public List&lt;Measurement&gt; getSensorData(SensorID id, Timespan timespan) throws SensorDataOperationFault
	{
	...
	// implementation code
	}
}
</pre>
<p>In order to have a Session Bean exposed as a Web Service, the JAX-WS specification defines a set of annotations. The most important two are <code>@javax.jws.WebMethod</code> and <code>@javax.jws.WebService</code>. The <code>@WebService</code> annotation is used to mark the class to be exposed e.G.</p>
<pre class="brush: java;">
@Stateless
@WebService(
	serviceName = &quot;MeasurementProviderService&quot;,
	name = &quot;MeasurementProviderPortType&quot;,
	portName = &quot;MeasurementProviderPort&quot;,
	targetNamespace = &quot;http://www.techjava.de/2010/ws4jee/measurement/&quot;
)
public class MeasurementProviderFacadeBean implements MeasurementProviderFacade
{
	@WebMethod(
		operationName=&quot;GetSensorDataOperation&quot;,
		action=&quot;http://www.techjava.de/2010/ws4jee/measurement/GetSensorDataOperation&quot;
	)
	public List&lt;Measurement&gt; getSensorData(SensorID id, Timespan timespan) throws SensorDataOperationFault { ... }
}
</pre>
<p>All the attributes of the annotation are optional and their values will be derived from the classname and the name of the business interface. The default target namespace for the service definition is derived from the package name, the annotated class is located in. By default, all public methods of the annotated class will be exposed as WSDL operations, with operation&#8217;s name derived from the method name. Using the <code>@WebMethod</code> annotation, the name of the WSDL operation and the SOAP action can be changed.</p>
<p>The careful reader might have observed that the <code>getSensorData</code>-method is throwing an exception. In order to map the exception to a SOAP-Fault, the <code>javax.xml.ws.WebFault</code> class-level annotation can be used. The <code>faultBean</code> attribute is used to provide the full-qulified class name of the exception.</p>
<pre class="brush: java;">
...
@WebFault(
	name=&quot;GetSensorDataFault&quot;,
	targetNamespace=&quot;http://www.techjava.de/2010/ws4jee/measurement/&quot;,
	faultBean=&quot;de.techjava.sensor.bean.SensorDataOperationFault&quot;)
public class MeasurementProviderFacadeBean implements MeasurementProviderFacade { ... }
</pre>
<p>In order to increase the quality of the WSDL further, the method parameters and return type can be annotated with <code>javax.jws.WebParam</code> and <code>javax.jws.WebResult</code> respectively, so the method signature becomes a little unreadable. In order not to copy the long string containing the taget namespace a String constant can be used.</p>
<pre class="brush: java;">
...
	public final static String TYPES = &quot;http://www.techjava.de/2010/ws4jee/measurement/types/&quot;;
...
	@WebResult(name=&quot;measurement&quot;, targetNamespace=TYPES)
	public List&lt;Measurement&gt; getSensorData(
		@WebParam(name=&quot;sensor-id&quot;, targetNamespace=TYPES) SensorID id,
		@WebParam(name=&quot;timespan&quot;, targetNamespace=TYPES) Timespan timespan) throws SensorDataOperationFault	{ ... }
</pre>
<p>Finally, in order to force the marshaller / unmarshaller to map the custom data types (<code>Measurement</code>, <code>SensorID</code> and <code>Timespan</code>) to belong to the same namespace, the JAX-B class-level annotation <code>javax.xml.bind.annotation.XmlType</code> has to be used. By default, the datatypes will be mapped to XML Schema types according to their package name and class name.</p>
<pre class="brush: java;">
@XmlType(namespace = &quot;http://www.techjava.de/2010/ws4jee/measurement/types/&quot;, name = &quot;TimeSpan&quot;, propOrder = { &quot;start&quot;, &quot;end&quot; })
public class Timespan
{
	private Date start;
	private Date end;
</pre>
<p>If deployed to the JBoss, the resulting WSDL looks as following:</p>
<pre class="brush: xml; collapse: true; light: false; toolbar: true;">
&lt;definitions name='MeasurementProviderService' targetNamespace='http://www.techjava.de/2010/ws4jee/measurement/' xmlns='http://schemas.xmlsoap.org/wsdl/' xmlns:ns1='http://www.techjava.de/2010/ws4jee/measurement/types/' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:tns='http://www.techjava.de/2010/ws4jee/measurement/' xmlns:xsd='http://www.w3.org/2001/XMLSchema'&gt;
 &lt;types&gt;
  &lt;xs:schema targetNamespace='http://www.techjava.de/2010/ws4jee/measurement/types/' version='1.0' xmlns:tns='http://www.techjava.de/2010/ws4jee/measurement/types/' xmlns:xs='http://www.w3.org/2001/XMLSchema'&gt;
   &lt;xs:element name='measurement' type='tns:Measurement'/&gt;
   &lt;xs:element name='sensor-id' type='tns:sensor-id'/&gt;
   &lt;xs:element name='timespan' type='tns:TimeSpan'/&gt;
   &lt;xs:complexType name='sensor-id'&gt;
    &lt;xs:sequence&gt;
     &lt;xs:element name='sensorId' type='xs:long'/&gt;
    &lt;/xs:sequence&gt;
   &lt;/xs:complexType&gt;
   &lt;xs:complexType name='TimeSpan'&gt;
    &lt;xs:sequence&gt;
     &lt;xs:element minOccurs='0' name='start' type='xs:dateTime'/&gt;
     &lt;xs:element minOccurs='0' name='end' type='xs:dateTime'/&gt;
    &lt;/xs:sequence&gt;
   &lt;/xs:complexType&gt;
   &lt;xs:complexType name='Measurement'&gt;
    &lt;xs:sequence&gt;
     &lt;xs:element name='critical' type='xs:boolean'/&gt;
     &lt;xs:element minOccurs='0' name='sensorID' type='tns:sensor-id'/&gt;
     &lt;xs:element minOccurs='0' name='timestamp' type='xs:dateTime'/&gt;
     &lt;xs:element minOccurs='0' name='unit' type='xs:string'/&gt;
     &lt;xs:element minOccurs='0' name='value' type='xs:base64Binary'/&gt;
    &lt;/xs:sequence&gt;
   &lt;/xs:complexType&gt;
  &lt;/xs:schema&gt;
  &lt;xs:schema targetNamespace='http://www.techjava.de/2010/ws4jee/measurement/' version='1.0' xmlns:ns1='http://www.techjava.de/2010/ws4jee/measurement/types/' xmlns:tns='http://www.techjava.de/2010/ws4jee/measurement/' xmlns:xs='http://www.w3.org/2001/XMLSchema'&gt;
   &lt;xs:import namespace='http://www.techjava.de/2010/ws4jee/measurement/types/'/&gt;
   &lt;xs:element name='GetSensorDataOperation' type='tns:GetSensorDataOperation'/&gt;
   &lt;xs:element name='GetSensorDataOperationResponse' type='tns:GetSensorDataOperationResponse'/&gt;
   &lt;xs:element name='SensorDataOperationFault' type='tns:SensorDataOperationFault'/&gt;
   &lt;xs:complexType name='GetSensorDataOperation'&gt;
    &lt;xs:sequence&gt;
     &lt;xs:element minOccurs='0' ref='ns1:sensor-id'/&gt;
     &lt;xs:element minOccurs='0' ref='ns1:timespan'/&gt;
    &lt;/xs:sequence&gt;
   &lt;/xs:complexType&gt;
   &lt;xs:complexType name='GetSensorDataOperationResponse'&gt;
    &lt;xs:sequence&gt;
     &lt;xs:element maxOccurs='unbounded' minOccurs='0' ref='ns1:measurement'/&gt;
    &lt;/xs:sequence&gt;
   &lt;/xs:complexType&gt;
   &lt;xs:complexType name='SensorDataOperationFault'&gt;
    &lt;xs:sequence&gt;
     &lt;xs:element minOccurs='0' name='message' type='xs:string'/&gt;
    &lt;/xs:sequence&gt;
   &lt;/xs:complexType&gt;
  &lt;/xs:schema&gt;
 &lt;/types&gt;
 &lt;message name='MeasurementProviderPortType_GetSensorDataOperation'&gt;
  &lt;part element='tns:GetSensorDataOperation' name='GetSensorDataOperation'&gt;&lt;/part&gt;
 &lt;/message&gt;
 &lt;message name='SensorDataOperationFault'&gt;
  &lt;part element='tns:SensorDataOperationFault' name='SensorDataOperationFault'&gt;&lt;/part&gt;
 &lt;/message&gt;
 &lt;message name='MeasurementProviderPortType_GetSensorDataOperationResponse'&gt;
  &lt;part element='tns:GetSensorDataOperationResponse' name='GetSensorDataOperationResponse'&gt;&lt;/part&gt;
 &lt;/message&gt;
 &lt;portType name='MeasurementProviderPortType'&gt;
  &lt;operation name='GetSensorDataOperation' parameterOrder='GetSensorDataOperation'&gt;
   &lt;input message='tns:MeasurementProviderPortType_GetSensorDataOperation' /&gt;
   &lt;output message='tns:MeasurementProviderPortType_GetSensorDataOperationResponse' /&gt;
   &lt;fault message='tns:SensorDataOperationFault' name='SensorDataOperationFault' /&gt;
  &lt;/operation&gt;
 &lt;/portType&gt;
 &lt;binding name='MeasurementProviderPortTypeBinding' type='tns:MeasurementProviderPortType'&gt;
  &lt;soap:binding style='document' transport='http://schemas.xmlsoap.org/soap/http'/&gt;
  &lt;operation name='GetSensorDataOperation'&gt;
   &lt;soap:operation soapAction='http://www.techjava.de/2010/ws4jee/measurement//GetSensorDataOperation'/&gt;
   &lt;input&gt;&lt;soap:body use='literal'/&gt;&lt;/input&gt;
   &lt;output&gt;&lt;soap:body use='literal'/&gt;&lt;/output&gt;
   &lt;fault name='SensorDataOperationFault'&gt;&lt;soap:fault name='SensorDataOperationFault' use='literal'/&gt;&lt;/fault&gt;
  &lt;/operation&gt;
 &lt;/binding&gt;
 &lt;service name='MeasurementProviderService'&gt;
  &lt;port binding='tns:MeasurementProviderPortTypeBinding' name='MeasurementProviderPort'&gt;
   &lt;soap:address location='http://127.0.0.1:8080/de.techjava.ws4ee-de.techjava.ws4ee.sensor/MeasurementProviderFacadeBean'/&gt;
  &lt;/port&gt;
 &lt;/service&gt;
&lt;/definitions&gt;
</pre>
<p>Please note, that the domain datatypes are mapped to the different namespace as the target namespace of the Web Service.</p>
<p>After some tuning the WSDL, like changing the cardinality of elements (minOccurs = 1, maxOccurs = 1) or adding comments we can let the container use the changed WSDL file instead of generating a new one. In order to do this, let us package the WSDL together with the source code. A good place for it is for example <code>/META-INF/wsdl/</code>, so we can provide a reference to it in an <code>wsdlLocation</code>attribute of the <code>@WebService</code> annotation:</p>
<pre class="brush: java;">
@WebService(
...
        wsdlLocation=&quot;META-INF/wsdl/MeasurementProviderService.wsdl&quot;
)
</pre>
<h2>Putting all together</h2>
<p>After the creation of the Facade Bean and its exposure as a Web Service, we need to delegate the call to the SensorManagerBean, providing the actual implementation. In order to do so, add a private member of type <code>SensorManager</code> inside of the facade bean and annotate it with the <code>javax.ejb.EJB</code> annotation. The container will intialize the member using Dependency Injection and provide a valid reference which can be simply used inside of the method.</p>
<pre class="brush: java; highlight: [4,5,20];">
...
public class MeasurementProviderFacadeBean implements MeasurementProviderFacade
{
	@EJB(mappedName=&quot;de.techjava.sensor/SensorManager&quot;)
	private SensorManager sensorManager;

	/**
	 * Simple delegate to the business method of the sensor manager
	 */
	@WebMethod(
			operationName=&quot;GetSensorDataOperation&quot;,
			action=TNS + &quot;/GetSensorDataOperation&quot;
	)
	public @WebResult(name=&quot;measurement&quot;, targetNamespace=TYPES) List&lt;Measurement&gt; getSensorData(
			@WebParam(name=&quot;sensor-id&quot;, targetNamespace=TYPES) SensorID id,
			@WebParam(name=&quot;timespan&quot;, targetNamespace=TYPES) Timespan timespan) throws SensorDataOperationFault
	{
		try
		{
			return sensorManager.getSensorData(id, timespan);
		} catch (SensorManagerException e)
		{
			throw new SensorDataOperationFault(&quot;Error accessing the Sensor Manager: &quot; + e.getMessage() + &quot;&quot;);
		}
	}
}
</pre>
<p>Here is the call in Web Service Explorer:<br />

<a  href="http://www.techjava.de/wp-content/uploads/ws-explorer.png" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/ws-explorer.png');" ><img style="margin: 5px;" title="WS Explorer" src="http://www.techjava.de/wp-content/uploads/ws-explorer.png" alt="image WS Explorer" /></a></p>
<h2>Outline</h2>
<p>In this article we showed how to expose the functionality implemented in an EJB 3 Session Bean using Web Service Technology. In fact, the creation of a FacadeBean was not required since one could annotate the <code>SensorManager</code>-Bean directly, but we separated the implementation Bean from the exposing Bean to make it easier to understand. Even if we didn&#8217;t match the WSDL from the J2EE 1.4 example exactly, we came very close. Merely some message-related datatypes have different names. In this example we used the Document/Literal/Wrapped style of Web Services in order to gain maximum interoperability. Even though the creation of the Web Service is a simple task using the annotations. The number of tools and dependencies has dramataically reduced since J2EE 1.4 and the development became less error-prone. Together with other EJB3 improvements it makes the JEE framework suitable for development in the context of enterprise distributed systems.</p>
<h2>References and Resources</h2>
<p>The example source code is available for download (
<a  href="http://www.techjava.de/download/examples/ws4jee.zip" onclick="javascript:pageTracker._trackPageview('/downloads/download/examples/ws4jee.zip');" >ws4jee.zip</a>). Just import the projects from the archive into Eclipse Worskspace. Make sure to set up the JRE and JBoss Server instance for the projecst to work.</p>
<ul>
<li>
<div>[2008,techreport] 
<a  href="#JAVAEE" class="toggle">bibtex</a>  
<a  href='http://java.sun.com/javaee/5/docs/tutorial/doc/' title='Go to document' onclick="javascript:pageTracker._trackPageview('/external/java.sun.com/javaee/5/docs/tutorial/doc/');" ><img src='http://www.techjava.de/wp-content/plugins/bib2html/external.png' width='10' height='10' alt='Go to document' /></a></div>
<div>E. Jendrock, J. Ball, D. Carson, I. Evans, S. Fordin, and K. Haase, &quot;The Java EE 5 Tutorial,&quot; 2008.</div>
<div class="bibtex" id="JAVAEE">
         <code>@techreport{JAVAEE, <br />
 &nbsp;&nbsp;author =	{Eric Jendrock and Jennifer Ball and Debbie Carson and Ian Evans and Scott Fordin and Kim Haase}, <br />
 &nbsp; title =	{The Java EE 5 Tutorial}, <br />
 &nbsp; url = {http://java.sun.com/javaee/5/docs/tutorial/doc/}, <br />
 &nbsp; month =	{Oct}, <br />
 &nbsp; year =	{2008}<br />
}</code>
    </div>
</li>
<li>
<div>[2007,book] 
<a  href="#IHNS_2003" class="toggle">bibtex</a>  
<a  href='Oliver Ihns, Dierk Harbeck, Stefan M. Heldt, Holger Koschek, Roman Schlmmer, Jo Ehm, Carsten Sahling' title='Go to document'><img src='http://www.techjava.de/wp-content/plugins/bib2html/external.png' width='10' height='10' alt='Go to document' /></a></div>
<div>O. Ihns, D. Harbeck, S. M. Heldt, H. Koschek, R. Schl&#5954405;r, J. Ehm, and C. Sahling, <em>EJB 3 professionell. Grundlagen- und Expertenwissen zu Enterprise JavaBeans 3 fr Einsteiger, Umsteiger und Fortgeschrittene , publisher	DPunkt Verlag</em>, , 2007.</div>
<div class="bibtex" id="IHNS_2003">
         <code>@Book{IHNS_2003, <br />
 &nbsp;&nbsp;author =	{Oliver Ihns and Dierk Harbeck and Stefan M. Heldt and Holger Koschek and Roman Schlmmer and Jo Ehm and Carsten Sahling}, <br />
 &nbsp; title =	{EJB 3 professionell. Grundlagen- und Expertenwissen zu Enterprise JavaBeans 3 fr Einsteiger, Umsteiger und Fortgeschrittene }, <br />
 &nbsp; publisher	{DPunkt Verlag}, <br />
 &nbsp; year =	{2007}, <br />
 &nbsp; month =	{Jul}, <br />
 &nbsp; url = {Oliver Ihns, Dierk Harbeck, Stefan M. Heldt, Holger Koschek, Roman Schlmmer, Jo Ehm, Carsten Sahling}<br />
}</code>
    </div>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/01/functionality-web-services-jee/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Configuring JBoss Datasource for Firebird DB</title>
		<link>http://www.techjava.de/topics/2010/01/configuring-jboss-datasource-for-firebird-db/</link>
		<comments>http://www.techjava.de/topics/2010/01/configuring-jboss-datasource-for-firebird-db/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 00:33:17 +0000</pubDate>
		<dc:creator>shuron</dc:creator>
				<category><![CDATA[enterprise systems]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[Datasource]]></category>
		<category><![CDATA[firebird]]></category>
		<category><![CDATA[jaybird]]></category>
		<category><![CDATA[jca]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[rar]]></category>
		<category><![CDATA[server-side]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=537</guid>
		<description><![CDATA[
Accessing a relational database system from Java is a basic step required for many applications. The JEE architecture defines a standard for gaining this access, calls Java Connector Architecture (JCA). This article is a short HOWTO of configuring JCA-compliant datasource to a Firebird 2.x RDBMs using JBoss AS 5.1.0 as example. This tutorial is based [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 5px; float:right;" title="FirebirdPhoenix_Logo" src="http://www.techjava.de/wp-content/uploads/FirebirdPhoenix_Logo-150x150.gif" alt="FirebirdPhoenix_Logo" width="150" height="150" /><br />
Accessing a relational database system from Java is a basic step required for many applications. The JEE architecture defines a standard for gaining this access, calls Java Connector Architecture (JCA). This article is a short HOWTO of configuring JCA-compliant datasource to a Firebird 2.x RDBMs using JBoss AS 5.1.0 as example. This tutorial is based on a Windows installation, but can be easily ported to Linux, or other OS.</p>
<p>For the configuration of the datasource two steps are required:</p>
<ul>
<li>Deployment of the Firebird RAR resource adapter (<code>jaybird-*.rar</code>)</li>
<li>Creation of the <code>firebird-ds.xml</code> configuration</li>
</ul>
<p><span id="more-537"></span></p>
<h2>RAR Resource Adapter</h2>
<p>The RAR Resource Adapter is a version of RDBMs drivers packaged in a special way, defined by the JCA specifcation. The<br />

<a  href="http://www.ibphoenix.com/main.nfs?page=ibp_download_jaybird" target="_blank" onclick="javascript:pageTracker._trackPageview('/external/www.ibphoenix.com/main.nfs');" >latest versions of Type 4 JCA-JDBC Firebird Driver</a> (JayBird) can be downloaded from the IBPhoenix site. Inside of the downloaded archive you will find <code>jaybird-*.rar</code> (The version used during the creation of this tutorial was jaybird-2.1.6.rar). Since deployment in JBoss AS is performed by simple file copy, make sure to put the RAR-adapter-file into the deployment location of the application server. (e.G. ${JBOSS_ROOT}\server\default\deploy\).</p>
<p>After deployment, you can check the status of the resource adapter, by looking on the Administration Console of the JBoss (by default accessing the server URL http://localhost:8080/admin-console/ if run locally).</p>
<h2>Datasource Description</h2>
<p>After a successful deployment of the Resource RAR, the configuration of the datasource has to be created. The Firebird datasource configuration is supplied in a file, located in the default deployment location. JBoss AS auto-deplyoer will automatically look for the  <code>*-ds.xml</code> files, so we name it e.G. <code>firebird-ds.xml</code>.</p>
<p>The following datasource configuration defines a local transactional datasource. You just need to replace placeholders USERNAME, PASSWORD and path to your database-file (In the used installation the file was located in: <code>c:\databses\tesdb.fdb</code>)</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

  &lt;!-- ==================================================================== --&gt;
  &lt;!-- New ConnectionManager setup for firebird dbs using jca-jdbc xa driver--&gt;
  &lt;!-- Build jmx-api (build/build.sh all) and view for config documentation --&gt;
  &lt;!-- ==================================================================== --&gt;

&lt;connection-factories&gt;
	&lt;local-tx-datasource&gt;
		&lt;jndi-name&gt;DataSourceFirebirdDS&lt;/jndi-name&gt;
		&lt;connection-url&gt;jdbc:firebirdsql:localhost/3050:c:${/}databses${/}tesdb.fdb&lt;/connection-url&gt;
		&lt;driver-class&gt;org.firebirdsql.jdbc.FBDriver&lt;/driver-class&gt;
		&lt;transaction-isolation&gt;TRANSACTION_REPEATABLE_READ&lt;/transaction-isolation&gt;
		&lt;connection-property name=&quot;lc_ctype&quot; type=&quot;java.lang.String&quot;&gt;ISO8859_1&lt;/connection-property&gt;
		&lt;connection-property name=&quot;maxStatements&quot;&gt;10&lt;/connection-property&gt;
		&lt;user-name&gt;USERNAME&lt;/user-name&gt;
		&lt;password&gt;PASSWORD&lt;/password&gt;
		&lt;min-pool-size&gt;0&lt;/min-pool-size&gt;
		&lt;max-pool-size&gt;10&lt;/max-pool-size&gt;

		&lt;blocking-timeout-millis&gt;5000&lt;/blocking-timeout-millis&gt;

		&lt;idle-timeout-minutes&gt;15&lt;/idle-timeout-minutes&gt;
		&lt;check-valid-connection-sql&gt;SELECT CAST(1 as INTEGER) FROM rdb$database&lt;/check-valid-connection-sql&gt;
		&lt;track-statements&gt;false&lt;/track-statements&gt;
		&lt;prepared-statement-cache-size&gt;0&lt;/prepared-statement-cache-size&gt;
		&lt;metadata&gt;
			&lt;type-mapping&gt;Firebird&lt;/type-mapping&gt;
		&lt;/metadata&gt;
	&lt;/local-tx-datasource&gt;
&lt;/connection-factories&gt;
</pre>
<h2>Usage</h2>
<p>The datasource in the example above is registered in the <code>java</code> JNDI namespace and is called <code>DataSourceFirebirdDS</code>. In the source code, this resource should be accessible via <code>java:/DataSourceFirebirdDS</code>. Here is the example using Dependency Injection (DI):</p>
<pre class="brush: java;">
@Ressource(mappedName = &quot;java:/DataSourceFirebirdDS&quot;)
private DataSource firebirdDataSource;
</pre>
<p>In order to use the datasource in a JPA, the persistence unit has to be configured. For example, for using Hibernate, the following persistence unit can be configured.</p>
<pre class="brush: xml;">
...
&lt;persistence-unit name=&quot;testunit&quot;&gt;
	&lt;jta-data-source&gt;java:/DataSourceFirebirdDS&lt;/jta-data-source&gt;
	&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
	...
	&lt;properties&gt;
		&lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.FirebirdDialect&quot;/&gt;
		&lt;property name=&quot;hibernate.show_sql&quot; value=&quot;true&quot; /&gt;
		...
	&lt;/properties&gt;
&lt;/persistence-unit&gt;
...
</pre>
<p>Then in the DAO for manipulation of Persistent Entities, the Persistence Context can be injected by:</p>
<pre class="brush: java;">
@Stateless
public class TestDAOBean implements TestDAO {

	@PersistenceContext(unitName = &quot;testunit&quot;)
	private EntityManager manager;

	...
}
</pre>
<p>Have fun and please provide some feedback.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/01/configuring-jboss-datasource-for-firebird-db/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Eclipse CNF: Navigator Content Extensions</title>
		<link>http://www.techjava.de/topics/2009/08/eclipse-common-navigator-framework-2/</link>
		<comments>http://www.techjava.de/topics/2009/08/eclipse-common-navigator-framework-2/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 20:55:11 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[rcp]]></category>
		<category><![CDATA[cnf]]></category>
		<category><![CDATA[common navigator framework]]></category>
		<category><![CDATA[navigator content extension]]></category>
		<category><![CDATA[NCE]]></category>
		<category><![CDATA[plug-in]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=471</guid>
		<description><![CDATA[Abstract
 After 
providing the basic example of how the Eclipse Common Navigator Framework (CNF) can be used to display custom content, this article focuses on the main feature of the CNF &#8211; the contribution of content to the same navigator by several independent plug-ins. First of all, I will explain some minor changes introduced to [...]]]></description>
			<content:encoded><![CDATA[<h2>Abstract</h2>
<p><img class="alignnone size-thumbnail wp-image-501" style="float:right; margin:10px;" title="compass" src="http://www.techjava.de/wp-content/uploads/compass2-150x150.jpg" alt="compass" width="150" height="150" /> After 
<a  href="http://www.techjava.de/topics/2009/04/eclipse-common-navigator-framework/">providing the basic example</a> of how the Eclipse Common Navigator Framework (CNF) can be used to display custom content, this article focuses on the main feature of the CNF &#8211; the contribution of content to the same navigator by several independent plug-ins. First of all, I will explain some minor changes introduced to the CNF in the Gallileo Edition, then I will focus on the content itself and finally provide an overview of how the action contributions can be provided. In the end of the post, some ideas on control of dynamic content are explained.</p>
<h2>Gallileo Changes</h2>
<p>There are two noticeable changes in the CNF that have been added with 
<a  href="http://www.techjava.de/topics/2009/06/galileo-has-arrived/">Eclipse Galileo</a>. The return type of the method <span id="more-471"></span><code>CommonNavigator#getInitialInput()</code> has been changed to <code>Object</code> (which is important for the RCP usage of the CNF) and the call of the method <code>org.eclipse.ui.internal.ide.model.WorkbenchAdapterBuilder#registerAdapters()</code> has been replaced by the <code>org.eclipse.ui.ide.IDE.registerAdapters();</code> which should be executed in the <code>initialize</code> method of the <code>ApplicationWorkbenchAdvisor</code> of your RCP if you are using resources with the CNF.</p>
<pre class="brush: java;">
public class CommonNavigator ...
{
  /**
   * Used to provide the initial input for the {@link CommonViewer}.
   * By default getSite().getPage().getInput() is used.
   * Subclass this to return your desired input.
   * @return The initial input for the viewer.
   * Defaults to getSite().getPage().getInput()
   * @since 3.4
   */
  protected Object getInitialInput() {...}
}
</pre>
<h2>Content contribution</h2>
<p>The main advantage of the use of the CNF over a simple tree view is the ability to contribute content to the view from several plug-ins. Thus, the plug-in that contains the view does not depend on the contributing plug-ins. If you are not familiar with the CNF, please review the 
<a  href="http://www.techjava.de/topics/2009/04/eclipse-common-navigator-framework/">previous post</a>, since the example provided there will be extended. The data model used previously will be extended by an additional layer: along with parents and children, the pets are introduced. Let&#8217;s assume that pets are owned by children.</p>
<pre class="brush: java;">
/**
 * Represents a pet
 * @author Simon Zambrovski
 */
public class Pet
{
    private String name;
    private Child owner;

    public Pet(String name, Child owner)
    {
        super();
        this.name = name;
        this.owner = owner;
    }
    ...
    // getter and setter
}
</pre>
<p>First of all create a new plug-in project called <code>de.techjava.rcp.cnf.subcontent</code>, add a plug-in dependency to the <code>de.techjava.rcp.cnf</code> and to the <code>org.eclipse.ui.navigator</code>. Then add two extensions <code>org.eclipse.ui.navigator.navigatorContent</code> and <code>org.eclipse.ui.navigator.viewer</code>. The first extension defines the new Navigator Content Extension (NCE) and the second one is used to bind it to the existing viewer.</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;org.eclipse.ui.navigator.navigatorContent&quot;&gt;
      &lt;navigatorContent
            activeByDefault=&quot;true&quot;
            contentProvider=&quot;de.techjava.rcp.cnf.subcontent.provider.CNFSubContentProvider&quot;
            id=&quot;de.techjava.rcp.cnf.subcontent.navigatorContent&quot;
            labelProvider=&quot;de.techjava.rcp.cnf.subcontent.provider.CNFSubLabelProvider&quot;
            name=&quot;Sub Content&quot;
            priority=&quot;normal&quot;
            providesSaveables=&quot;false&quot;&gt;
         &lt;enablement&gt;
            &lt;instanceof value=&quot;de.techjava.rcp.cnf.data.Child&quot; /&gt;
         &lt;/enablement&gt;
      &lt;/navigatorContent&gt;
   &lt;/extension&gt;
   &lt;extension
         point=&quot;org.eclipse.ui.handlers&quot;&gt;
      &lt;handler
            class=&quot;de.techjava.rcp.cnf.subcontent.handler.RenameHandler&quot;
            commandId=&quot;org.eclipse.ui.edit.rename&quot;&gt;
         &lt;activeWhen&gt;
            &lt;reference definitionId=&quot;de.techjava.rcp.cnf.subcontent.petSelected&quot; /&gt;
         &lt;/activeWhen&gt;
         &lt;enabledWhen&gt;
            &lt;reference definitionId=&quot;de.techjava.rcp.cnf.subcontent.petSelected&quot;/&gt;
         &lt;/enabledWhen&gt;
      &lt;/handler&gt;
   &lt;/extension&gt;
</pre>
<p>The Sub Content is defined following the same scheme as the content in the previous article of this series.  Its <code>contentProvider</code> and <code>labelProvider</code> attributes point to the corresponding classes. The label provider implementation is straight forward. The content provider has to be able to return a list of children, if the instance of the <code>Child</code>-class is selected in the Navigator. The <code>enablement</code> is defined in this way respectively. An important thing to understand at this point is that the CNF will <strong>join</strong> contributions of all NCEs triggered on the element selection. This means, that even if the NCE of the first plug-in does not provide any children for the <code>Child</code> element, there will be children contributed by the second plug-in&#8217;s content provider. Here is the example content provider, which returns the number of pets depending on the last digit in a child&#8217;s name:</p>
<pre class="brush: java;">
public class CNFSubContentProvider implements ITreeContentProvider
{
    ...
    public Object[] getChildren(Object parentElement)
    {
        if (parentElement instanceof Child
                &amp;&amp; !(parentElement instanceof Parent))
        {
            Child child = ((Child) parentElement);
            char lastDigit = child.getName().charAt(child.getName().length() - 1);
            if (Character.isDigit(lastDigit))
            {
                int petCount = Integer.parseInt(String.valueOf(lastDigit));
                Pet[] pets = new Pet[petCount];
                for (int i = 0; i &gt; petCount; i++)
                {
                    pets[i] = new Pet(child.getName() + &quot;'s pet &quot; + (i + 1), child);
                }
                return pets;
            }
            return EMPTY_ARRAY;
        } else
        {
            return EMPTY_ARRAY;
        }
    }
    ...
}
</pre>
<p>After this trivial configuration and the inclusion of the new plug-in into the example product, the resulting Navigator should show pets as sub-elements of the child-elements.<br />
<img class="alignnone size-full wp-image-484" title="CNF2" src="http://www.techjava.de/wp-content/uploads/CNF2.png" alt="CNF2" width="400" height="300" /></p>
<h2>Shared commands</h2>
<p>If the Navigator displays content from several plug-ins, the contributed commands should be handled carefully. The commands (contributed to the pop-up menu shown upon right-click on the corresponding item) should appear only on items they belong to. In order to achieve this, let us first look at the standard way of the command contribution. The CNF developer is strongly recommend to use the declarative contribution techniques instead of the Action Contribution Provider. For this purpose, the extension point <code>org.eclipse.ui.navigator.viewer</code> allows to contribute a <code>popupMenu</code> element as a child element of the <code>viewer</code>. The pop-up menu element defines the structure (in terms of separators) of the pop-up menu. There is a standard pop-up menu structure defined, which is default if a user-specific definition is ommited. In the example, the user-specific pop-up menu is defined:</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;org.eclipse.ui.navigator.viewer&quot;&gt;
      &lt;viewer
            viewerId=&quot;de.techjava.rcp.cnf.view&quot;&gt;
         &lt;popupMenu
               allowsPlatformContributions=&quot;true&quot;
               id=&quot;de.techjava.rcp.cnf.view.popup&quot;&gt;
            &lt;insertionPoint
                  name=&quot;group.new&quot;
                  separator=&quot;false&quot;&gt;
            &lt;/insertionPoint&gt;
            &lt;insertionPoint
                  name=&quot;group.open&quot;
                  separator=&quot;false&quot;&gt;
            &lt;/insertionPoint&gt;
            &lt;insertionPoint
                  name=&quot;group.edit&quot;
                  separator=&quot;true&quot;&gt;
            &lt;/insertionPoint&gt;
            ...
         &lt;/popupMenu&gt;
      &lt;/viewer&gt;
      ...
    &lt;/extension&gt;
</pre>
<p>Using the 
<a  href="http://wiki.eclipse.org/index.php/Platform_Command_Framework" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/index.php/Platform_Command_Framework');" >Eclipse Command Framework</a>, the commands can be contributed to the defined pop-up menu in the following way. Using the <code>org.eclipse.ui.menus</code> extension point one or several <code>menuContribution</code> elements can be defined. Each menu contribution defines a set of commands, controls, menus, tool bars or dynamic contributions (or any combination) which are added to a specific separator addressed in a special way (see Command Framework Documentation). In this example the set of commands is contributed:</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;org.eclipse.ui.menus&quot;&gt;
      &lt;menuContribution
            locationURI=&quot;popup:de.techjava.rcp.cnf.view.popup?after=group.edit&quot;&gt;
         &lt;command
               commandId=&quot;org.eclipse.ui.edit.delete&quot;
               id=&quot;cnf.popupmenu.delete&quot;
               label=&quot;Delete&quot;
               mnemonic=&quot;D&quot;
               style=&quot;push&quot;&gt;
         &lt;/command&gt;
         &lt;command
               commandId=&quot;org.eclipse.ui.edit.rename&quot;
               id=&quot;cnf.popupmenu.rename&quot;
               label=&quot;Rename&quot;
               mnemonic=&quot;R&quot;
               style=&quot;push&quot;&gt;
         &lt;/command&gt;
      &lt;/menuContribution&gt;
      ....
    &lt;/extension&gt;
</pre>
<p>Please note that the <code>commandId</code> must point to an existing command, which is either user-defined, or defined by the Eclipse platform. A <code>command</code> is an abstraction of a user command which is referenced from the User Interface on one hand and has assigned handlers (which execute the command) on the other hand. The representation of the command is shown in the UI only if a handler is assigned to it. The idea of using shared commands is to have multiple handlers for the same command, which are activated depending on the selected element.</p>
<p>In order to enable and disable handlers in a declarative way, the 
<a  href="http://wiki.eclipse.org/Command_Core_Expressions" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/Command_Core_Expressions');" >Eclipse Core Expressions</a> are used. Core expressions can be written in the <code>enabledWhen</code> and <code>activeWhen</code> child elements of the handler definition. The core expressions can also be defined and referenced externally using the <code>org.eclipse.core.expressions.definitions</code> extension point. Here is an example definition of the handler assigned to the Rename command:</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;org.eclipse.ui.handlers&quot;&gt;
      &lt;handler
            class=&quot;de.techjava.rcp.cnf.handler.RenameHandler&quot;
            commandId=&quot;org.eclipse.ui.edit.rename&quot;&gt;
         &lt;activeWhen&gt;
            &lt;reference definitionId=&quot;de.techjava.rcp.cnf.elementSelected&quot; /&gt;
         &lt;/activeWhen&gt;
         &lt;enabledWhen&gt;
            &lt;reference definitionId=&quot;de.techjava.rcp.cnf.elementSelected&quot; /&gt;
         &lt;/enabledWhen&gt;
      &lt;/handler&gt;
   &lt;/extension&gt;
</pre>
<p>The handler is enabled and active if the expression <code>de.techjava.rcp.cnf.elementSelected</code> is triggered. The definition of the expression is as follows. It defines the <code>with</code>-scope on the current selection, <code>iterates</code> over the elements and applies the <code>instance of</code> operator on the elements using the OR-conjunction. In doing so, the expression will trigger if among the currently selected elements is at least one <code>Child</code> element.</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;org.eclipse.core.expressions.definitions&quot;&gt;
      &lt;definition id=&quot;de.techjava.rcp.cnf.elementSelected&quot;&gt;
         &lt;with variable=&quot;selection&quot;&gt;
            &lt;iterate ifEmpty=&quot;false&quot; operator=&quot;or&quot;&gt;
               &lt;instanceof value=&quot;de.techjava.rcp.cnf.data.Child&quot; /&gt;
            &lt;/iterate&gt;
         &lt;/with&gt;
      &lt;/definition&gt;
   &lt;/extension&gt;
</pre>
<p><img class="alignnone size-full wp-image-486" title="CNF2-rename-child" src="http://www.techjava.de/wp-content/uploads/CNF2-rename-child.png" alt="CNF2-rename-child" width="384" height="239" /><br />
In order to use the same action (the Rename item of the pop-up menu) in the Pet plug-in, the handler enabled on the Pet element has to be provided. The code is analogous to the code before:</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;org.eclipse.ui.handlers&quot;&gt;
      &lt;handler
            class=&quot;de.techjava.rcp.cnf.subcontent.handler.RenameHandler&quot;
            commandId=&quot;org.eclipse.ui.edit.rename&quot;&gt;
         &lt;activeWhen&gt;
            &lt;reference
                  definitionId=&quot;de.techjava.rcp.cnf.subcontent.petSelected&quot;&gt;
            &lt;/reference&gt;
         &lt;/activeWhen&gt;
         &lt;enabledWhen&gt;
            &lt;reference definitionId=&quot;de.techjava.rcp.cnf.subcontent.petSelected&quot; /&gt;
         &lt;/enabledWhen&gt;
      &lt;/handler&gt;
   &lt;/extension&gt;
   &lt;extension
         point=&quot;org.eclipse.core.expressions.definitions&quot;&gt;
      &lt;definition
            id=&quot;de.techjava.rcp.cnf.subcontent.petSelected&quot;&gt;
         &lt;with variable=&quot;selection&quot;&gt;
            &lt;iterate ifEmpty=&quot;false&quot; operator=&quot;or&quot;&gt;
               &lt;instanceof value=&quot;de.techjava.rcp.cnf.subcontent.data.Pet&quot; /&gt;
            &lt;/iterate&gt;
         &lt;/with&gt;
      &lt;/definition&gt;
   &lt;/extension&gt;
</pre>
<p>This should enable the Rename action on the Pet elements, too.<br />
<img class="alignnone size-full wp-image-487" title="CNF2-rename-pet" src="http://www.techjava.de/wp-content/uploads/CNF2-rename-pet.png" alt="CNF2-rename-pet" width="384" height="239" /></p>
<h2>Dynamic content change</h2>
<p>Finally, the last topic, which is covered in this article is the control of which content is shown in the Common Navigator. The developer can define the initial behaviour by setting the <code>activeByDefault</code> attribute of the <code>NavigatorContent</code> element. The user can customize the visible NCEs in the special dialog:<br />
<img class="alignnone size-full wp-image-489" title="CNF2-available-customizations" src="http://www.techjava.de/wp-content/uploads/CNF2-available-customizations.png" alt="CNF2-available-customizations" width="407" height="339" /><br />
Of course there is a way to change the content shown in the Common Navigator at run-time. The following section describes how this can be done.</p>
<p>Responsible for loading the NCEs is the NavigatorContentService, which can be retrieved from the running Navigator instance. Using it is straight forward.</p>
<pre class="brush: java;">
    /**
     * Sets the status of a NCE of the current viewer if any
     */
    public static void setToolboxNCEActive(final String extensionId, final boolean active)
    {
        CommonNavigator instance = findCommonNavigator(CNFNavigator.VIEW_ID);
        if (instance != null)
        {
            INavigatorContentService contentService = instance.getNavigatorContentService();
            boolean isActive = contentService.getActivationService().isNavigatorExtensionActive(extensionId);
            if (active &amp;&amp; !isActive)
            {
                contentService.getActivationService().activateExtensions(new String[] { extensionId }, false);
            } else if (!active &amp;&amp; isActive)
            {
                contentService.getActivationService().deactivateExtensions(new String[] { extensionId }, false);
            } else
            {
                // do nothing, just quit
                return;
            }
            contentService.getActivationService().persistExtensionActivations();
            contentService.update();
        }
    }
</pre>
<p>The method <code>findCommonNavigator(String viewId)</code> is responsible for delivering the instance of the CNF. For example it could query the view for visible viewers and compare them with the requested Id:</p>
<pre class="brush: java;">
    public static CommonNavigator findCommonNavigator(String navigatorViewId)
    {
        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        if (page != null)
        {
            IViewPart view = page.findView(navigatorViewId);
            if (view != null &amp;&amp; view instanceof CommonNavigator)
                return ((CommonNavigator) view);
        }
        return null;
    }
</pre>
<p>After the NCE status is changed the viewer has to be updated. Please note, that retrieving the instance of the <code>INavigatorContentService</code> via the Factory (<code>NavigatorContentServiceFactory</code>) will not work for this scenario (see 
<a  href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=284650" onclick="javascript:pageTracker._trackPageview('/external/bugs.eclipse.org/bugs/show_bug.cgi');" >Bug 284650</a>).</p>
<p>Making a step back and thinking about the usage of the method above, I realized that it can be reduced to the usage of core expressions instead of the simple boolean <code>activeByDefault</code> attribute. Maybe this enhancement could be contributed to the CNF at some point&#8230;</p>
<p>The source code to this post is available for 
<a  href="http://www.techjava.de/wp-content/uploads/rcp-cnf2.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/rcp-cnf2.zip');" >download</a>. It includes two plug-in projects (the CNF and the child content) which are packaged into a small RCP application. Just launch the product included in the CNF plug-in.</p>
<h3>References</h3>
<ul>
<li>
<a  href="http://wiki.eclipse.org/index.php/Common_Navigator_Framework" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/index.php/Common_Navigator_Framework');" >http://wiki.eclipse.org/index.php/Common_Navigator_Framework</a></li>
<li>
<a  href="http://wiki.eclipse.org/Command_Core_Expressions" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/Command_Core_Expressions');" >http://wiki.eclipse.org/Command_Core_Expressions</a></li>
<li>
<a  href="http://wiki.eclipse.org/index.php/Platform_Command_Framework" onclick="javascript:pageTracker._trackPageview('/external/wiki.eclipse.org/index.php/Platform_Command_Framework');" >http://wiki.eclipse.org/index.php/Platform_Command_Framework</a></li>
</ul>
<p>The compass image used in the post is taken from the 
<a  href="http://www.flickr.com/photos/bio_inc/484534267/" onclick="javascript:pageTracker._trackPageview('/external/www.flickr.com/photos/bio_inc/484534267/');" >FlickR gallery</a> of Jean Franco Castro.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2009/08/eclipse-common-navigator-framework-2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Passing Data between Plug-ins</title>
		<link>http://www.techjava.de/topics/2009/07/passing-data-between-plug-ins/</link>
		<comments>http://www.techjava.de/topics/2009/07/passing-data-between-plug-ins/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 20:57:12 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[rcp]]></category>
		<category><![CDATA[extension point]]></category>
		<category><![CDATA[pde]]></category>
		<category><![CDATA[plug-in]]></category>
		<category><![CDATA[schema]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=436</guid>
		<description><![CDATA[Abstract

The Eclipse Platform provides a very rich API for the development and configuration of plug-ins and RCPs. It does this in two ways: by providing the corresponding classes and interfaces or by using the extension point mechanism. During the development the question arises, how to develop own extension points and how those plug-in interfaces look [...]]]></description>
			<content:encoded><![CDATA[<h2>Abstract</h2>
<p><img src="http://www.techjava.de/wp-content/uploads/imp_extplug_wiz.png" alt="Passing Data between Plug-ins" title="Passing Data between Plug-ins" width="75" height="66" style="margin:10px;float:right;" /><br />
The Eclipse Platform provides a very rich API for the development and configuration of plug-ins and RCPs. It does this in two ways: by providing the corresponding classes and interfaces or by using the extension point mechanism. During the development the question arises, how to develop own extension points and how those plug-in interfaces look like. This article summarizes some of my experiences with developing plug-ins extension points.</p>
<h2>Introduction</h2>
<p>The extensive use of extension points is the standard approach during the development of own plug-ins and Eclipse-based applications. Especially, in the 3.x branch, the Eclipse Developers introduced tons of new extension points, primarily for the user interface, moving towards the declarative definition of the UI. Even if the the topic of the definition of extension points is covered in several 
<a  href="http://www.amazon.de/Contributing-Eclipse-Principles-Patterns-Plug-Ins/dp/0321205758" onclick="javascript:pageTracker._trackPageview('/external/www.amazon.de/Contributing-Eclipse-Principles-Patterns-Plug-Ins/dp/0321205758');" >books</a> and 
<a  href="http://www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html');" >articles</a>, it is a bit challenging to come up with a clean extension point design for a particular scenarios, especially for beginners. This has to do with the specific way, how the Eclipse platform handles extensions.</p>
<p>In order to have a concrete scenario, lets assume that a small RCP application consisting of two plug-ins is being developed. The application prints out the time every ten seconds. One plug-in is responsible for the functionality of the time generation (lets call it the Core plug-in) and another, for the presentation of the results of the first one (lets call it UI plug-in). The separation of code in UI and non-UI plug-ins is a common practice and the standard question is, how to to pass data between the two. In general we assume, that the UI plug-in depends on the Core plug-in.<br />
<span id="more-436"></span><br />
In the following the different alternatives are discussed.</p>
<h2>Call me synchronously</h2>
<p>One of the most simple and common cases is the situation, in which the UI plug-in has the control and needs to call a method on some instance of the Core plug-in. This happens particularly in cases, in which a command handler or an action implemented in the UI plug-in is invoked on behalf of user interaction and the functionality of the Core plug-in is called. The only thing to do is to add the classes to the exported by the Core plug-in. Since the UI plug-in depends on Core, the classes will become visible (in terms of OSGi) and can be imported and used directly. If the method is synchronous, the result can be received upon the completion of the method and displayed by the UI plug-in. In this case the plug-in boundary disappears.</p>
<h2>Call me asynchronously</h2>
<p>The things get more complicated, if the call is not synchronous, but is invoked inside of a <code>IWorkspaceRunnable</code> or a <code>Job</code>. This situation is common in enterprise scenarios, when the invoked functionality is a long running operation, like loading data from a database or accessing a resource over the network. The signatures of the methods for those operations do not provide a possibility to get the invocation result.</p>
<pre class="brush: java;">
public interface IWorkspaceRunnable {
    public void run(IProgressMonitor monitor) throws CoreException;
}
</pre>
<pre class="brush: java;">
public abstract class Job extends InternalJob implements IAdaptable {
    protected abstract IStatus run(IProgressMonitor monitor);
}
</pre>
<p>In fact the method invocation of asynchronous calls can be performed from any plug-in (so not only UI) and it does not play any role for the result. Thus, this case can be discussed together with the case, in which the Core plug-in broadcasts the data change.</p>
<h2>Don&#8217;t call us, we will call you</h2>
<p>Another case, which can be seen as a general extension of the asynchronous case is if the state changes, and consequently the UI change originates from the Core plug-in. This use case is possible if there are several UI plug-ins working with one Core plug-in, and the changes inside of the Core plug-in have to be propagated to the views, following the well-known Model-View-Controller Design Pattern. Then, a common approach is the implementation of the Listener-Broadcaster Design Pattern. The UI plug-ins (Views) should register themselves as listeners by the Core plug-ins and will be notified on changes of its (Model) state. In this case the extension point mechanism of Eclipse can be used as discussed in the following. It is also a good idea, to hide the code dealing with Eclipse Extension Registry and extensions, so a simple implementation of the broadcaster is provided, too.</p>
<h3>Definition of the extension point (Core plug-in side)</h3>
<p>The definition of extension point for the listener/broadcaster case involves four steps:</p>
<ul>
<li>Creation of the listener interface</li>
<li>Registration of the extension point</li>
<li>Creation of the extension point schema</li>
<li>Implementation of the broadcaster</li>
</ul>
<p>The so defined extension point can be used by plug-ins, which then provide implementations of the listener interface. The broadcaster, located in the Core plug-in is responsible for sending the data to them. Note, that providing the implementation of the listener via extension point <strong>is logically equivalent to the creation of a factory</strong> which is responsible for the production of listeners. The Core plug-in has the control of how this factory is used, how many listeners (from each extension) are created, and when these are notified.</p>
<h4>Creation of the listener interface</h4>
<p>The interface for the listener is usually very simple. It provides a method, which is called by the broadcaster, e.G:</p>
<pre class="brush: java;">
public interface ISimpleListener
{
    public void eventOccured();
}
</pre>
<p>Sometimes the method takes parameters, like <code>public void eventOccured(String message)</code> or <code>public void eventOccured(ISimpleEvent event)</code> and sometimes it returns a value. In general, the signature of the notification method is application-specific and will not be discussed further. Since the implementers of the listener does not have control over the way, how and when this method is used, it is advised to add two life-cycle methods to the interface <code>initialize()</code> and <code>terminate()</code>:</p>
<pre class="brush: java;">
package de.techjava.rcp.plugins.core.listener;

/**
 * A simple listener
 * @author Simon Zambrovski, TechJava Group
 */
public interface ISimpleListener
{
    /**
     * Initialization life-cycle method
     */
    public void initialize(Object source);

    /**
     * Signals the event occurrence
     * @param event
     */
    public void eventOccured(SimpleEvent event);

    /**
     * Termination life-cycle method
     */
    public void terminate();
}
</pre>
<p>The life-cycle of the listener is then defined as follows: first, its parameter-less constructor is called, then the <code>initialize</code> method is invoked, providing the ability to hook into some infrastructure inside of the implementing plug-in. After the initialization, the <code>eventOccured</code> method is called multiple times. Finally, the listener is informed about the fact that the source will not send any information by the invocation of the <code>terminate</code> method. The <code>source</code> parameter of the <code>ISimpleListener#initialize(Object)</code> method again is application specific and should be chosen that way, that the listener is able to determine the source of events. Alternatively, the method <code>ISimpleListener#eventOccured(SimpleEvent)</code> can carry this information on every invocation, either in the <code>SimpleEvent</code> object or as additional parameter.</p>
<h4>Registration of the extension point</h4>
<p>After the Java interface of the listener has been created, the extension point can be defined. The easiest way to this, is to use the Plug-In Manifest Editor &gt; Extension Points, but you can edit the <code>plugin.xml</code> directly. Basically, three values are required: <code>id</code>, <code>name</code> and <code>schema location</code>.<br />
<img class="alignnone" style="margin: 5px;" title="extension-point-wizard" src="http://www.techjava.de/wp-content/uploads/extension-point-wizard.png" alt="extension-point-wizard" width="435" height="311" /></p>
<p>The corresponding <code>plugin.xml</code> code looks like this:</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;?eclipse version=&quot;3.5&quot;?&gt;
&lt;plugin&gt;
   &lt;extension-point
      id=&quot;de.techjava.rcp.plugins.core.listener&quot;
   	  name=&quot;Simple Core Listener&quot;
   	  schema=&quot;schema/org.techjava.rcp.plugins.core.listener.exsd&quot;/&gt;
&lt;/plugin&gt;
</pre>
<p>Since the dependent plug-ins should implement the <code>ISimpleListener</code> interface, the containing package  has to be exposed. This can be done either by adding the package to the list of exported packages using the Plug-In Manifest Editor &gt; Runtime &gt; Exported Packages or by simple editing of the <code>MANIFEST.MF</code> file and adding the following line to it:</p>
<pre class="brush: xml;">
Export-Package: de.techjava.rcp.plugins.core.listener
</pre>
<h4>Creation of the extension point schema</h4>
<p>The definition of the extension point is performed by creation of the XML-Schema document, describing the structure and the data of the extension point. The Eclipse IDE provides a convenient Extension Point Schema Editor for this task, implemented as multi-page editor with master-detail page for schema definition. The creation wizard already creates the extension element. What has to be done is this:</p>
<ul>
<li>Create <code>New Element</code></li>
<li>Provide an adequate <code>Name</code> for it (<code>listener</code> in our case)</li>
<li>Add an <code>Attribute</code> to this element</li>
<li>Provide an adequate <code>Name</code> for it (<code>class</code> in our case)</li>
<li>Change the <code>Use</code> to required</li>
<li>Change the <code>Type</code> to <code>java</code></li>
<li>Fill the <code>Implements</code> with the full-qualified name of the listener interface (<code>de.techjava.rcp.plugins.core.listener.ISimpleListener</code>)</li>
<li>Optionally, fill the description</li>
<li>Add a <code>Sequence</code> to the <code>extension</code></li>
<li>Add a reference to the <code>listener</code> to the <code>Sequence</code></li>
<li>Optionally, adjust the multiplicity of the <code>listener</code> element, to allow multiple listeners to be registered using one extension point</li>
</ul>
<p>In the Extension Point Schema Editor the corresponding changes should look like this: <img class="alignnone" style="margin: 5px;" title="extension-point-editor" src="http://www.techjava.de/wp-content/uploads/extension-point-editor1.png" alt="extension-point-editor" width="549" height="419" /></p>
<h4>Implementation of the broadcaster</h4>
<p>After the interface is created and the corresponding extension point is defined, a broadcaster can be implemented. Its purpose is to hide the code related to the use of the Extension Point Registry. For convenience, the broadcaster can implement the same interface as the listeners do (<code>ISimpleListener</code>).</p>
<pre class="brush: java;">
/**
 * Simple broadcaster implementing the listener interface
 * @author Simon Zambrovski, TechJava Group
 */
public class SimpleBroadcaster implements ISimpleListener
{

    private static final String POINT_ID = &quot;de.techjava.rcp.plugins.core.listener&quot;;
    private static final String CLASS_ATTRIBUTE = &quot;class&quot;;

    private List&lt;ISimpleListener&gt; listeners = null;

    /**
     * Construct the broadcaster and initializes the listeners registered
     * using {@link de.techjava.rcp.plugins.core.listener} extension
     * point
     */
    public SimpleBroadcaster(Object source)
    {
        // initialize on creation
        initialize(source);
    }

    public void eventOccured(SimpleEvent event)
    {
        // broadcast the events
        for (ISimpleListener listener : this.listeners)
        {
            if (listener != null)
            {
                listener.eventOccured(event);
            }
        }
    }

    public void initialize(Object source)
    {
        // retrieve the registered listeners
        this.listeners = getRegisteredListeners();

        // initialize
        for (ISimpleListener listener : this.listeners)
        {
            if (listener != null)
            {
                listener.initialize(source);
            }
        }
    }

    public void terminate()
    {
        // terminate
        for (ISimpleListener listener : this.listeners)
        {
            if (listener != null)
            {
                listener.terminate();
            }
        }
        this.listeners = null;
    }
...
}
</pre>
<p>The broadcaster holds the list of registered <code>ISimpleListener</code> instances. Its own implementation of the <code>ISimpleListener</code> is trivial and just delegates the calls to the elements of this list. The static method <code>SimpleBroadcaster#getRegisteredListeners()</code> is responsible for querying the registry for the registered extension and looks as follows:</p>
<pre class="brush: java;">
    /**
     * Retrieves all registered listeners
     */
    public static List&lt;ISimpleListener&gt; getRegisteredListeners()
    {
        IConfigurationElement[] decls = Platform.getExtensionRegistry().getConfigurationElementsFor(POINT_ID);

        Vector&lt;ISimpleListener&gt; validExtensions = new Vector&lt;ISimpleListener&gt;();
        for (int i = 0; i &lt; decls.length; i++)
        {
            try
            {
                ISimpleListener extension = (ISimpleListener) decls[i].createExecutableExtension(CLASS_ATTRIBUTE);
                validExtensions.add(extension);
            } catch (CoreException e)
            {
                Activator.logError(&quot;Error instatiating the &quot; + POINT_ID + &quot; extension&quot;, e);
            }
        }
        return validExtensions;
    }
</pre>
<h4>Use of the broadcaster</h4>
<p>The use of the broadcaster from the Core plug-in is straight-forward. Here is an example of a job, which periodically sends message containing the time to the  listeners.</p>
<pre class="brush: java;">
/**
 * Broadcasts the current time
 * @author Simon Zambrovski
 * @version $Id$
 */
public class SimpleTimeBroadcastJob extends Job
{
    private SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-MM-dd hh:mm:ss&quot;);
    private SimpleBroadcaster broadcaster = null;

    public SimpleTimeBroadcastJob()
    {
        super(&quot;Time Broadcast Job&quot;);
    }

    protected IStatus run(IProgressMonitor monitor)
    {
        try
        {
            broadcaster = new SimpleBroadcaster(this);
            broadcaster.eventOccured(new SimpleEvent(&quot;Curent time in Core is &quot; + sdf.format(new Date())));
            broadcaster.terminate();
            return Status.OK_STATUS;
        } finally
        {
            // restart again in a 10 seconds
            schedule(10 * 1000);
        }
    }
}
</pre>
<p>Now, after the Core part is implemented, we focus on the implementation of the UI part, which receives the events.</p>
<h3>Use of extension point (UI plug-in side)</h3>
<p>The usage of the extension point is simpler than its definition and basically consists of the implementation of the listener interface and its registration. Here is a sample implementation writing to System.out:</p>
<pre class="brush: java;">
public class SimpleListener implements ISimpleListener
{
    private Object source;

    public SimpleListener()
    {
    }

    public void eventOccured(SimpleEvent event)
    {
        String message = &quot;Event from &quot; + source.toString() + &quot;: &quot; + event.getMessage();
        System.out.println(message);
    }

    public void initialize(Object source)
    {
        this.source = source;
        System.out.println(&quot;New &quot; + SimpleListener.class.getName() + &quot; listens to &quot; + source.toString());
    }

    public void terminate()
    {
        this.source = null;
        this.consoleStream = null;
        System.out.println(&quot;Listners destroyed&quot;);
    }
}
</pre>
<p>In order to tell the Eclipse Platform about the existence of this implementation, the extension point defined in the Core plug-in and has to be used in the UI plug-in.  For this purpose, the UI plug-in must list the Core plug-in in its <code>Dependencies</code> and define the use of the extension point in the <code>plugin.xml</code>:</p>
<pre class="brush: xml;">
   &lt;extension
         point=&quot;de.techjava.rcp.plugins.core.listener&quot;&gt;
      &lt;listener
            class=&quot;de.techjava.rcp.plugins.ui.SimpleListener&quot;&gt;
      &lt;/listener&gt;
   &lt;/extension&gt;
</pre>
<p>That&#8217;s it.</p>
<h2>Example</h2>
<p>The example source for this article is available 
<a  href="http://www.techjava.de/download/examples/rcp-plugins.zip" onclick="javascript:pageTracker._trackPageview('/downloads/download/examples/rcp-plugins.zip');" >here</a>. It is a little bit more elaborate and provides a simple application, which prints the time into the Eclipse Console. I used Eclipse Galileo (3.5.0) &#8211; just copy the two projects into your workspace and run the product.<br />
<img src="http://www.techjava.de/wp-content/uploads/time-rcp1.png" alt="time-rcp" title="time-rcp" width="585" height="265" class="alignnone size-full wp-image-449" style="margin:10px;"/></p>
<h2>References</h2>
<ul>
<li>
<a  href="http://www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html');" >Notes on the Eclipse Plug-in Architecture</a></li>
<li>
<a  href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=sr_1_2?ie=UTF8&amp;s=books&amp;qid=1248225439&amp;sr=8-2" onclick="javascript:pageTracker._trackPageview('/external/www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=sr_1_2');" >Design Patterns: Elements of Reusable Object-Oriented Software</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2009/07/passing-data-between-plug-ins/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Packaging Eclipse-based RCP for the use in enterprise context</title>
		<link>http://www.techjava.de/topics/2009/07/packaging-eclipse-based-rcp-for-the-use-in-enterprise-context/</link>
		<comments>http://www.techjava.de/topics/2009/07/packaging-eclipse-based-rcp-for-the-use-in-enterprise-context/#comments</comments>
		<pubDate>Wed, 08 Jul 2009 20:00:33 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[enterprise systems]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[rcp]]></category>
		<category><![CDATA[feature]]></category>
		<category><![CDATA[packaging]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[product]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=394</guid>
		<description><![CDATA[
Abstract
Using Eclipse-based rich-clients as stand-alone applications is discussed in many 
books and 
articles. In the context of enterprise systems, the software development adopted several paradigms to improve the quality of the overall architecture. This short article describes some issues in packaging the application for using it in the context of enterprise systems.
Architectural Assumptions
Designing enterprise architectures [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 5px; float: right" title="Packaging" src="http://www.techjava.de/wp-content/uploads/packaging.jpg" alt="Packaging" width="120" height="120" /></p>
<h2>Abstract</h2>
<p>Using Eclipse-based rich-clients as stand-alone applications is discussed in many 
<a  href="http://www.amazon.com/Eclipse-Rich-Client-Platform-Applications/dp/0321334612" onclick="javascript:pageTracker._trackPageview('/external/www.amazon.com/Eclipse-Rich-Client-Platform-Applications/dp/0321334612');" >books</a> and 
<a  href="http://www.eclipse.org/articles/Article-RCP-1/tutorial1.html" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/articles/Article-RCP-1/tutorial1.html');" >articles</a>. In the context of enterprise systems, the software development adopted several paradigms to improve the quality of the overall architecture. This short article describes some issues in packaging the application for using it in the context of enterprise systems.</p>
<h2>Architectural Assumptions</h2>
<p>Designing enterprise architectures is a standard discipline for IT-consulting companies or freelancers involved in software development. Maybe one of the main characteristics of enterprise architectures is the framework-driven approach of software creation. Thus, the software has to comply certain rules and standards adopted inside the enterprise. In order to simplify such constrained development process, it is common to use an in-house software framework, which enforces the  compliance of the enterprise-internal standards and acts as glue between different technologies adopted as parts of the enterprise architecture.</p>
<p>Using such frameworks has major implications for the software development in general, and especially for the rich client development. The design issues are summarized in the next section.</p>
<h2>Usaging an Enterprise Framework</h2>
<p>The major goal of the enterprise in-house framework is to simplify the process of software systems development and to enforce standardization among the software systems. This usually includes the following aspects:</p>
<ul>
<li>Domain-specific component framework</li>
<li>Methods for master data management</li>
<li>Infrastructure services: authentication, authorization, communication, security, printing, reporting</li>
<li>Application skeletons and launchers</li>
</ul>
<p>The more unification and standardization is included inside the framework, the easier it is for a software developer to concentrate on the particular business task and the easier is the maintenance of the software system.</p>
<p>From the previous list, the most interesting part related to RCP packaging and deployment is the existence of the application skeletons and launchers. So, when launching an application, the framework libraries are loaded and executed first and pass the control to the application-specific modules. The advantage of this approach is that infrastructure services can be loaded first, which can be developed and shared among different applications.<br />
<span id="more-394"></span></p>
<h2>The required plug-ins</h2>
<p>Following the general idea of RCP packaging (see rules provided in the 
<a  href="http://www.amazon.com/Eclipse-Rich-Client-Platform-Applications/dp/0321334612" onclick="javascript:pageTracker._trackPageview('/external/www.amazon.com/Eclipse-Rich-Client-Platform-Applications/dp/0321334612');" >RCP Book</a>) and assuming one target platform (in terms of one RCP product), <strong>one top-level plug-in and should be defined</strong>. In addition, we assume at least one <strong>in-house framework plug-in</strong> and at least <strong>one application-specific plug-in</strong>. Usually there will be more of each type, but it will not change the picture much. Important at this point is the fact, that the application-specific code depends on the in-house framework code. In order to simplify the identification of the plug-ins, an example project is introduced. Let’s assume the project is called <strong>FooBar</strong>. Then, the plug-ins are called:</p>
<ul>
<li><code>de.techjava.foobar</code>: This is the functional plug-in, which contains the application-specific code.</li>
<li><code>de.techjava.framework</code>: This is the framework plug-in, which contains framework component code.</li>
<li><code>de.techjava.foobar.product.standalone</code>: This is an application and product definition plug-in which contains the definition of the product and application-agnostic code for launching the application.</li>
</ul>
<h2>Managing plug-in dependencies</h2>
<p>A difficult issue for the RCP beginners is the management of dependencies between plug-ins. Especially, the transition from the development of a single plug-in to the configuration of features and products seem to be non-trivial. In order to solve this problem, there are simple rules to follow. You can violate these rules in sophisticated scenarios, but for the beginners it is a good idea to follow them.</p>
<ol>
<li><em>Create dependencies only if you need them</em>. Each plug-in should only list plug-ins (or even better packages) it really depends on. Make sure to check it with the “<strong>Find unused dependencies</strong>” action available on the right-click in the Dependencies Tab of the Plug-in Manifest Editor.</li>
<li><em>Use versioning information. </em>Plug-ins (or better bundles, or as 
<a  href="http://www.aniszczyk.org/" onclick="javascript:pageTracker._trackPageview('/external/www.aniszczyk.org/');" >Chris</a> call them Plundles) provide version information. And it is highly advisable to include them in the import statements of the plug-ins, which simplifies the migration later on…</li>
<li><em>Don’t forget anything</em>. Every Plug-in should appear in at least in one Plug-In section of the Feature definition. Every feature should be included by another feature, higher in the hierarchy.</li>
<li><em>Keep the hierarchy flat</em>. For simple scenarios, it is sufficient to have two levels of features (top-level feature, one per-product and the underlying features include their plug-ins).</li>
<li><em>Don’t re-export dependencies</em>. Every Feature for a group of plug-ins should also include plug-ins required by the members of the group. It does not hurt if a plug-in is included several times, but it does if it is not included at all. You can optimize here if you check which plug-ins are imported by the Eclipse RCP feature (which can be considered as stable), but it does not make assumptions about features developed by third parties.</li>
</ol>
<p>Following these rules it is simple to create features for the corresponding plug-ins. Several plug-ins which belong together and are handled as a fixed piece can be grouped into Features. Usaging Features is highly advisable, and sometimes simply required (e.G. by RCP in a Java Web Start target deployment strategy). So in addition to the previously mentioned plug-in projects, at least three feature projects are required:</p>
<ul>
<li><code>de.techjava.foobar.feature</code>: This is a functional feature, which includes the <code>de.techjava.foobar</code> plug-in and all plug-ins required by it, which do not appear in the Eclipse RCP feature</li>
<li><code>de.techjava.framework.feature</code>: This is a framework feature, which includes the <code>de.techjava.framework</code> plug-in and all plug-ins required by it, which do not appear in the Eclipse RCP feature</li>
<li><code>de.techjava.foobar.feature.standalone</code> This is the top level feature, which is used for the product configuration. <strong>It includes the two features above and the Eclipse RCP feature </strong>(and optional other features used, like e.G. org.eclipse.help). <strong>It also includes exactly one plug-in</strong>, which is not included anywhere else: <code>de.techjava.foobar.standalone.product</code></li>
</ul>
<h2>The product definition plug-in</h2>
<p>The definition of the product is spread among several files. First of all the plug-in.xml of the <code>de.techjava.foobar.standalone.product</code> plug-in makes uses of two extensions:</p>
<ul>
<li><code>org.eclipse.core.runtime.applications</code></li>
<li><code>org.eclipse.core.runtime.products</code></li>
</ul>
<p>The application extension point is used to point to the Java class implementing the interface <code>org.eclipse.equinox.app.IApplication</code>. Along with this implementation, other classes needed to start up the RCP (like Advisors, etc…) are placed into the source directory of the plug-in. The product extension point is used for the association of the application with a product id. The previously-defined top-level feature includes all required features and the product definition plug-in. Finally, the <code>.product</code> file is the place, where all things are bound together: product id, application id, launcher parameters, and the one top level feature: <code>de.techjava.foobar.feature.standalone</code>. Other customization of the RCP is possible from the <code>plugin-customization.ini</code>, which is placed together with the <code>.product</code> file into the plug-in root directory.</p>
<p><img class="alignnone size-full" style="margin:10px;" title="Product configuration" src="http://www.techjava.de/wp-content/uploads/product_feature_plugin1.png" alt="Product configuration" width="385" height="499" /><br />
As a result the following configuration should be achieved after the packaging is finished. The product references the product-id and the application, defined in the plugin.xml of the plug-in project it is contained in. The product configuration is feature-based and includes one top-level feature. The top-level feature includes all other features (functional, framework, Eclipse RCP, other optional) and the one plugin, in which the product file resides.</p>
<p>The simple example provided in this articles is available as sourcecode for download (
<a  href="http://www.techjava.de/download/examples/rcp-packaging.zip" onclick="javascript:pageTracker._trackPageview('/downloads/download/examples/rcp-packaging.zip');" >rcp-packaging.zip</a>).</p>
<h2>The framework hooks</h2>
<p>In the introduced scenario, the packaging is not specific to the in-house framework. It just includes the feature containing the framework plug-in. This approach works fine, if the framework is used in a white-box manner, which means that the framework provides ready-to-use components to be plugged-in to the application (like e.G. a component for the master data management). The other type of frameworks is the so-called black-box framework, which provides components that have to be configured and integrated into the application components. In this case, the framework components can not be plugged-in using some declarative extension points, but need to be called from the application code. In the latter case, the dependencies appear between the plug-in launching the application (<code>de.techjava.foobar.standalone.product</code>) and the framework plug-ins. This requires a modification in the previous setup and the violation of one of the rules posted above. The plug-in has to define the dependency to the framework plug-in, but the top-level feature does not include the required plug-in directly, but imports the whole framework feature.</p>
<p></p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">Technorati-Tags: 
<a rel="tag"  href="http://technorati.com/tags/eclipse" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/eclipse');" >eclipse</a>,
<a rel="tag"  href="http://technorati.com/tags/java" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/java');" >java</a>,
<a rel="tag"  href="http://technorati.com/tags/rcp" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/rcp');" >rcp</a>,
<a rel="tag"  href="http://technorati.com/tags/packaging" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/packaging');" >packaging</a>,
<a rel="tag"  href="http://technorati.com/tags/plugin" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/plugin');" >plugin</a>,
<a rel="tag"  href="http://technorati.com/tags/feature" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/feature');" >feature</a>,
<a rel="tag"  href="http://technorati.com/tags/product" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/product');" >product</a>,
<a rel="tag"  href="http://technorati.com/tags/enterprise+systems" onclick="javascript:pageTracker._trackPageview('/external/technorati.com/tags/enterprise+systems');" >enterprise systems</a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2009/07/packaging-eclipse-based-rcp-for-the-use-in-enterprise-context/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Eclipse DemoCamp Galileo Hamburg</title>
		<link>http://www.techjava.de/topics/2009/05/eclipse-democamp-galileo-hamburg/</link>
		<comments>http://www.techjava.de/topics/2009/05/eclipse-democamp-galileo-hamburg/#comments</comments>
		<pubDate>Tue, 26 May 2009 23:25:06 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[cnf]]></category>
		<category><![CDATA[DemoCamp]]></category>
		<category><![CDATA[Distributed OSGI]]></category>
		<category><![CDATA[Galileo]]></category>
		<category><![CDATA[Hamburg]]></category>
		<category><![CDATA[hotel east]]></category>
		<category><![CDATA[Metamodel Evalutions]]></category>
		<category><![CDATA[ObjectTeams]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=372</guid>
		<description><![CDATA[
 As announced in a 
previous post the Eclipse Demo Camp Hamburg &#8211; Galileo Edition took place in the East Hotel in Hamburg. Organized by 
Peter and 
Martin, the event was again an interesting meeting with Eclipse-interested people in a wonderful location. Five presenters introduced Eclipse and OSGi-related topics. 
Moritz Eysholdt reported about the 
(Meta)Model [...]]]></description>
			<content:encoded><![CDATA[<p>
<a  href="http://www.flickr.com/photos/sza/3567653112/in/photostream" onclick="javascript:pageTracker._trackPageview('/external/www.flickr.com/photos/sza/3567653112/in/photostream');" ><img style="margin: 10px; float: right;" title="Moritz on DemoCamp" src="http://farm3.static.flickr.com/2272/3567653112_a2399f1a11_m.jpg" alt="" width="240" height="160" border="0" /></a> As announced in a 
<a  href="http://www.techjava.de/topics/2009/04/eclipse-democamp-2009-galileo-edition/">previous post </a>the Eclipse Demo Camp Hamburg &#8211; Galileo Edition took place in the East Hotel in Hamburg. Organized by 
<a  href="http://www.peterfriese.de/towels-models-and-bundles-eclipse-democamp-in-hamburg/" onclick="javascript:pageTracker._trackPageview('/external/www.peterfriese.de/towels-models-and-bundles-eclipse-democamp-in-hamburg/');" >Peter</a> and 
<a  href="http://www.xing.com/profile/Martin_Lippert" onclick="javascript:pageTracker._trackPageview('/external/www.xing.com/profile/Martin_Lippert');" >Martin</a>, the event was again an interesting meeting with Eclipse-interested people in a wonderful location. Five presenters introduced Eclipse and OSGi-related topics. 
<a  href="http://www.xing.com/profile/Moritz_Eysholdt" onclick="javascript:pageTracker._trackPageview('/external/www.xing.com/profile/Moritz_Eysholdt');" >Moritz Eysholdt</a> reported about the 
<a  href="http://www.eclipse.org/proposals/edapt/" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/proposals/edapt/');" >(Meta)Model Evolutions</a>, he was focusing on during his masters thesis. The interesting part of his solution are two Xtext DSLs for description of the Metamodel changes (EPatch) and model migration algorithms (MetaPatch). 
<a  href="http://www.1160pm.net/2009/05/26/xtext-at-eclipse-democamp-may-2009-in-hamburg/" onclick="javascript:pageTracker._trackPageview('/external/www.1160pm.net/2009/05/26/xtext-at-eclipse-democamp-may-2009-in-hamburg/');" >Heiko Behrens</a> gave a funny and really good introduction of Xtext and DSLs for not Xtext developers. I really like his examples: these are simple and understanding for everyone. Great job! 
<a  href="http://www.swt.tu-berlin.de/menue/ueber_uns/team/marco_mosconi/" onclick="javascript:pageTracker._trackPageview('/external/www.swt.tu-berlin.de/menue/ueber_uns/team/marco_mosconi/');" >Marco Mosconi</a> showed some 
<a  href="http://www.objectteams.org/" onclick="javascript:pageTracker._trackPageview('/external/www.objectteams.org/');" >ObjectTeams</a> (black) magic. A 
<a  href="http://www.objectteams.org/publications/democamp09.html" onclick="javascript:pageTracker._trackPageview('/external/www.objectteams.org/publications/democamp09.html');" >very intersting technology</a> using aspect-oriented programming for type-safe framework modifications. Seem to be pretty advanced technology with interesting tooling. 
<a  href="http://www.linkedin.com/pub/3/4b6/59b" onclick="javascript:pageTracker._trackPageview('/external/www.linkedin.com/pub/3/4b6/59b');" >Markus Alexander Kuppe</a> had a talk on ECF and 
<a  href="http://www.osgi.org/download/osgi-4.2-early-draft.pdf" onclick="javascript:pageTracker._trackPageview('/external/www.osgi.org/download/osgi-4.2-early-draft.pdf');" >RFC 119</a> and gave some sneak preview of the upcomming features. Finally, I had a short talk on Common Navigator Framework, basically explaining the 
<a  href="http://www.techjava.de/topics/2009/04/eclipse-common-navigator-framework/">article posted here</a> and something I documented for Galileo. Here are some visual impressions: 
<a  href="http://www.flickr.com/photos/sza/sets/72157618745344503/" onclick="javascript:pageTracker._trackPageview('/external/www.flickr.com/photos/sza/sets/72157618745344503/');" >my FlickR set</a> and  
<a  href="http://www.flickr.com/photos/peterfriese/sets/72157618835467216/" onclick="javascript:pageTracker._trackPageview('/external/www.flickr.com/photos/peterfriese/sets/72157618835467216/');" >Peter&#8217;s</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2009/05/eclipse-democamp-galileo-hamburg/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
