Monday, 28 November 2011

JavaEE Revisits Design Patterns: Observer

Aside from being implemented in many languages and many applications, Observer Pattern has been a part of Java since version 1.0. Observer Pattern is also a good implementation of Hollywood Principle. Just like Agents in Hollywood like to callback the candidates for a role instead of being called daily to be asked about available jobs, most of the server side resources like the push the available data to the appropriate client instead of being asked for updates on a time interval.

Such time interval queries can be both consuming to much resource on the server and also cause more network traffic than actually needed. Although Java had support for Observer Pattern since day 0, it is always argued to be not the best implementation (Have a look at Observer and Observable). Being on JavaEE world may even complicate things. However JavaEE6 comes with an alternative.

JavaEE6 offers '@Observable' annotation as an easy out of box implementation of Observer Pattern. Lets visit the previous post and extend it to use observers.

package com.devchronicles.observer;


import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;


/**
 *
 * @author Murat Yener
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
    @Inject
    private String message;
    
    @Inject 
    Event<String> event;
    
    public void startService(){
        System.out.println("start service call "+message);
        event.fire("this is my "+message);
        System.out.println("done...");
    }
}


The EventService class will be injected an Event object of type String which can be used to fire String objects. If you had not read the previous post,  message object is a String which will be produced by a factory and injected to the EventService class. To make it simpler you can just type any string constant to the variable called message.

Since we are already done with the observable part, now it is time to create an observer to listen our events.

package com.devchronicles.observer;


import javax.ejb.Stateless;
import javax.enterprise.event.Observes;


/**
 *
 * @author Murat Yener
 */
@Stateless
public class EventObserver {


    public void doLogging(@Observes String message){
        System.out.println("Observed:"+message);
    }
}

The Observes annotation marks the method as an observer for fired String events. If you run the server and fire up start service method, you will realize how magically a string will be injected to EventService class and than fired where it will be caughed (observed) by EventObserver class. Surprisingly that is all you need to implement the observer pattern in JavaEE6.

JavaEE Revisits Design Patterns: Factory Pattern


Factory pattern is a popular pattern among most of the programming languages. The idea behind factories are encapsulating the object creation which may subject to change.
Factory Pattern might be considered as one of the easy to understand and implement design pattern which also can be quite useful. However, the implementation even gets easier JavaEE6.

In JavaEE world '@Produces' annotation is used to create object factories and '@Inject' (aka dependency injection) is used for injecting the needed resource to where approciate. Here is a simple example based on the last post.

package com.devchronicles.producer;
import javax.enterprise.inject.Produces;


/**
 *
 * @author Murat Yener
 */
public class EventProducer {
    @Produces
    public String getMessage(){
        return "A message!!";
    }
}

The method annotated with '@Produces' produces string objects. Although the type produced is given as string, you may choose any Java type or your own objects and let the producer method to act as a factory for you.

To use the produced objects we need to inject the same type.

package com.devchronicles.observer;


import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;


/**
 *
 * @author Murat Yener
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
    @Inject
    private String message;
    
    public void startService(){
        System.out.println("start service call "+message);
    }
}

When you run and invoke the startService method you will see the string value in the producer method to be injected and printed on the console. Although it might seem a bit magical, JavaEE Producer annotation relies on types which is String in our case, to create objects and inject them when they are asked for,

Producer annotation offers a simple and easy to implement and use. It simply constructs the object type given which works quite well and simple.
To construct and Inject your own types you may create new Classes or Annotate the injection so a String class might be produced by different factories.


Sunday, 13 November 2011

JavaEE revisits the Design Patterns: Dependency Injection

On dark days of J2EE, one of the highlights of Spring Framework was Dependency Injection (or Inversion of Control). Instead of highly complicated and error prone xml configurations and JNDI lookups, Spring offered an easier way of injecting resources (still with the help of xml until Spring 2.0).

JavaEE5 already introduced injection of EJBs via @EJB annotation but JavaEE6 takes this one step forward introducing CDI (Contexts and Dependency Injection). Actually CDI offers a wide range of possibilities (some you may see in following posts) including cdi extensions.

Lets start with seeing some DI in action. Although I have been familiar with JSF from first beta version, I have never been a quite fan of it and prefered either flex or gwt as the front end. However with JSF 2.0, everything is much simpler and tightly integrated with the backend. Just like the previous post, start with an empty JavaEE6 Web profile project in the IDE of your choice. With JSF 2.0 the web pages can be named with extension 'xhtml'. Start with creating a simple index.xhtml file in your web source folder with the following content.


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Trying Dependency Injection</title>
    </h:head> 
    <h:body>
        Expecting myModel to be injected!
        <h:form>
            <h:commandButton value="Ok" action="#{myModel.doEvent()}"/>
        </h:form>
    </h:body>
</html>


Although our backing bean is not there yet, this xhtml file is expecting a bean named myModel (which would be a class name of MyModel) and a method doEvent. Now we can continue with creating the backing bean. Navigate to the source folder of the project and create a class named MyModel.class.


package com.devchronicles.injection;


import javax.enterprise.inject.Model;
import javax.inject.Inject;
/**
 *
 * @author Murat
 */
@Model
public class MyModel {
    
    public Object doEvent(){
        return null;
    }      
}


This class will be the model for the xhtml page. Since the page has already defined the doEvent method of the injected bean for the action of the command button, every click will fire the doEvent method. Let's continue with adding some functionality to the doEvent method by calling startService from another service bean which would be injected to the model bean.


@Model
public class MyModel {
    
    @Inject
    EventService service;
            
    public Object doEvent(){
        service.startService();
        return null;
    }      
}


You may have noticed there is no new keyword and a constructor call for the EventService class which will be created and injected seamlessly by the time the model bean wants to use it.

Now it is time to add the stateless session EJB which our model bean will be using.


package com.devchronicles.injection;


import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;
/**
 *
 * @author Murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService
    public void startService(){
        System.out.println("Doing something very important!!");
    }
}


You may deploy the war file on a test server and navigate to index.xhtml. By the time the page is displayed MyModel class is created and injected into the page which would call its doEvent method when the button is clicked. Also the EventService bean has been created and injected to the MyModel class, thus allowing the model to call startService method.

As you may noticed there is no single new keyword or any constructor call but the two classes has been created and injected by the time they were needed which would let you deal with the real programing work while the cdi is handling the creation.

Saturday, 12 November 2011

JavaEE revisits the Design Patterns: Singleton

If you haven't read Design Patterns: Elements of Reusable Object-Oriented Software by the famous Gang of Four or Head First Design Patterns , I strongly suggest you to start with either of them since I will rather show how to implementing the patterns than to describe what they are. However, if you are already familiar with the concept, JavaEE might offer you a pathway to many abilities some considered to be unnatural.

To start coding you would need:
 - JavaEE6 SDK
 - a JavaEE server
 - an IDE (Eclipse/Netbeans/IntelliJ)

JavaEE SDK for your operating system can be downloaded from Oracle's website. Some of the SDK bundles also include Glassfish. If you prefer to use another JavaEE server you may go for JBoss or TomEE which is the regular Tomcat bundled with OpenJPA and OpenEJB. Also you may choose to download Netbeans which comes bundled with the SDK and the Glassfish in just one package (great for beginners, no configuration needed).

Singleton Pattern can be useful although it is out fashion. The idea is basically having only one instance of a class which might be expensive to create. The usual way is just making the constructor private and either creating the object or returning the already cached instance by controlling if it has been created before. There are some pitfalls which the pattern may fail on race conditions or via reflection if the implementation is not right.

JavaEE offers a simple elegant way to create and use Singletons just by adding a simple annotation. Create a new project to start, basically a JavaEE Web Profile Project would be enough to run the examples.

package com.devchronicles.singleton;


import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
/**
 *
 * @author Murat Yener
 */


@Singleton
public class SomeExpensiveBean {
    @PostConstruct
    public void start(){
        System.out.println("Started!");
    }
}

Thanks to annotations, JavaEE6 do not need any configuration xml. You may see there is a beans.xml in the project which is actually empty and you do not need to add any configuration here. @Singleton annotation marks the class as an Singleton EJB and the container takes care of handling the only instance. To make sure the instance is created at startup, the @Startup annotation is used.

...
@Startup
@Singleton
public class SomeExpensiveBean {
 ...

However the Singleton bean might rely on some other bean which we may need to make sure it was created before "SomeExpensiveBean". Surprisingly annotations would still be enough to configure.

...
@Startup
@DependsOn("SomeConfigurationBean")
@Singleton
public class SomeExpensiveBean {
 ...

... and a new bean which the container would make sure it is created first.

package com.devchronicles.singleton;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
/**
 *
 * @author Murat Yener
 */

@Startup
@Singleton
public class SomeConfigurationBean {
    @PostConstruct
    public void start(){
        System.out.println("Well, I started first!!!");
    }
}

Thats it! The beans will be created as single instances and any time you inject the bean you will get the same instance.

Friday, 11 November 2011

JavaEE6 and the Ewoks

JavaEE 6 is a great step forward in Web/Enterprise development. The Web Profile, introduced in JavaEE 6 offers an even lighterweight version of JavaEE6. However there are two problems ahead. First the famous adoption problem as still many coorporations are stuck with version 1.4 and next the resistance to not to use JavaEE.

Star Wars fans usually have mixed feelings on teddy bear like creatures called Ewoks. Those who had watched the tv show 'How I met your Mother', may remember the episode on Barney's Ewok theory. According to Barney the appreciation for the Ewoks can be explained with the Ewok Line which basically suggests that anyone born May 25, 1973 and was old enough to think Ewoks are childish by the time they appeared on the Return of the Jedi, simply hates them. However those who were born after, thus being young enough to find them cute, loved them as Ewoks remind them teddy bears.



There is a similar pattern in the JavaEE world. Those who are old (and unlucky) enough to use J2EE 1.4 (EJB 1.0/2.0/2.1) in large projects which were heavyweight, had a killing development environment (RAM eating buggy IDEs, servers booting over minutes), over engineered architectures and probably failed resulting a migration to Spring, tend to hate and stay away from JavaEE with a passion, no matter what version is subject to use. So actually the release of JavaEE5 did not really impressed everyone.

However JavaEE has changed. With the advantage of being open and having a large community, forced JavaEE to reshape itself by taking good parts from frameworks such Spring, Hibernate and others. First change was the architecture and coding style. EJBs became lightweight POJOs, unusable entity beans had been replaced with JPA, REST and Web Services became standard and an integral part of the runtime and finally annotations took over XML. Still some might argue JavaEE5 was not yet ready since it was not as mature as Spring and the development environment was still not quick and responsive which I might agree. Using Spring on Tomcat instead of EJBs and JavaEE5 on an application server would greatly increase the development productivity but still JavaEE5 was big step forward designing, leveraging and architecting the Enterprise Java platform from strach.

JavaEE6 aimed the weakest points left. Maturing the platform while offering a fast, lightweight runtime and development platform. Those who suggest using Tomcat because it starts up few seconds where a JavaEE Application Server would take minutes lost their ground with the new JavaEE servers such as Glassfish or Jboss which would start just a little slower than Tomcat. Still if you are a fan of Tomcat, it already has an JavaEE certified version called TomEE which uses OpenEJB / OpenJPA and boots in just a few seconds more than a regular Tomcat.

JavaEE6 not only offers the standards, ease of use, a proven design but also what has been left till now, the developer productivity with the Web Profile which support all you need other than the MDBs. You do not need full blown heavy servers or frankestein IDEs and do not need coffee breaks on builds and server restarts. Downloading the JavaEE6 sdk which is bundled with Glassfish and your favorite IDE is all you need. You can also use Jboss or TomEE as your server.

JavaEE6 is definitely worth to try. It might have taken some time but with following the path which frameworks and the community has pointed, JavaEE became rock solid, cool and productive environment. Some may argue about the vendor support but as the community shifts to JavaEE6, all vendors would only left with one choice to follow and it is for sure whatever happens Java will be the future of development on the enterprise world.



Wednesday, 9 November 2011

Adobe kills Flash on Mobile

Adobe officially announced that they are not going to support Flash on any mobile platform anymore which ironically I read from my mobile phone. Some might agree Adobe has already moved from Flash to AIR on mobile and this news is exaggerated. However, I just disagree with a passion and here is why.

I like Sony and usually not afraid to buy their new products because they have (mostly) a good history on supporting their products. Anybody remember minidiscs? It was one of the most innovative product Sony has ever released. It was a bold step to revolutionize CD, it was a great step forward on mobility while preserving quality and finally it was the father of MP3. Sony, without telling anyone, did used a compression on the recordings. Although people reacted in a negative way once it was discovered, the idea brought the mp3 in everyones life. However the product had failed in the market. Sony did not step back and tried to strike back in every possible way. They even brought MiniDisc back to life as a mp3 player. Over a decade they kept MiniDisc in the market. They might have failed to get a market share but they did show their support and faith to their own product. Later they did a similar strategy to support with the first PlayStation which did not take that much attention in the beginning.

The moment I read Adobe's retrieval I remember a GTUG meeting which I had a session on Android. Just before me someone had a session on Flex/Air on Android which was still beta that time. As I started my presentation I did take a break on my subject and ask if anyone really believed Adobe could catch up with Apple and Google on supporting the new APIs. Not many people did. Adobe has failed providing the Flash Lite. By the time they were still developing an average mobile device had 1gz cpu and hundreds of mbs of ram which was even ok to full blown JRE. So they moved the other way, porting the full Flash to mobile. By the time the beta has landed on Android (remember the show on AdobeMax?), suddenly we realize that Steve Jobs was right. Flash on mobile device was power consuming, laggy and not good to be operated by touch. Still there was hope so developers waited with faith.

Today Adobe announced the death of Flash on mobile, so can we count on they will hugely invest on AIR on mobile? They did kill flash on mobile, flex builder on linux, flash on linux which were all promises they made. Now can anyone really trust on AIR? Adobe not just abondoned Flash they are loosing developers faith really fast.

Besides Flash is still the most widely available platform on desktop and with the rise of the Android they became available on half of the smart phones which they let it go. I have never seen such a retrieval move from any vendor while having such a market share. It is sad Adobe... it is a sad day for Flash...