Berichten met label OSGi

Kennissessie Services op 24 oktober: de videos

Op 24 oktober 2011 vond een kennissessie plaats over services in gedistribueerde en/of embedded omgevingen. Deze sessie was georganiseerd door Luminis in samenwerking met Thales en leden van de Apache community, en ging in op de vraag hoe het toepassen van services kan helpen bij het verbeteren van de flexibiliteit van bestaande systemen.

De video presentaties van deze sessie zijn nu beschikbaar.

Innovatie, Services en Open Source
Rene van Hees, Technical Authority Software bij Thales

OSGi en Dynamische Services
Marcel Offermans, lid van de Apache Software Foundation

Apache Celix en Apache Foundation
Alexander Broekhuis, Software Engineer Luminis, committer Apache Celix

, , , , , ,

Nog geen reacties

Apache Celix – Introduction

Apache Celix

Last summer I started working on a project to see if it is possible to implement OSGi concepts in C. After a simple Proof of Concept the idea grew to see if it is possible to not only use the OSGi concepts, but actually implement the OSGi specification. Since the OSGi specification is written for Java, simply implementing it in C cannot be done. So an adaptation is needed.

This adaptation will be based on the previously mentioned proof of concept, and, after being accepted by the Apache Incubator PMC, hosted at apache as an Incubator project named Apache Celix.

With a series of posts I will detail how Celix implements the OSGi specification, where and why it deviates from the original specification. But for a start, why is it created and what will it deliver?

Why?

OSGi provides a dynamic, extensible and easily maintainable environment for complex and distributed architectures. But with one large restriction, it is written for Java based systems only. For embedded/realtime systems there is no alternative, and yet the need for a well defined and modular architecture is becoming more and more important. Besides the dynamics, such architecture also makes it possible to reuse parts of a system, which reduces the time needed to implement and maintain software.

Why OSGi?

Celix uses C functions (Dynamic Loading) that have been around for a long time, so why follow the OSGi specification, and create abstractions to be able to expose the dynamic concepts like OSGi does?

There are three reasons for this, the first being the fact that OSGi solves much more than existing C functions do. For example, dynamic loading only solves how a library can be added at runtime, but for a complete solution a registry is needed to keep track of available libraries and services provided by these libraries. The OSGi specification provides a good and proven specification for this.

This is also where the second reason emerges, since the OSGi specification is implemented by several vendors (commercial and open source), and being used by many organizations and people, it is a well known and proven API. Following this API makes it easier to understand and use Celix.

Finally, implementing the OSGi Compendium specifications for Remote Services also makes it possible to create a seamless, yet flexible, integration between Celix and OSGi implementations.

Why Apache?

As mentioned before, Apache Celix is open sourced at the Apache Incubator. This is mainly for two reasons:

  • Community

    As a middleware project, we think Celix can benefit from a large community. Apache provides the means to support such a community.

  • Apache Felix

    Several parts of Celix are a direct port of Apache Felix, and with Felix being hosted at Apache, it is a logical choice to also open source Celix at Apache.

While Apache provides a great basis for Celix as an Open Source project, the community still has to grow. Celix is a new project, and user, committers as well as testers are still needed and always welcome. As with all Apache project, communication is done using mailing lists, to subscribe to the development list of Celix send an email to <celix-dev-subscribe@incubator.apache.org>.

The original proposal can be found on the wiki of the Apache Incubator and the status of Celix in the Apache Incubator can be tracked on the project page for Celix.

What will it deliver?

Eventually, the goal is to have an implementation of the full OSGi Core, and part of the Compendium specification in C. But as with all good things, the OSGi specification was written over a longer period, and expecting Celix to implement everything at once, and still deliver a usable product in a reasonable time would be naive.

So for a first release the following goals are set:

  • Provide a basic implementation of the OSGi Framework API

  • Provide an implementation of Remote Services

    For both Celix <-> Celix but also Celix <-> OSGi

While this is a short list, actually implementing the OSGi Framework API entails a lot of functionality. In the coming blog posts I will detail parts of the specification, and how they are implemented in Celix.

Call for help

Finally, I would like to invite everyone to join the Apache Celix community, and provide us with feedback, ideas, bugs, and maybe even bugfixes and additions to the current code base.

, , ,

Nog geen reacties

Apachecon NA 2010, some trends

With Apachecon NA 2010 about a month behind us, I’d like to share some of the trends I picked up there.

Big Data, the cloud

One of the main trends I noticed is the interest in Big Data (mainly Apache Cassandra) and Big Data processing in various shapes and forms (e.g. Apache Lucene, Apache Hadoop). In relation to many of these, we find a ring of ‘cloudness’: the products tend to allow distribution and replication of data and functionality.

But it doesn’t stop there. It’s no surprise to find cloud-references in talks about Apache Tuscany (including a talk on Building cloud native software, which I regrettably missed), but for instance Tomcat is making its move into cloud territory with Stratos.

OSGi all around

Of course I have a vested interest in OSGi, and my talk during the OSGi track on friday shows this. However, apart from in its own track, OSGi and OSGi-based technologies popped up in a number of other tracks. To name a few,

  • Apache Sling is an OSGi based web application platform, and showed up in the Content Technologies track,
  • Apache Geronimo 3.0 (in the Content Technologies track) is now based on OSGi, and
  • in the Enterprise Track, a number of sessions were decidated to Apache Aries, which focuses on the OSGi Enterprise specification.

It is an interesting development that OSGi is now mainly being referenced in the web- and enterprise spaces, whereas it started out as a specification for embedded devices.

Does this mean that OSGi is really getting traction in the software community? Yes and no. I believe the thing that is really getting traction is the notions of modularity on the one hand, and µServices on the other. OSGi is currently the main technology that marries those two notions.

Business is not a dirty word

I noticed there were roughly three kinds of talks,

  • Community talks are all about how Apache works, and how open source software fits into the world around it,
  • Technology talks focus on some Apache project, or a combination of projects, and go into the technical details, and
  • Industry talks that show how the projects are used in industry.

The last kind of talk shows how industry, the ‘people with the problem’ use open source technology to run their business. No, I probably don’t really care about the products and services you deliver, but I am very interested in your case studies in using open source in your daily life.

A few days ago, Slashdot ran a story Paid Developers Power the Linux Kernel. In the light of sessions on open source in industry (I counted about half a dozen on this year’s schedule), this is not that surprising: if you’re a good enough developer to become a committer in an open source project, it’s very unlikely you’re working as a janitor during the daytime. All of us work for a corporation in some way, and many of us work on open source project during our paid time. I believe this is a good thing!

, , ,

Nog geen reacties

FitNesse and OSGi

As a demonstrator for a customer, I recently built a set of fixtures that allow FitNesse acceptance tests to talk to an OSGi framework. This code is by no means production quality, but merely intended to show the concept and explain the challenges.

I will not explain the details of the acceptance tests here, however, if there’s one point I would like to get across, it’s your fixtures should be as narrow as possible to easily accommodate for implementation changes. Study the different UserAdmin fixtures for more details. Also, I assume some familiarity with OSGi.

FitNesse and OSGi. Why?

Of course its fun, there is some real benefit to be gained here. While the industry well understands the need for unit- and integration testing, also in a modular context, it becomes more complex to create the necessary link between business and code. Yes, using a modular architecture we can behave in a more agile fashion, but all that agility is no good if the business doesn’t hop on the train, and explain well what it needs. FitNesse allows the business to explain its goals in business-lingo, while forcing the specification to be precise enough to be executable: if a concept cannot be explained by simple scenarios, something is wrong, but that’s a different story.

The modular nature of OSGi means that behavior of an application is more emergent than deterministic, making it harder to reason about its correctness: we can prove that our code and bundles are correct (unit tests), that everything works together as it should (integration tests), and that it looks right (user interface tests). However, proving that the business rules (which may well be one of those emergent properties) are handled correctly in a given setting, is another can of worms: we need to connect our acceptance tests to the OSGi framework.

The big picture

FitNesse and OSGi - overview

The solution presented below uses a special ‘fixtures’ bundle, which can be deployed along side other bundles in your framework. This bundles exposes an interface (in our case, through an HTTPServlet), which is used by a set of connectors, which in turn are used by FitNesse.

The details

FitNesse and OSGi - detailed

The ingredients are two parts connector code, one part boiler plate, and one part genuine OSGi-aware fixtures.

The connectors

Starting at the level closest to FitNesse, we find a set of fixtures that FitNesse can use. For us, these contain merely boiler plate code.

public void removeUser(String name) throws Exception {
    doRemoteCall(buildRemoteCall("UserAdmin", name), Void.class);
}

This code instructs our RemoteInvoker to do some call to the outside world. For more details, see RemoteInvoker.java in the UserAdminRemoteFixtures project.

The fixture bundle

Moving one step closer to our service, and into the OSGi framework, we find a FixtureServlet, whose task it is to receive calls from the RemoteInvoker, and turn them into actual method calls on the fixtures.

The fixtures, then, are almost regular OSGi aware objects. I chose to use the Apache Felix Dependency Manager for the dependency management of the fixtures. So, for our UserAdmin fixture, the dependencies are

manager.add(createService()
    .setInterface(UserAdminListener.class.getName(), null)
    .setImplementation(userAdmin)
    .add(createServiceDependency()
        .setService(UserAdmin.class)
        .setRequired(true)));

Here, we state that we have some instance of a fixture userAdmin that registers itself as a UserAdminListener and needs a UserAdmin. How straightforward is that?

The final step takes us to the actual fixture,

public class UserAdminFixture implements UserAdminListener {
	private volatile UserAdmin m_userAdmin;
...
	public void addUser(String name) {
		m_usersCreatedInLastCall = 0;
		m_userAdmin.createRole(name, Role.USER);
	}
...
}

which is just another component using a the UserAdmin service.

Putting it all together

All we now need to do is deploy the fixture bundle in our project, and instruct FitNesse to use the remote connector. The zip file at the bottom of this post contains two shell scripts to do exactly that.

Future work

As I stated at the top of this story, this is by no means production quality code, but the concepts stand as they are. Given the way FitNesse works, the connectors do not need much extra work, perhaps support for collections. However, we could use

  • a way to reduce the boiler plate code,
  • a way to ensure that that both side of the fixtures use the same function naming, and
  • better integration, for instance by only firing up a framework once a FitNesse suite is started.

Let’s play with it!

I have built a zip file containing everything you need to get started, including a set of scenarios that can run with both a homebrew implementation of a User Admin, and the actual Apache Felix User Admin. A Readme gives you more information on getting it all up and running.

, , , ,

1 reactie

Online video: Beyond OSGi software architecture

Op 11 november 2009 gaf Marcel Offermans samen met Jeroen van Grondelle (Be Informed) een duo presentatie over “Beyond OSGi software architecture”. De video van deze presentatie is inmiddels online beschikbaar. De gehele presentatie van 50 minuten kan je hier downloaden. Maar de eerste tien minuten zijn hieronder gelijk online te bekijken.

OSGi is niet meer weg te denken uit het Enterprise Java domein. Dit lightweight framework krijgt al een aantal jaren flinke aandacht en is met name bekend om z’n modulaire applicaties op basis van bundles. Minder bekend is het services model, waarbij applicaties worden ontwikkeld op basis van service interfaces en van elkaar ontkoppelde implementaties (POJO’s) van die interfaces. Krachtige eigenschappen van dit model zijn:

  • complexiteitsreductie door stricte scheiding van services;
  • declaratieve services en dependency management (IoC);
  • aspect oriëntatie op basis van stub services;
  • security model.

Lean software is een nieuwe manier om enterprise applicaties te bouwen op basis van OSGi, die ook goed aansluit bij Agile methoden, waarbij non-functional requirements ingevuld kunnen worden in een compact gebleven framework. In die context kijken we naar:

  • applicaties deployen op allerlei platformen en omgevingen;
  • applicaties automatisch installeren en updaten;
  • applicaties voorzien van management interfaces;
  • product software uitbreidbaar maken middels een SDK;
  • product software verkopen als combinatie van standaard onderdelen en optionele uitbreidingen;
  • modulaire User Interfaces.

De slides van de presentatie zijn te vinden op de NLJUG website.

, , , , , ,

1 reactie

Swing & OSGi — please play nice!

In a recent blog by Peter Karich, he showed how to create a pluggable Swing application using OSGi. While this works fine for smaller examples, you might run into more serious issues once you application starts to grow.

Plugging Swing: it leaks?

Let’s start with an application not unlike the one from aforementioned blog; it uses a window as host, and has a pluggable menu, and a pluggable table.

SWING_OSGI_Pluggable components600

You can find the code we used at the end of this entry (or, for the impatient, here).

Using this pluggable system, we could end up with several curious situations. For instance, you might have a mixed look and feel in you application.

SWING_OSGI_wrong_menus

Or worse, you might end up with a UI that (sometimes) fails to start, and spits a stacktrace your way.

swing_osgi_NPE

It leaks, but why?

Our host, and all components have been stored in separate bundles, meaning we don’t have full control about the order in which actions are performed (more about that later). However, we do know there are orders of execution that are less than ideal; let’s force one of those.

The project contains an Ant script to make things easier. From the root of the extracted project, run

$ &gt; ant run1

This starts the framework, installing the necessary bundles, but does not start them (note that this step uses Pax Runner, and therefore needs internet access). We can now start our bundles in the order we like.

A tale of two look-and-feels

After starting the framework, wait for the “Welcome to Felix” message, and run

     [java] Welcome to Felix
     [java] ================
     [java]
start 2
start 1

The situation arises because the look and feel is a static concept in Swing. The menu bundle creates its JMenu before (see Menu.java, ln 30) the host sets its look and feel (Host.java, ln 51), and keep that look and feel, even when the host bundle changes it later.

Tables, ScrollPanes and NPEs

The NullPointerException above is a different story, but it goes back to the same staticness of Swing too. To force this situation, start only bundle 4.

     [java] Welcome to Felix
     [java] ================
     [java]
start 4
     [java] Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
     [java]      at net.luminis.swingosgi.part1.scrolltable.impl.TableComponent$1.run(TableComponent.java:31)
     [java]      at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
     [java]      at java.awt.EventQueue.dispatchEvent(EventQueue.java:633)
     [java]      at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
     [java]      at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
     [java]      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
     [java]      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
     [java]      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
     [java]      at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Let’s take a look at the line where this NPE happens:

JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getColumnHeader().setBackground(Color.blue);
m_panel.add(scrollPane);

We know that the ColumnHeader is null. This is because its JTable’s responsibility to create the header, but this is only done once the table knows it is part of an AWT hierarchy. The following lines come from the 1.5 JDK on a Mac; configureEnclosingScrollPane() creates the column header. This addNotify method comes from Component, and notifies of, exactly, the event of being added to an AWT container.

public void addNotify() {
  super.addNotify();
  configureEnclosingScrollPane();
}

Order, order!

So, the static nature of Swing and the dynamic nature of OSGi seem to hurt each other seriously here.

One way to get the application right is by fixing the order in which Swing components can be created. By starting bundle 1 first in our application, we at least fix the look and feel. Getting the scrolling table to run correctly is an entirely different story.

Regarding order, a few possible solutions spring to mind immediately,

  1. Put all UI stuff in one bundle
  2. Use OSGi bundle start levels

Sure, all UI in a single bundle will give you the control necessary, but it also defeats the purpose. OSGi start levels can at least solve the ordering issues, but will not get you out of the NullPointerException and might have more impact than you desire.

What order?

As we have seen, absolute order does not solve our problem. How about separating creation and initialization? Still, we need to impose some order, or at least some hierarchy.

SWING_OSGI_Application composition600

We represent each Swing component by an OSGi service, and leverage the OSGi service dependency resolution to build up our hierarchy; this way, we know the host service will be started last.

  1. Resolve services Once the host bundle starts, we know all components are locked and loaded; the host can now start setting up Swing’s static elements like the look and feel.
  2. Create components Component creation ripples downward: the host gets its direct children, adding them to its container, and in the process triggering the children to get their child components.
  3. Initialize components Once the component creation is done, the host instructs each component to initialize; we can now be certain that all components are part of the AWT hierarchy.

To reach this situation, we introduce a new OSGi service that wraps the component.

SWING_OSGI_Using component provider600

All components are handled by a service implementing ComponentProvider; notice how methods are required to be called on the EventDispatchThread, making sure that all components are created on the EDT, while retaining the order necessary.

public interface ComponentProvider {
 /**
 * Constant to identify ComponentProvider services.
 */
 public static final String COMPONENT_ID_KEY = "component.id";
 
 /**
 * This function should always be called from the EDT. The implementor
 * may assume that this function is called once and before {@link #addedToContainer()}
 *
 * @return the implementors (Swing) component which it provides.
 */
 public JComponent getComponent();
 
 /**
 * Triggered when the component is added to a container. The implementation
 * can validate some stuff. This function must be called on the EDT.
 * Implementors may assume this function is called after {@link #getComponent()}.
 */
 public void addedToContainer();
}

The getComponent function is analogous to the create step above; the addedToContainer triggers the initialize.

Let’s try that out!

To check that this actually works OK, run

$ &gt; ant run2

from the root of the project, and start the bundles in any order you like. The UI will only show up once all required components are available; notice that the Table and the ScrollPane component can be used interchangeably.

Is it all good?

For the most part, yes. You do give up some flexibility: the UI is assembled at runtime, but it is no longer possible to (easily) plug components into a running system without special provisions. Then again, how often do you deploy new Swing-based functionality to a running application?

In the example application, we use ServiceTrackers to keep track of the components needed by the host. In a real system, you should consider using some dependency management mechanism; we have used the Apache Felix Dependency Manager in the past.

The project and the story

The project mentioned above is available as a zipped Eclipse project. You can directly import this into Eclipse, or just unzip it and run the Ant build file.

To run the examples, you will need Apache Ant. Also, since we use Pax Runner, you will need an internet connection.

The presentation we gave about this at Devoxx 09 is at SlideShare.

, ,

14 reacties

ApacheCon US 2009 – Celebrating a decade of open source leadership

The Apache Software Foundation celebrated its 10th anniversary last week at the ApacheCon US in Oakland, California. The event, which lasted from November 2nd to 6th, consisted of many different types of events, ranging from full-day trainings to lightning talks, from a hackathon to technical and marketing sessions. On friday, the event featured a full-day track about OSGi, where all OSGi related Apache projects like Felix, ACE, Sling and Tuscany where present. The big announcement of the conference was the fact that Subversion wanted to join Apache. In fact, during the event, just like with any other project, there was a vote to accept Subversion into the incubator. As with many projects, this triggered some discussion, debating the merits of doing a release during incubation, even though this is a project with many seasoned Apache committers on board.

A conference like no other

Apache probably is the strongest brand in the open source space, but the conference itself focusses strongly on content. Here you will see no sponsored talks by commercial vendors, no sales people trying to sell you anything, it’s all about the code, the community and collaborating with each other. In that sense it’s quite different from most other conferences and if you like meeting and discussing fellow developers, this is a great place to visit. Many events facilitate discussion, and power and internet connectivity are available everywhere.

What open source is all about

Brian Behlendorf summarized the three main cultural elements of Apache quite well:

  • write good code and debate it to the bone
  • be humble
  • collaborate

In essence, Apache is a meritocracy, of which only individuals can become a member. It’s sometimes also described as a do-ocracy as projects are driven by contributions: if you want something done, just do it. Another important aspect is that everything that is done on the Apache projects is discussed and archived on the mailing list. All discussions, code diffs and decisions must be recorded there.

Presenting Apache ACE

Tuesday evenings “birds of a feather” session featured a discussion about Apache ACE, where questions mostly centered around the use cases for ACE and possible integrations with other OSGi components. One of the conclusions is that there are probably three different phases of deployment:

  1. Using Apache Felix File Installer, which allows you to drop components in a local folder to have them installed.
  2. Using Apache Felix Karaf’s provisioning components, which allow you to define features which basically group components and allow you to define dependencies on other features.
  3. Using Apache ACE, which allows you to group components and automatically deploy them to many remote systems.

Friday’s OSGi track started with an introduction to OSGi and moved into more advanced topics during the day. The Apache ACE talk was received well, with several people expressing an interest in wanting to use it and contribute to it.

Final thoughts

Summarizing the week, Floris and I had a great time talking to many interesting people and learning about various projects. ApacheCon is a great conference, and I’m already looking forward to the next one.

, , , , , , , , , ,

Nog geen reacties

Oredev 2009

Update 2010-05-08
The video of my session is up! Check it out at http://oredev.com/videos/dynamic-deployment-with-osgi.

This past week (4 – 6 November), I went to Øredev, probably the largest developer conference in Scandinavia. I had been invited as a speaker, thanks for having me!

Great food, nice ambiance

The first thing that strikes me about this conference is how well it has been prepared. The food is great, there is a good evening program, and overall both your inner geek and inner person are well looked after.

Highlights

Interactive Visualizations from Microsoft research – Eric Stollnitz (User Experience track)
One of the rare talks I actually did not like. Having not read the session description properly, I had totally wrong expectations; the session demoed visual tools like Photosynth, which are cool, but not something we haven’t seen before. And besides, running Vista on a Mac, and having to kill Internet Explorer…?

Open source Java: ten things you didn’t know you could do – Terrence Barr (Java track)
Early in the talk it felt like a plug for the greatness of Sun, making Java open source. Later, however, it mentions some seriously cool technology that has become possible now! Some honorable mentions,

  • The Maxine guest VM is an effort to run a Java VM directly on a HyperVisor, skipping the entire OS!
  • IKVM.NET is a project aiming to run Java code on a .NET VM. Somehow, it turns out that Java bytecode and .NET assembly language are so similar, that an effort has been started to create automatic translation tools between compiled Java and compiled .NET (and vice versa). I would like to add that this is allows not only Java to run on a .NET VM, but likely any language that runs on the Java VM! Interesting…
  • Zero writes a Java VM in plain C without using assembler code, making it easier to port it to new platforms.

The Manager’s Guide to Agile Adoption – Mike Cottmeyer (PM In Practice track)
A great talk showing the issues that might hamper agile adoption, especially in larger organizations. Some snippets,

  • “Agile adoption at the team level is not the issue, it’s adopting agile across teams.”
  • Don’t speak of features of a system, speak of capabilities (think about that one!)
  • Depending on the amount of dependencies between teams, we could use a Scrum of Scrums (resource dependency), Product Owner team (requirements dependency), or a Product Owner team with Architects (technical dependencies). Whatever method is used, this higher level should build a normalized backlog, intended to create some alignment along the teams. The team’s backlogs are based on this normalized backlog.
  • Feature teams will break down at some level; at a certain system size, it’s no longer possible to create a top-to-bottom slice of the system which is small enough for a single team to manage.

In short, I really enjoyed this talk, and I feel there might be some applications for these ideas somewhere near me…

How Exactly Can Developers Create a Compelling User Experience? – Ben Galbraith (User Experience track)
Exactly the way I would expect a user experience talk to look (and feel!) like: polished imagery, a well-oiled story line, and lots of inspiration. Besides, I have two new books to add to my reading list: About Face by Alan Cooper, which seems to be the standard volume on interaction design, and The humane interface by Jeff Raskin.

Reconsidering cherished design dogmas – Johannes Brodwall & Finn-Robert Kristensen (Architecture track)
I actually had a beer with these guys a few days earlier, and they told me about their ideas. In short, there are a number of dogmas in software design we came to hold true, but are they actually true? For instance, is generic code really more reusable than specific code?

It’s a shame the talk didn’t really come across, and I could not put my finger on the problem; it might have something to do with the over-abstracted example they chose.

Dynamic Deployment with OSGi – Angelo van der Sijpt (Java track)
Well, let the crowds decide on this one. Have you visited my talk, and have an opinion about it? Let me know in the comments?

Modeling in the Age of Agility – Kevlin Henney (Agile Architecture track)
“Working software over comprehensive documentation” sounds good, but how about modeling? Are all models potential waste? Of course not, but when applying modeling because it is modeling, is sure to create models no one will ever look at, and the few good ones in there are buried. Some snippets,

  • “Agile is all about doing.” Actually, I did not know the word ‘Agile’ comes from the Latin verb for ‘to do’.
  • “The most important aspect of modeling is the -ing.”

So?

Like I said, a great conference, and I’m sorry I missed the test track. I will leave you with a quote I picked up on Twitter (I don’t know which session it’s from),

“Don’t build frameworks, extract them”

, , , ,

Nog geen reacties

Using GWT to create an OSGi-aware web application

Update 2010-02-20 Both Pax Runner 1.3.0 and GWT 2.0 have caused quite some changes to this post. I have tried to stay up to date as well as I could (the zipped project now uses GWT 2.0), but you might find some inconsistencies when following the tutorial.

Google Web Toolkit is cool, and so is OSGi. However, when building a web UI for Apache ACE, I found out that creating a web application that can use OSGi services is not that easy. By the end of this tutorial, you will have created a GWT project that delivers a usable jar. If you’re impatient, skip to the end for the downloadable Eclipse project.

Step 1: Create a GWT project

Create a regular GWT project using the regular webAppCreator; this will give you a project that includes an Ant buildfile, we will need that later on.

angelos:workspace angelos$ ./gwt-mac-1.6.4/webAppCreator -out GwtDemo net.luminis.gwt.gwtdemo
Created directory GwtDemo/src
Created directory GwtDemo/war
Created directory GwtDemo/war/WEB-INF
Created directory GwtDemo/war/WEB-INF/lib
Created directory GwtDemo/src/net/luminis/gwt
Created directory GwtDemo/src/net/luminis/gwt/client
Created directory GwtDemo/src/net/luminis/gwt/server
Created file GwtDemo/src/net/luminis/gwt/gwtdemo.gwt.xml
Created file GwtDemo/war/gwtdemo.html
Created file GwtDemo/war/gwtdemo.css
Created file GwtDemo/war/WEB-INF/web.xml
Created file GwtDemo/src/net/luminis/gwt/client/gwtdemo.java
Created file GwtDemo/src/net/luminis/gwt/client/GreetingService.java
Created file GwtDemo/src/net/luminis/gwt/client/GreetingServiceAsync.java
Created file GwtDemo/src/net/luminis/gwt/server/GreetingServiceImpl.java
Created file GwtDemo/build.xml
Created file GwtDemo/README.txt
Created file GwtDemo/.project
Created file GwtDemo/.classpath
Created file GwtDemo/gwtdemo.launch
Created file GwtDemo/war/WEB-INF/lib/gwt-servlet.jar

If you want to, you can import this project directly into your Eclipse. If you check the mark “use Google Web Toolkit” in the project properties, you can use all the same goodies that creating the project in Eclipse would have given you. Remember to replace the buildpath entries for gwt-user.jar and gwt-dev-*.jar by a Library import for GWT.

Step 2: Include the necessary OSGi references

Create an ‘ext’ directory, and add org.osgi.core.jar to that. In Eclipse, add this jar to your build path.

Step 3: Use OSGi services from your web applicaiton

We will first add a simple Activator on the server side.

package net.luminis.gwt.server;
 
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
 
public class Activator implements BundleActivator {
    private static BundleContext m_context;
 
    public static BundleContext getContext() {
        return m_context;
    }
 
    public void start(BundleContext context) throws Exception {
        m_context = context;
    }
 
    public void stop(BundleContext context) throws Exception {
    }
}

Then, we up the GreetingServiceImpl to actually use this BundleContext (note that we use it directly here, but you could use it to get other services, create a ServiceTracker, etc.)

public String greetServer(String input) {
  String serverInfo = getServletContext().getServerInfo();
  String userAgent = getThreadLocalRequest().getHeader("User-Agent");
  return "Hello, " + input + "!
 
I am running " + serverInfo
    + ".
 
It looks like you are using:" + userAgent +
    "The framework we run from has " + Activator.getContext().getBundles().length + " bundles in it.";
}

Step 4: Add OSGi dependencies for the compiler

Add our OSGi dependencies to the classpath, so the compiler can find all of it.

    <!-- Add any additional non-server libs (such as JUnit) -->

Right, let’s give it a try!

angelos:GwtDemo angelos$ ant war
Buildfile: build.xml
 
...some output removed...
 
war:
[zip] Building zip: /Users/angelos/workspace/workspace/GwtDemo/gwtdemo.war
 
BUILD SUCCESSFUL
Total time: 36 seconds

You will find a war in your project directory now. There still is one ingredient we need. We need to make this into a proper bundle. We can use bnd to help us with that.

Step 5: use bnd to create a proper war

Download bnd, and put into a lib directory, and add it to your buildfile.

We create a new target that transforms our war into a jar.

<target name="jar">
    <copy file="gwtdemo.war" tofile="gwtdemo.jar"/>
    <echo file="gwtdemo.bnd">Import-Package: junit.framework;resolution:=optional, com.google.gwt.*;resolution:=optional, org.w3c.*;resolution:=optional, sun.misc;resolution:=optional, javax.imageio;resolution:=optional, javax.servlet.*;resolution:=optional, *
Bundle-Name: GWT Demo
Bundle-ClassPath: WEB-INF/classes, WEB-INF/lib/gwt-servlet.jar
Bundle-SymbolicName: net.luminis.gwt.gwtdemo
Webapp-Context: gwtdemo
Bundle-Activator: net.luminis.gwt.server.Activator
    </echo>
    <bndwrap jars="gwtdemo.jar" output="gwtdemo.jar"/>
    <jar file="gwtdemo.jar" update="true">
    <manifest>
        <attribute name="Bundle-ClassPath" value="WEB-INF/classes, WEB-INF/lib/gwt-servlet.jar, ."/>
     </manifest>
    </jar>
    <delete file="gwtdemo.bnd"/>
</target>

What’s happening here?

  • we copy our war to the same file, but with a jar extension,
  • we create a file for bnd to use, stating that we
    • want optional imports for junit and the gwt benchmarks, and non-optional imports for everything else (that what the * is for),
    • have some classes that we want bnd to scan for finding dependencies,
    • want to use a given Webapp-Context (this is a Pax war extender specific entry),
  • let bnd do its magic,
  • update our manifest: we put the . back on the classpath. This is important for the web application to find all resources, but if we would tell bnd to do it like this, it would treat . as the root of the classpath.
  • Finally, we delete that temporary bnd file.

What does that give us?

angelos:GwtDemo angelos$ ant jar
Buildfile: build.xml
 
...some output removed...
 
jar:
[copy] Copying 1 file to /Users/angelos/workspace/workspace/GwtDemo
[bndwrap] gwtdemo 41 910305
[bndwrap] Warnings
[bndwrap] Superfluous export-package instructions: [WEB-INF.classes.net, gwtdemo.gwt.standard.images, WEB-INF, gwtdemo, WEB-INF.classes.net.luminis.gwt, gwtdemo.gwt.standard, WEB-INF.classes.net.luminis, WEB-INF.lib, WEB-INF.classes, gwtdemo.gwt.standard.images.ie6, WEB-INF.classes.net.luminis.gwt.client, WEB-INF.classes.net.luminis.gwt.server, gwtdemo.gwt]
[jar] Updating jar: /Users/angelos/workspace/workspace/GwtDemo/gwtdemo.jar
[delete] Deleting: /Users/angelos/workspace/workspace/GwtDemo/gwtdemo.bnd
 
BUILD SUCCESSFUL
Total time: 23 seconds

That’s it! You can now deploy this jar into a framework that uses the pax web tools. Right, let’s give that a try.

Download pax-runner, and unzip that somewhere. Copy in your new jar, an try the following command

angelos:pax-runner angelos$ sh bin/pax-run.sh --profiles=war,compendium gwtdemo.jar

Now visit http://localhost:8080/gwtdemo:

gwtdemo

Summary

So, what did we need?

  • A fairly regular GWT project, create with an Ant file,
  • some code that tries to use OSGi services,
  • some bnd magic to make the war into a jar,
  • Pax tools to get it all running quickly.

If you don’t want to use pax runner, you can need to deploy pax-web-extender-war(jar, snapshot 23 June) and an http server, preferably pax-web-service(jar), into your framework.

You can download the gwtdemo Eclipse project to play around with it. I have not provided the GWT runtime in this download; you should edit line 4 of the build.xml to point to your installation of GWT.

, , , , , , , , , , ,

16 reacties

EZdroid launched


The EZdroid initiative is launched: www.ezdroid.com

We are pleased to announce the launch of EZdroid, the world’s first open-source, collaborative platform for the safe deployment of component-based software applications and content across Android, and other Linux-based mobile devices.
EZdroid was founded by two of Europe’s leading companies in the field of OSS technology; the platform consists of Android, Apache Felix and a number of their own enhancements (e.g. software license-, device- and integrated software-management). EZdroid supports the secure deployment of software applications and content (known as Provisioning) to Android phones and in the future, other Linux-based operating systems. It is available to any organization or individual wishing to make software and content available to Android users world-wide. Further information and a demonstration of the platform is now available and downloadable to Android phones at: http://www.ezdroid.com.

EZdroid’s founders: Luminis BV (www.luminis.nl/en) of The Netherlands and Akquinet GmbH (www.akquinet.com/en) of Germany are now inviting partners and collaborators to become part of the EZdroid community – whether these are developers, wishing to show-case their applications, business partners interested in co-development or an OEM relationship, or organizations which are interested in owning and controlling their own application repository/App Store.

The launch of EZdroid is very significant; it is the world’s first platform, built from open source components, which will allow the mass deployment of applications without proprietary licensing issues. The founders intend to supplement the platform with a validation and quality assurance system – to ensure that applications are safe and do not interfere with Android’s normal operations.

, , , , , , ,

Nog geen reacties