redVoodo – a good idea to use eclipse databinding

June 29, 2011

Actually i am writing the UI controllers which are connecting the redVoodo UI model with the UI parts that are responsible to visualize the model. After a sleepless night i decided to refactor the whole controller code. The problem was that i had to implement tons of observing code which observes the UI model for a few nodes and causes the UI parts to reflect these changes immediately. Of course, this solutions would have worked really well, but i did not like the way how this solution works.

In this blog i am going to describe why i decided to use eclipse databinding and show some code.

The UI model

RedVoodo offers a functionality called scoped actions and menu items. See post redvoodo-scoped-actions-and-menu-items

Based on this feature actions and menu items are hidden if they are not in the scope of the active framework or sub application. For instance, an action called “delete Item” will only be visible in the “Item Subapplication” but will be hidden for the “Customer Supapplication”. These actions and menu items have “subapplication scope” which means, that they are only visible if a defined sub application is active. But there are also “framework scoped” actions and menu items. Their visibilty depends on the active framework like Sales, Inventory,…

If you want to write an application which tracks the currently active subapplication or framework, perhaps you have to write tons of code if the underlying UI model has a deep structure.

This class diagram shows a simplified version of the redVoodo UI model. The root element of the model is called YUiModel. It can contain exactly one YApplication which is an abstraction of the vaadin application. The YApplication contains many YFrameworks (like Sales, Inventory,…), but only one YFramework can be active at a time. Based on the active framework, different sub applications are shown. So each framework has its own set of YSubapplications. For instance, the framework sales could contain sub applications like Customers, SalesCampains,…

The application, each framework and each sub application can contain their own set of actions. Depending on the active framework and the active sub application, different actions should be visible at the UI.

This image shows what i am talking about:

If the sales framework or a different sub application would be selected, completely different actions and menu items would be shown.

The model shown above is an EMF model. But since redVoodo should be a very extendable framework, using EMF is the default implementation. The core of redVoodo does not have any dependency to EMF. Instead it has a dependency to model controllers. These controllers are called edit parts. The UI parts like the “framework switcher” or the “sub application tree” are using these edit parts to visualize the model but do not have a dependency to the underlying model. So everybody can easily change the default implementation and provide edit parts that are based on a JPA implementation or edit parts that are even hardcoded.

The problem

Yesterday i started to write a lot of code to observe the ui model. I had to fetch the RootModelEditPart which represents YUiModel.

  • I registered a listener at the RootModelEditPart which will be notified if the active application changes.
  • Then i implemented the same issue for the active application and added a listener to the active application which becomes notified if the active framework changes.
  • Then i added a listener to the active framework which becomes notified if the active subapplication changes.
  • Then i added a listener that becomes notified if actions are added or removed.
  • Then i started to handle many different constellations based on parts that become active and deactive.
    • Remove listener from the lower containment structure
    • Switch the parent
    • Add the listener again to the lower contaiment structure
  • Then i detected that each UI part has a different behaviour to the observables. The SubApplicationTabBar has to observe the OpenSupApplications-reference from YFramework too.
  • Then, at 10 p.m. i thought -> Hmmmmmmmmmm, what a boring job!

After a sleepless night, i took all the controller implementations and put it to trash since eclipse databinding can do all that stuff for me. I can heavily reduce the amount of required code and safe a lot of time.

The (really easy) solution

// 1. define a nested property
// 1. define a nested property
String nestedProperties =
 "application.activeFramework.activeSubapplication.actions";

// 2. create the observable model value
IObservableValue modelOV = BeansObservables.observeDetailValue(
	new WritableValue(rootModel, IRootEditPart.class),
	nestedProperties, ISubapplicationEditPart.class);

// 3. create the observable target value
IObservableValue targetOV = PojoObservables.observeValue(
	ActionbarPart.this, "subapplicationActions");

// 4. bind model to target
subapplicationActionsBinding = dbContext.bindValue(targetOV,
  modelOV, new UpdateValueStrategy(
	UpdateValueStrategy.POLICY_NEVER),
  new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)
	.setConverter(new NotNullConverter()));

1. define a nested property

This nested property will be splitted by the “.” and the reference path starting at the IRootEditPart will be followed for each property.

// "application.activeFramework.activeSubapplication.actions"
// "application.activeFramework.activeSubapplication.actions"
// can be visualized as:
rootModel
	.getApplication()
	.getActiveFramework()
	.getActiveSubapplication()
	.getActions()

The property “actions” inside the “activeSubapplication” will be observed. Every time it changes – nevertheless why it changes (due to a change of active framework or something) – we are becoming notified.

So we do not have to implement that boring listener hierarchy as described under “the problem”.

2. create the observable model value

Creates an IObservableValue which represents the “actions” property inside the “activeSubapplication” inside the “activeFramework” inside the “application”

3. create the observable target value

Addresses the property “subapplicationActions” of this instance (ActionbarPart.this). Every time the “actions” from “activeSubapplication” changes, the setter this#setSubapplicationActions(IActionEditPart editPart) should be invoked.

4. bind model to target

Therefore the DatabindingContext is used to bind the ObservableValues (model and target) to each other.

And here you can see the implementation of the setSubapplicationActions-method. It stores the subapplicationActions and puts it to the UI.

/**
 * Sets the list of subapplication actions.

 * Called by databinding.
 *
 * @param subapplicationActions
 *            the subapplicationActions to set
 */
public void setSubapplicationActions(
		List subapplicationActions) {
	internalSetSubapplicationActions(subapplicationActions);

	toUI_subapplications();
}

That’s all i had to write to observe a nested property inside my model tree.

I hope you can see the big advantage of eclipse databinding too and hope you give it a try.

Additional informations

Eclipse databinding
redVoodo.org
vaadin.com

redVoodo – scoped actions and menu items

June 27, 2011

As described in my last post, redVoodo is a project which target is to provide an environment that supports a developer to write business applications on a very quickly and easy way. A lot of base functions like selection support, lookups,… should be provided by the framework itself.

Also the scoping of actions and menu items should be handled by redVoodo and no additional code should be required for this issue.

Scoping of actions and menu items means, that only actions and menu items that are in the scope of an active ui part should be visible. If the active ui part changes, also the visible actions and menu items should be adjusted to the current active part. In order to avoid confusion of users it is good practice to hide actions which are not required right now.

This image shows what i am talking about. The “purchasing (scoped) actions” and the “purchasing (scoped) menu items” are only visible if the purchasing framework is active.

For instance, if the inventory framework is active, no scoped actions and menu items are available. See next image.

Of course, scoping is not limited to frameworks. Also active applications can cause actions and menu items to become visible.

Implementation

My current solution is well grounded and based on EMF (eclipse modeling framework). The ui is abstracted by an EMF metamodel. Instances of this metamodel (ui models based on this metamodel) are used by the core runtime to build the ui. States like active framework, active subapplication, open subapplications,… are stored in this model.

Additionally a “selection support OSGi service” was implemented. Ui parts are using the selection support to observe active ui model controller like “active framework controller” and “active sub application controller”. Based on the selections and the ui EMF model the parts are adjusting the actions and menu parts.

Since the ui is based on an EMF model I am going to write a Xtext grammar in a few week which allows the developer to define the ui model on a very very comfortable way.

Further it should be also possible to use the redVoodo Xtext grammar to change the ui during runtime.

  • open an redVoodo grammar editor in eclipse
  • connect to a running OSGi server
  • open the currently used ui model
  • modify the ui at runtime
  • changes are immediatelly pushed to the ui

This implementation is a well grounded default. But since redVoodo offers a really extendable API everybody can easily write its own implementation.

The sourcecode will be available in about 2 – 4 weeks.

Movie

I have prepared a movie which shows how actions and menu items are hidden and showed again based on an active ui part. I hope you enjoy the movie.
Direct link to the movie:

http://vimeo.com/channels/redvoodo#25664283

Additional information

If you are interested in redVoodo just follow our blogs and website.

ekkescorner.wordpress.com

redVoodo.org

redVoodo EOS – early results

June 9, 2011

I am very happy to present the early results of redVoodo EOS.

EOS is a independent part / component of redVoodo.

It will become a project which offers a lot of base functionality for web based business applications like ui layouting, selection support, business drag and drop, multi tab enablement and many more very useful features. It will be highly extendable by the use of OSGi services and can be customized to any requirements.

Today i finished some very important steps.

  • Selection support
  • Multi browser tab functionality
  • UI elements contribution services
  • Active part set management
  • ICEPush for many browser tabs

Right now some basic ui element prototypes like a framework switcher have been finished. It is provided by an OSGi service which can be stopped and started at runtime. Stopping a bundle means, that the ui element is removed from the available elements immediately. Starting the bundle provides the element to EOS again.

Additionally the state of the ui elements is completely decoupled from the ui and is stored in an EMF (Eclipse modeling framework) model. So the state can be restored every time an “ui element contribution OSGi service” like the “framework switcher” is started.

But you can store the state in your preferred way. EMF is only a default implementation –> redVoodos basic statement “convention over configuration”.

Movie

I hope you enjoy this movie which demonstrates the result of starting and stopping bundles and restoring ui states.
Direct link to the movie:

http://vimeo.com/channels/redvoodo#24881893

Additional information

If you are interested in redVoodo just follow our blogs and website.

ekkescorner.wordpress.com

redVoodo.org

User scoped OSGi services

June 1, 2011

This post describes a possible way to handle and access stateful user scoped OSGi services in an vaadin environment. Of course, we would like to use the powerful dynamics provided by OSGi DS (declarative services). The provided classes and services should be highly extendable and it should be really easy to change the behaviour of the system.

But if you are dealing with user sessions you have to ensure, that some of the used services are session or user based. Which means, that exactly one service instance per user session or user exists. If you want to affect the instantiation process of OSGi services, you have to deal with ComponentFactories.

A ComponentFactory gives you the opportunity to create many instances of the same service with different properties. So we have a tooling to do exactly what we want to do.

But what kind of architecture would be the best one? For the last two weeks i tried different approaches and I’d like to present that one i like most.

To keeps things simple, i am going create a “shopping cart” example. Each user should have it’s own shopping cart associated by its user id. Many web sessions can share one shopping cart for one user id.

Defining the service

So lets start.
I am going to prepare an interface for the shopping cart which should be provided as an user scoped service.

IShoppingCart

public interface IShoppingCart {

/**
* Returns the user id this cart is responsible for.
*
* @return
*/
String getUserid();

/**
* Adds an item to the shopping cart.
*
* @param item
*/
void addItem(IItem item);

/**
* Returns the total value in the base currency of the user.
*
* @return
*/
float getTotalValue();

}

ShoppingCart implementation

In the next step i am creating an implementation for that interface and provide it as a “Component Factory Service”.

public class ShoppingCart implements IShoppingCart {

private String userId;

/**
* Called by OSGi DS on service activate
*/
void startup(Map<String, Object> properties) {
userId = (String) properties.get("userId");
}

@Override
public String getUserid() {
return userId;
}

@Override
public void addItem(IItem item) {
// to be implemented
}

@Override
public float getTotalValue() {
// to be implemented
return 0;
}

}

Component Factory Definition

As explained above, i am going to create a ComponentFactory which is used to create many instances of that service.

Since the created IShoppingCart service will be associated with an user id, i am adding a property called user id to service definition.

Attention: This property will be changed before the session based service is created. So i gave it a value called “ToBeDefinedAtRuntime” which should visualize that this property exists, but its value has to be redefined.

The xml tag “activate” from the ComponentFactoryDefinition targets a method called startup. This method will be called after the session based service has been created. As an argument the properties which have been used to create that service are passed. And for sure, these properties are containing the user id of the user this shopping cart is associated with.

Writing a scoped service manager

Well, we have created a shopping cart service and a component factory definition. But for sure, we want to access our shopping cart instance by user id. If an instance for a given user id exists, we want to reuse it. Otherwise we prepare a new instance of the shopping cart service and configure it with the user id property.

IShoppingCartManager

So let’s write a ShoppingCartManager. This manager is an OSGi service and we use it to cache all created shopping cart services. This manager offers a method to access a shopping cart by an user id and a method to dispose the created service.

public interface IShoppingCartManager {

/**
* Returns a shopping cart for the user.
*
* @param userId
* @return
*/
IShoppingCart getShoppingCart(String userId);

/**
* Has to be called if the shopping cart should
* be destroyed. For instance if the user
* account was deleted.
*
* @param userId
*/
void disposeCart(String userId);

}

ShoppingCartManager implementation

public class ShoppingCartManager implements IShoppingCartManager {

private ComponentFactory factory;
private Map<String, ComponentInstance> shoppingCarts =
      Collections.synchronizedMap(
      new HashMap<String, ComponentInstance>());

/**
* Called by OSGi DS
*
* @param factory
*/
void bindShoppingCartFactory(ComponentFactory factory) {
     this.factory = factory;
}

/**
* Called by OSGi DS
*
* @param factory
*/
void unbindShoppingCartFactory(ComponentFactory factory) {
     this.factory = null;
}

@Override
public IShoppingCart getShoppingCart(String userId) {
    if (!shoppingCarts.containsKey(userId)) {
    // create a new instance
    //
    shoppingCarts.put(userId,
    newInstance(userId));
}

    // return the instance
    //
    ComponentInstance instance =
       shoppingCarts.get(userId);
    return (IShoppingCart) instance.getInstance();
}

private ComponentInstance newInstance(String userId) {
    // create properties with user id
    //
    Hashtable<String, Object> properties =
       new Hashtable<String, Object>();
       properties.put("userId", userId);

    // create a new instance
    //
    ComponentInstance instance =
      factory.newInstance(properties);
    return instance;
}

@Override
public void disposeCart(String userId) {
    if (shoppingCarts.containsKey(userId)) {
      ComponentInstance instance =
        shoppingCarts.remove(userId);
      instance.dispose();
     }
}
}

ShoppingCartManager service definition

And the service component definition.

How does it work?

The following images show you how this manager uses the component factory to create new instance of the shopping cart service.

Summary

So far we have prepared a service and a service manager.

  • The services for the shopping carts are
    • scoped by user id
    • cached by the shopping cart service manager
  • The manager allows you to access the cached services by the user id
  • If no service exists yet, the manager creates a new instance configured with the user id

Consume the service

The last thing you have to do, is to use the service manager inside your code.

public class MyService implements IMyService {

/**
* Called by OSGi DS
*
* @param manager
*/
@SuppressWarnings("unused")
void bindShoppingCartManager(IShoppingCartManager manager) {
  IShoppingCart cart1 = manager.getShoppingCart("user1");
  IShoppingCart cart2 = manager.getShoppingCart("user2");
}

/**
* Called by OSGi DS
*
* @param manager
*/
void unbindShoppingCartManager(IShoppingCartManager manager) {

}
}

Service Overview

This image shows an overview about the services created above and their relations.

Conclusion

If you have any suggestions please let me know. Any comments are highly welcome.

Something you can’t do with ComponentFactories

May 26, 2011

About 2 weeks ago i started to implement the main architecture of EOS which is a subproject based on redVoodo. The main goal is to provide a very flexible and extendable base implementation for business applications. Based on OSGi DS (declarative services) i started to design my application. I decided to use ComponentFactories to create different instances of the same interface / class. For instance this is necessary to provide web session based classes like an ApplicationContext with application scope. I was suppressed how powerful OSGi services are. But then i recognized, that i have used ComponentFactory a way they are not intended to be used. See http://www.eclipse.org/forums/index.php/t/209483/

This post should explain the problems i faced during the implementation of EOS. Therefore i have prepared a simple example based on “shapes”. A IShapeFactory provides instances of IShapes for different types (circle, square,…). Implementations of IShapes are provided by ComponentFactories. These componenteFactories are required by the shapeFactory.

Class dependencies

This image shows the dependencies between the classes involved and their function.

ShapeFactory

public interface IShapeFactory {

/**
* Creates a new shape for the given type or <code>null</code> if no shape
* is registered for the type.
*
* @param type
* @return
*/
IShape createNewShape(String type);

}

Based on the shape factory several new instances of a shape can be created. Since the architecture of this factory is extendable, the type should be specified by a property (study1.shapeType) in the OSGi component definition of the IShape component factory. The component factories are registered at the shapeFactory by the OSGi DS (declarative service) framework.

If createNewShape is called, the factory tries to find a component factory which is responsible for the given type and uses this factory to create a new instance of IShape.

IShape

public interface IShape {

/**
* Calling this method will paint the
* content of that shape instance.
*/
void paint();

}

Instances of IShape are used to paint the shape defined by the implementation. For instance it paints a circle or a square or something else.
Since each visualized shape is a new instance of the IShape interface, i decided to use a ComponentFactory which provides new instances of that interface. How this works will be described later.

A really nice way, which allows the new instantiated components to use OSGi “declarative services” as well. If we would instantiate the shapes with “new SomeShape()”, that classes can not use DS since they are not defined by a service component definition. But since we are using ComponentFactories the IColorProvider from image above could also be defined as a required service for the class Circle. That’s the BIG advantage using ComponentFactories.

Service dependencies

This image shows the service dependencies.

org.redvoodo.osgi.study1.services

This bundle contains all service interfaces. The ComponentFactory rectangle in the image above is only displayed there to make the visualization much clearer. So it is not really contained in that bundle.

org.redvoodo.osgi.componentfactory.shape

This bundle contains 2 IShape implementations. Square and Circle. Instead of providing the IShape interface, it provides a ComponentFactory service which can be used to create new instances of the IShape implementation.

The really important entries in that service component definition are:

factory="study1.shapesfactory"

Defines the service component as a component factory.

property name="study1.shapeType" type="String" value="circle"

Adds a shape type property to the component definition. The shapeFactory should use this property to identify the type of the shape which is provided by the component factory.

org.redvoodo.osgi.componentfactory.factory

It provides the IShapeFactory service and contains an implementation of ShapeFactory. The ShapeFactory requires 0:n “ComponentFactories providing IShape”.

If a ComponentFactory was added (addShapeComponentFactory), the passed properties will be used to determine the type of the shape that is provided by the component factory. And the component factory is registered in an internal map.

If a ComponentFactory was removed, it will be removed from the internal map by its type.

If createNewShape(String) is called, the factory registered by the given type will be used to create a new instance of the shape. If no registered factory could be found, null will be returned.

public class ShapeFactoryImpl implements IShapeFactory {

private Map<String, ComponentFactory> factories
= new HashMap<String, ComponentFactory>();

/**
* Called by OSGi
*
* @param shapeFactory
* @param properties
*/
protected void addShapeComponentFactory(
     ComponentFactory shapeFactory,
     Map<String, Object> properties) {

     String type = (String)
       properties.get("study1.shapeType");
     factories.put(type, shapeFactory);
}

/**
* Called by OSGi
*
* @param shapeFactory
* @param properties
*/
protected void removeShapeComponentFactory(
     ComponentFactory shapeFactory,
     Map<String, Object> properties) {

     String type = (String)
       properties.get("study1.shapeType");
     factories.remove(type);
}

@Override
public IShape createNewShape(String type) {
     IShape result = null;
     if (factories.containsKey(type)) {
        ComponentFactory factory =
          factories.get(type);
        result = (IShape) factory
          .newInstance(null).getInstance();
        // for normal you should also
       // handle the lifecycle of
       // ComponentInstance
     }
  return result;
}

Conclusion

After finishing this implementation i was really suppressed. Really suppressed that nothing happend! My architecture did not work at all.

But what is the problem? Well, the problem was, that i did not know some issues about ComponentFactories. So i asked at the newsgroup (equinox newsgroup) an got following answer:

BJ Hargrave

DS spec. From 112.2.4 Factory Component:

SCR must register a Component Factory service on behalf of the component as soon as the component factory is satisfied. The service properties must be:

* component.name The name of the component.
* component.factory The factory identifier.

The service properties of the Component Factory service must not include the component properties.

The error

Now i know why this kind of architecture does not work.

I assumed, that the properties specified in the service component definition of the ComponentFactory are passed as properties to the instance of the ComponentFactory. But, as DS spec. about Factory Components describes, only the properties component.name and component.factory are passed to the service. So the ShapeFactory could not determine the type the ComponentFactory is responsible for!

This property is not accessible for the component factory service!

And so the type will always be null.

The solution

Currently i am working on a nested component factory solution. It uses a service which provides some kind of IFactory. Implementations of the IFactory are using nested ComponentFactories to avoid the instantiation by new().

The solution should be probably finished next week. Then i am writing a new post about it.

If you have any suggestions feel free to post a comment. Any input is welcome!

Eclipse Democamp Vienna Flyers Indigo 2011

May 20, 2011

Flyers democamp indigo 2011

To promote the eclipse democamp indigo in vienna, daria motamedi sponsored the design of flyers. Yesterday we could send them to the printing shop. In about 4 days they should be ready for shipment.

I think that they became really nice. Thanks a lot to daria.

and stickers

Of course we have stickers for all attendees too. We have printed 250 pieces. So i think we should have enough.

If you would like to attend, follow this link to the eclipse demo website.

Vaadin OSGi ICEPush Services

May 8, 2011

1. Introduction

About 4 years ago i started working with OSGi, but this is the first project i am using declarative OSGi services. The concept of OSGI allows to build very extendable and loose coupled software environments. In particular the use of OSGI-services is very important to create some kind of plugin architecture which allows to provide functionality on a very flexible way.

OSGi and vaadin

So far web applications did not support these concepts very well. Some time ago Chris Brind, Neil Bartlett and Peter Kriens have written different vaadin OSGi integrations which make it possible to run vaadin inside an OSGi container. (See blog from Chris Brind: Comparing approaches to vaadin and OSGi)

Vaadin is a framework to build web applications based on java code. It uses GWT (google web toolkit) to render the UI elements and offers serversided counterparts to the client UI widgets. A really amazing framework to build high level web UIs.

Kai Tödters vaadin demo app

The vaadin OSGi implementation from Chris Brind was used by Kai Toedter to write his amazing vaadin application based on OSGI-services. Using the “whiteboard pattern”, OSGi-services that are used to provide UI elements like Actions and Components are injected into the com.vaadin.Application. With this approach Kai could build a very loose coupled application environment. The UI elements “contributed” to the application depend on the installed and started OSGi-bundles.

Basically Kai’s vaadin application can be divided into two different parts:

  1. The main bundle with its main application that requires OSGi-services to build the UI.
  2. Contributor bundles providing services required by the main application.

The main bundle defines the layout of the main application but there is no knowledge about the exact content of the application involved. The content is provided by “contributor bundles” and may contain Actions, Buttons or Views as some kind of vaadin.Component.

This image displays Kai’s demo application. All shown bundles contain OSGi-services that are used to access the UI-elements. As an example the red arrows are pointing to the provided UI elements.

The next image gives you a summary about the bundle dependencies. To keep things simple, we only consider the IViewContribution service. IActionContribution works nearly the same way.

The main bundle requires IViewContribution services which offer access to the UI elements that should be added to the user interface. The interface IViewContribution will be implemented by classes located in different bundles. The OSGi-service-component-runtime observes starting and stopping bundles and injects the upcomming services into the bound MainApplication. Bindings are defined in the service component definition.

Service component definition:
com.siemens.ct.osgi.vaadin.pm.main/META-INF/vaadinMain.xml

Contribution to Kai’s demo application

At the end of this blog i am going to tell you, how applications can be push enabled automagically. All you have to do is to install and start a couple of bundles and all vaadin applications have the capability to become pushed.

Therefore we have to enhance Kai’s application by a provided interface called IApplicationProvider.

public interface IApplicationProvider {

/**
* Returns the provided application.
*
* @return
*/
Application getApplication();

}

That interface returns an instance of the application associated with this applicationProvider.

Additionally we let Kai’s application implement that interface and return “this” as the reference.

public class MainApplication extends Application implements
IApplicationProvider {

@Override
public Application getApplication() {
return this;
}

No we are going to provide the MainApplication.class as an OSGi-service for the interface IApplicationProvider.

Each time a new application was created by the component factory, then service components which reference this interface will be called.

2. Services come and services go

Before i start writing about the vaadin osgi push service, i’d like to talk about the flexibility of OSGi-services.

People already using OSGi know that bundles have a lifecycle. They can become installed, started, stopped,… into a running OSGi container without the requirement of restarting the container. A very flexible way of providing functionality.

Of course, if a bundle contains OSGI-services and the bundle was started a new service is offered by the framework. If the bundle becomes stopped, the service will be deregistered from the OSGi-runtime. It would be good practice to handle this flexibility inside your applications if you are using OSGi-services. Of course you can assume that services are static, but if you don’t so, then your application should be designed to handle the lifecycle of bundles.

Referring to Kai’s application this would imply that stopping a service bundle (a yellow one from image above) will remove all UI contributions like actions, menu bar actions and views associated with this bundle from the UI. You can use Kai’s “bundle view” to demo this issue.

Stopping or starting a bundle like “com.siemens.ct.osgi.vaadin.pm.printaction” will remove a service from the main application which reflects the changes immediatly and updates the UI. The menu bar action and the button “print” will be removed.

OSGi management console

Kai used the client UI of his application to control the lifecycle of bundles, but OSGi offers another way. You can use the OSGi management console. The commands “start bundleNumber” and “stop bundlenumber” will start and stop these bundles.

But if you are using the management console with Kai’s application, a starting or stopping bundle will not update the UI immediately since the server cannot notify the UI about this change! So you have to wait for the next UI refresh until the client UI has reflected the stopped bundle.

This image displays the problem using the management console to control the lifecycle of bundles. If a bundle becomes stopped, the serversided components get a dirtyState, which cannot be pushed to the client!

The changes will be transfered to the client at the next client UI refresh. Since vaadin clients are not pushable without using any addons, the server cannot inform the client about changes.

But vaadin offers an addon called ICEPush. ICEPush allows the client UI to be notified by the server on changes. A really helpful addon which perfectly matches the requirements described above.

3. Details about the implementation

This chapter of my post gives you an introduction how i have implemented ICEPush using the vaadin OSGi integration from Chris Brind.

Main goal was to provide bundles which enable the ICEPush addon and the “vaadin OSGi ” addon at the same time. And to push changes from the server the client UI in OSGi environments.

Main issue

ICEPush and vaadin-OSGi both provide their own servlet.

  • ICEPushServlet is responsible to serve the ICEPush javascript code and to handle requests ending with “.icepush”
  • VaadinOSGiServlet is responsible to create a new instance of com.vaadin.Application based on an OSGi-ComponentFactory

Servlet

Since exactly one servlet is required for my issue i decided to merge the contents of both servlets and to create a new one called ICEPushVaadinOSGiServlet. Luckily both implementations are based on the “Apache License 2.0″ license and so it was legal to combine them.

The ICEPushVaadinOSGiServlet offers a compound functionality as ICEPushServlet and VaadinOSGIServlet do.

This code displays a stub of the new servlet class. At the beginning of the method stub you can see where is it original from.

/**
* Merges org.vaadin.osgi.VaadinOSGiServlet (vaadins osgi addon) and
* {@link org.vaadin.artur.icepush.ICEPushServlet} (vaadins icePush addon).
*/
public class ICEPushVaadinOSGiServlet extends AbstractApplicationServlet {

// from org.vaadin.osgi.VaadinOSGiServlet
@Override
protected Class<? extends Application> getApplicationClass()
throws ClassNotFoundException {
return Application.class;
}

// from org.vaadin.osgi.VaadinOSGiServlet
@Override
protected Application getNewApplication(HttpServletRequest request)
throws ServletException {
// ...
}

@Override
// from org.vaadin.artur.icepush.ICEPushServlet
public void init(ServletConfig servletConfig) throws ServletException {
// ...
}

@Override
// from org.vaadin.artur.icepush.ICEPushServlet
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// ...
}

/**
* Sends the ICEPush javascript code to the client.<br>
* from org.vaadin.artur.icepush.ICEPushServlet
*
* @param request
* @param response
* @throws IOException
*/
private void serveIcePushCode(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// ...
}

/**
* Track the component instance and session. If this is disposed the entire
* associated http session is also disposed.<br>
*
* from org.vaadin.osgi.VaadinOSGiServlet
*/
class VaadinSession {
// ...
}
}

VaadinOSGiApplicationManager

The VaadinOSGiApplicationManager is the main class of the vaadin OSGi integration. It runs as an OSGi component and is responsible to create and register a servlet at the http service. In the org.vaadin implementation the VaadinOSGiServlet is used.

I  enhanced this manager and added a required OSGi-service (interface == IServletFactory ) which provides a HttpServlet. With this approach the used servlet is very loose coupled and can be provided by OSGi-services. The service has to provide an implementation of the IServletFactory which creates new instances from a http servlet.

/**
* A factory provided by OSGI-Services to contribute servlets.
*/
public interface IServletFactory {

/**
* Returns a servlet to be used by the {@link VaadinOSGiApplicationManager}.
*
* @param factory
*            which has create the {@link Application}
* @param servletpath
*            which is used to register the servlet
* @param initialProperties
*            Properties registered against the component factory.
* @return
*/
HttpServlet createServlet(ComponentFactory factory, String servletpath,
Map<String, Object> initialProperties);

}

4. Vaadin OSGi Push Addon bundles

The original VaadinOSGiApplicationManager was copied since i did not want to change the “none pushing osgi vaadin” implementation from Chris Brind and have created a new bundle called org.vaadin.pushosgi.

This bundle is replacing the org.vaadin.osgi bundle and contains the VaadinOSGiApplicationManager including the extended IServletFactory functionality.

As you can see, no servlets are contained in the bundle. Since the servlets are provided by OSGi-services, they are defined in different bundles.

The next image displays two servlet contributor bundles which offer OSGi-services.

With this approach you only have to decide which servlet should be used and to install the prefered bundle into the target platform. No further steps are required. The dependencies between the OSGi bundles and services will be resolved by the OSGi framework and the installed servlet will be used automatically.

That image displays a summary about the bundles involved.

ICEPush implementation

If you are using the ICEPush addon by Artur Signell you have to install the ICEPush addon. It is divided into a server side and a client UI part.

Serverside

All required java code for the server side is contained in the bundle “org.redvoodo.vaadin.addon.icepush“. No changes have been made to the sourcecode. Just an OSGi-bundle has been created from the ICEPush-jar-files.

Client UI

Using vaadin all client side addons have to be compiled at once. The resulting widgetset has to be provided as described in redvoodo.org. The example from this post uses the widgetset from bundle-fragment “org.redvoodo.extension.ct.osgi.widgetset.fragment“.

The widgetset has been speficied in the launch configuration:

-Dorg.redvoodo.addon.osgi.push.servlet.widgetset=
org.redvoodo.extension.ct.osgi.pushosgi.widgetset.PushosgiWidgetset

Minimal bundle requirement

If you want to use the vaadin OSGi ICEPush, you have to install a minimal set of bundles:

  • org.vaadin.pushosgi – the main bundle which contains VaadinOSGiApplicationManager
  • org.redvoodo.addon.osgi.push.servlet – provides the ICEPushVaadinOSGiServlet
  • org.redvoodo.vaadin.addon.icepush – server side java classes from ICEPush
  • some fragment bundle like org.redvoodo.extension.ct.osgi.widgetset.fragment containing the compiled widgetset

Thats all you have to add to your OSGi launch configuration to have a properly configured “vaadin OSGi pushable application”.

But there is no further support. You have to handle the ICEPush yourself.

pusher = new ICEPush();
application.getMainWindow().addComponent(pusher);

// doing the push
pusher.push();

Demo

This movie demos what i was writing about so far:

5. redVoodo Push Services

So far you can use ICEPush in vaadin OSGi applications. But there is no further support for some kind of “OSGi push services”.

Therefore i have prepared a set of very flexible and loose coupled bundles which offer “OSGi push services” and help you to manage your pushing applications.

Bundles:

  • org.redvoodo.addon.osgi.push.services – The service interface definition
  • org.redvoodo.addon.osgi.push.services.impl.service – Provides default implementation for IPushService
  • org.redvoodo.addon.osgi.push.services.impl.manager – Provides default implementation for IPushServiceManager
  • org.redvoodo.addon.osgi.push.services.impl.managed.pusher – Provides default implementation for IManagedPusher
  • org.redvoodo.addon.osgi.push.services.application.bridge – The queen of this addon. Bridges IApplicationProvider and IManagedPusher

org.redvoodo.addon.osgi.push.services

Lets start with the service interfaces:

The main interfaces of these services are IPusher and IPushService:

public interface IPusher {

/**
* Forces a push to the client. If the pusher is not active, a call to
* this method must not result in an error.
*
* @return true if the push was successful. False otherwise. If the pusher
*         was not active, false will be returned.
*/
boolean push();

/**
* Returns the application the pusher is prepared for. Or <code>null</code>
* if the pusher is a compound pusher which pushes several applications.
*
* @return
*/
Application getApplication();

}

The IPusher is responsible to push changes to the client. Each pusher is associated with exactly one Application.

/**
* A push service is used to notify the client, that it should refresh its
* state.
*/
public interface IPushService {

/**
* Activates the push functionality for the given application and ensures,
* that the pusher for this application can be accessed by this service.<br>
* The acitvated pusher will be stored in this service until deactivate
* pusher is called.
*
* @param application
* @return
*/
IPusher activatePusher(Application application);

/**
* Deactivates the push functionality for the given application. Further
* calls to a pusher associated with this application will result in an
* error.
*
* @param application
* @return
*/
void deactivatePusher(Application application);

/**
* Deactivates the push functionality for the application associated with
* the given pusher. Further calls to pusher associated with this
* application will result in an error.
*
* @param application
* @return
*/
void deactivatePusher(IPusher pusher);

/**
* Returns a pusher which pushes all applications that are registered within
* this pushService.
*
* @return
*/
IPusher getGlobalPusher();

/**
* Returns a pusher for the given application.
*
* @param application
* @return
*/
IPusher getPusher(Application application);

/**
* Returns a compound pusher based on the scope. The scope allows to collect
* pushers which are registered within this pushService.
*
* @param scope
* @return
*/
IPusher getPusher(IScope scope);

/**
* Scope is used to create a compound pusher based on other pushers.
*/
public static interface IScope {

/**
* Returns a compound pusher which delegates the push call to the
* contained pusher.
*
* @param pushers
* @return
*/
IPusher getPusher(Map<Application, IPusher> pushers);

}
}

The IPushService is responsible to activate and deactivate pusher for their associated Application and to access them.

Since IPushService is an OSGi-service, you have to handle the lifecycle of that service. See chapter “services come and services go”.

org.redvoodo.addon.osgi.push.services.application

ATTENTION: Bundle was removed with 0.7.2. Was not an OSGi like approach.

org.redvoodo.addon.osgi.push.services.impl.service

ATTENTION: In Version 0.7.1 this bundle was named

org.redvoodo.addon.osgi.push.services.impl

This image is a summary about the service and its default implementation.

The bundle org.redvoodo.addon.osgi.push.services.impl.service can be used as a default implementation of the push service. But you can write your own implementation and provide it as a service.

org.redvoodo.addon.osgi.push.services.impl.manager

Was added with 0.7.2

The image shows a summary and the default implementation of the IPushServiceManager. The PushServiceManager is responsible to manage IPushServices. It allows clients to register listener and to observe the services and their lifecycle.

The bundle org.redvoodo.addon.osgi.push.services.impl.manager can be used as a default implementation of the IPushServiceManager. But you can write your own implementation and provide it as a service.

org.redvoodo.addon.osgi.push.services.impl.managed.pusher

Was added with 0.7.2

To hide the lifecycle of IPushService and IPushServiceManager, i have prepared an interface which describes some kind of a helper class.

IManagedPusher.class

It internally uses the IPushServiceManager and IPushService, but hides the lifecycle handling from the developer. If services come and services go, the ManagedPusher does not have to be refreshed externally. All the refreshing stuff is handled internally.

A very useful class to minimize the amount of effort required to use the redVoodo push services.

The component factory can be required as any OSGi-service. But you have to specify the target of the requirement.

(component.factory=org.redvoodo.addon.osgi.push.services.managed.pusher)

Code samples how to use the service:

/**
* Called by the OSGi framework
*/
public void bindManagedPusherFactory(ComponentFactory pusherFactory,
Map<String, Object> properties) {
      this.pusherFactory = pusherFactory;
}

/**
* Called by the OSGi framework
*/
public void unbindManagedPusherFactory(ComponentFactory factory,
Map<String, Object> properties) {
      this.pusherFactory = null;
}

// to create a new pusher
IManagedPusher pusher = (IManagedPusher) pusherFactory.
newInstance(null).getInstance();
pusher.setup(application);
pusher.pushToClient();

// to dispose the pusher
pusher.dispose();

For details how to use see class

org.redvoodo.addon.osgi.push.services.application.bridge.ApplicationPusherBridge

org.redvoodo.addon.osgi.push.services.application.bridge

This bundle is a really important bundle for the vaadin OSGi push services addon. It bridges the IApplicationProvider and the IManagedPusher. Installing this bundle into the target platform will automatically enable push for all applications provided by IApplicationProvider.

The org.redvoodo.addon.osgi.push.services.application.bridge bundle requires the IApplicationProvider OSGi-Service. Each time a new application was created by the component factory, the service component will be notified about the new application and uses the ComponentFactory to create an instance of IManagedPusher. The managed pusher itself handles the registration at the IPushService. If the application is destroyed the service component will also be notified and the pusher for the destroyed application will be removed.

Additionally this class requires the componentFactory-service. If a new ComponentFactory for IManagedPusher became available, the class will handle this notification. If no factory was installed yet, nor of the applications are push enabled. But an upcoming component factory service causes the bridge to create new instances of IManagedPusher for each application. And so all applications become push enabled.

Referring to Kai’s demo application, only one change had to be made to his application. The IApplicationProvider was added to the vaadin.xml compontent definition as a provided service. But his application does not have any dependency to the redVoodo push services. Immediately after the instantiation of an application by a component factory, the application becomes push enabled automatically.

The push to Kai’s application is triggered by the bundle “org.redvoodo.extension.ct.osgi.observer” (All org.redvoodo.extension.ct.osgi bundles are extensions of Kai’s application). Since this bundle requires the IPushServiceManager service, it has access to all registered push enabled applications and can use that service to push all applications. (Remember: The applications have been registered at the pushService by the ManagedPusher above).

String symbolicName = event.getBundle().getSymbolicName();
if ((symbolicName.startsWith("com.siemens.ct.osgi.vaadin.pm")
|| symbolicName.startsWith("com.siemens.ct.pm.model."))
&& !((symbolicName.contains("main")
|| symbolicName.contains("theme")
|| symbolicName.contains("bundleview")
|| symbolicName.contains("logback")))) {
       // push all registered clients
       serviceManager.getPushService().getGlobalPusher().push();
}

If a bundle becomes started or stopped, the bundleChanged event will be called. For specified bundles the AppPusherPlugin#pushAll() method will be called, which pushed all dirty states to the client.

How to use push services

There are several ways how redVoodo push services can be used.

Require a service

Require a service like IPushServiceManger, IPushService or IManagedPusher. Depends what the service will be used for.

Use the default implementations

Provided by bundles:

  • org.redvoodo.addon.osgi.push.services.impl.managed.pusher
  • org.redvoodo.addon.osgi.push.services.impl.manager
  • org.redvoodo.addon.osgi.push.services.impl.service

Write your own services

Feel free to write your own services and to provide them as a service.

Conclusion

I hope this blog post could give you an introduction about the redVoodo OSGi ICEPush services. If you have any suggestions it would be really nice if you may write a comment.

Thanks a lot to Kai Tödter, Chris Brind, Neil Bartlett and Peter Kriens for the really great available code and blog posts how vaadin OSGi integration can be implemented.

Further informations

In bed with vaadin and OSGi by Chris Brind

Dynamic modular Web Applications with Vaadin and OSGi by Kai Tödter

OSGi vaadin integration by Peter Kriens

blog by Neil Bartlett

blog by Ekkehard Gentz

redVoodo.org

how to use vaadin and OSGi from redVoodo

how to use vaadin addons from redVoodo

how to push to browser from redVoodo

Comparing approaches by Chris Brind

06 – Attributes

March 19, 2011

The way how variables are defined in Objective-C is very different to Java. Since Objective-C is dealing with pointers (see (NSString **) value) and developers have to be aware of memory management, the definition of variables is much more complicated and powerful than in Java.

1 – Java attributes

In this blog post I decided to start with the very basics based on Java.

We are deciding between two different kind of variables:

  • instance variables
  • class variables

1.1 – Instance variables

An instance variable is an attribute from a classes instance and exists for each instance. It will be initialized during the creation of the class instance. Instance variables can only be accessed by class instances and not by classes.

Instance variables are accessed like this:

SomeObject object = new SomeObject();
String value = object.value;

 

 

1.2 – Class variables

A class variable is an attribute of a class and exists exactly once by class and classloader. It will be initialized at class loading time and can be accessed by classes and class instances. All instances of a class will share this unique state of the variable. If you change the variable, it becomes changed for all instances of this class.

Class variables are accessed like this:

String value = SomeObject.value;

 

1.3 – Visibility Modifier

Java decides 4 different visibilities:

  • public – visible for all objects
  • protected – visible for all subclasses. Also visbile for classes in the same package
  • private – only visible inside the class
  • default – only visible for classes in the same package

1.4 – Final Modifier

The final modifier defines, that a variable has to be initialized once during the class loading or instance creation, but must never change.

1.4.1 – Final instance variable

 

Final instance variables are used for different behaviours. Eg to ease the handling of concurreny or to protect the state of a class.

1.4.2 – Final static variable

 

Final class variables are often used for constant definitions. “static final String” are very common to define constants.

 

2 – Objective-C attributes

In the second part of this post i am going to define the attributes defined above using Objective-C.

We are going to start with instance variables.

2.1 – Instance variables

Variables are defined in the .h interface file.

If you do not define something special, the attribute has visibility “protected”. You can use it in the .m implementation file and deal with it. Also subclasses of MyClass can access the attribute.

This image shows the attribute access in a subclass of MyClass.

See also: iphonedevelopertips.com, omnigroup.com

2.2 – Class variables

Differing to Java, Objective-C does not allow to use public / protected class variables. If variables are defined as static, they are allways private.

static NSString *anAttribute;

This variable can only be used inside of the class which defines this variable.

Another very confusing behaviour of static attributes is the fact, that they can be defined inside a method and will retain their value during subsequent calls. For instance the singleton pattern uses this very havily.

See stackoverflow.com for a similar example and a detailed description.

 

2.3 – Visibility Modifier

If the attribtue should be accessible from other classes, you have to use visibility modifiers.

Please not, that static attributes are always private.

For explanation i changed MyClass and added 3 attribtues with 3 different visibilities.

 

No i am trying to access them from

  • MyClass.m – should work for all 3 attributes
  • MySubClass.m – should work for protected and public
  • OtherClass.m – should work for public
MyClass.m

Everything is fine. No problems reported.

 

MySubClass.m

 

Private attributes can not be accessed by subclasses.

 

OtherClass.m

Since OtherClass is not a subclass of MyClass, only public attributes can be accessed. For sure, directly accessing public attributes from classes outside the typehierarchy is not good pratice! But for demonstration it is really well.

 

2.4 – Final modifier

As you could see, the visibility modifier has a very close semantic to java. But what is about the final modifier?

Actually, Objective-C does not provide a final modifier, but the keyword const (means constant).

But Const offers a much more complex semantic as final does. It allows pointers and / or values of pointers to be defined as “constant”.
“Final” only defines a constant reference which can not be changed, since java does not divide between reference and its value.

Lets compare the different possibilities:

Java

private final Char someString;

The one and only way to define the char as final using java. Final means, that the value of the attribtue can only be assigned once. (During initilization)

Objective-C
It provides 3 different combinations of the const keyword.

// Pointer to constant char
const char* someString;


// Constant Pointer to char
char* const someString;


// Constant Pointer to constant char
const char* const someString;

We are going to use a few lines of code to get a feeling what i am talking about. The following image shows the three combinations of const mentioned above.

 

  • Example 1“const char* charPtr1″ means that the pointer charPtr1 is variable, but “the data the pointer is pointing to” is const. So only the “adress the pointer points to” can be changed. The “value the pointer is pointing to” is constant.

 

  • Example 2“char* const charPtr2″ means that the pointer charPtr2 is constant, but “the data the pointer is pointing to” is variable. So only the value the pointer is pointing to” can be changed. The “adress of the pointer” is constant.

 

  • Example 3“const char* const charPtr3″ means that the pointer charPtr3 is constant, and “value the pointer is pointing to” is constant. Nor the “value or the adress” of the pointer can be changed.

How to define final variables using Objective-C?

I found  a nice discussion about this issue: See iphonedevelopertips.com

Example 1 : final instance variable

Java
public final String MY_STRING = "MyString";

Objective-C:
.h-File:
extern const NSString* const MYSTRING;

.m-File
const NSString* const MYSTRING = @"myValue";

 

Example 2 : final static variable

Since static attributes are always private, we do not have to specify anything in the header file. It is enough to specify the attribute in the implementation file.

Java
public static final String MY_STRING = "MyString";

Objective-C:
.h-File:
==> Nothing to do. static attribute is always private!

.m-File
static const NSString* const MYSTRING = @"myValue";

WordPress in google webmaster tools

March 13, 2011

How to register your blog at webmaster tools

The last hours it tried to register this wordpress blog in google webmaster tools.

After several unavailing attempts using the “Upload an HTML file to your server” option, i found a really simple solution.

Some time ago it seemed, that registering a wordpress blog at the google webmaster tooling was performed using the “Upload an HTML file to your server”. But it does not work anymore! I always got the error that the content of the website has wrong format.

The way to do

Assumed you already have a google webmaster account, i am going to explain the steps required to register a wordpress blog.

The first step is to add your site. There is nothing special.

To perform the next step, you have to select the option “Add a meta tag to your home page”. For normal you would have to paste this meta tag to the head section of your html-file.

Since we do not have access to the wordpresssite head tag, we are using a feature provided by wordpress.

Navigate to tools and paste the meta tag to the input field “Google Webmaster Tools”. Accept your input by saving the settings.

Final step – now you can return to “google webmaster tools” and verify your site. Everything should work properly and your wordpress blog had been added to the “google webmaster tools”.

05 – Protocol for Interface

March 10, 2011

Java Interface

Interfaces are used very havily inside of java applications. They allow the programmer to decouple different parts of the code and to make them independent.

Additionally they are used to define a contract which specifies methods which have to be implemented by subclasses. It is very comfortable to code against interfaces, rather than implementations.

Interface

Interface implementation

The following syntax is used to implement an interface into a class:

class MyClass implements SomeInterface

 

Objective-C Protocols

Objective-C provides a similar approach called Protocols. Protocols have a very close semantic as interfaces, but allow you to mark methods as @optional. Optional methods can be implemented by subclasses, but it is not required.

Protocols are defined by the @protocol directive.

@protocol SomeProtocol
    .... methods
@end

The SoundMachine protocol would look like this:

It’s really looks very close to the java declaration. Also the implementation class of this interface is very similar to java.

The .h file

and the .m file

 

ConformsToProtocol

If you would like to test whether a class implements a protocol you can use the conformsToProtocol message. It is similar to the instanceof check from java.

Objective-C: conformsToProtocol

Java: instanceof

 

@optional methods

In contrast to Java, Objective-C adds an additional semantic feature for protocols. Methods can be defined as optional. This means, that they do not have to be implemented by the class that implements the interface.

Java does not allow unimplemented interface methods. All the methods from an interface have to be declared in the classes type hierarchy.

The following image shows how optional methods can be implemented in Objetive-C:

If a class implements this protocol but does not add a method implementation for the optional methods, the compiler won’t mention this issue.

Therefore i have prepared an MyProtocolImpl.m class which implements MyProtocol. No methods have been implemented in the class before compiling it.

As you can see at the screenshot, the compiler only mentioned the missing required methods.

Calling an optional unimplemented method

If you are providing optional protocol methods, you have to ensure that messages are sent to these classes only if they implement the methods addressed by the message. Otherwise the call will result in an error.

The following image shows an implementation of MyProtocol. The anotherOptional-method is NOT implemented. A call to it would result in an error.

Therefore i have prepared a second class which will call the missing method by sending a message.

During the call of the anotherOptional-method call the Objective-c runtime sends the following error to the message console.

2011-03-10 12:56:02.923 MS4[21571:a0f] -[MyProtocolImpl anotherOptional]:
                        unrecognized selector sent to instance 0x1001611a0

To avoid such errors, the call schould be protected by the respondsToSelector message. This message will return FALSE, if the receiver of the message does not implement a method which responds to the message.

Since the receiver does not implement the method, it will not be called.

 

Additional informations

developer.apple.com


Follow

Get every new post delivered to your Inbox.