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.