Wouter Deman@Java

Google Guice 1.0

by on Jan.06, 2009, under Uncategorized

Guice a lightweight dependency injection framework developed by Google. After using Spring all the time this is a different way of dependency injection but keep in mind that its still a lightweight framework so the support you get from Spring is somewhat bigger but Guice is at version 1.0 so the future will tell.

Modules:
Guice is based on modules, the modules are used to define what Guice has to inject. You can write a module by implementing the Module interface or by extending the AbstractModule class. The interface and the class define the implementation of the configure method. In this method you get a binder, this binder is used to instruct Guice on what to inject.

An example will tell more about how its done:

public class MyModule implements Module {
       public void configure(Binder binder) {
           binder.bind(Service.class)
           .to(ServiceImpl.class)
           .in(Scopes.SINGLETON);
       }
}

The example shows the binding of the Service interface to the ServiceImpl class as a Singleton.
Guice will inject the same(singleton) instance of ServiceImpl class when you ask to inject the Service.
Injecting can be done very easily with the @Inject annotation and you can use this on constructors, fields and methods:

public class Client {
       private final Service service;

      @Inject
      public Client(Service service) {
           this.service = service;
      }

      public void go() {
          service.go();
      }
}

Instead of binding to a “.class” you can also bind to an instance:

// Bind Bar to an instance of Bar.
Bar bar = new Bar();
binder.bind(Bar.class).toInstance(bar);

Annotations:
Besides instructing the Guice framework by binding in a module you can also use annotations to instruct Guice.
The binding between the Service interface and the ServiceImpl class as in the first example can be done with the @ImplementedBy annotation:

@ImplementedBy(ServiceImpl.class)
public interface Service {
       void go();
}

This doesn’t cover the singleton scope, to make the ServiceImpl class a singleton you have to annotate it with @Singleton:

@Singleton
public class ServiceImpl implements Service {
     public void go() {
         …
     }
}

Startup:
The first stage of the Guice architecture is the startup, during the startup you create an injector that is used to inject into objects at runtime.

An example of a main method will explain more than words:

public class Main {
      public static void main(String[] args) {
           Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyModule());
           Client client = injector.getInstance(Client.class);
           client.go();
       }
}

In the example we create an injector by passing an instance of our module “MyModule” and the wanted Stage. Guice creates the binder and passes it to the module which contains the defined bindings. The Stage we specify is an extra attribute but very handy. There are two stages available, the Development and the Production stage. The difference is that in the development stage the singletons are instantiated on demand and in the production stage they are instantiated on startup.

Runtime:
Runtime is the second stage of the architecture, at this time we can use the injector created in the startup stage to inject objects. The injector consists of bindings. These bindings are represented by a key and the key consists of a type and an optional annotation. More on the optional annotation in the part about Annotation bindings.

Each binding has a provider which you can give a class and Guice will create an instance of that class.

Creating a new instance each time is the default for having no scope but each binding can have a custom scope that can decide if Guice needs to create a new instance or not. For example, you can create one instance per HttpSession:

binder.bindScope(SessionScoped.class, ServletScopes.SESSION);

To write a custom scope you need to add the @ScopeAnnotation annotation to your custom annotation.
Annotating bindings:
If you need to bind multiple Service implementations to the Service interface you need to be able to differentiate the bindings. This can be done with annotations:
bind(Service.class)
.annotatedWith(Blue.class)
.to(BlueService.class);
 

Here you see the bind being extended to check for the @Blue annotation:

@Inject
public void injectService(@Blue Service service) {
     …
}

The @Blue annotation is custom annotation. Creating annotations that can be used in Guice requires you to use a guice annotation in your custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Blue {}

The @BindingAnnotation is the Guice specific annotation that indicates the usage of this annotation @Blue in Guice.

Annotation attributes:
If you already have enough differentiation with the basic annotation like @Blue you can skip this part. This part is about annotation attributes to add even more differentation to the injections. You can create your own annotation or you can use the @Named annotation provided by Guice in the com.google.inject.name package:

@Inject
public Client(@Named(“cars”) Service service) {
      this.service = service;
}

The binding configured in the module:

@Override
protected void configure() {
      bind(Service.class)
      .annotatedWith(Names.named(“cars”))
      .to(CarServiceImpl.class);
}

Implicit bindings:
Declaring bindings to concrete classes(not behind an interface) isn’t useful. You can declare them but it doesn’t make much sense:

bind(Concrete.class);
Providers:
If you need multiple instances of the same class then you can inject a provider for that class which enables you to call Provider<T>.get(); :@Inject
public void injectAtm(Provider<Money> atm) {
     Money one = atm.get();
     Money two = atm.get();
     …
}
It will happen that you need to create the objects because of 3rd party tools. This can be fixed by writing a custom provider for that class:

class WidgetProvider implements Provider<Widget> {
     final Service service;

     @Inject
     WidgetProvider(Service service) {
          this.service = service;
     }

     public Widget get() {
          return new Widget(service);
     }
}

The binding is done as follows:

bind(Widget.class).toProvider(WidgetProvider.class);

A great example on how to integrate with JNDI can be found in the Guice user guide.

Constant values:
Guice has a special treatment when injecting constant values:
- primitive types(int, char, …)
- primitive wrapper types(Integer, Double, …)
- Strings
- Enums
- Classes

An example:
bindConstant().annotatedWith(TheAnswer.class).to(42);

When binding Strings Guice will check for enums and classes by converting the String.
This can be handy when binding Strings from a properties file.Eagerly loading bindings:
To load an object at startup for initialization you need to declare them as eager singletons:
bind(StartupTask.class).asEagerSingleton();

 


Injection between scopes(switching scopes):
This can be done in a safe manner, you can inject an HttpSession scoped object into an HttpRequest scoped object. Going from a bigger scope to a smaller one is no problem but the other way around is harder. This can be fixed by injecting a Provider<T> to retrieve the object.


Intercepting methods:
Just like in Spring you can write intercepting methods using AOP. An example is a Transaction interceptor that intercepts all methods with the @Transactional annotation:binder.bindInterceptor(
     any(), // Match classes.
     annotatedWith(Transactional.class), // Match methods.
     new TransactionInterceptor() // The interceptor.
);

Optional injection:
Injection can be made optional for methods and fields, not constructors.
This is useful when there is no binding available then a default instance is used:

@Inject(optional=true) Formatter formatter = new DefaultFormatter();

 

 

Testing:
Last but not least I want to give you an example of a unit test using Guice:

@Before
public void setUp() throws Exception {
      mockService = new MockService();
      Module module = new AbstractModule() {
          @Override
          protected void configure() {
               bind(Service.class).toInstance(mockService);
          }
      };
      injector = Guice.createInjector(Stage.DEVELOPMENT, module);

@Test
public void testGo() {
      Client client = injector.getInstance(Client.class);
      client.go();
      assertTrue(mockService.isGone());
}

I hope this is a start on using Guice as a dependency injection framework. I’m looking forward to using/learning more google innovations.

1 Comment :, , , , , , , , , , , , , , , , , , , more...

Spring Web Flow 2.0

by on Nov.20, 2008, under Uncategorized

Spring Web Flow 2.0 is another project from the Spring Source community. This module is build for implementing flows. The Web Flow engine works together with the Spring MVC framework and provides a declarative flow definition language.

We start with a simple example of a flow definition:

<flow xmlns=”http://www.springframework.org/schema/webflow”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd”>

         <view-state id=”enterBookingDetails”>
               <transition on=”submit” to=”reviewBooking” />
         </view-state>

         <view-state id=”reviewBooking”>
               <transition on=”confirm” to=”bookingConfirmed” />
               <transition on=”revise” to=”enterBookingDetails” />
               <transition on=”cancel” to=”bookingCancelled” />
         </view-state>

      <end-state id=”bookingConfirmed” />      
         <end-state id=”bookingCancelled” />
</flow>

As you can see in this example there are three main elements in a flow declaration: view-state, transition and end-state. These 3 allow you to express the navigation logic of your flow.

A view-state with only an id defined will look for a page with that id as a filename, in this example the enterBookingDetails view-state will find the file “enterBookingDetails.jsp” that is located in the same folder as the flow xml file.

There are a few possibilities to change this by adding the “view” property:
- Flow relative view ids:

<view-state id=”enterBookingDetails” view=”bookingDetails.xhtml”>

- Absolute view ids

<view-state id=”enterBookingDetails” view=”/WEB-INF/hotels/booking/bookingDetails.xhtml”>

- Logical view ids: These are resolved by the viewResolver from Spring MVC.

<view-state id=”enterBookingDetails” view=”bookingDetails”>

The transitions in our flow definition are the events the user can trigger and what has to happen when that event occurs. A transition can bring you to another view, execute an action, re-render the current view, etc…. If you are using ajax you can use the re-rendering of fragments in the view. More details about the possibilities of transitions later on.

The end-state ends the flow and determines the flow outcome.

Besides navigation logic you need to be able to invoke business services to retrieve or save objects during the run of your flow. This can be done by defining actions that execute at a certain point in the flow: during a transition, at the start of the flow, at the end, when rendering a view, etc…
An example of an action is the evaluate element which you will use most of the time.

<evaluate expression=”entityManager.persist(booking)” />

To save the result of an expression you can to add the result property and for type conversions you can add the result-type property:

<evaluate expression=”bookingService.findHotels(searchCriteria)” result=”flowScope.hotels” result-type=”dataModel”/>

In this evaluate example the result gets saved in the flowScope. The flow engine offer many scopes where you can play with and I will tell more about these scopes later on.

Besides objects that are present in scopes which have a certain lifespan you can declare instance variables for the flow. These variables get saved and reinitialized when the flow starts. The objects used in the variable declaration have to implement Serializable so they can be saved:

<var name=”searchCriteria” class=”com.mycompany.myapp.hotels.search.SearchCriteria”/>

For some flows to get started they need input to start with or they need to generate output. This can be done by defining the input and output elements:

<input name=”hotelId” type=”long” value=”flowScope.hotelId” required=”true” />

<end-state id=”bookingConfirmed” >    
       
<output name=”bookingId” value=”booking.id”/>
</end-state>

Inside your main flow you can also declare subflows that you can repeat and allow you to create multiple users or book 10 guests at a hotel for example:

<subflow-state id=”addGuest” subflow=”createGuest”>    
      <transition on=”guestCreated” to=”reviewBooking”>
              <evaluate expression=”booking.guests.add(currentEvent.attributes.guest)” />
       </transition>
  <transition on=”creationCancelled” to=”reviewBooking” />
</subfow-state>

To call a subflow you just refer the id of the subflow in a transition:

<transition on=”addGuest” to=”addGuest” />

This covers the basics needed to create your flows. Don’t forget to check out the samples that come with Spring Web Flow when you download it.

Scopes and Expression Language(EL):
Within the flows the flow engine allows you to use Expression Language to access data in the flow, invoking methods on spring beans, accessing data on all the scopes, etc… .

They have two types of expressions:
- Standard eval expressions where you don’t need to surround the expression with the ${ } or #{ }:

<evaluate expression=”searchCriteria.nextPage()” />

- Template expressions that allow you to combine literal text and expressions to evaluate:

<view-state id=”error” view=”error-${externalContext.locale}.xhtml” />

There are many scopes which you can use, each scope has his/her lifespan and can offer access to user variables:
- flowScope: Start -> end flow
- viewScope: During view-state
- requestScope : Assign request variables that are available from calling the flow until the flow returns.
- flashScope : Available from start to end of the flow but after each view it gets cleared(flashed).
- conversationScope: Start -> end of the top-level flow and objects are saved in a HTTP session.
- requestParameters: Access to client request parameters.
- currentEvent: Access to attributes of the current event.
- currentUser: Access to the authenticated user Principal.
- messageContext: For retrieving flow execution, success and error messages.
- resourceBundle: Access to the message source.
- flowRequestScope: Access to the requestContext.
- flowExecutionScope: Access to the flowExecutionContext.
- flowExecutinUrl: Access to the context-relative URI of the current flow execution.
- externalContext: Access to the users environment, for example the session attributes.

When you don’t refer to a certain scope then the scope searching algorithm will look in the request, flash, view, flow and conversation scope. If it doesn’t find the anything an Evaluation Exception will be thrown.

Working with View states:
Declaring view states and linking them to a certain file(defining view ids) is already covered in first section but there are many more things you can do with a view.

Binding your view to a model is used when working with forms, which enables validation on the properties that get filled up by the user input. The model can be accessed later on in the flow in the flow or view scope. Besides adding the model property to a view-state you can also define a binder where you can specify the properties that can be used and which ones are required:

<view-state id=”enterBookingDetails” model=”booking”>
        <binder>
                <binding property=”checkinDate” converter=”shortDate” required=”true” />
                <binding property=”checkoutDate” converter=”shortDate” required=”true” />
                <binding property=”creditCard” required=”true” />
         </binder>
         <transition on=”proceed” to=”reviewBooking”>
         <transition on=”cancel” to=”bookingCancelled” bind=”false” />
</view-state>

Conversion is another aspect that comes to play when binding to a model. If you have user-defined types you need to override the default conversion and implement your own. Writing your own converter can be done by implementing the “TwoWayConverter” interface. To register this convertor and to be able to use it you need to override the “DefaultConversionService” class where you can add your custom convertors. The custom DefaultConversionService can be configured in the flow-builder-services element. More about setting up the webflow at the end of the post.

If you want to suppress model binding on a certain transition you can add the bind=”false” property.

Implementing model validation can be done in 2 ways:

- add validation rules to your model: implement a method for each view-state that has to be validated, the method name should start with validate and then the name of the view-state. For example “validateEnterBookingDetails(ValidationContext context)”.
- write a separate validator class: The separate validator classname should be the model + validator. For example BookingValidator. By using this name and adding the @Component annotation then this validator will be used for validating the model. The validation methods in the validator should also be named “validate” + {State name}.

Both ways get a validationContext where you can retrieve user information and add error messages to the messageContext.
Suppressing validation on a certain transition can be done by adding the validate=”false” property.

A very nice feature is the popup property of the view states, by setting popup=”true” you let the view appear in a popup which can be handy when working out your subflow that creates multiple hotel guests or when you need to change a value in a view. I don’t like using popups but a few can’t hurt :p.

Last thing to remember when working with views you also have to consider view backtracking. You need to be able to deny the user to go back to the previous view or to all the previous views for example. This can be defined with the history attribute used in the transitions you use within the view:
- Discarding history to prevent backtracking to the last view:

<transition on=”cancel” to=”bookingCancelled” history=”discard”>

- Invalidating history to prevent backtracking to all the previous views:

<transition on=”confirm” to=”bookingConfirmed” history=”invalidate”>

Transitions:
Transition elements are defined to handle the user events in a view but besides using them to change go to another view when an event occurs you can also execute actions, render or re-render fragments of your view, etc…
- Transition actions:
<transition on=”submit” to=”bookingConfirmed”>
        <evaluate expression=”bookingAction.makeBooking(booking, messageContext)” />
</transition>
- Global transitions: Transitions that apply on all the views.
<global-transitions>
        <transition on=”login” to=”login”>
        <transition on=”logout” to=”logout”>
</global-transitions>
- Event transitions: Transitions without a target, they don’t change the flow but they can re-render a view or execute an action for example.
<transition on=”event”>
        <!– Handle event –>
</transition>
- Rendering fragments: The fragments property refers to the element id on the view.
<transition on=”next”>
        <evaluate expression=”searchCriteria.nextPage()” />
        <render fragments=”searchResultsFragment” />
</transition>

Actions:
As mentioned in the first part, actions are used to invoke business services. There are 3 possible ways of implementing an action:

- A POJO action:

<evaluate expression=”pojoAction.method(flowRequestContext)” />

public class PojoAction {
         public String method(RequestContext context) {
         …
         }
}

- Custom Action implementation:

<evaluate expression=”customAction” />

public class CustomAction implements Action {
        public Event execute(RequestContext context) {
        …
        }
}

- Custom MultiAction implementation:

<evaluate expression=”multiAction.actionMethod1″ />

public class CustomMultiAction extends MultiAction {
        public Event actionMethod1(RequestContext context) {
        …
        }

        public Event actionMethod2(RequestContext context) {
        …
        }
        …
}

An aspect that you can’t forget is exception handling of the actions. Here is an example of a POJO action:

<evaluate expression=”bookingAction.makeBooking(booking, flowRequestContext)” />

public class BookingAction {
       public String makeBooking(Booking booking, RequestContext context) {
              try {
                    BookingConfirmation confirmation = bookingService.make(booking);
                    context.getFlowScope().put(“confirmation”, confirmation);
                    return “success”;
              } catch (RoomNotAvailableException e) {
                   context.addMessage(new MessageBuilder().error().defaultText(“No room is available at this hotel”).build());
                   return “error”;
              }
       }
}

In this example the exception gets catched and the method returns “error” which refers to and event id that gets handled as a flow event.

When implementing custom Actions or customer MultiActions you need to return error(); or success(); which returns an Event object. This is better because it provides better type safety while the POJO action has more freedom.

As you can see implementing and using these actions isn’t difficult. For examples take a look at the included samples in the Spring Web Flow download.

Executing these actions can be done in many places in your flow:
- on-start: When the flow starts
- on-end: When the flow ends
- on-entry: Used in the view-state and called when the view-state is entered
- on-exit: Also defined in the view-state for when it exits
- on-render: Can be declared in a view-state to do an action when the view-state gets rendered
- on-transition: If you want to do an action on a transition put your action within the transition declaration. There is no on-transition element that you can define
- named actions: add a name attribute element within your action and you can refer to these actions in transitions:

<evaluate expression=”service.thingTwo()”>
       <attribute name=”name” value=”thingTwo” />
</evaluate>
<transition on=”thingTwo.success” to=”showResults” />

If you want to invoke an action and then transition to another state based on the outcome you can use the action-state:

<action-state id=”moreAnswersNeeded”>
      <evaluate expression=”interview.moreAnswersNeeded()” />
      <transition on=”yes” to=”answerQuestions” />
      <transition on=”no” to=”finish” />
</action-state>

The transitions are called depending on the boolean that’s returned. The mapping of the method return type is different.

Here is a small overview of the action outcome event mappings:
- java.lang.String -> the String value
- java.lang.Boolean -> yes (for true), no (for false)
- java.lang.Enum -> the Enum name
- any other type -> success

If you want to do some routing depending on the outcome you can use the decision-state which is an alternative for the action-state. The decision-state uses an if/else syntax:
<decision-state id=”moreAnswersNeeded”>
       <if test=”interview.moreAnswersNeeded()” then=”answerQuestions” else=”finish” />
</decision-state>

Don’t forget the mapping of the method returns, just like the action-states.

Working with messages:
When handling exceptions it happens that you need the user to get an error message like “Date must be a future date” for example. The MessageContext can be used to record your messages, you can add plain text messages or internationalized messages. The international messages get resolved by Springs MessageSource also used in Spring MVC for example.

Constructing messages can be done very easily with the MessageBuilder, the three categories of messages are info, warning and error. Note that the web flow engine can also add messages when binding or a conversion fails. You can customize these error messages by defining them in the properties files.
- Plaintext messages:

MessageContext context = …
MessageBuilder builder = new MessageBuilder();
context.addMessage(builder.error().source(“checkinDate”).defaultText(“Check in date must be a future date”).build());

- Internationalized messages:

MessageContext context = …
MessageBuilder builder = new MessageBuilder();
context.addMessage(builder.error().source(“checkinDate”).code(“checkinDate.notFuture”).build());

Using the resourceBundle scope you can access these messages in the view or flow.

Persistence:
Web flow provides persistence in cooperation with Hibernate or JPA.

Adding flow persistence is made very easy, the first thing you have to do is marking your flow:

<persistence-context />

Next you register an execution listener for JPA for example:

<webflow:flow-executor id=”flowExecutor” flow-registry=”flowRegistry”>
         <webflow:flow-execution-listeners>
                  <webflow:listener ref=”jpaFlowExecutionListener” />
         </webflow:flow-execution-listeners>
</webflow:flow-executor>

<bean id=”jpaFlowExecutionListener” class=”org.springframework.webflow.persistence.JpaFlowExecutionListener”>
         <constructor-arg ref=”entityManagerFactory” />
         <constructor-arg ref=”transactionManager” />
</bean>

The listener will handle the allocation of a new EntityManager in the flowScope with the reference persitenceContext.

The last thing you need to do is add the commit property in the end-state and you have fully working flow persistence:

<end-state id=”bookingConfirmed” commit=”true” />

Security:
To secure your flows you have to go do 3 steps:
1) Configure Spring Security
2) Annotate the flow with the secured element to define the required security roles
3) Add a SecurityFlowExecutionListener to process the security rules

<secured attributes=”ROLE_USER, ROLE_ANONYMOUS” match=”any” />

This secured element defines that the user should have ROLE_USER or ROLE_ANONYMOUS to be able to access the flow. The match property can be set on “all” or “any”.

<webflow:flow-executor id=”flowExecutor” flow-registry=”flowRegistry”>
        <webflow:flow-execution-listeners>
               <webflow:listener ref=”securityFlowExecutionListener” />
        </webflow:flow-execution-listeners>
</webflow:flow-executor>

<bean id=”securityFlowExecutionListener” class=”org.springframework.webflow.security.SecurityFlowExecutionListener” />

This is the SecurityFlowExecutionListener that you need to register to process the security rules. You can modify the listener by defining a custom AccessDecisionManager and for more about that check the documentation of Spring Web Flow and the documentation of Spring security.

For more information about the configuring Spring Security, check the Spring Security documentation.

Flow Inheritance:
Flow inheritance is also possible in Spring Web Flow, even multiple inheritance is possible on flow and state level.
- Flow Level:

<flow parent=”common-transitions, common-states”>

- State level:

<view-state id=”child-state” parent=”parent-flow#parent-view-state”>

Adding the abstract=”true” property to your flow makes the flow abstract and a FlowBuilderException is thrown when it tries to run.

A small note is that parents should have absolute paths in their views otherwise this will not work from a child flow that is situated in a different directory. For a list of the mergeable and non-mergeable elements take a look at the Spring Web Flow documentation.

Spring MVC Integration:
To integrate both modules you register a FlowHandlerAdaptor and register your flowmapping where you refer to the flowRegistry.
You can also implement your own handler to handle the execution outcome of your flow. The matching ids from both the custom handler and the flow should match then.

As seen above you can also reuse the Spring MVC viewResolver.

Signaling which event has to be triggered in the view can be done in 3 ways:
- A named HTML button

<input type=”submit” name=”_eventId_proceed” value=”Proceed” />
<input type=”submit” name=”_eventId_cancel” value=”Cancel” />

- A hidden HTML element

<input type=”submit” value=”Proceed” />
<input type=”hidden” name=”_eventId” value=”proceed” />

- A HTML link

<a href=”${flowExecutionUrl}&_eventId=cancel”>Cancel</a>

Spring Javascript:
Spring Javascript allows you to decorate DOM elements with Dojo, the validateAllDecoration for serverside validation or the AjaxEventDecoration. Just like I said above you can render a certain fragment of the page by using these Ajax calls.

For more details check the Web Flow documentation.

Other Integrations and Testing:
Spring Web Flow also integrates with JSF and Portlets and has good testing capabilities but check the documentation of Spring Web Flow for more information.

2 Comments :, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , more...

Springsource dm server

by on Nov.05, 2008, under Uncategorized

The Springsource dm(dynamic module) server is a module based Java application server that can be used for spring powered applications and Java enterprise applications. The reason im writing a blog post about this project is the use in combination with Sping dynamic modules.

The server is build up with Spring Framework, Tomcat(web container), OSGi R4.1, Equinox(OSGi impl.), Spring dynamic modules, SpringSource Tool Suite and Spring Application Management Suite.

For more information about Spring dynamic modules I refer to my previous blog post.

The server is at version 1.0.0 but it’s already a nice package to work with. The Documentation offers a user guide and a programming guide. The user guide helps you installing and configuring the server, the telnet console, the deployment timeout, the embedded tomcat server, linking the user bundles to an Ivy cache or a maven local repository, etc…

The programming guide is the one I liked the most, it helps you out step by step how to convert your web application to a web application with shared libraries at first and later on they explain how to work with shared services. If you have your libraries, services and web module as seperate bundles you can group them in a .PAR. A Packaging archive containing all your modules to deploy at once.

Besides the versioning of modules/bundles you also have the shared libraries and that is something I like the most. Not having to add the same libraries when working with 2 projects. Now they can just use the same shared libraries.

To help you out they also have Eclipse support so that working with the server gets easy and besides the already known Spring nature you can add to projects they also added the OSGi bundle project nature so that the manifest.mf file gets a nice editor to manage dependencies, export certain packages, etc…

For a tutorial I refer to the programming guide which contains the form tags example and that was a great help to start with.

A last note on the OSGi world is that many vendors of popular application servers are going to offer OSGi support in the next generation of server platforms.

Leave a Comment :, , , , , , , , , , , , , , , , , more...

Spring dynamic modules(OSGi)

by on Nov.04, 2008, under Uncategorized

Before we start with the Spring dynamic modules project it’s best we that we take a look at OSGi itself so that you understand what Spring dm offers you.

A good tutorial for OSGi is Getting Started with OSGi – by Neil Bartlett but I will give a small summary of OSGi. OSGi is short for Open Services Gateway Initiative and its all about modularity, being able to deploy and undeploy services at runtime. Examples of services are web applications, services bundles, domain bundles and even libraries.

To be able to deploy your bundles you need an OSGi framework. Popular examples of OSGi frameworks are Apache Felix, Eclipse Equinox and Knopflerfish. OSGi is used in the Eclipse IDE, mobile phones, cars, industrial automatisation, grid computing, etc…

If you take a look at the examples of OSGi you will need to use the BundleContext to register or retrieve the services you need or you can make use of the serviceTracker from OSGi to keep track of your services.

Exporting a spring bean as an OSGi service:
The simplest way to export a spring bean as an OSGi service is to declare it in the osgi-context.xml in the META-INF/spring folder:

<service ref=“beanToPublish” interface=“com.xyz.MessageService”/>

Here we just have a reference to the bean and the interface of the bean. The bean gets declared in the module-context.xml in the META-INF/spring folder. After declaring the OSGi service we have to expose the packages that contain the entities and the service interfaces. We do that by adding them to the exported packages in the manifest.mf file.

You can also add an id to the service registration which allows you to use this ServiceRegistration object in other beans. Besides declaring a separate bean to reference to you can just add it inside the <service /> element, we also call this an anonymous inner bean.

Another addition is a new scope for our beans, the bundle scope that provides one instance for each unique client and when the service importing is stopped the bean instance is disposed.

There are many other ways and additional properties for declaring your spring beans as an OSGi service but you should take a look at the documentation of Spring dm if you want all the spicy details. Here is a small overview of what can be done:

- Declaring multiple interfaces for an OSGi service
- Automatically detecting the interfaces with the auto-export attribute
- Adding service properties to your OSGi service
- Depending on other services with the depends-on attribute
- Setting the context-class-loader attribute to ‘service-provider’ ensures that the context class loader can see all the resources on the classpath. Standardised support for dealing with these resources is being added in R5 of OSGi.
- Rank your services with the ranking attribute
- Defining a listener for registration and unregistration of your service

Defining references to OSGi services:
To declare a reference to an OSGi service we need to add a reference in the applicationContext.xml or the module-context.xml:

<reference id=“messageService” interface=“com.xyz.MessageService”/>

This is the simplest way of referencing a service with the attributes id and the interface of the service.
To be able to access this interface you need to add the packages you need to your dependencies in the manifest.mf file.

Just like declaring OSGi services it is possible to declare a reference that has multiple interfaces:

<osgi:reference id="importedOsgiService">
  <osgi:interfaces>
     <value>com.xyz.MessageService</value>
     <value>com.xyz.MarkerInterface</value>
  </osgi:interfaces>
</osgi:reference>

Here is an overview of the additional properties:
- The filter attribute is used to filter out some services: filter=“(asynchronous-delivery=true)”. This example gets you the service that has an OSGi property asynchronous-delivery set on true.
- The bean-name attribute gives you the service that matches the interface and the bean-name property. This property gets set automatically and matches the id of the bean used in the ref property of the
service declaration.
- Depending on other services to be up first can be declared with the depends-on attribute.
- Setting how much services you need of that type can be done with the cardinality attribute. Possible values are 1..1(default) or 0..1.
- OSGi R4.1 doesn’t specify which resources and types are visible on the context class loader but we can add the context-class-loader attribute.
   The attribute can be set to client(default), service-provider and unmanaged.
       * Unmanaged disables the context class loading management.
       * Client guarantees the types available on the classpath of the invoking bundle.
       * Service-provider guarantees the types of the exporting bundles classpath.
- A timeout(in milliseconds) can be set to wait for a backing service to be available. After the timeout a ServiceUnavailableException is thrown.
- Listeners can also be declared to listen for the binding and unbinding of services.

An extra addition is injection of the ServiceReference instead of the service itself. Spring dm can automatically convert the managed service to a ServiceReference object. Use this to get the OSGi properties and not for anything else because other OSGi frameworks use their own version of the ServiceReference class.

Referencing a collection of services:
Referencing a collection of services can be done with a list or a set declaration:

<set id="myServices" interface="com.xyz.MyService"
  comparator-ref="someComparator"/>

<list id="myOtherServices"
  interface="com.xyz.OtherService">
  <comparator>
     <beans:bean class="MyOtherServiceComparator"/>
  </comparator>
</list>

The difference between list and set is that set doesn’t allow duplicate services. As you can see in the example they both use a comparator that sorts the list or set of services. A natural order can also be applied on the set or list:

<list id="myServices" interface"com.xyz.MyService">
  <comparator><natural basis="services"/></comparator>
</list>

<set id="myOtherServices"interface="com.xyz.OtherService">
  <comparator><natural basis="service-references"/></comparator>
</set>

The natural ordering is based on the OSGi specifications but you can also make your service comparable and then it will sort based on that.

Setting the greedy-proxying attribute on ‘true’ enables Spring dm to create proxies for all the classes advertised by the service. These additional classes can be handy for your application. Besides the greedy-proxying attribute you also have the cardinality attribute (1..N or 0..N), the context-class-loader, filter and bean-name attribute just like referencing a single service. 

This covers the installing and using of OSGi services but Spring dm also provides the interaction with Bundles to manage their lifecycle and has Web support.

For more details I refer to the Spring dynamic modules documentation but I hope this helps you get started.

5 Comments :, , , , , , , , , , , , , , , more...

Spring modules: XT Framework

by on Oct.28, 2008, under Uncategorized

The XT Framework of the Spring Modules is a very handy framework that offers help for richer domain models and richer user interfaces. The richer domain models get help from the XT Modeling Framework that follows the Domain Driven Design by Martin Fowler. The richer user interfaces get help from the XT Ajax Framework.

The XT Modeling Framework:
-
DynamicBeanIntroducer: This lets you add additional interfaces to an Object at runtime. The DynamicBeanIntroduces also implements the get/set methods.

- Collections Introductor: This uses a DynamicBeanIntroducer to add an additional interface to every contained object in a List, Set or Collection. 

- DynamicFactoryGenerator: This lets you build an Object Factory by defining an interface and annotating it with the ConstructorArg annotation, the Property(getters/setters) annotation and the FactoryMethod annotation. The FactoryMethod gets called at last to create the Object.

- Notification Interface: This is used to communicate between different application layers using the message interface and the notification interface. The messages are used by the specifications.

- Specifications: The specifications pattern can be implemented using the Specification interface. Specifications are predicate like objects and besides the Specification interface Spring also offers you a way to use the Predicate from Apache Commons. The Composite Specification interface is used to combine specifications through logical operators and you can also define the Message that is used when the specification is satisfied/unsatisfied.

The XT Ajax Framework:
The XT Ajax Framework is based on Events, Handlers, Actions, Components and Responses.

The two events available are the Action events and the Submit events. You can trigger events using the javascript library from Spring XT. This provides two methods, the XT.doAjaxAction and the XT.doAjaxSubmit that are used in the onClick of an HTML component or somewhere in your javascript code.

- Ajax Handlers(Action Events): Ajax Handlers can be implemented by extending the AbstractAjaxHandler. In your Ajax handler class you implement methods returning an AjaxResponse. For example getStockExhange that returns you an AjaxResponse containing a ReplaceContentAction to refresh you table of Stock Exhanges.
- EnhancedSimpleFormController(Submit events): The SimpleFormControllers from Spring MVC can be reused by extending the EnhancedSimpleFormController, this allows you to return an AjaxModelAndView.

These Action and Submit event handlers aren’t usable without implementing an Ajax Interceptor in your Spring MVC configuration. The first step is adding a reference to the interceptor in the UrlHandlerMapping, after that is done you can define the url mappings on which an Ajax Handler and/or an Ajax validator has to be triggered.

- Validation: It is very easy to reuse the spring MVC validators by adding the DefaultValidationHandler in your Spring MVC configuration. The errors are displayed in div’s representing a single validation error or more at once. The handler also allows you to define a custom ErrorRenderingCallback and a SuccessRenderingCallback which is very handy to show messages after a submit.

- Exception handling: The exceptions that happen during an ajax call have to be catched using the AjaxExceptionHandler and these exceptions can be forwared to a page by the RedirectExceptionResolver.

- Scriptaculous and Prototype: The XT Ajax Framework also integrates with other javascipt libraries like Scriptaculous and Prototype. You can use these to add drag and drop functionalities to your pages or to show fancy effects when a validation error occurs.

I’ve used the XT Ajax Framework in a project and we added it after writing the Spring MVC controllers and the validators. The integration went very smooth but we needed a way to show messages to the user after a submit and we also wanted to use a different loading Image. The way this is done is explained in my examples which I added to the example that comes with Spring Modules.

The extended example can be downloaded here.

Leave a Comment :, , , , , , , , , , , , , , more...

SCWCD 5.0(CX-310-083) experience…

by on Oct.24, 2008, under Uncategorized

This week I passed my SCWCD 5.0 exam and with a score of 82%, but it was harder than expected.
The studying material I used was the Head First Servlets and JSP book from Basham, Sierra and Bates. The book covers a big part of the exam but not everything. Besides reading and studying the book you should check out the API of the servlet package, mainly the HttpServletRequest and the HttpServletResponse methods but don’t forget to peek at the Cookie methods and so on. Another API that appears on the exam is JSTL ofcourse check that API because the HF book covers a lot but not everything. I got questions about the <c:import …/> attributes and I could answer it because of the API studying.

Another small tip is about the final mock exam in the book, most people don’t score high on it because its very difficult but just take a look and try to score as high as possible but don’t use the score as a reference for the real exam :p.

Besides reading the book and the API’s also take a look at javaranch.com they have many great tips and user experiences, maybe you can ask questions there.

Between the SCWCD links on javaranch.com I also found a great overview about the J2EE patterns. It explains how to read the J2EE pattern questions from the exam and that makes them easy to answer. The exam is all about the six patterns you have to know so ignore the other patterns that come up on the exam they are there to make you go crazy :p.

If you have any other questions don’t bother mailing me ;) .

Leave a Comment :, , , , , , , , , more...

SCJP 6.0(CX-310-065) experience…

by on Sep.23, 2008, under General

Last month I past the SCJP 6.0(CX-310-065) certification and this week I finally received all the gadgets from Sun. They really made something nice of it but I’m not planning to wear the pin or carry the sun card around :) .

The preparation material I used was the book from Katherine Sierra and Bert Bates. Besides this great learning book with many mock exam questions I used the trial of Whizlabs and I gained lots of exam information on javaranch.com.
Another website that can be interesting to raise your skill level is javablackbelt.com, they also have some SCJP mock questions and lots of other Java SE questions.

The mock questions from the book and from Whizlabs were very difficult but that’s just the preparation you need. They don’t give you the number of answers you need to give, you just have to know you stuff very well.

If you have any other questions about the exam don’t mind commenting or mailing me on wouter@blackbeast.be.

1 Comment :, , , , , , , , , , more...

Welcome on my blog…

by on Sep.23, 2008, under General

Welcome to everyone visiting my blog, I will be blogging about the things I learn during my professional career as a Java programmer. In July I started my first job as a Junior Java consultant @ Compuware. The project im currently working on is a timesheet management system. I will be posting more about that project in another post.

I got my bachelor degree in Applied Informatics with Application development as specialisation @ Karel De Grote Hogeschool in Antwerp. These 3 years have prepared me for the coming years but the real learning experience just has to start by working in the field.

In August I got my first Sun certification, I can now say that I am a Sun Certified Java Programmer(SCJP) for version 6.0. Next week I’m going for the SCWCD 5.0 certification and I hope that one goes as well as the first one.

Besides working I also do other stuff like riding my motorcycle(currently a Ducati 620ie), playing games, watching movies and series and doing some fitness but my personal life doesn’t have to be on this blog :) . For that I suggest that you add me on facebook or linkedIn for example.

1 Comment :, , , , , , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

Archives

All entries, chronologically...