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

<channel>
	<title>TechJava&#187; TechJava &#8211; Articles tagged by plug-in</title>
	<atom:link href="http://www.techjava.de/topics/tag/plug-in/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.techjava.de</link>
	<description>Journal on Java Technology</description>
	<lastBuildDate>Thu, 17 Jun 2010 10:41:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Eclipse CNF: Navigator Content Extensions</title>
		<link>http://www.techjava.de/topics/2009/08/eclipse-common-navigator-framework-2/</link>
		<comments>http://www.techjava.de/topics/2009/08/eclipse-common-navigator-framework-2/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 20:55:11 +0000</pubDate>
		<dc:creator>Simon Zambrovski</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[rcp]]></category>
		<category><![CDATA[cnf]]></category>
		<category><![CDATA[common navigator framework]]></category>
		<category><![CDATA[navigator content extension]]></category>
		<category><![CDATA[NCE]]></category>
		<category><![CDATA[plug-in]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public SimpleListener()
    {
    }

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

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

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