Apache Felix Configuration Admin (CM) is widely used component which is responsible for provisioning of one of most common OSGi services. Main responsibility of it is to bring configurations stored in property files to services.

While digging into Felix CM code I have found that it is able to create scalar values of certain type ie. Long, but also more complex structures such Array or Vector. The biggest issue was that I couldn’t find any way to force it to create array from string representation. Thanks to google (FELIX-4431 found on 4th page of results) and debugger goodnes I finally managed to do it. Here is recipe how to proceed.

Configuration file

Config file name which is source of properties must be named .config – otherwise array will not be created.
Property must be written as follows:

property=["value 1", "value 2", "value x"]

Internally config admin is also storing information about value type. By default created values and collections will consist elements of type String. If you wish to change type of collection following prefixes are allowed:

  • T = String
  • I = Integer
  • L = Long
  • F = Float
  • D = Double
  • X = Byte
  • S = Short
  • C = Character
  • B = Boolean

Small prefix letters represents simple type. If you want to construct array of primitive ints then configuration syntax is following:

property=i["1", "2", "3"]

Small note for Karaf users

By default Karaf etc/ directory uses *.cfg suffix as fileinstall filter which means that this feature of Felix Configuration Admin will not work for you. You have two workarounds.
Edit etc/config.properties and navigate to first line shown in listing and replace it with second:

felix.fileinstall.filter = .*\\.cfg
felix.fileinstall.filter = .*\\.(cfg|config)

Create new file org.apache.felix.fileinstall-config.cfg with following contents:

felix.fileinstall.dir     = ${karaf.base}/config
felix.fileinstall.tmpdir  = ${karaf.data}/generated-bundles
felix.fileinstall.poll    = 1000
felix.fileinstall.filter  = .*\\.(cfg|config)

Quick summary

I am using Configuration Admin service since years and I didn’t realize this feature exists and it’s supported since very long time. Hope that this will let you to go over your more complex configurations! 🙂

I use Eclipse since years. Some of you may say that I’m a masochist. Well, people have different preferences. 🙂 I prefer Eclipse over other editors.

What’s the pain?

Eclipse had same look and feel since years. I used to have the same appearance under Windows/Linux/OSX. Everything was the same except fonts. I was very unhappy with default Juno look and feel which looks like few widgets deployed in browser. Even web-based IDEs looks better than Juno! There was some posts about that and some solutions. However nobody told how to get older look and feel in place.

What’s the solution?

It’s really simple. Go to Preferences > General > Apperance and change Theme to classic.
Here hows Mac theme looks like:

Here hows classic theme looks like:

Thanks to this small change I may finally upgrade my environment to Juno. I just realised that my eclipse installation is almost 2 years old!

Piątego lutego miałem niekłamaną przyjemność podziwiać Jacka Laskowskiego prezentującego temat Praktyczne wprowadzenie do OSGi i Enterprise OSGi. Link do filmiku z prezentacją Jacka znajdziecie na Jego blogu. Tymczasem, poniżej wideo z Karafem. 🙂
 

Apache Camel supports a mapped diagnostic context which can be used to improve log entries, but also there is a log component which makes it easier to create log entries. Together they can be used to create foundations of activity monitoring without need to deploy another tool or database.
Read the rest of this entry »

Few months ago I’ve read an article written by my friend Jacek LaskowskiEnterprise OSGi runtime setup with Apache Aries Blueprint. In his article Jacek describes which bundles should be installed to get the blueprint working. As IBM employee Jacek can always promote IBM WebSphere in version X or Y which started (or will start) supporting blueprint as dependency injection mechanism. That’s not fine for these who do not run IBM producs and want something light. As you know, Aries and OSGi Blueprint is an alternative for old-fashion Spring approach. Read the rest of this entry »

One of bigest benefits of Java is byte code manipulation. You can change everything you want in your application without touching source code. That’s usefull for many cases, starting from legacy code, where we can’t simply modify and recompile library up to modern applications where aspects can be used to handle runtime exceptions. The most popular project is AspectJ which is part of Eclipse ecosystem, in this post I going to show you how to use AspectJ with Karaf.
Read the rest of this entry »

Few hours ago I’ve found an usefull post about preserving message order with ActiveMQ written by Marcelo Jabali from FUSE Source.

In his example Marcelo used broker feature called Exclusive Consumers. It lets send messages only to one consumer and if it fails then second consumer gets all messages. I think it is not the best idea if we have many messages to process. Why we wouldn’t use few consumers with preserved message order? Well, I was sure it is not possible, but during last training I’ve found solution.

Broker configuration


So how to force ActiveMQ to preserve message order? It’s really simple, we just need to change dispatch policy for destination. We can do this for all queues or only for selected.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core">

    <broker xmlns="http://activemq.apache.org/schema/core">
        <destinationPolicy>
            <policyMap>
                <policyEntries>
                    <policyEntry queue=">"><!-- Please refer 2nd part of this post -->
                        <dispatchPolicy>
                            <strictOrderDispatchPolicy />
                        </dispatchPolicy>
                    </policyEntry>
                </policyEntries>
            </policyMap>
        </destinationPolicy>
    </broker>
</beans>

After this consumers should receive messages in same order like they were sent from producer. You can find example code on github: example-activemq-ordered. You can run all from maven:

cd broker1; mvn activemq:run
cd broker2; mvn activemq:run
cd consumer; mvn camel:run
cd consumer; mvn camel:run
cd producer; mvn camel:run

Upgrade

After posting update about this blog post to Twitter Dejan Bosanac send me fewupdates. He is co-author of ActiveMQ in Action so his knowledge is much more deeper than mine. 🙂
First of all I mixed XML syntax. strictOrderDispatchPolicy is handled by topics, not queues. For second destination type strict order is turned on by strictOrderDispatch attribute set to true for policyEntry element. This preserves order but, as Dejan wrote, it will broke round robin and all messages will go to only one consumer, as in previous example given by Marcelo.

Also, Marcelo published second post about Message Groups which allows to preserve order and have multiple concurrent consumers on queue.

Management of OSGi – let’s face it – is not very hard. The OSGi environment is clearly defined and that gives programmers many mechanisms to create administrative tools. The problem begins when we would like to use only one tool to manage few projects or artifacts of different types. I know this from personal experience because when I run Camel, ActiveMQ and CXF every from them provides own administration console. Every of them requires own security configuration, looks differently, have own dependencies and so on.

This stands a little bit in contradiction with the OSGi specification idea, which tries to unify management of different things, not only dependencies (Core) but aspects like configuration (ConfigAdmin), deployment (DeploymentAdmin), meta data (MetaType), preferences (PreferencesService), users (UserAdmin) or permissions (PermissionAdmin). Naturally, creation of standard for management tools is too hard to be closed in any specification, even so good like OSGi.

Felix WebConsole

As response for problems with lack of common tool, available from browser a project Felix WebConsole was created. This is a subproject of Felix’a. In its assumptions Felix WebConsole should let easily extend itself through the use of mechanisms known from the core OSGi – that is, services. It should also let change look and feel and localize the tool. All these assumptions was covered, but number of extensions for Felix WebConsole do not grow like mushrooms after the rain.
The question is, why? Now, in its simplicity Felix WebConsole make difficult creation of more complex extensions such as JMX. The problem is that our extension is only a servlet. From one hand it’s too much to put a link in list of bundles, on the other hand it is too little to make a few pages. If we’ll try we’ll begin to implement the second Struts framework based on servlets.
Project team do not make things easier because it puts on the “lightness” console. It is expected to deploy console on mobile devices too.

Karaf WebConsol as alternative

Apache Karaf WebConsole is brand new project, which was made few months ago. After dynamic incubation phase, which maybe was too short, it was moved to sub-project of Karaf. Similar as precursor it points to lightness but also points to collaboration with other web frameworks, in this case it is another ASF project – the Apache Wicket. Through its use we obtained far-reaching component model. It means that you may add link to menu and style it with fragment CSS (without fragment bundle). You may add new tab with content or simply put another widget to dashboard. All these things you may see right after logging into console.
All these extension won’t be possible without Wicket and Pax-Wicket. Thanks to huge amount of work made by Andreas Pieber on second project. Everything is stable and works as fast as Felix WebConsole.

Architecture of Karaf WebConsole

As I meintoned before, WebConsole uses Pax-Wicket and Wicket as presentation layer (we don’t count Java Script libraries). Most of extensions uses also blueprint to register services. There is no problem, similary like in case of Felix WebConsole, to use Spring DM or declarative services. Everything works with Pax-Web, but it should be possible to run it with any HttpService.
Whats’s more, an experimental branch of pax-wicket which I worked on previously named jsr330 let to use same components in a traditional container like is Tomcat. This means that the administrative tool went beyond the OSGi framework and will allow creation of multi-modular consoles, also in a traditional environment.

Extensions

New elements who are added to Karaf WebConsole are typically Wicket components or they are converted to them. Let see how to add new element to navigation:

package org.apache.karaf.webconsole.blueprint.internal.navigation;

import java.util.ArrayList;
import java.util.List;

import org.apache.karaf.webconsole.blueprint.internal.BlueprintPage;
import org.apache.karaf.webconsole.core.navigation.NavigationProvider;
import org.apache.wicket.Page;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;

public class BlueprintNavigationProvider implements NavigationProvider {

    public List<Link<Page>> getItems(String componentId, String labelId) {
        List<Link<Page>> items = new ArrayList<Link<Page>>();

        Link<Page> link = new BookmarkablePageLink<Page>(componentId, BlueprintPage.class);
        link.add(new Label(labelId, "Blueprint"));
        items.add(link);

        return items;
    }

}


Interface org.apache.karaf.webconsole.core.navigation.NavigationProvider is universal supplier of navigation elements. In web application it’s mostly about links. Now, when we have implementation we need to submit it into registry to let use it. In this particular example we going to use blueprint, but it might be a standard activator or any other declarative way as well.

<?xml version="1.0" encoding="utf-8" ?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <service ref="provider" interface="org.apache.karaf.webconsole.core.navigation.NavigationProvider">
        <service-properties>
            <entry key="extends" value="osgi" />
        </service-properties>

    </service>

    <bean id="provider" class="org.apache.karaf.webconsole.blueprint.internal.navigation.BlueprintNavigationProvider" />

</blueprint>

Fragment above will cause addition of BlueprintPage as child of OSGi menu, because we set extends property. Result of execution you may see on attached picture.

Navigation is only example, remember – you have much more possibilities:

  • org.apache.karaf.webconsole.core.brand.BrandProvider – lets to change design (without fragment bundles)
  • org.apache.karaf.webconsole.core.navigation.ConsoleTabProvider – causes addition of new tab in navigation
  • org.apache.karaf.webconsole.core.navigation.SidebarProvider – adds new elements on left side
  • org.apache.karaf.webconsole.core.widget.WidgetProvider – lets to publish new panels with content
  • org.apache.karaf.webconsole.osgi.bundle.IActionProvider – adds specific link to bundle list
  • org.apache.karaf.webconsole.osgi.bundle.IColumnProvider – adds column to bundle list
  • org.apache.karaf.webconsole.osgi.bundle.IDecorationProvider – adds icon bundle list

Last two days I’ve spent hacking Swing code. I decided to run standalone producer application to show real interaction with broker. You may treat this Swing app like entry point for people to our middleware system. Users simply do “transfers” from this application and don’t know anything about technical details. I added text area to main window to show structure of message sent to broker.

Producing messages with JMS

Most of communication systems, whanever you will go have two different kinds of values, first – main and mainly used is body, second is typical metadata named headers or properties or parameters. JMS is not different, you can create different kinds of messages and set headers to them (in JMS world they’re named property, but I preffer header).
Let check messaging code we have:

// import declarations ...
public class JmsMessageSender implements MessageSender, InitializingBean {

	private ConnectionFactory connectionFactory;
	private Session session;
	private final String destination;
	private MessageProducer producer;

	public JmsMessageSender(String destination) {
		this.destination = destination;
	}

	public void sendMessage(String message, Map<String, Object> headers)
		throws Exception {

		if (session == null || producer == null) {
			afterPropertiesSet();
		}

		TextMessage jmsMsg = session.createTextMessage(message);
		for (String header : headers.keySet()) {
			jmsMsg.setObjectProperty(header, headers.get(header));
		}
		producer.send(jmsMsg);
	}

	public void afterPropertiesSet() throws Exception {
		Connection connection = connectionFactory.createConnection();
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Queue queue = session.createQueue(destination);
		producer = session.createProducer(queue);
	}

	// not important
}

First of all we inject connectionFactory using Spring configuration file. In line 20 we create text message, because we sending messages with String as content. Line 22 sets headers for message and finally sends it in line 24 using message producer created in lines 28-31. If we’ll look closer these lines we’ll see standard initalization code automatically called during bean creation by Spring. In line 29 we create session without transaction support and create producer to send messages. Connection factory is configured in XML with properties file to extract informations like broker url username and password.

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

    <bean id="view" class="org.code_house.mom.producer.ProducerWindow">
        <property name="title" value="Bank Agent APP" />
    </bean>

    <bean id="controller" class="org.code_house.mom.producer.ProducerController">
        <constructor-arg ref="view" />
        <property name="messageSender">
            <bean class="org.code_house.mom.producer.JmsMessageSender">
                <constructor-arg value="MOM.Incoming" />
                <property name="connectionFactory" ref="connectionFactory" />
            </bean>
        </property>
        <property name="mapper" ref="mapper" />
    </bean>

    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="${url}" />
        <property name="userName" value="${user}" />
        <property name="password" value="${pass}" />
    </bean>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:activemq.properties" />
    </bean>

    <bean id="mapper" class="org.codehaus.jackson.map.ObjectMapper" />

</beans>

I decided to use JSON over XML. Regarding last post about data structures it is not the best choice but it is very simple. So don’t treat it as reference implementation. I just wish to don’t use JAXB annotations. 🙂

Headers

Headers are common thing for routing. This is main reason why I allow to provide headers as parameter to sendMessage method. In many cases it is better to use headers or even extract headers from body of message in one endpoint to reduce number of content reads. Example how to use headers for routing we’ll see in next part about Apache Camel.

Just as a note types of headers supported by JMS spec:

  • Boolean
  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  • String
  • Object

We can get or set headers using getTypeProperty(String name) or setTypeProperty(String name, Type value). Remember that headers of type “object” set by setObjectProperty must be serializable, otherwise they will be dropped before sending.

Producer application

As I said at begining of the post I spent two days on Swing hacks. 🙂 I injected two additional depentencies to this module – mig layout and better beans binding. First is responsible for frame layout, second for interactions between model and Swing controls. Whole application is simple form. All informations are displayed in status bar at bottom of the window, rest is taken by message area and combo boxes.

I have say, that binding framework is cool and reduced number of code lines I had to write without it. If you are interested in exact code structure, please go to producer module in mom-sample github repository. Because it is not in area of this post I will not write more about desktop implementation details.

For these who wish run sample (I belive you would do that) – after executing

mvn clean install

You can simply execute target/producer.jar by doulbe click. This is fat-jar with all dependencies needed by producer application.

XML Schema jest bodajże najlepszym sposobem walidacji dokumentów XML. Model zastosowany w przypadku tego meta-języka pozwala na tworzenie złożonych konstrukcji. W oparciu o niego można budować własne rozszerzenia czy też zagnieżdżać w sekcjach xsd:appinfo dodatkowe metadane. Dzisiaj jednak nie o tym, a o wzorcach projektowych. Sam się zdziwiłem gdy trafiłem na artykuł Introducing Design Patterns in XML Schemas. W życiu się nie zastanawiałem czy to co piszę w XSD ma coś wspólnego z wzorcami czy nie. Sun wyprzedził w tym momencie chyba wszystkich. 🙂

Wzorce, które zostały wymienione we wspomnianym artykule odnoszą się do powiązania definiowanych typów z definiowanymi elementami. Ciężko mi się zgodzić z tym, że wybór wzorca jest krytyczny przy projektowaniu schematu, ponieważ schemat zazwyczaj ma przeznaczenie już w chwili pisania i zazwyczaj nie możemy powiedzieć, zrobimy to wzorcem X, ponieważ sam nasuwa się wzorzec Y. Ale to tak tylko moim zdaniem.

Tabelka poniżej prezentuje zawartość przeniesioną ze strony Suna. Zawiera ona 4 najpopularniejsze wzorce. Dwa najczęściej spotykane w internecie to Venetian Blind oraz Garden of Eden ze względu na to, że są bardzo podatne na ponowne użycie.

Wzorzec Charakterystyka
Russian Doll, przykład Zawiera jeden element globalny, pozostałe są lokalne.
  • Jest tylko jeden poprawny element.
  • Może uprościć przestrzeń nazw poprzez zastosowanie atrybutu elementFormDefault dla elementu xsd:schema.
  • Nadaje się tylko dla pojedynczych schematów.
  • Pozwala na ponowne użycie tylko całej gałęzi, a nie każdego typu z osobna.
Salami Slice, przykład Wszystkie elementy są globalne, stąd każdy może być użyty w charakterze root node’a.
  • Wszystkie elementy można ponownie użyć.
  • Łatwe wiązanie schematów pomiędzy plikami.
  • Powoduje większą złożoność w przestrzeni nazw.
  • Trudny do określenia root.
Venetian Blind, przykład Pochodna Russian Doll, zawiera jeden element globalny, pozostałe są lokalne
  • Zawiera tylko jeden element nadrzędny.
  • Pozwala na ponowne użycie wszystkich typów oraz elementu nadrzędnego.
  • Łatwa praca z wieloma plikami.
  • Ograniczona enkapsulacja poprzez ekspozycję wszystkich typów.
Garden of Eden, przykład Połączenie Venetian Blind oraz Salami Slice. Wiele elementów globalnych, wiele typów publicznych. Wiele kandydatów na root node.
  • Pozwala ponownie użyć elementy oraz typy.
  • Łatwa praca z wieloma plikami.
  • Zawiera wiele potencjalnych elementów nadrzędnych.
  • Ograniczona enkapsulacja.
  • Trudna do czytania i zrozumienia.
Źródło: Sun Developers Network

Przykłady

Russian Doll

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://schemas.sun.com/point/russiandoll"
    xmlns:tns="http://schemas.sun.com/point/russiandoll"
    elementFormDefault="qualified">

    <xsd:element name="Line">
	<xsd:complexType>
	    <xsd:sequence>
		<xsd:element name="PointA">
		    <xsd:complexType>
			<xsd:attribute name="x" type="xsd:integer"/>
			<xsd:attribute name="y" type="xsd:integer"/>
		    </xsd:complexType>
		</xsd:element>
		<xsd:element name="PointB">
		    <xsd:complexType>
			<xsd:attribute name="x" type="xsd:integer"/>
			<xsd:attribute name="y" type="xsd:integer"/>
		    </xsd:complexType>
		</xsd:element>
	    </xsd:sequence>
	</xsd:complexType>
    </xsd:element>
</xsd:schema>

Salami Slice

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://schemas.sun.com/point/salami"
    xmlns:tns="http://schemas.sun.com/point/salami"
    xmlns="http://schemas.sun.com/point/salami"
    elementFormDefault="qualified">

    <xsd:element name="PointA">
	<xsd:complexType>
	    <xsd:attribute name="x" type="xsd:integer"/>
	    <xsd:attribute name="y" type="xsd:integer"/>
    	</xsd:complexType>
    </xsd:element>

    <xsd:element name="PointB">
	<xsd:complexType>
	    <xsd:attribute name="x" type="xsd:integer"/>
	    <xsd:attribute name="y" type="xsd:integer"/>
	</xsd:complexType>
    </xsd:element>

    <xsd:element name="Line">
    	<xsd:complexType>
	    <xsd:sequence>
		<xsd:element ref="PointA"/>
		<xsd:element ref="PointB"/>
	    </xsd:sequence>
	</xsd:complexType>
    </xsd:element>
</xsd:schema>

Venetian Blind

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://schemas.sun.com/point/venetianblind"
    xmlns:tns="http://schemas.sun.com/point/venetianblind"
    xmlns="http://schemas.sun.com/point/venetianblind"
    elementFormDefault="qualified">

    <xsd:complexType name="PointType">
	<xsd:attribute name="x" type="xsd:integer"/>
	<xsd:attribute name="y" type="xsd:integer"/>
    </xsd:complexType>

    <xsd:element name="Line">
	<xsd:complexType>
	    <xsd:sequence>
		<xsd:element name="PointA" type="PointType"/>
		<xsd:element name="PointB" type="PointType"/>
	    </xsd:sequence>
	</xsd:complexType>
    </xsd:element>
</xsd:schema>

Garden of Eden

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://schemas.sun.com/point/gardenofeden"
    xmlns="http://schemas.sun.com/point/gardenofeden"
    elementFormDefault="qualified">

    <xsd:complexType name="PointType">
	<xsd:attribute name="x" type="xsd:integer"/>
	<xsd:attribute name="y" type="xsd:integer"/>
    </xsd:complexType>

    <xsd:complexType name="LineType">
	<xsd:sequence>
	    <xsd:element ref="PointA"/>
	    <xsd:element ref="PointB"/>
	</xsd:sequence>
    </xsd:complexType>

    <xsd:element name="PointA" type="PointType"/>

    <xsd:element name="PointB" type="PointType"/>

    <xsd:element name="Line" type="LineType"/>
</xsd:schema>
top