<?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>A World Of Documents &#187; OSGi</title>
	<atom:link href="http://www.jeremias-maerki.ch/blog/category/java/osgi/feed" rel="self" type="application/rss+xml" />
	<link>http://www.jeremias-maerki.ch/blog</link>
	<description>Jeremias Märki&#039;s thoughts about XSL-FO, Apache FOP, Barcode4J and other interesting topics</description>
	<lastBuildDate>Sat, 20 Aug 2011 10:36:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JAX-RS applications in OSGi &#8211; whiteboard style</title>
		<link>http://www.jeremias-maerki.ch/blog/2011/08/20/jaxrs-applications-in-osgi-whiteboard-style</link>
		<comments>http://www.jeremias-maerki.ch/blog/2011/08/20/jaxrs-applications-in-osgi-whiteboard-style#comments</comments>
		<pubDate>Sat, 20 Aug 2011 10:30:54 +0000</pubDate>
		<dc:creator>Jeremias</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[JAX-RS]]></category>
		<category><![CDATA[Whiteboard Pattern]]></category>

		<guid isPermaLink="false">http://www.jeremias-maerki.ch/blog/?p=77</guid>
		<description><![CDATA[There are various ways to publish a JAX-RS application when running inside OSGi. Some use Blueprint or Spring, and I&#8217;m sure there are other methods. I&#8217;d like to show how you can publish JAX-RS applications using the whiteboard pattern.
The nice thing about JAX-RS is that it offers the abstract &#8220;Application&#8221; class. So, why not just [...]]]></description>
			<content:encoded><![CDATA[<p>There are various ways to publish a JAX-RS application when running inside OSGi. Some use Blueprint or Spring, and I&#8217;m sure there are other methods. I&#8217;d like to show how you can publish JAX-RS applications using the <a href="http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf">whiteboard pattern</a>.</p>
<p><span id="more-77"></span>The nice thing about JAX-RS is that it offers the abstract &#8220;Application&#8221; class. So, why not just put your application in the OSGi service registry? That&#8217;s very simple and you don&#8217;t need to know anything about the JAX-RS implementation. Let someone else worry about how to get the JAX-RS application into the web container at the right place. Here&#8217;s how your Application subclass could look like:</p>
<p><small></p>
<pre>public class ContentRepositoryApplication extends Application {

    private static final Set&lt;Class&lt;?&gt;&gt; CLASSES
        = new java.util.HashSet&lt;Class&lt;?&gt;&gt;();

    static {
        CLASSES.add(RootResource.class);
        CLASSES.add(DocumentMetadataResource.class);
        CLASSES.add(DocumentResource.class);
        CLASSES.add(RepositoryResource.class);
        CLASSES.add(URIMessageBodyWriter.class);
    }

    @Override
    public Set&lt;Class&lt;?&gt;&gt; getClasses() {
        return CLASSES;
    }
}</pre>
<p></small></p>
<p>I&#8217;d like to demonstrate how to do the publishing part with <a href="http://jersey.java.net/">Jersey</a> (the reference implementation). It&#8217;s particularly easy with this one. Actually, I&#8217;ve tried and failed with both <a href="http://cxf.apache.org/docs/restful-services.html">Apache CXF</a> and <a href="http://incubator.apache.org/wink/">Apache Wink (Incubating)</a>, probably mostly for lack of in-depth knowledge on how to build a servlet instance from an Application instance.</p>
<p>What we need is simply a ServiceTracker that tracks Application services in the OSGi registry. Whenever a new Application becomes available, build a servlet for it and register that with the OSGi registry. A whiteboard-capable web container can then pick up the servlet and expose it. The code is quite straight-forward:</p>
<p><small></p>
<pre>package ch.jm.rest.jersey;

import java.util.Dictionary;
import java.util.Hashtable;

import javax.servlet.Servlet;
import javax.ws.rs.core.Application;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

import com.sun.jersey.spi.container.servlet.ServletContainer;

/**
 * Bundle activator for the Jersey-based JAX-RS Application deployer. It tracks all JAX-RS
 * {@link Application} services and publishes a servlet for each of them. The "alias" service
 * property is propagated to the servlet service so you can control the endpoint for the JAX-RS
 * service. This follows the whiteboard pattern. Similarly, we publish servlet services
 * in whiteboard style.
 */
public class Activator implements BundleActivator {

    private Log log = LogFactory.getLog(Activator.class);

    private BundleContext context;
    private ServiceTracker tracker;

    /** {@inheritDoc} */
    public void start(BundleContext context) throws Exception {
        this.context = context;

        //Track all JAX-RS Applications
        this.tracker = new ServiceTracker(context,
            Application.class.getName(), new Customizer());
        this.tracker.open();
    }

    /** {@inheritDoc} */
    public void stop(BundleContext context) throws Exception {
        this.tracker.close();
        this.tracker = null;
        this.context = null;
    }

    private class Customizer implements ServiceTrackerCustomizer {

        private Dictionary createProps(ServiceReference reference) {
            String alias = reference.getProperty("alias").toString();
            if (log.isDebugEnabled()) {
                log.debug("Alias: " + alias);
            }

            Dictionary props = new Hashtable();
            props.put("alias", alias);
            return props;
        }

        /** {@inheritDoc} */
        public Object addingService(ServiceReference reference) {
            Application app = (Application)context.getService(reference);
            if (log.isDebugEnabled()) {
                log.debug("Adding JAX-RS application: " + app);
            }

            //For each JAX-RS Application, create a servlet wrapping that Application instance
            ServletContainer servlet = new ServletContainer(app);

            Bundle sourceBundle = reference.getBundle();
            BundleContext sourceContext = sourceBundle.getBundleContext();
            ServiceRegistration reg = sourceContext.registerService(
                    Servlet.class.getName(), servlet, createProps(reference));

            return reg;
        }

        /** {@inheritDoc} */
        public void modifiedService(ServiceReference reference, Object service) {
            ServiceRegistration reg = (ServiceRegistration)service;
            if (log.isDebugEnabled()) {
                log.debug("Modifying JAX-RS application: " + reg);
            }
            reg.setProperties(createProps(reference));
        }

        /** {@inheritDoc} */
        public void removedService(ServiceReference reference, Object service) {
            ServiceRegistration reg = (ServiceRegistration)service;
            if (log.isDebugEnabled()) {
                log.debug("Removing JAX-RS application: " + reg);
            }
            reg.unregister();
            context.ungetService(reference);
        }

    }

}</pre>
<p></small></p>
<p>Please note how the servlet service is published under the BundleContext of the bundle that published the Application service. That&#8217;s not really necessary but keeps things in their context.</p>
<p>That&#8217;s all I put in that deployer bundle, just this BundleActivator. That already does the whole job in the Jersey case.</p>
<p>This approach may not work for everyone. Like with the whiteboard approach for servlets, there may be some restrictions of what you can do. But so far it has served me well.</p>
<p>One catch I ran into was multipart support. The old story. I was forced to introduce a hard dependency on Jersey&#8217;s multipart support in one of my JAX-RS applications. Unfortunately, Jersey Core 1.5 exports the JAX-RS API directly instead of in a separate bundle, and hasn&#8217;t assigned versions to exported packages. That would make it difficult to use its multipart support with Apache CXF (it properly imports the JAX-RS API with a version range). Maybe I should look at doing it the other way around (use CXF&#8217;s multipart with Jersey). But to deploy the huge CXF package including dependencies just for getting multipart support (as long as I don&#8217;t manage to create a JAX-RS servlet) is probably not the best of ideas. BTW, the problem with CXF is that I didn&#8217;t find a way to instantiate/configure the servlet without having to rely on web-inf.xml for the initialization parameters. Probably just lack of knowledge. If you have a suggestion, I&#8217;m all ears.</p>
<p>I think it would be cool if all JAX-RS implementations that strive to be OSGi-compatible implemented such a whiteboard support for JAX-RS Applications. All you have to do as a user is register your Application object with the OSGi registry. Ideally, you don&#8217;t have a dependency on any JAX-RS implementation. I&#8217;m still hoping for that multipart support in the next JAX-RS API version.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremias-maerki.ch/blog/2011/08/20/jaxrs-applications-in-osgi-whiteboard-style/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OSGi Bundle Utility 1.0 released</title>
		<link>http://www.jeremias-maerki.ch/blog/2010/11/18/osgi-bundle-utility-1-0-released</link>
		<comments>http://www.jeremias-maerki.ch/blog/2010/11/18/osgi-bundle-utility-1-0-released#comments</comments>
		<pubDate>Thu, 18 Nov 2010 14:02:05 +0000</pubDate>
		<dc:creator>Jeremias</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OSGi]]></category>

		<guid isPermaLink="false">http://www.jeremias-maerki.ch/blog/?p=73</guid>
		<description><![CDATA[Writing OSGi bundle manifests by hand is nothing anyone wants to do, although some entries will always need to be added explicitely. The most prominent of tools for automatically getting imports and exports right is Peter Kriens&#8217; Bnd. However, I found Bnd difficult to manage and to get to work right with Apache Ant. I [...]]]></description>
			<content:encoded><![CDATA[<p>Writing OSGi bundle manifests by hand is nothing anyone wants to do, although some entries will always need to be added explicitely. The most prominent of tools for automatically getting imports and exports right is <a href="http://www.aqute.biz/Code/Bnd">Peter Kriens&#8217; Bnd</a>. However, I found Bnd difficult to manage and to get to work right with <a href="http://ant.apache.org/">Apache Ant</a>. I wanted something simpler because in most cases, you don&#8217;t need all the flexibility Bnd provides. Finally, I wanted the bundle descriptor to be written in XML. So, I wrote my own tool. It turned out to work quite well, and it was a good way for me to learn more about OSGi. I&#8217;ve finally taken some time to document it and make it available to anyone interested. Please note that it does not aim to handle all possible cases. The idea is to follow the 80:20 rule to ensure ease of use for most use cases.</p>
<p>So, if you produce OSGi bundles using <a href="http://ant.apache.org/">Apache Ant</a> and you&#8217;re not quite happy with Bnd or writing bundle metadata by hand, my <a href="http://www.jeremias-maerki.ch/development/osgi/bundle-utility.html">OSGi Bundle Utility</a> might be something for you. The utility is published under the <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License v2.0</a>. Source and Binary distributions and documentation is <a href="http://www.jeremias-maerki.ch/development/osgi/bundle-utility.html">available here</a>.</p>
<p>Hopefully, I&#8217;ve followed all the best practice and it is useful to some people. I&#8217;ve been using it for over a year now for dozens of bundles and for converting third-party JARs to OSGi bundles. <a href="mailto:dev@jeremias-maerki.ch">Feedback</a> is welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremias-maerki.ch/blog/2010/11/18/osgi-bundle-utility-1-0-released/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OSGi Declarative Services: Configuring multiple instances of a component</title>
		<link>http://www.jeremias-maerki.ch/blog/2010/04/22/osgi-ds-configuring-multiple-instances-of-a-component</link>
		<comments>http://www.jeremias-maerki.ch/blog/2010/04/22/osgi-ds-configuring-multiple-instances-of-a-component#comments</comments>
		<pubDate>Thu, 22 Apr 2010 13:44:30 +0000</pubDate>
		<dc:creator>Jeremias</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[Declarative Services]]></category>
		<category><![CDATA[MetaType]]></category>
		<category><![CDATA[SCR]]></category>

		<guid isPermaLink="false">http://www.jeremias-maerki.ch/blog/?p=41</guid>
		<description><![CDATA[Declarative Services are a nice way to create services in the OSGi environment, but there are some subtleties that are not always easy to get under control. Imagine you have a component that observes a directory and acts on the presence of new files (a &#8220;hotfolder&#8221;, much like the Apache Felix FileInstall bundle). You may [...]]]></description>
			<content:encoded><![CDATA[<p>Declarative Services are a nice way to create services in the OSGi environment, but there are some subtleties that are not always easy to get under control. Imagine you have a component that observes a directory and acts on the presence of new files (a &#8220;hotfolder&#8221;, much like the Apache Felix FileInstall bundle). You may have multiple such directories which you want to observe, which you want to configure. You could create a ManagedServiceFactory but there&#8217;s a simpler way with Declarative Services once you&#8217;ve figured out the subtleties.<br />
Let&#8217;s first define a very simple service interface:</p>
<pre>public interface Greeter {
    void sayHello();
}</pre>
<p>Then let&#8217;s implement this interface:</p>
<pre>public class GreeterImpl implements Greeter {

    private ComponentContext context;

    protected void activate(ComponentContext context) {
        this.context = context;
        System.out.println("Creating new greeter for " + getName()
                + ": " + context.getComponentInstance().toString());
    }

    protected void deactivate(ComponentContext context) {
        System.out.println("Deactivating greeter for " + getName()
                + ": " + context.getComponentInstance().toString());
        this.context = null;
    }

    public void sayHello() {
        System.out.println("Hello, I'm " + getName());
    }

    private String getName() {
        return (String)this.context.getProperties().get("name");
    }

}</pre>
<p>Through the <code>activate(ComponentContext)</code> method, we&#8217;ll get the component&#8217;s configuration once an instance is activated.<br />
Now, we need the component descriptor for our Greeter component (<code>OSGI-INF/component.xml</code>):</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;component name="demo.scr.componentfactory.greeter"&gt;
  &lt;!-- No factory attribute here! --&gt;
  &lt;implementation class="demo.scr.componentfactory.impl.GreeterImpl"/&gt;
  &lt;service&gt;
    &lt;provide interface="demo.scr.componentfactory.Greeter"/&gt;
  &lt;/service&gt;
  &lt;property name="service.description"
      value="A nice component that can say hello"/&gt;
&lt;/component&gt;</pre>
<p>If you know a little bit about Declarative Services, you might at first expect a factory attribute on the component, since we&#8217;re going to create multiple instances, but it would really just wrong with the approach I&#8217;m showing here. The final missing clue to make this work with multiple configurations lies with the MetaType descriptor we need to build (<code>OSGI-INF/metatype/metatype.xml</code>):</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;metatype:MetaData xmlns:metatype="http://www.osgi.org/xmlns/metatype/v1.0.0"
    localization="OSGI-INF/metatype/metatype"&gt;
  &lt;metatype:OCD id="demo.scr.componentfactory.greeter"
      name="SCR Component Factory Demo"&gt;
    &lt;metatype:AD id="name" type="String"
        name="%name.name" description="%name.desc"/&gt;
  &lt;/metatype:OCD&gt;
  &lt;metatype:Designate pid="demo.scr.componentfactory.greeter"
      factoryPid="demo.scr.componentfactory.greeter"&gt;
    &lt;metatype:Object ocdref="demo.scr.componentfactory.greeter"/&gt;
  &lt;/metatype:Designate&gt;
&lt;/metatype:MetaData&gt;</pre>
<p>Note especially the &#8220;Designate&#8221; Element which has both a &#8220;pid&#8221; and a &#8220;factoryPid&#8221; attribute. The important part is the &#8220;factoryPid&#8221; attribute which will enable the desired &#8220;factory&#8221; functionality.<br />
If you want, a properties file with the translations (<code>OSGI-INF/metatype/metatype.properties</code>):</p>
<pre>name.name=Name
name.desc=The name. D'oh!</pre>
<p>Just for completeness and illustration, here&#8217;s the effective bundle manifest:</p>
<pre>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: DemoScrComponentFactory
Bundle-SymbolicName: demo.scr.componentfactory
Bundle-Version: 1.0.0
Export-Package: demo.scr.componentfactory
Import-Package: org.osgi.framework,
 org.osgi.service.cm,
 org.osgi.service.component,
Service-Component: OSGI-INF/component.xml</pre>
<p>If you deploy the resulting bundle in Felix, for example, you should see our new component in the dropdown list of factory configurations on the configuration page of Felix&#8217;s WebConsole.<br />
Besides the UI in the WebConsole, you can also use Apache Felix FileInstall&#8217;s configuration feature. Just create a properties file (ex. &#8220;demo.scr.componentfactory.greeter-C3PO.cfg&#8221;) in the directory observed by FileInstall:</p>
<pre>name=C3PO, human cyborg relations</pre>
<p>Just use the component&#8217;s PID followed by a dash and a name of your choosing. You can create as many configuration files as you like. For each one, SCR will create a service for you.</p>
<p><strong>Update, 2010-05-19:</strong><br />
There may be a little problem with the above. If there are no configurations in ConfigurationAdmin, one component instance will still always be activated which may have unwanted side-effects if your component depends on certain values in the configuration. If you experience that, you can switch to the version 1.1 of Declarative Services and use the configuration policy to control this. The following example will require at least one configuration in the ConfigurationAdmin before the component is activated:</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
    name="demo.scr.componentfactory.greeter"
    configuration-policy="require"&gt;
[..]
&lt;/scr:component&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremias-maerki.ch/blog/2010/04/22/osgi-ds-configuring-multiple-instances-of-a-component/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

