Friday, 30 December 2011

GWT meets Flex: gwt4flex

2011 was definitely not the year of Flex. With the rise of the mobile devices including tablets, Adobe decided to step back instead of striking back.

Lately most of the web UI work I have been doing has moved to gwt from flex. I still feel flex is a great platform and enjoy coding in actionscript but have really doubts about its future. 

While I go deeper in GWT, I found out a very interesting project by Alain Ekambi. I downloaded and gave a test drive. Honestly what I had in mind was different from Alain's aim. I was expecting to find an easy integration of flex from gwt but what Alain had achieved was much more complex, building a Flex application (compiled swf) from gwt style code which is pure java.

I had been teaching and coding flex since version 2 beta, thus I feel very comfortable with actionscipt, mxml and event oriented programming. However not everyone feel that way and that was what Alain tried to achieve with gwt4flex which lets you to code in in GWT but compiles swf files offering a easier learning curve for Java developers.

I emailed Alain to see if I can achieve what I had in my mind, using flex components partially in GWT applications as if they were GWT components. Surprisingly Alain was kind and fast enough to implement what I wanted and sent me a beta jar in several hours.

GWT4Flex can be dowloaded on this link. The live demo shows a nice looking flex application, however, if you click the view source button what you will find out will be GWT style source code which does a client side pdf creation.

  1. public class Gwt4FlexExplorer extends  FlexEntryPoint {  
  2.    @Override  
  3.     public void onLoad() {  
  4.                 final Panel panel = Panel.newInstance("Gwt4Flex and AlivePDF");  
  5.                 panel.setPercentSize(70);  
  6.                 panel.setCenter(0);  
  7.                   
  8.                 final RichTextEditor richTextEditor = RichTextEditor.newInstance();  
  9.                 richTextEditor.setPercenSize(100);  
  10.                 panel.addElement(richTextEditor);  
  11.                 Application.get().addElement(panel);  
  12.   
  13.                 ControlBar controlBar = ControlBar.newInstance();  
  14.                 Button pdfButton = Button.newInstance("Export text to PDF""demo/pdf.png");  
  15.                 pdfButton.addEventListener(MouseEvent.CLICK, new FlashEventListener<Event>() {  
  16.                     @Override  
  17.                     protected void onFlashEvent(Event event) {  
  18.                         if (richTextEditor.getText() == null || richTextEditor.getText().isEmpty()) {  
  19.                             Alert.show("Please enter a text in the RichTextEditorControl");  
  20.                         } else {  
  21.                             PDF pdf = PDF.newInstance();  
  22.                             pdf.addPage();  
  23.                             pdf.writeFlashHtmlText(richTextEditor.getHtmlText());  
  24.                             Application.get().saveFile( pdf.save(), "Generated.pdf");  
  25.                         }  
  26.   
  27.                     }  
  28.                 });  
  29.                 pdfButton.setHeight(40);  
  30.                 controlBar.addElement(pdfButton);  
  31.   
  32.                 Spacer spacer = Spacer.newInstance();  
  33.                 spacer.setPercentWidth(100);  
  34.                 controlBar.addElement(spacer);  
  35.   
  36.                 Button sourceButton = Button.newInstance("View Source","demo/code.png");  
  37.                 sourceButton.addEventListener(MouseEvent.CLICK, new FlashEventListener<Event>() {  
  38.                     @Override  
  39.                     protected void onFlashEvent(Event event) {  
  40.                         FLEX.navigateToURL(SourceCodeController.getSourceFor("RichTextEditor"));  
  41.                     }  
  42.                 });  
  43.                 controlBar.addElement(sourceButton);  
  44.                 panel.addElement(controlBar);  
  45.             }  
  46. }  

If you check Emitrom's website actually they offer much more such as GWT4Touch which lets you code in GWT style Java and use Sencha Touch in the background! 

Although I do encourage everyone to learn new languages, similar to Google's approach of compiling javascript from well known Java, Emitron's tools offer the most easy path for a Java developer to produce Flex or Sencha apps.  

Great work Alain!

Wednesday, 28 December 2011

JavaEE Revisits Design Patterns: Asynchronous

Although you may not find Asynchronous method calls listed as a design pattern, I find it worth to mention. So here comes the last post of my JavaEE Revisits Design Patterns series.

Asynchronous method calls is not much more than multithreading. Basically it refers to a a method call which would run in a separate thread, thus the main (caller) thread does not need to wait for the result of the execution of the called method. In the age of web programming, developers mostly delegate the threading issues to the running server and creating new threads can be tricky and sometime dangerous on web servers since they usually like to manage the threads themselves.

However, playing nice with the servers while using threads can be very simple with JavaEE. Annotating a method with @Asynchronous would be enough to tell the JavaEE container to run the called method in a separate thread asynchronously. To test asynchronous execution lets add a new method marked with the Asynchronous annotation to our previous example.


package com.devchronicles.observer;


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


/**
 *
 * @author Murat Yener
 */
@Stateless
public class EventObserver {
    
    @Asynchronous
    public void doLogging(@Observes String log) {
        System.out.println("1.Start logging:"+log);
        try{
             Thread.sleep(3000);
        }catch (InterruptedException e){}
        System.out.println("1.done logging");
    }
    
    public void doLogging2(@Observes String log) {
        System.out.println("2.Start logging:"+log);
        try{
             Thread.sleep(3000);
        }catch (InterruptedException e){}
        System.out.println("2.done logging");
    } 
}

The EventService class remains same except for few lines for logging.

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...");
    }
}

Run the application and click on the button on the index.xhtml which would fire up the startService method. The log file should be something similar to the one below.


INFO: Observer was successfully deployed in 553 milliseconds.
INFO: start service call A message!!
INFO: 2.Start logging:this is my A message!!
INFO: 2.done logging
INFO: done...
INFO: 1.Start logging:this is my A message!!
INFO: 1.done logging

Although the log might differ, you should still clearly see the startService method is called which fired the event followed by the execution of the second logging method. The startService method waited until the execution of the second log method is complete. However, the first logging method started and end its execution independently from either of the other methods execution.

Although this example is based on void methods, its quite simple to use Future<> as a return type and to receive a result asynchronously.

Asynchronous annotation is very easy to use and can be very useful in situations where you do not want to wait for the execution of the called method.

Tuesday, 6 December 2011

JavaEE Revisits Design Patterns: Observer Part 2

As seen in the previous post, JavaEE6 offers an easy way to implement the Observer Pattern. After publishing the post, I had receive few questions on how to differentiate string types that are fired and observed.

Although in real world scenarios you wouldn't probably firing and observing plain strings but your own objects which would be observed by their type, still it is pretty easy to differentiate same type of objects and setup different observers to listen them.

First lets start with the part to differentiate plain strings.


package com.devchronicles.observer;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;


/**
 *
 * @author Murat Yener
 */

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
public @interface MyEvent {
    
    Type value();
    
    enum Type{
        LOGGING, MESSAGE
    } 
}

The interface above will act as annotation to mark the string to be fired and later to be observed just by annotating the appropriate parts.

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 @MyEvent(MyEvent.Type.LOGGING)
    Event<String> event;


    @Inject @MyEvent(MyEvent.Type.MESSAGE)
    Event<String> anotherEvent;

    
    public void startService(){
        System.out.println("start service call "+message);
        event.fire("this is my "+message);
        System.out.println("done...");
        anotherEvent.fire("done with the service!");
    }
}

We just add MyEvent annotation with the desired type and later fire the events as we did before. The parts marked with red is all we added to the example in the previous post.

Now lets annotate the observer part. Again We will be just adding the red parts to the previous example.

package com.devchronicles.observer;

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

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

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



    public void doLogging(@Observes @MyEvent(MyEvent.Type.MESSAGE) String message){
        System.out.println("Observed another type of message:"+message);
    }

}

That would be all you would need to differentiate even the same type of objects to observe.

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.