Example on accessing Apache HBase with JPA

31 08 2010

A few month ago I started to play with Apache HBase, Apache’s Bigtable implementation. Since the Bigtable impl. from the Google AppEngine (->Datastore) can be accessed with JPA, I searched for a way to use HBase with JPA as well.

Fortunately there is an easy: The DataNuculeus plugin (used by Google AppEngine) does have support for Apache HBase as well.

Over the time I noticed that folks are searching for “JPA HBase” are coming to my blog. As of now there is a SIMPLE demo: A (JSF2-based) web application that uses JPA to talk to an existing HBase installation.

I did commit to the code to github.

On http://github.com/matzew/hbase-jpa-jsf I also added a little README that gives some more details on how to run the example on your machine.

Note: It is just a quick and simple example that mainly should act as a playground for those that are interested in this topic.

Enjoy!





Using CDI Scopes with Spring 3

6 05 2010

With the advent of Spring 3 the framework now supports the Java Injection standard (JSR 330). However, unfortunately, they do not support the scoping, which is introduced in Java EE 6,through the CDI specification (JSR 299).

Now the big difference between a JSF “managed bean” in Java EE 6 and Spring is that they basically use a different scoping (JavaEE vs. Spring)!

However, the remaining parts are exactly the same, in both worlds:

  • @Named and Qualifiers for for naming and type-safety…
  • @Inject to identify “injection points” for dependencies/resources…

During our JAX 2010, Lars Röwekamp and I showed how enable the Spring Framework to understand the CDI scopes, such as @RequestScoped or @SessionScoped.

Before that, I spoke to Juergen Hoeller on the JAX conference, and he explained me the underlying mechanism and how something like that could be easily done!

The Spring Framework uses a ScopeMetadataResolver to resolve the SPRING-based scopes of the bean definitions. To actually enable the CDI scopes I “decorated” their default implementation, the AnnotationScopeMetadataResolver class:

public class CdiScopeMetadataResolver
extends AnnotationScopeMetadataResolver
{
 @Override
 public ScopeMetadata resolveScopeMetadata(BeanDefinition definition)
 {
 ScopeMetadata metadata = new ScopeMetadata();
 if (definition instanceof AnnotatedBeanDefinition)
 {
 AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
 Set<String> annotationTypes = annDef.getMetadata().getAnnotationTypes();

 if (annotationTypes.contains(
 javax.enterprise.context.RequestScoped.class.getName())
 )
 {
 metadata.setScopeName("request");
 }
 else if (annotationTypes.contains(
 javax.enterprise.context.SessionScoped.class.getName())
 )
 {
 metadata.setScopeName("session");
 }

...
//more...
//
 else
 {
 // do the regular Spring stuff..
 return super.resolveScopeMetadata(definition);
 }
 }
 return metadata;
 }
}

The CdiScopeMetadataResolver class scans the actual Spring beans and checks if the CDI
scope annotations are declared. If they are present we simply map them to their corresponding
Spring scopes!

So the trick is that you annotate them with CDI, but under the hood they are Spring scopes!

Now in your Spring configuration you simply enable it like:

...
 <context:component-scan
base-package="my.packages..."
scope-resolver="...CdiScopeMetadataResolver" />
...

Now you are able to define your Spring/JSF beans with 100% JavaEE-based annotations.

Enjoy!





Apache MyFaces 2.0.0 has been released

22 04 2010

Almost one year after the JavaServer Faces 2.0 specification went final, the Apache MyFaces project released the first release of it’s 2.0 offerings. Before this “final” release, there were a bunch of alpha/beta releases.

The announcement about MyFaces 2.0.0 can be find here.





Spring 3.0 and JSR 330: Using @Inject

20 04 2010

In here I showed how to use the @Named with Spring 3 to create “named beans”, to be used in frameworks like JSF2… Since we usually want to inject service implementations into our JSF beans, we need to use the @Inject from the JSR 330 (of course the regular Spring DI mechanism works as well). The JSF bean could look like:

@Model
public class SimpleBean
{
@Inject Service service;
...
public void callSomething()
{
service.myStuff();
...

Now we need to have an implementation of the Service interface. In order to allow the Spring Framework to find the (right) implementation the class itself needs to be annotated with the @Component annotation (or one of its specializations, like @Service which marks the class to be a “business service facade”):

@org.springframework.stereotype.Service
public class ServiceImpl implements Service
{
...
}

If your class (->interface implementation) does not have a meaning like that, you could simply use the @Named annotation from the JSR 330, like:

@javax.inject.Named
public class ServiceImpl implements Service
{
...
}

The good news with @Named and Spring here is that you could also combine the “Component” annotations and the @Named. This is useful if you have multiple implementations, like:

@org.springframework.stereotype.Service
@javax.inject.Named("bonusCustomerSerivce")
public class ServiceImpl implements Service
{
...
}

The injection point inside of your “clients”, like the JSF managed beans now also need to use @Named(“bonusCustomerService”) if the bean wants to use this specific one. The @Named usage may look a bit verbose, but there is help. You could create your own annotations, leveraging the @Qualifier from JSR 330. This is also supported in Spring3…

Good news here is (again) that most of the Dependency Injection “API” is similar in JavaEE 6 and Spring 3. You can used the @Inject, @Named and/or custom @Qualifiers (more soon). Right, there are also some differences between the two, but that’s coming in a later post…





Spring 3.0 and JSR 330: Using @Named

17 04 2010

The Spring 3.x release comes with a build-in support for the JSR 330, called “at inject” (or Dependency Injection for Java). So it is now possible to use these annotation as an alternative for the @Autowired et al.

The benefit of the JSR330 is that it is supported in different environments:

  • JavaEE 6
  • Spring 3.0
  • Guice 2.0

So the dependency base for all these frameworks is now the same, with some small differences. Using JSR330 with Spring is actually very simple. In your application-context.xml file you need to have the <context:component-scan> element, like:

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
...>

<context:component-scan base-package="net.wessendorf" />

</beans>

Now the annoations can be used in your classes:

package net.wessendorf.spring;

import java.io.Serializable;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;

@Named("mybean")
@Scope("session")
public class SimpleBean implements Serializable
{
...
}

The above snippet defines a session-scoped bean, which has the name “mybean”. So when using the SpringBeanFacesELResolver class (for JSF), your XHTML page can easily use the bean in it…

In CDI there are similar annotations for scoping, like RequestScoped, SessionScoped or ApplicationScoped. Spring has just one Scope annotation which itself takes the actual scope as its parameter. CDI also has a convenience annotation which combines @Named and @RequestScoped, and you can create similar ones, as extensions.

Of course this is possible with Spring 3.0 as well:

package net.wessendorf.spring.stereotype;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Named;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Named
@Scope("request")
@Component
@Target( { TYPE, METHOD, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Model
{ }

The interesting part is the @Named, which makes the name available, the @Scoped, which is set to request on your new @Model annotation and the @Component to mark the annotated class a as “Spring component”. Now instead of always adding @Named and @Scope(“request”) you could simply use the new @Model:

@net.wessendorf.spring.stereotype.Model
public class TesterBean
{
...
}

Now the above TesterBean can be resolved as “testerBean” in your JSF XHTML page.

Have fun!





Trinidad: JSF state-saving per page

7 04 2010

In a JSF/Trinidad application the “state-saving” is configured via some parameters in the web.xml file. Trinidad adds a bit more to it with its TOKEN approach, check the documentation for the “org.apache.myfaces.trinidad.CLIENT_STATE_METHOD” to read more. The result of the configuration via WEB.XML file is that the entire configuration for the state-staving behavior is GLOBAL. In Trinidad most of the time we use a hybrid approach (server+token on client), but sometimes you want a specifc page to be just client-side, to avoid nasty “session expired errors”. A good example would be a login page, to have (client-only) state – of course a totally stateless page would make sense too, but this means a login page is created outside of the (Trinidad/JSF) framework.

We recently introduced a new feature to enable the configuration of the state-saving on a per-page base! For that we introduce a new attribute on the <tr:document> component (stateSaving). The “stateSaving” attribute takes three different values:

  • client (force to be (full) client)
  • server (force to be server-side)
  • default (do what ever the user said in web.xml)

So with this it is possible to tweak the state-saving on a per-page base, instead of all done globally!





UIComponent references in session scoped JSF beans

31 03 2010

In this blog my colleague Blake Sullivan described a lot of issues with JSF managed beans that are placed in the session. This maybe easy for the developer on first hand, but the tax you pay later..

Even if you do take and implement (correctly) the Serializable interface, the oddness starts when you have UIComponent fields inside of those beans (mostly the case IF the developer uses the binding attribute). But hey, it’s good that the UIComponent don’t implement Serializable…

In Trinidad we offer some help for that (if you have to (or need to) use UIComponents in those “session beans”) with the ComponentReference util. Inside of your session scoped managed bean you don’t use the components directly, you use the tool. Here is a code snippet for a “UIComponent field” and its set/get:

...
private ComponentReference<UIInput> searchField;
...
public void setSearchField(UIInput searchField)
{
 if( this.searchField == null)
 this.searchField = ComponentReference.newUIComponentReference(searchField);
}

public UIInput getSearchField()
{
 return searchField ==null ? null : searchField.getComponent();
}
....

So, when you need a reference of the UIComponent in question, call the “getComponent()”. When the reference object is created it remembers the entire path to the UIComponent (by remembering all index or the names of facets). The getComponent() walks down the remembered path to look it up from there. If we hadn’t luck with the path, the reference util uses a scoped ID and calls the regular “findComponent()“. If that was successful, we renew the path and return the desired UIComponent instance. However, a few things to remember when using the util:

  • This class is not thread-safe, since it depends on UIComponent APIs
  • The passed in UIComponent is required to have an ID
  • The reference will break if the UIComponent is moved between NamingContainers or if any of the ancestor NamingContainers have their IDs changed
  • The refrence is persistable. However UIComponents are not Serializable and therefore can not be used at any scope longer than request

We have a good amount of different JUnit test-cases, including simulating some failover – this will give you also some ideas on how to use the util.

So, now please no longer use session-based managed beans WITH UIComponents as their members ;-)





Client side logging with JavaScript and ADF Faces

29 03 2010

ADF Faces is using (on the server) a “wrapper” around the standard Java logging. Based on the given log-level, the server-side console “prints” out different messages. To make life (and debugging) easier we did a similar thing for the client-side: ADF Faces contains a rich client-side Logger API. In order to use it, you need to enable it inside of the web.xml file, like:

<context-param>
 <param-name>oracle.adf.view.rich.LOGGER_LEVEL</param-name>
 <param-value>WARNING</param-value>
</context-param>

Now you can also start to use the LOGGER API in your custom JavaScript code, like:

AdfLogger.LOGGER.logMessage(AdfLogger.SEVERE, "This is from your logger!");

This is really a nice feature. When running with Firebug, you see the messages inside of the FB console!





Nice inline JavaScript and CSS via ADF Faces resource tag

29 03 2010

Sometimes it is required that you need (or want) to write some custom JavaScript (and/or CSS). In JSF2 there are two tags to refer to JavaScript and CSS files. While the functionally to seamlessly integrate (external) resources, not always you really want to create an external file for that stuff…

ADF Faces has a nice <af:resource> tag which gives you a good amount of flexibility to write embedded JS. Sure you can also reference to external files as well:

<af:resource type="javascript">
function myJavaScriptFunction()
{
// do stuff in here...
}
...
</af:resource>

This is pretty nice, since you can edit stuff inside of the page. If you figure the CSS (or JavaScript) is getting bigger and bigger, you can always stick it into an external file and reference it with the source attribute of the <af:resource> tag.





Mobile Development with Apache MyFaces Trinidad

20 03 2010

Since smartphones, like iPhone or Android phones, are getting more and more popular, more companies are getting serious about a “mobile strategy”. JavaServer Faces is a natural fit, since it’s rich component model allows you to simply switch the renderer… Yes you could introduce new tags/components for that, but’s that for sure an anti-pattern.

Apache MyFaces Trinidad is offering “mobile” support for a bunch of interesting devices, including Android, Microsoft Windows Mobile 5 and 6, or Apple’s iPhone. When companies want to offer a mobile version, they don’t just want “modern” phones… Consumer phones are still common and therefore used by potential customers. However supporting the wide range of different phones is not trivial: Some phones support JavaScript with Ajax, some without… Some have no JavaScript, some have a bad performance etc. All not to easy to deal with, when you have to do it from scratch!

The Apache MyFaces Trinidad renderkit covers that for your convenience, since it handles JavaScript free fallback during mobile rendering! Basically Trinidad assigns the JavaScript capability for a few mobile user-agents to ‘none’ in their capability files (Trinidad maintains a capability file for each/several user-agents). Fellow committer Mamallan is describing technical details here, on a thread to discuss “Apache MyFaces – JS free JSF” for Google Summer of Code.

Not only the capability of JavaScript is different, the size of the screen and the (native) look-and-feel differ as well. To archive a nice and almost native way of rendering ONE PAGE on different phones, (mobile) web developers use the the Skinning facility of Trinidad. Users/Developers have to create phone specific CSS files (every SDK has a tutorial for that, like Apple for its iPhone). Trinidad is able to switch the Skin during runtime. So you could use an EL and some code to attach the right skin, via user-agent detection.

Besides the device-specific CSS creating (and detaching) a custom skin is fairly easy. In the trinidad-config.xml you have the following:

<skin-family>#{agentUtil.phoneFamily}</skin-family>

The trinidad-skins.xml file, which contains would look like:

...
<skin>
<id>iphone</id>
<family>iphoneFamily</family>
<render-kit-id>org.apache.myfaces.trinidad.desktop</render-kit-id>
<style-sheet-name> iPhone/iPhone.css </style-sheet-name>
</skin>
...

While the “phoneFamily()” method in the underlying JavaBean would do something like:

public String getPhoneFamily()
{
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest req =
(HttpServletRequest)fc.getExternalContext().getRequest();
//Get the User Agent string from the browser
String agent = req.getHeader("User-Agent");
// Prints out user agent.  Comment out the line below for production system
if (agent != null && agent.indexOf("iPhone") > -1)
{
// If iPhone is returned.
// Comment out the followling line for production system
return IPHONE_SKIN;
 }
...

Tipp: You can ship your skins in a JAR, so that multiple (mobile) applications could benefit from the work!

Once that all is done, you are good to go! The source code of the JSPX/XHTML pages look like regular Trinidad pages! No new tags/components are required! That’s a good news, since you can leverage the knowledge you gained.

So to give an idea how rich your page could look on different phones, below are some screenshots:


This screenshot has also some information about the Trinidad TAGs that are used.

There my iPod touch and my (old ;-) ) Nokia phone:

The both show the same page, just with a different style sheet. The JSPX page is not different. All the magic is done by the Trinidad Skinning-Engine.

The ADF mobile team at Oracle put together a nice tutorial, which contains a decent demo application. It includes already some Skinnings for different mobile phones. So the getting started is fairly simple with that demo! The Trinidad developers guide has also some resources on mobile JSF development.

Generally the Trinidad library offers a pretty decent and stable framework-core (besides the 100+ components). Without its rock-solid architecture doing mobile applications would be way more odd (or complicated)!

Enjoy!