waffel’s Weblog

März 28, 2011

Run eclipse RCP application via WebStart

Filed under: java — Thomas Wabner @ 7:07 pm
Tags: , , , , , , , ,

The last days I need to create a small prototype to demonstrate how to start a eclipse RCP application via webstart. After reading many tutorials and tipps I have now a working setup which I want to share with you.

The main tutorial which I followed was the eclipse help itself. But there are some hidden points which are important to respect.

Lets start:

You need 4 Projects:

  • Eclipse RCP plugin
  • Feature for the plugin
  • Wrapping feature for webstart
  • entry or start JNLP file

At least you need an webserver which can deliver your files.

Create eclipse RCP plugin with a example RCP application provided by eclipse:

This plugin will provide the RCP application with a small demo UI. In a larger project you will normally have more than one plugin. But for demonstration proposed this would be enough.

  1. From the eclipse main menu, go to File > New > Project… (the New Project wizard opens), select Plugin-in Development > Plug-in Project
  2. Press Next > enter „org.test.webstart.demo.plugin“ as Project name
  3. Press Next > change the Version to „0.1.0“
  4. Press Next > select RCP application with an view > press Finish

At this point you should have a small RCP „application“ which can started from eclipse. Select the project root > select Run from the menu > select Run As > Eclipse Application. Now you should see the demo UI.

Next we need a Eclipse feature project which uses the plugin.

Create eclipse feature which contains the plugin and a reference to the eclipse rcp feature:

We need a feature which depends on the demo plugin and on the eclipse rcp feature. The dependency to the eclipse rcp feature is required to export later all required plugins and features for webstart, to run the complete rcp application.

  1. In the eclipse main menu go to File > New > Project… (the New Project Dialog opens), select Plug-in Development > Feature Project
  2. Press Next > enter „org.test.webstart.demo.feature“ as project name > change the Version to „0.1.0“
  3. Press Next > select „org.test.webstart.demo.plugin“ from plug-ins list > press Finish

The feature editor opens. Now you need to add the eclipse rcp feature as included feature. To do so select Included Feature tab in the feature editor > add „org.eclipse.rcp“ as feature. Save and close the feature editor.

This feature contains now all you need to run your application as a full featured eclipse RCP application. Now we need another wrapping feature to get the Webstart launcher on board.

Create wrapping feature for webstart

This feature will be used to export all required JAR files with the eclipse java webstart exporter into a local filesystem.

  1. From the eclipse main menu select File > New > Project… (the New Project Dialog opens), select Plug-in Development > Feature Project
  2. Press Next > enter „org.test.webstart.demo.wrapperfeature“ as project name > change the Version to „0.1.0“
  3. Press Finish. The feature editor opens.

Now we need a dependency to the equinox launcher plugin and include our own feature.

  1. In the feature editor select the Plug-ins tab > add „org.eclipse.equinox.launcher“.
  2. Select the Included Feature tab > add „org.test.webstart.demo.feature“ > save the editor.
  3. From the project root select the eclipse main menu > select File > Export… > select Deployable Features (the export wizard opens)
  4. Press Select All
  5. In the Desitination tab select a directory where you want to export the JAR and JNLP files.
  6. In the Options tab only select Package as individual JAR archives. If you select Generate metadata repository nothing will be exported!
  7. In the JAR Signing tab fill in all fields with the information from your keystore. If you do not have an keystore you can create your own by follow these instructions.
  8. In the Java Webstart tab select Create JNLP manifests for the JAR archives > add the Site URL like http://localhost:8080/demoui-webstart > set 1.5+ for the JRE version > pess Finish

Now you should have in your destination folder a folder structure like
– features
– plugins

Under the features folder you should have some JNLP files. Because of an error in the eclipse exporter you need to adjust the JNLP files. For example the JNLP file of the feature looks like:

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/demoui-webstart">
	<information>
		<title>Demo_rcp_feature</title>
		<offline-allowed/>
	</information>
	<security>
		<all-permissions/>
	</security>
	<component-desc/>
	<resources>
		<j2se version="1.5+" />
	</resources>
	<resources>
		<extension href="features/org.eclipse.rcp_3.5.2.R35x_v20100119-9SA0FxwFnoCU5XxWItFdXXb27BA6.jnlp" />
		<jar href="plugins/demo_rcp_0.1.0.201103241351.jar"/>
	</resources>
</jnlp

You need to change the tag and add the required vendor information. The resulting information tag should look like

	<information>
		<title>Demo_rcp_feature</title>	
		<vendor>Me</vendor>
		<offline-allowed/>
	</information

You need to do this for all JNLP files in the features folder!

Create start.jnlp file as the entry point for the web application

As a final step you need to create your entry JNLP file which is the starting point of your webstart application. Here is an example for start.jnlp:

<?xml version="1.0" encoding="UTF-8"?>
<jnlp 
    spec="1.0+" 
    codebase="http://localhost:8080/demoui-webstart" 
    href="start.jnlp"> 
  <information>
    <!-- user readable name of the application -->
    <title> Demo UI Application </title>  
    <!-- vendor name -->
    <vendor>Me</vendor>
    <!-- vendor homepage --> 
    <homepage href="http://www.me.org" /> 
    <!-- product description -->
    <description>description</description> 
    <offline-allowed/>
  </information>
 
  <!--request all permissions from the application. This does not change-->
  <security>
    <all-permissions/>
  </security>
 
  <!-- The name of the main class to execute. This does not change-->
  <application-desc main-class="org.eclipse.equinox.launcher.WebStartMain">
    <argument>-nosplash</argument>
  </application-desc>
 
  <resources>
    <!-- Reference to the launcher jar. The version segment must be updated to the version being used-->
    <jar href="plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar"/>
 
    <!-- Reference to all the plugins and features constituting the application -->
    <!-- Here we are referring to the wrapper feature since it transitively refers to all the other plug-ins  necessary -->
    <extension 
        name="Wrapper feature"
        href="features/
org.test.webstart.demo.wrapperfeature_0.1.0.jnlp"/>
 
    <!-- Information usually specified in the config.ini -->
    <property 
        name="osgi.instance.area" 
        value="@user.home/Application Data/demoui-rcp"/>
    <property 
        name="osgi.configuration.area" 
        value="@user.home/Application Data/demoui-rcp"/>
    <!-- The id of the product to run, like found in the overview page of the product editor -->
    <property 
        name="eclipse.application" 
        value="org.demo.webstart.plugin.application"/>
  </resources>

  <!-- Indicate on a platform basis which JRE to use --> 
  <resources os="Windows">
    <j2se version="1.5+"/>
  </resources>
  <resources os="Linux">
    <j2se version="1.5+"/>
  </resources>
</jnlp>

Some remarks according the main JNLP file:

You need to adjust (or take care) of the lines 04, 30, 36, 48.

Line 04 defines the codebase. Every time you want to deploy you application on an websever you need to adjust the codebase (in every JNLP file in your project!) to the web application location.

Line 30 depends on you eclipse distribution (I have used eclipse 3.5 with some updates). You have to check the right version in your plugins folder and update the start.jnlp file.

Line 36 defines the starting feature JNLP file. This file itself refers to the other JNLP files in the features folder (which is automatically done from the eclipse exporter). You need to adjust this line if your project name differs from this example.

Line 48 defines the entry point to your application. This is the application ID from the example plugin. You can find the ID if you open the plugin editor of your example plugin. To do so open your example plugin and open the plugin.xml file. Under the tab Overview you can find the ID: „org.demo.webstart.plugin“. Now you also need to open the tab Extensions. Under the Extensions Details you can find the ID of your application. The complete application ID which you need to refer in the JNLP file is then „org.demo.webstart.plugin.application“.

If you now put the main JNLP file and the plugins + features folders under an webserver which delivers the files from http://localhost:8080/demoui-webstart/ you can see your test application. You should have following structure:

– start.jnlp
|– features
|– plugins

Simple click following link: http://localhost:8080/demoui-webstart/start.jnlp

Hint:
A small problem over which I stumbled while developing the example application:

If you start the application and you get from webstart an exception that plugin with *WTP* are not found, you can have a look into the JNLP files in the features folder. Some of these files define resources which are not exported by the eclipse webstart exporter. I have simple removed these resources from the JNLP files and it works.

Update:
I have created a Github repository with some code examples. You may clone my repo or send me patches with corrections.

Additional update:
I have now finished my github example and pushed also a complete working example. If you want to see how it works you can pull the https://github.com/waffel/Wordpress-examples/tree/master/org.waffel.worpress.demo.webstart.result project. With the help of maven you can simple start the application via

mvn jetty:run

This launches the jetty webserver and you can hit your browser to http://localhost:8080/demoui-webstart/start.jnlp

I have done all the mentioned steps from this blog for myself with a eclipse 3.7.

Werbung

August 21, 2009

use your own variable in eclipse code templates

Filed under: java — Thomas Wabner @ 2:08 pm
Tags: , , ,

On my work we develop eclipse plugins and want to add the current bundle id and bundle version to the since field for class comments. There are not much examples around this problem (we have searched google and eclipse help) so let me explain how you can achive this.

For example we want to define follow code template:

/**
 * @author ${user}
 *
 * ${tags}
 * @since ${bundleId} ${bundleVersion}
 */

The bundleId and bundleVersion variable are not provided by the standard code template variables. Now we have to find out how we can achive this problem.

First of all you need to develop your own eclipse plugin which should provide such feature. The new plugin requires follow dependencies:

  • org.eclipse.core.resources;bundle-version=“3.5.0″,
  • org.eclipse.ui;bundle-version=“3.5.0″,
  • org.eclipse.jface.text;bundle-version=“3.5.0″,
  • org.eclipse.jdt.core;bundle-version=“3.5.0″,
  • org.eclipse.jdt.ui;bundle-version=“3.5.0″,
  • org.eclipse.core.runtime;bundle-version=“3.5.0″,
  • org.eclipse.pde.core;bundle-version=“3.5.0″

The PDE dependency is needed to get the current bundle id and the bundle version. If you need other features (for example a maven project version) you have depend on other plugins. But in this example I’ll show you how to add bundle id and bundle version as extra variable for the eclipse code templates.

Next you have to create a extention to register your own variable resolver at startup. The variable resolvers are the heart of the plugin because they providing new variables for the code templates to be used and resolving the content if you use the code template.

plugin.xml:

< ?xml version="1.0" encoding="UTF-8"?>
< ?eclipse version="3.4"?>
<plugin>
   <extension point="org.eclipse.ui.startup">
      <startup class="yourplugin.eclipse.javadoc.internal.RegisterResolvers">
      </startup>
   </extension>
</plugin>

The RegisterResolvers class implements the IStartup interface from eclipse. This class registers the variable resolvers to the code template context. This is required to have the variables available in the code templates from eclipse.

RegisterResolver:

/**
   * 
   * {@inheritDoc}
   * 
   * @see IStartup#earlyStartup()
   * 
   */
  public void earlyStartup() {
    // check if plug-in org.eclipse.jdt.ui is already active
    final Bundle bundle = Platform.getBundle(PLUGIN_ID);
    if (bundle != null && bundle.getState() == Bundle.ACTIVE) {
      // register resolvers
      registerResolvers();
    } else {
      // register listener to get informed, when plug-in becomes active
      final BundleContext bundleContext = Activator.getDefault().getBundle().getBundleContext();
      bundleContext.addBundleListener(new BundleListener() {
        public void bundleChanged(final BundleEvent pEvent) {
          final Bundle bundle2 = pEvent.getBundle();
          if (!bundle2.getSymbolicName().equals(PLUGIN_ID)) {
            return;
          }
          if (bundle2.getState() == Bundle.ACTIVE) {
            registerResolvers();
            bundleContext.removeBundleListener(this);
          }
        }
      });
    }
  }

/**
   * 
   * Internal method to register resolvers with all context types.
   * 
   */
  private void registerResolvers() {
    final ContextTypeRegistry codeTemplateContextRegistry = JavaPlugin.getDefault().getCodeTemplateContextRegistry();
    final Iterator ctIter = codeTemplateContextRegistry.contextTypes();
    while (ctIter.hasNext()) {
      final TemplateContextType contextType = (TemplateContextType) ctIter.next();
      contextType.addResolver(new BundleIdResolver());
      contextType.addResolver(new BundleVersionResolver());

    }
  }

The bundleIdResolver extends the TemplateVariableResolver and defines (in the default constructor) the variable name which can be used later in the code template, a description and overrides the resolve method.

The resolve method checks if the current project is a plugin project and if so returns the bundle id from the project.

public class BundleIdResolver extends TemplateVariableResolver {
  /**
   * 
   * Constructs a new <code>BundleIdResolver</code>.
   * 
   */
  public BundleIdResolver() {
    super("bundleId", "id of the bundle containing the current compilation unit");
  }

  /**
   * 
   * {@inheritDoc}
   * 
   * @see TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateContext)
   * 
   */
  @Override
  protected String resolve(final TemplateContext pContext) {
    final CodeTemplateContext context = (CodeTemplateContext) pContext;
    final IPluginModelBase pluginModelBase = PluginRegistry.findModel(context.getJavaProject().getProject());
    if (pluginModelBase == null) {
      return null;
    }
    return pluginModelBase.getBundleDescription().getSymbolicName();
  }
}

Now you can come up with the question why not you can use the standard eclipse extention point mechanism and create your own context.

Well, we want to extend the java context but the current eclipse implementation doe’s not provide such functionality. For sure if you want to have your own context you can do this with the standard extention point mechanism (as the Ant example). There is a small example about the eclipse editor templates.

Thanks to my colleague Marco Lehmann for the complete solution.

April 27, 2009

How to test spring session or request scope beans

Filed under: spring — Thomas Wabner @ 1:45 pm
Tags: , , , , , , , ,

Update Newer Spring Framework versions (I guess starting with 3.1) have better support and a better solution for this problem.

Often you need test cases where you want to use spring configured beans from a existing spring configuration instead of writing mock objects.

In such cases you can use the spring ContextConfiguration class annotation to load your spring configurations. For test cases you may also extend the AbstractTestNGSpringContextTests which gives you nice test support facilities.

But how to test beans which using special scopes like session or request?

The AbstractTestNGSpringContextTests does not provide support to test scoped beans.

Our test module provides a SimpleMapScope implementation, which can be used for scoped beans. There is also a spring configuration for the scopes request and session: session-request-testscopes.xml which can be used as a ContextConfiguration location.

For example you can write follow simple test case:

....

@ContextConfiguration(locations = {"/org/waffel/test/session-request-testscopes.xml", 
  "/org/waffel/my-app-beans.xml})
public class SimpleScopeBeansTest extends AbstractTestNGSpringContextTests {

  /**
   * A bean which is in scope session.
   */
  @Autowired
  @Qualifier("sessionScopedBean")
  private MyBean sessionScopedBean;
  
  @Test
  public void testAccessToBean() {
    AssertNotNull(sessionScopedBean);
  }

....

This test uses the test scope spring configuration and another spring configuration, where the sessionScopedBean is in scope session. With the autowired feature, you have instantly access to the bean. Also if the bean is in session or request scope.

The SimpleMapScope implementation:

package org.waffel.test.spring;

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

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * This simple scope implementation uses internal a {@link Map} to hold objects
 * in the scope. This scope implementation can be used for testing beans which
 * wants to be stayed for example in session or request scope.
 * <p>
 * To use this scope in your test cases, simple configure a
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} with
 * the required scope name:
 * 
 * <pre>
 * &lt;bean class=&quot;org.springframework.beans.factory.config.CustomScopeConfigurer&quot;&gt;
 *   &lt;property name=&quot;scopes&quot;&gt; 
 *     &lt;map&gt; 
 *       &lt;entry key=&quot;session&quot;&gt; 
 *         &lt;bean class=&quot;org.waffel.spring.SessionScope&quot; /&gt; 
 *       &lt;/entry&gt; 
 *     &lt;/map&gt;
 *   &lt;/property&gt; 
 * &lt;/bean&gt;
 * </pre>
 * 
 * Because the
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} is a
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} all
 * requested beans for the scope loaded with that post processor if the
 * registered scope match.
 * </p>
 * 
 * @author waffel
 */
public class SimpleMapScope implements Scope {

  /**
   * This map contains for each bean name or ID the created object. The objects
   * are created with a spring object factory.
   */
  private final Map<string , Object> objectMap = new HashMap</string><string , Object>();

  /**
   * {@inheritDoc}
   */
  public Object get(final String theName, final ObjectFactory theObjectFactory) {
    Object object = objectMap.get(theName);
    if (null == object) {
      object = theObjectFactory.getObject();
      objectMap.put(theName, object);
    }
    return object;
  }

  /**
   * {@inheritDoc}
   */
  public String getConversationId() {
    return null;
  }

  /**
   * {@inheritDoc}
   */
  public void registerDestructionCallback(final String theName, final Runnable theCallback) {
    // nothing to do ... this is optional and not required
  }

  /**
   * {@inheritDoc}
   */
  public Object remove(final String theName) {
    return objectMap.remove(theName);
  }

}

The session-request-testscopes.xml source:

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

  <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
      <map>
        <entry key="session">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        </entry>
        <entry key="request">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        </entry>
      </map>
    </property>
  </bean>

</beans>

Another approach can be found in ahöhma’s weblog.

Juni 13, 2008

getting node data from rich tree on user selection

Filed under: java,JSF,software — Thomas Wabner @ 3:33 pm
Tags: , ,

I have had the problem to get node data from a richfaces tree, if the user selects a node. I have used a recursive tree adapter:

<rich:tree switchType="server"
           stateAdvisor="#{treeStateAdvisor}"
           nodeSelectListener="#{treeMgrt.onSelect}">
                 
   <rich:recursiveTreeNodesAdaptor roots="#{treeMgrt.roots}" var="item" nodes=" {item.nodes}">

     <rich:treeNode>
         <h:outputText value="#{item}"/>
     </rich:treeNode> 
          
  </rich:recursiveTreeNodesAdaptor>
</rich:tree>  

The method in my tree manager onSelect(…) looks like this:

public void onSelect(final NodeSelectedEvent event) {
  final UITree theTree = this.getTree(event);
  if (null == theTree) {
    return;
  }
  final Object rowKey = theTree.getRowKey();
  // this works better
  final Object rowData = theTree.getRowData(rowKey);
  if (rowData instanceof ProductNode) {
    this.selectedNode = (ProductNode) rowData;
  }
}

Normally you can use theTree.getTreeNode(); but with a recursive tree model which method returns alway null. Instead of this I have used the getRowData() method which works for me.
I have filed a bug for richfaces. Hope the problem becomes shortly a solution.

Oktober 9, 2007

Fast stream copy using java.nio channels

Filed under: java,nio,software — Thomas Wabner @ 11:21 am
Tags: , , ,

Many times I was asked how to copy fast and simple an input stream to an output stream. I have found a nice solution on koders.com . A programmer named Mr. Hitchens has contributed this code.

Here are my utility method which makes the real fast copy stuff:

public final class ChannelTools {
  public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
      // prepare the buffer to be drained
      buffer.flip();
      // write to the channel, may block
      dest.write(buffer);
      // If partial transfer, shift remainder down
      // If buffer is empty, same as doing clear()
      buffer.compact();
    }
    // EOF will leave buffer in fill state
    buffer.flip();
    // make sure the buffer is fully drained.
    while (buffer.hasRemaining()) {
      dest.write(buffer);
    }
  }
}

And how you can use this method to copy an input stream into an output stream? Here comes the answer:


// allocate the stream ... only for example
final InputStream input = new FileInputStream(inputFile);
final OutputStream output = new FileOutputStream(outputFile);
// get an channel from the stream
final ReadableByteChannel inputChannel = Channels.newChannel(input);
final WriteableByteChannel outputChannel = Channels.newChannel(output);
// copy the channels
ChannelTools.fastChannelCopy(inputChannel, outputChannel);
// closing the channels
inputChannel.close();
outputChannel.close()

Erstelle kostenlos eine Website oder ein Blog auf WordPress.com.