<?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</title>
	<atom:link href="http://www.techjava.de/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.techjava.de</link>
	<description>Journal on Java Technology</description>
	<lastBuildDate>Fri, 29 Mar 2013 23:40:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Ranked in Scala</title>
		<link>http://www.techjava.de/topics/2013/03/ranked-in-scala/</link>
		<comments>http://www.techjava.de/topics/2013/03/ranked-in-scala/#comments</comments>
		<pubDate>Fri, 29 Mar 2013 23:40:52 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[Enterprise Systems]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[case class]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[ranked]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=786</guid>
		<description><![CDATA[Just started to develop a small application in Scala running on a standard enterprise java stack. You can find more details on github: https://github.com/holisticon/ranked. Today, I&#8217;ll post some details on the persistence layer. The idea is to use Scala case classes and JPA as a persistence layer. For simple attributes it looks very cute: Stay [...]]]></description>
			<content:encoded><![CDATA[<p><img style="float: left;" title="Ranked" src="http://www.techjava.de/wp-content/uploads/google-ranking.jpg" alt="Ranked" width="170" height="170" /></p>
<p>Just started to develop a small application in Scala running on a standard enterprise java stack. You can find more details on github: 
<a  href="https://github.com/holisticon/ranked" onclick="javascript:pageTracker._trackPageview('/external/github.com/holisticon/ranked');" >https://github.com/holisticon/ranked</a>.</p>
<p>Today, I&#8217;ll post some details on the persistence layer. The idea is to use Scala case classes and JPA as a persistence layer. For simple attributes it looks very cute:</p>
<pre class="brush: scala; title: ; notranslate">
/**
 * Superclass for all persistent entities.
 */
@MappedSuperclass
abstract class PersistentEntity(
  @BeanProperty @(Column @field)(name = &quot;ID&quot;)@(Id @field)@(GeneratedValue @field)(strategy = GenerationType.AUTO) id: Long,
  @BeanProperty @(Column @field)(name = &quot;VERSION&quot;)@(Version @field) version: Long) {
  def this() = this(-1, -1);
}

/**
 * Represents a player. A player has a name, initial and current ELO ranking.
 */
@Entity
@Table(name = &quot;PLAYER&quot;)
case class Player(
  @BeanProperty @(Column @field)(name = &quot;NAME&quot;) name: String) extends PersistentEntity {

  def this() = this(null);
}

/**
 * Represents a team. A team contains of et least one player and might have a name.
 */
@Entity
@Table(name = &quot;TEAM&quot;)
case class Team(
  @BeanProperty @(Column @field)(name = &quot;NAME&quot;) name: String) extends PersistentEntity {

  def this() = this(null);
}
</pre>
<p>Stay tuned about the development progress.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2013/03/ranked-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xtext 2.0 Milestone Installation</title>
		<link>http://www.techjava.de/topics/2011/04/xtext-2-0-milestone-installation/</link>
		<comments>http://www.techjava.de/topics/2011/04/xtext-2-0-milestone-installation/#comments</comments>
		<pubDate>Tue, 19 Apr 2011 19:45:02 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Modeling]]></category>
		<category><![CDATA[dependency]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[installation]]></category>
		<category><![CDATA[mwe]]></category>
		<category><![CDATA[p2]]></category>
		<category><![CDATA[xtend]]></category>
		<category><![CDATA[xtext]]></category>
		<category><![CDATA[xtext 2.0]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=749</guid>
		<description><![CDATA[If you are interested in Xtext and its new features introduced in the upcomming version 2.0 you might want to install and try them out. Since it will be officially realeased together with Eclipse Indigo, you have to execute some manual steps. In order to be able to install the new feature, you will require [...]]]></description>
			<content:encoded><![CDATA[<p>If you are interested in Xtext and its new features introduced in the upcomming version 2.0 you might want to install and try them out. Since it will be officially realeased together with Eclipse Indigo, you have to execute some manual steps. In order to be able to install the new feature, you will require to enter two additional update sites into you update manager and download the update site containing xtext itself. The following steps worked for me:</p>
<ul>
<li>Download 
<a  href="http://www.eclipse.org/downloads/packages/eclipse-classic-362/heliossr2" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/downloads/packages/eclipse-classic-362/heliossr2');" >Eclipse 3.6.1 Classic</a></li>
<li>Add the tow following Update Sites to the Update Manager: <br />
Xpand: 
<a  href="http://download.eclipse.org/modeling/m2t/xpand/updates/nightly/" onclick="javascript:pageTracker._trackPageview('/external/download.eclipse.org/modeling/m2t/xpand/updates/nightly/');" >http://download.eclipse.org/modeling/m2t/xpand/updates/nightly/</a><br />
MWE:   
<a  href="http://download.eclipse.org/modeling/emft/mwe/updates/nightly/" onclick="javascript:pageTracker._trackPageview('/external/download.eclipse.org/modeling/emft/mwe/updates/nightly/');" > http://download.eclipse.org/modeling/emft/mwe/updates/nightly/</a>
  </li>
<li>Download the TMF 2.0 M6 Update Site from 
<a  href="http://www.eclipse.org/modeling/tmf/downloads/" onclick="javascript:pageTracker._trackPageview('/external/www.eclipse.org/modeling/tmf/downloads/');" >Eclipse TMF Site</a> and add it as a local update site</li>
<li>Install all TMF Features from the archive update site</li>
<li>Restart Eclipse and Enjoy Xtext 2.0!</li>
</ul>
<p>Thanks to Dennis Huebner 
<a  href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=329719" onclick="javascript:pageTracker._trackPageview('/external/bugs.eclipse.org/bugs/show_bug.cgi');" >for the hints&#8230;</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2011/04/xtext-2-0-milestone-installation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Validating JFace Databinding with JSR-303</title>
		<link>http://www.techjava.de/topics/2011/02/validating-jface-databinding-jsr-303/</link>
		<comments>http://www.techjava.de/topics/2011/02/validating-jface-databinding-jsr-303/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 09:22:39 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[constraint]]></category>
		<category><![CDATA[databinding]]></category>
		<category><![CDATA[IValidator]]></category>
		<category><![CDATA[jface]]></category>
		<category><![CDATA[jsr 303]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[validator]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=726</guid>
		<description><![CDATA[JFace Databinding enables an easy binding between values inside of data models and SWT/JFace widgets. No more boring listeners to implement &#8211; just create observables and connect them using the data binding context. There are several brilliant articles written about it. My favorites are those from Ralf Ebert and Lars Vogel. One of the interesting [...]]]></description>
			<content:encoded><![CDATA[<p><img style="float: right; margin: 10px;" title="binding" src="http://www.techjava.de/wp-content/uploads/binding-150x150.jpg" alt="" width="150" height="150" /><br />
JFace Databinding enables an easy binding between values inside of data models and SWT/JFace widgets. No more boring listeners to implement &#8211; just create observables and connect them using the data binding context. There are several brilliant articles written about it. My favorites are those from 
<a  href="http://www.ralfebert.de/rcpbuch/jface_data_binding/" onclick="javascript:pageTracker._trackPageview('/external/www.ralfebert.de/rcpbuch/jface_data_binding/');" >Ralf Ebert</a> and 
<a  href="http://www.vogella.de/articles/EclipseDataBinding/article.html" onclick="javascript:pageTracker._trackPageview('/external/www.vogella.de/articles/EclipseDataBinding/article.html');" >Lars Vogel</a>.</p>
<p>One of the interesting aspects of databinding is data validation. The update strategies, responsible for propagation of changes in models or in widgets can be supplied with validators, making sure that the data changes are legal. In the same time the 
<a  href="http://jcp.org/en/jsr/detail?id=303" onclick="javascript:pageTracker._trackPageview('/external/jcp.org/en/jsr/detail');" >JSR-303 Bean Validation</a> specification focuses on a modern standardized way of data validation. In this post, I combine these subjects and use JSR-303 in JFace Databinding Validators.</p>
<p>One of the core insights of the JSR-303 is the idea of annotation of data validation constraints on data itself. It is indeed a good observation, that validation code strongly relies on the data structure and semantics. To follow this idea consequently, the application developer should care of validation during implementation of business logic as less as possible. A much better idea is to encapsulate the entire validation into domain-specific types. Let me demonstrate it by example, imagine the following class:</p>
<pre class="brush: java; title: ; notranslate">
public class Customer {
  private String name;
  private String address;
  private String zip;
  private String city;
}
</pre>
<p>This is perfectly reasonable, but now consider not only the data storage/transport aspects, but also the validation aspects. A standard approach would be to use the following validator logic, in the databinding:</p>
<pre class="brush: java; highlight: [5,6,7,8,9,10,11,12,13,14,20,21,22,23,24,25,26,27,28,29]; title: ; notranslate">
public class CustomerComposite {
[...]
  public void bindValues(Customer model, DataBindingContext dbc) {
    UpdateValueStrategy m2t = new UpdateValueStrategy();
    m2t.setAfterGetValidator(new IValidator() {
      @Override
      public IStatus validate(Object value) {
        String name = (String) value;
        if (name == null || Helper.isRegex(name, &quot;[A-Za-z -]*&quot;)) {
          return ValidationStatus.error(&quot;Wrong name&quot;);
        }
          return ValidationStatus.ok();
        }
      });
    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(namefield),
      BeanProperties.value(Customer.class, &quot;name&quot;).observe(model),
      new UpdateValueStrategy(), m2t);

    m2t = new UpdateValueStrategy();
    m2t.setAfterGetValidator(new IValidator() {
      @Override
      public IStatus validate(Object value) {
        String zipCode = (String) value;
        if (zipCode == null || zipCode.length() &gt; 5 || zipCode.length() &lt; 5 || Helper.isRegex(zipCode, &quot;[0-9]*&quot;)) {
          return ValidationStatus.error(&quot;Wrong zip code&quot;);
        }
          return ValidationStatus.ok();
        }
      });
    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(zipfield),
      BeanProperties.value(Customer.class, &quot;zip&quot;).observe(model),
      new UpdateValueStrategy(), m2t);
  [...]
  }
</pre>
<p>Pretty much code, and rememeber that JFace Databinding code like this can not be reused in other parts of the application. Let&#8217;s put the validation logic on the data declaration in a way how JSR-303 proposes to do this:</p>
<pre class="brush: java; title: ; notranslate">
public class Customer {
  @NotNull
  @Pattern(regexp = &quot;[A-Za-z -]*&quot;)
  private String name;
  private String addressLine;
  @Size(min=1, max=5)
  @Pattern(regexp = &quot;[0-9]*&quot;)
  private String zip;
  @NotNull
  @Pattern(regexp = &quot;[A-Za-z -]*&quot;)
  private String city;
}
</pre>
<p>As a next step, let us develop an update strategy factory which create update strategies with embedded Validator for JSR-303 Bean Validation constaints.</p>
<pre class="brush: java; title: ; notranslate">
public class BeanValidator implements IValidator {
  private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

  @Override
  public IStatus validate(Object value) {
    Set&lt;ConstraintViolation&lt;Object&gt;&gt; violations = factory.getValidator().validate(value,
      new Class&lt;?&gt;[] { Default.class });
    if (violations.size() &gt; 0) {
      List&lt;IStatus&gt; statusList = new ArrayList&lt;IStatus&gt;();
      for (ConstraintViolation&lt;Object&gt; cv : violations) {
        statusList.add(ValidationStatus.error(cv.getMessage()));
      }
      return new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR,
        statusList.toArray(new IStatus[statusList.size()]), &quot;Validation errors&quot;, null);
    }
    return ValidationStatus.ok();
  }
}

public class StrategyFactory {
 public static UpdateValueStrategy getStrategy() {
   UpdateValueStrategy strategy = new UpdateValueStrategy();
   strategy.setAfterConvertValidator(new BeanValidator());
   return strategy;
 }
}
</pre>
<p>Using the <code>StrategyFactory</code>, the validation code inside of the composite becomes trivial:</p>
<pre class="brush: java; title: ; notranslate">
public class CustomerComposite {
[...]
  public void bindValues(Customer model, DataBindingContext dbc) {
    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(namefield),
      BeanProperties.value(Customer.class, &quot;name&quot;).observe(model),
      new UpdateValueStrategy(), StrategyFactory.getStrategy());

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(zipfield),
     BeanProperties.value(Customer.class, &quot;zip&quot;).observe(model),
     new UpdateValueStrategy(), StrategyFactory.getStrategy());
 [...]
}
</pre>
<p>An important property of the introduced validation approach is the fact, that it can be reused in other application layers (e.G. in service layer, or in data access layer). In other words you can use the same validation logic across the entire application and just remain valid&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2011/02/validating-jface-databinding-jsr-303/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Guicy Mocks in Eclipse RCP</title>
		<link>http://www.techjava.de/topics/2010/11/guicy-mocks/</link>
		<comments>http://www.techjava.de/topics/2010/11/guicy-mocks/#comments</comments>
		<pubDate>Wed, 24 Nov 2010 23:42:52 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Enterprise Systems]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[bundle]]></category>
		<category><![CDATA[business delegate]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[eclipse rcp]]></category>
		<category><![CDATA[extension point]]></category>
		<category><![CDATA[google guice]]></category>
		<category><![CDATA[java enterprise]]></category>
		<category><![CDATA[Modeling]]></category>
		<category><![CDATA[plug-in]]></category>
		<category><![CDATA[service locator]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=699</guid>
		<description><![CDATA[Abstract Development of Eclipse RCP as a rich client of the multi-tier Java Enterprise application becomes an an interesting alternative to other frontend technologies. An important aspect is the ability to develop and test the frontend independent from the backend. In this article, an approach for testing and de-coupling of server and client development in [...]]]></description>
			<content:encoded><![CDATA[<p>
<a  href="http://www.techjava.de/wp-content/uploads/juice.gif" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/juice.gif');" ><img style="float: right;" title="Google Guice" src="http://www.techjava.de/wp-content/uploads/juice.gif" alt="Google Guice" width="200" height="214" /></a></p>
<h2>Abstract</h2>
<p>Development of Eclipse RCP as a rich client of the multi-tier Java Enterprise application becomes an an interesting alternative to other frontend technologies. An important aspect is the ability to develop and test the frontend independent from the backend. In this article, an approach for testing and de-coupling of server and client development in Eclipse RCP is introduced.</p>
<h2>Business Delegate, Service Locator and Dependency Injection</h2>
<p>In a Java multi-tier application, the business logic is implemented in form of server-hosted components (EJB, Spring Beans, OSGi Services, etc&#8230;). In this example, the EJB Backend is used, but it can be easily replaced with other technologies mentioned previously. A rich client is connected to the server using some remoting technology and contains a local storage for the client-specific state, which allows to build more complex and reactive applications. A common approach to hide the aspects of remote invocations on the client side is the use of 
<a  href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html" onclick="javascript:pageTracker._trackPageview('/external/java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html');" >Business Delegate</a> enterprise design pattern. My favorite way of implementing it is to define the technology-independent business interface (POJI = Plain Old Java Interface) and implement it on the server side by the server beans and on the client side by the business delegates. This article uses the following business interface as example:</p>
<pre class="brush: java; title: ; notranslate">
public interface MyBusinessService extends BaseBusinessService {

	/**
	 * Full qualified name of the interface (used for Binding).
	 */
	String IF_FQN = &quot;....MyBusinessService&quot;;

	/**
	 * Does something on server.
	 *
	 * @param parameter Parameter of invocation.
	 * @return Result of execution.
	 */
	List&lt;OperationResultDto&gt; doSomeStuff(ParameterDto parameter);
}
</pre>
<p>The delegates make use of the 
<a  href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html" onclick="javascript:pageTracker._trackPageview('/external/java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html');" >Service Locator</a> design pattern. Here is an example, how the implementation of the Base Facade can look like, which is a superclass of all business delegates:</p>
<pre class="brush: java; title: ; notranslate">
public abstract class BaseFacade {
...
	/**
	 * Delegates a call to a stateless session bean on the server.
	 *
	 * @param &lt;T&gt; type business interface
	 * @param iterfaze business interface
	 * @param jndi binding on the server
	 * @return result of invocation
	 */
	public static &lt;T&gt; T delegate(Class&lt;T&gt; iterfaze, String jndi) {
		return Activator.getDefault().getServiceLocator().getStateless(iterfaze, jndi);
	}

	/** ... */
	public static void debug(String message) {...}
}
</pre>
<p>The <code>ServiceLocator.getStateless()</code> method is hiding the lookup of the remote EJB. Using the BaseFacade, the business delegate looks as following:</p>
<pre class="brush: java; title: ; notranslate">
public class MyBusinessServiceFacade extends BaseFacade implements MyBusinessService {

	public List&lt;OperationResultDto&gt; doSomeStuff(ParameterDto parameter) {
		debug(&quot;entering doSomeStuff(ParameterDto)&quot;);
		final List&lt;OperationResultDto&gt; result = delegate(MyBusinessService.class, MyBusinessService.IF_FQN)
				.doSomeStuff(parameter);
		debug(&quot;leaving doSomeStuff(ParameterDto)&quot;);
		return result;
	}

}
</pre>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">This setup results in a following architecture:</span></p>
<p style="text-align: center;">
<a  href="http://www.techjava.de/wp-content/uploads/architecture.png" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/architecture.png');" ><img class="size-full wp-image-713 aligncenter" src="http://www.techjava.de/wp-content/uploads/architecture.png" alt="Architecture" width="420" height="210" /></a></p>
<h2>Business Delegate Boilerplate</h2>
<p>The setup looks good in theory, but in fact it is pretty boring to program on the client side. You can reduce the effort of creating business delegates (in fact I use MDSD techniques and Xtext to generate it), but in every place a service is required,  the business delegate is instantiated directly. The approach works, but it just not nice, because you reference the implementation directly.</p>
<p>A common approach to avoid writing the code of direct instantiation is the usage of Dependency Injection frameworks. A very popular one is Google Guice, which is used in this article. The essential idea of Google Guice is to configure the binding between the dependency and its resolution and use Google Guice as a kind of factory to create instances and inject dependencies in it. For the creation of the binding, Guice offers a class <code>AbstractModule</code> to subclass from.</p>
<pre class="brush: java; title: ; notranslate">
public class ServiceFacadeModule extends AbstractModule {

	/**
	 * @see com.google.inject.AbstractModule#configure()
	 */
	@Override
	protected void configure() {
		bind(MyBusinessService.class).to(MyBusinessServiceFacade.class);
	}
}
...
public class InjectorHolder {
...
	private Injector injector;

	public static void configureInjector(AbstractModule module) {
		InjectorHolder.getInstance().setInjector(Guice.createInjector(module));
	}

	/**
	 * Creates an instance of a class.
	 *
	 * @param &lt;T&gt; type of the class
	 * @param clazz type to create
	 * @return a instance with injected dependencies
	 */
	public static &lt;T&gt; T get(Class&lt;T&gt; clazz) {
		return getInstance().getInjector().getInstance(clazz);
	}
...
}
</pre>
<p>In order to hide references to Guice classes in client code, the DI can be encapsulated inside of a <code>InjectorHolder</code>, which acts as factory for instances with service references:</p>
<pre class="brush: java; title: ; notranslate">
/**
 * Class with a reference.
 */
public class DataSource {

	/**
	 * Reference to the service.
	 */
	private MyBusinessService myBusinessService;

	@Inject
	public void setMyBusinessService(MyBusinessService myBusinessService) {
		this.myBusinessService = myBusinessService;
	}
}
/**
 * Client which requires the data source with injected references.
 */
public class MyView {

	/**
	 * Let Google Guice create the instance and inject dependencies.
	 */
	private DataSource source = InjectorHolder.get(DataSource.class);
}
</pre>
<p>Please note, that the data source is using setter-injection for the service implementations and the InjectorHolder as a factory to create an instance of data source with injected reference.</p>
<h3>Packaging Guice</h3>
<p>After this short introduction of Guice, it is time to package this 
<a  href="http://vannevarvision.wordpress.com/2007/03/08/making-external-libraries-available-as-an-eclipse-plug-in/" onclick="javascript:pageTracker._trackPageview('/external/vannevarvision.wordpress.com/2007/03/08/making-external-libraries-available-as-an-eclipse-plug-in/');" >3rd-party library into the Eclipse RCP client</a>. In fact it is all about putting the JARs (guice-2.0.jar, aopalliance-1.0.jar) into some folder inside of the client plug-in and modifying the MANIFEST.MF so that the JARs are on the bundle class-path and the packages are listed as &#8220;exported&#8221;.</p>
<h3>What about mock?</h3>
<p>After the client has the ability to use business delegates it can access the business functionality of the server. In fact this requires that the server is already implemented. In order to decouple the client from the server development, 
<a  href="http://en.wikipedia.org/wiki/Mock_object" onclick="javascript:pageTracker._trackPageview('/external/en.wikipedia.org/wiki/Mock_object');" >mocks</a> can be used. Mocks are popular in context of Unit tests, but can be used to simulate behavior of server implementation as well. Since mocks should not be delivered into production it is a good idea to put them into a separate mock plug-in, included into the special mock feature. The mock plug-in should export its packages. These should be imported by the main plug-in, instead of defining of a dependency on the mock plug-in directly. The mock feature is included in the product / top-level feature as an optional feature. This specific configuration allows the main plug-in to instantiate classes from the mock plug-in, if this is delivered, but doesn&#8217;t produce errors if the mock plug-in is not included into release.</p>
<p>Since the business delegate implementes the business interface, its mock should also do so:</p>
<pre class="brush: java; title: ; notranslate">
public class MyBusinessServiceMock implements MyBusinessService {

	public List&lt;OperationResultDto&gt; doSomeStuff(ParameterDto parameter) {
		debug(&quot;entering doSomeStuff(ParameterDto)&quot;);
		final List&lt;OperationResultDto&gt; result = new ArrayList&lt;OperationResultDto&gt;();
		result.add(new OperationResult(parameter.getValue()));
		debug(&quot;leaving doSomeStuff(ParameterDto)&quot;);
		return result;
	}
...
}
</pre>
<p>Since the mocks should also be injected by Guice, we define the binding module as well.</p>
<pre class="brush: java; title: ; notranslate">
public class ServiceMockModule extends AbstractModule {
	protected void configure() {
		bind(MyBusinessService.class).to(MyBusinessServiceMock.class);
	}
}
</pre>
<p>Finally, we got two implementations and two Guice&#8217;s AbstractModule implementation binding them. The last missing piece is the dynamic configuration which allows to switch between them easily. For this purpose we use the extension-point mechanism of Eclipse and define the following extension point (all documentation elements are removed for readability):</p>
<pre class="brush: xml; title: ; notranslate">
&lt;schema targetNamespace=&quot;...&quot; xmlns=&quot;...&quot;&gt;
   &lt;element name=&quot;extension&quot;&gt;
      ...
      &lt;complexType&gt;
         &lt;sequence&gt;&lt;element ref=&quot;moduleConfiguration&quot; minOccurs=&quot;1&quot; maxOccurs=&quot;unbounded&quot;/&gt;&lt;/sequence&gt;
         &lt;attribute name=&quot;point&quot; type=&quot;string&quot; use=&quot;required&quot;&gt;&lt;/attribute&gt;
         &lt;attribute name=&quot;id&quot; type=&quot;string&quot;&gt;&lt;/attribute&gt;
         &lt;attribute name=&quot;name&quot; type=&quot;string&quot;&gt;&lt;/attribute&gt;
      &lt;/complexType&gt;
   &lt;/element&gt;
   &lt;element name=&quot;moduleConfiguration&quot;&gt;
      &lt;complexType&gt;
         &lt;attribute name=&quot;moduleClassname&quot; type=&quot;string&quot; use=&quot;required&quot;&gt;
            &lt;annotation&gt;
               &lt;appInfo&gt;&lt;meta.attribute kind=&quot;java&quot; basedOn=&quot;com.google.inject.AbstractModule:&quot;/&gt;&lt;/appInfo&gt;
            &lt;/annotation&gt;
         &lt;/attribute&gt;
         &lt;attribute name=&quot;priority&quot; type=&quot;string&quot; use=&quot;required&quot;&gt;&lt;/attribute&gt;
      &lt;/complexType&gt;
   &lt;/element&gt;
&lt;/schema&gt;
</pre>
<p>Using this definition, the plug-in can extend the main plug-in, by providing <code>moduleConfigurations</code>, which is a class name of the class extending the Guice AbstractModule and the priority. Using the following utility class, the module configurations can be read:</p>
<pre class="brush: java; title: ; notranslate">
public class PluginUtility {

	public static TreeMap&lt;Integer, AbstractModule&gt; getModuleConfigurations() throws CoreException {
		final TreeMap&lt;Integer, AbstractModule&gt; moduleConfigurations = new TreeMap&lt;Integer, AbstractModule&gt;();
		IExtension[] moduleConfigurationExtensions = Platform.getExtensionRegistry().getExtensionPoint(&quot;...id...&quot;).getExtensions();
		for (IExtension moduleConfiguration : moduleConfigurationExtensions) {
			for (IConfigurationElement configElement : moduleConfiguration.getConfigurationElements()) {

				AbstractModule module = (AbstractModule) configElement.createExecutableExtension(&quot;moduleClassname&quot;);
				String priorityAsString = configElement.getAttribute(&quot;priority&quot;);
				int priority = 0;
				try {
					priority = Integer.parseInt(priorityAsString);
				} catch (NumberFormatException e) {
					throw new CoreException(...);
				}

				moduleConfigurations.put(Integer.valueOf(priority), module);
			}
		}
		return moduleConfigurations;
	}
}
</pre>
<p>Using this utility, the main plug-in can read in available AbstractModules available in runtime and configure Dependency Injection. Before the usage of InjectorHolder this should be configured. We use higher priority (bigger number) as a reason to select the AbstractModule.</p>
<pre class="brush: java; title: ; notranslate">
public class InjectorHolder {
...
	private Injector injector;

	public static InjectorHolder getInstance() {
		if (instance == null) {
			instance = new InjectroHolder();
			injector = Guice.createInjector(PluginUtility.getModuleConfigurations().lastEntry().getValue());
		}
		return instance;
	}
...
}
</pre>
<p>Finally, the two binding modules should use the extension-point. The plug-in containing the business delegates should define the module configuration with a &#8220;standard&#8221; priority:</p>
<pre class="brush: xml; title: ; notranslate">
   &lt;extension
         point=&quot;....ModuleConfiguration&quot; name=&quot;ModuleConfiguration&quot;&gt;
      &lt;moduleConfiguration
            moduleClassname=&quot;....ServiceFacadeModule&quot;
            priority=&quot;1&quot;&gt;
      &lt;/moduleConfiguration&gt;
   &lt;/extension&gt;
</pre>
<p>The mock plugin should define a higher priority, which would win against the business delegate, if included into release.</p>
<pre class="brush: xml; title: ; notranslate">
   &lt;extension
         point=&quot;....ModuleConfiguration&quot; name=&quot;ModuleConfiguration&quot;&gt;
      &lt;moduleConfiguration
            moduleClassname=&quot;....ServiceMockModule&quot;
            priority=&quot;10&quot;&gt;
      &lt;/moduleConfiguration&gt;
   &lt;/extension&gt;
</pre>
<h3>Summary</h3>
<p>In this article, an implementation approach for business delegates and service locator patterns is shown. Usage of Google Guice Dependency Injection framework allows for a flexible resolution of dependency in client code. Since it doesn&#8217;t support multiple binding configurations, we introduce a self-defined extension point, which allows to register different DI-Configuration modules and assign different priorities to them. In addition, we use the ability of Eclipse to define and use optional feature, to foster runtime-based configuration. Using different &#8220;Run Configurations&#8221;, you can start the RCP client with different implementation of your business services. If the mock plug-in is included, its higher priority will win against the business delegates. Therefore the development of the client can be performed using mock objects instead of real business delegates without any additional configuration.</p>
<p>Have Fun&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/11/guicy-mocks/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<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[Modeling]]></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. [...]]]></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; title: ; notranslate">
...
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; title: ; notranslate">
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; title: ; notranslate">
   &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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
  &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; title: ; notranslate">
...
	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; title: ; notranslate">
/*
 * 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]; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
         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: Having this structure, you [...]]]></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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
  ...
  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 [...]]]></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; title: ; notranslate">
&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; title: ; notranslate">
&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; title: ; notranslate">
@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; title: ; notranslate">
...
 &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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
@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; title: ; notranslate">
 &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; title: ; notranslate">
&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; title: ; notranslate">
&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; title: ; notranslate">
@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>6</slash:comments>
		</item>
		<item>
		<title>Launching Eclipse RCP via Java Web Start</title>
		<link>http://www.techjava.de/topics/2010/02/launching-rcp-via-jws/</link>
		<comments>http://www.techjava.de/topics/2010/02/launching-rcp-via-jws/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 16:32:15 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Enterprise Systems]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Application id not found]]></category>
		<category><![CDATA[bundle]]></category>
		<category><![CDATA[delivery]]></category>
		<category><![CDATA[export]]></category>
		<category><![CDATA[Java Web Start]]></category>
		<category><![CDATA[JNLP]]></category>
		<category><![CDATA[JWS]]></category>
		<category><![CDATA[osgi]]></category>
		<category><![CDATA[packaging]]></category>
		<category><![CDATA[rcp]]></category>

		<guid isPermaLink="false">http://www.techjava.de/?p=582</guid>
		<description><![CDATA[The Eclipse RCP became a prominent platform for building client software. One of the delivery mechanisms supported by Eclipse RCP is Sun&#8217;s Java Web Start (JWS). Since Galileo Edition some changes has been introduced in the platform. This article provides some hints for creation of the RCP delivered by Java Web Start. Packaging In order [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.techjava.de/wp-content/uploads/eclipse-rcp.png" alt="" title="eclipse-rcp" width="237" height="237" style="float:right; margin:5px" />The Eclipse RCP became a prominent platform for building client software. One of the delivery mechanisms supported by Eclipse RCP is Sun&#8217;s Java Web Start (JWS). Since Galileo Edition some changes has been introduced in the platform. This article provides some hints for creation of the RCP delivered by Java Web Start.</p>
<h2>Packaging</h2>
<p>In order to package the RCP I suggest to use feature-based products as described in 
<a  href="http://www.techjava.de/topics/2009/07/packaging-eclipse-based-rcp-for-the-use-in-enterprise-context/">a previous article</a>. Following it, you should have a top-level plug-in (also refered as product-defining plug-in) and top-level feature, which is called &#8220;wrap&#8221;-feature in the context of the Java Web Start. </p>
<h3>Exporting the product</h3>
<p>Before you start with Java Web Start (JWS), export the product and make sure it starts as a standalone application. In doing so, you have to ensure that your references to the plug-ins are correct. One of the way of doing it is to hit the Validate button in the top left of the product editor. <img src="http://www.techjava.de/wp-content/uploads/validate-product.png" alt="" title="validate-product" width="196" height="79" style="float:right; margin:5px;" /> If the validation is successful, try to export the product. The PDE builder will run and create a distribution. The errors of the compiler/builder/assembler, if any, are reported to files zipped to the <code>logs.zip</code> file in the distribution directory. <span id="more-582"></span> A prominent error is</p>
<pre class="brush: plain; light: true; title: ; notranslate">
Compliance level '1.3' is incompatible with source level '1.6'. A compliance level '1.6' or better is required.
</pre>
<p>Which actually means that the plug-in classes has not been compiled at all. In order to avoid this error make sure to set the following properties in the <code>build.properties</code> file of the corresponding plug-in:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
javacSource=1.3
javacTarget=1.3
</pre>
<h3>Exporting the wrap-feature</h3>
<p>After a successful export of the product, just export the top-level feature (the wrap-feature). Make sure to provide the signing information, since JWS requires all resources to be signed. If you are aiming to deliver for different platforms, make sure to define a target platform (<strong>Window > Preferences > Plug-in Development > Target Platform</strong>) which contains a Delta Pack. A Delta Pack is a set of plug-ins which can be downloaded separately on the 
<a  href="http://ww.eclipse.org/downloads/" onclick="javascript:pageTracker._trackPageview('/external/ww.eclipse.org/downloads/');" >Eclipse Homepage</a>. Also, don&#8217;t forget to switch over to the Java Web Start tab of the Feature Export Wizard, activate the checkbox &#8220;Create JNLP manifest for the JAR archives&#8221; and specify the site URL where the resulting JNLP will be located. Make sure all your features has the provider attribute set, since it is used as the &#8220;vendor&#8221; inside of the JNLP file, which is a mandatory attribute.</p>
<h3>Creating the main JNLP</h3>
<p>The PDE build will run and create a distribution in the specified directory. Along with the exported JARs in features and plug-ins, the packaging script will generate the JNLP descriptors for every feature. Still, the main JNLP file required for launching the application is missing and has to be provided separately. Here is, how it looks like:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;jnlp spec=&quot;1.0+&quot; codebase=&quot;http://localhost/app/&quot; href=&quot;app.jnlp&quot;&gt;
    &lt;information&gt;
        &lt;title&gt;application titel&lt;/title&gt;
        &lt;vendor&gt;provider&lt;/vendor&gt;
        &lt;offline-allowed/&gt;
    &lt;/information&gt;

    &lt;security&gt;
        &lt;all-permissions/&gt;
    &lt;/security&gt;

    &lt;application-desc main-class=&quot;org.eclipse.equinox.launcher.WebStartMain&quot;&gt;
	&lt;argument&gt;-product&lt;/argument&gt;
	&lt;argument&gt;de.techjava.app.webstart.productid&lt;/argument&gt;
	&lt;argument&gt;-application&lt;/argument&gt;
	&lt;argument&gt;de.techjava.app.webstart.appid&lt;/argument&gt;
    &lt;/application-desc&gt;

    &lt;resources&gt;
        &lt;j2se version=&quot;1.4+&quot; ax-heap-size=&quot;128m&quot; /&gt;
	&lt;jar href=&quot;plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar&quot;/&gt;
	&lt;extension name=&quot;wrap feature&quot; href=&quot;features/wrap_feature_1.0.0.jnlp&quot; /&gt;
	&lt;!-- OSGI setup --&gt;
        &lt;property name=&quot;osgi.instance.area&quot; value=&quot;@user.home/app&quot;/&gt;
        &lt;property name=&quot;osgi.configuration.area&quot; value=&quot;@user.home/app&quot;/&gt;
    &lt;/resources&gt;
&lt;/jnlp&gt;
</pre>
<p>Important is to specify both, the <strong>product id</strong> and the <strong>applciation id</strong>, otherwise you will see the &#8220;Application id not found&#8221; exception. Of course you can specify 
<a  href="http://help.eclipse.org/galileo/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html" onclick="javascript:pageTracker._trackPageview('/external/help.eclipse.org/galileo/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html');" >additional options</a> as command-line arguments of the launcher itself. I found it useful to be able to let the OSGi running and then connect to it and query for loaded bundles. You can do it by adding the following arguments:</p>
<pre class="brush: xml; title: ; notranslate">
	&lt;argument&gt;-console&lt;/argument&gt;
	&lt;argument&gt;1234&lt;/argument&gt;
	&lt;argument&gt;-noExit&lt;/argument&gt;
</pre>
<p>This will allow to connect via telnet with running OSGi, even after the application finishes.<br />
This is basically it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techjava.de/topics/2010/02/launching-rcp-via-jws/feed/</wfw:commentRss>
		<slash:comments>4</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[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[jboss]]></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 [...]]]></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; title: ; notranslate">
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; title: ; notranslate">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; title: ; notranslate">
/**
 * 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; title: ; notranslate">
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; title: ; notranslate">
@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; title: ; notranslate">
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; title: ; notranslate">
@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; title: ; notranslate">
...
@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; title: ; notranslate">
...
	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; title: ; notranslate">
@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; title: ; toolbar: true; notranslate">
&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; title: ; notranslate">
@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]; title: ; notranslate">
...
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 Schlömmer, 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 Schlömmer and Jo Ehm and Carsten Sahling}, <br />
 &nbsp; title =	{EJB 3 professionell. Grundlagen- und Expertenwissen zu Enterprise JavaBeans 3 für 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 Schlömmer, 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>
	</channel>
</rss>
