Tuesday, August 14, 2012

immutable classes in java

I've learned about designing immutable objects since Joshua Bloch published "Effective Java" book, but I never really practice it. I was very used to a traditional java beans with setters and getters, especially that my IDE can generate it for me.  Another reason is that we generate pojo from .xsd using jaxb, and jaxb does not generate immutable class yet.

But since I started using scala, I realized the value of having immutable objects in your code base.
Immutable objects greatly simplify your program, since they :
  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • do not need a copy constructor
  • do not need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • do not need to be copied defensively when used as a field
  • make good Map keys and Set elements (these objects must not change state while in the collection)
  • have their class invariant established once upon construction, and it never needs to be checked again
  • always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
Here's an example of an immutable object.

public final class User {
    private final String name;
    private final String username;
    private final String password;
    private final int permission;
    
    private int hashCode;

    public User(String name, String username, String password, int permission) {
        this.name = name;
        this.username = username;
        this.password = password;
        this.permission = permission;
    }

    public String getName() {
        return name;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public int getPermission() {
        return permission;
    }

    @Override
    public int hashCode() {
         //This is Lazily loading. 
         if (hashCode == 0) {
            int result = name.hashCode();
            result = 31 * result + username.hashCode();
            result = 31 * result + password.hashCode();
            result = 31 * result + permission;
            hashCode = result;
        }
        return hashCode;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (permission != user.permission) return false;
        if (!name.equals(user.name)) return false;
        if (!password.equals(user.password)) return false;
        if (!username.equals(user.username)) return false;

        return true;
    }
}


But what if you have more than 4 fields? It is not going to be pretty having a constructor with more than 4 parameters.

In that case, you can add a Builder.


public final class User {
    private final String name;
    private final String username;
    private final String password;
    private final int permission;
    private final Date createDate;
    private final Date updateDate;

    private int hashCode;

    private User(Builder builder) {
        this.name = builder.name;
        this.username = builder.username;
        this.password = builder.password;
        this.permission = builder.permission;
        this.createDate = builder.createDate;
        this.updateDate = builder.updateDate;
    }

    public String getName() {  return name; }

    public String getUsername() { return username; }

    public String getPassword() { return password; }

    public int getPermission() { return permission; }

    public Date getCreateDate() { return createDate; }

    public Date getUpdateDate() { return updateDate; }

     //equals and hashCode are ommitted.


    //User Builder
    public static class Builder {
        private String name;
        private String username;
        private String password;
        private int permission;
        private Date createDate;
        private Date updateDate;

        public Builder(String username, String password) {
            this.username = username;
            this.password = password;
        }

        public Builder(User user) {
            this.name = user.getName();
            this.username = user.getUsername();
            this.password   = user.getPassword();
            this.permission = user.getPermission();
            this.createDate = user.getCreateDate();
            this.updateDate = user.getUpdateDate();
        }

        public Builder setName(String name) {
            this.name = name;
            return this;
        }
        
        public Builder setUsername(String username) {
            this.username = username;
            return this;
        }

        public Builder setPassword(String password) {
            this.password = password;
            return this;
        }
        
        public Builder setPermission(int permission) {
            this.permission = permission;
            return this;
        }        

        public Builder setCreateDate(Date createDate) {
            this.createDate = createDate;
            return this;
        }
        public Builder setUpdateDate(Date updateDate) {
            this.updateDate = updateDate;
            return this;
        }

        public User build() { return new User(this); }

    }

}
 
This is how you use it:
 
 
User user = new User.Builder("username","pasword").setCreateDate(new Date()).setName("Allan").setPermission(1).build();
        
//to change the name
user  = new User.Builder(user).setName("Homer").build();
        
//change password
user = new User.Builder(user).setPassword("secret").build(); 


Now what happened, if you wanna use immutable Pojo in Hibernate?  You can do so, by

  1. Add @Access annotation in the class level
  2. Make hashCode transient

Example:

@Entity
@Table(name = "system_monitor")
@SequenceGenerator(name="PK",sequenceName="system_monitor_id_SEQ")
@Access(AccessType.FIELD)
public class SystemMonitor {
    
    @Id
    @Column(name = "id", unique = true, nullable = false)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="PK")
    private Long id;  
 
    ...
 
 
 
     

This looks cool, but it requires a lot of coding. I agree with you. This is why I created this ImmutablePojoGenerator, to help you generate the code. You download the app here - immutablePojoGenerator
 



Sunday, August 07, 2011

Reactor Design Pattern - using java nio

While working on nginx, I got so interested with the architecture on how it can address the C10K problem. Unlike traditional servers, Nginx doesn't rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture.

But what is event-driven (asynchronous) architecture really? To simplify, let's talk about Asynchronous I/O. Asynchronous I/O is also known as Non-blocking I/O. It can be best describe by the reactor design pattern.

Wikipedia explains, the reactor design pattern is a concurrent programming pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers. (The Reactor pattern is closely related to the Observer/Observable pattern in this aspect: all dependents are informed when a single subject changes. The Observer pattern is associated with a single source of events, however, whereas the Reactor pattern is associated with multiple sources of events.)

Reactor design pattern is easier to understand by examples and diagrams. In this illustration, I will be using the java nio.

Until JDK 1.4, the Java platform did not support nonblocking I/O calls. With an almost one-to-one ratio of threads to clients, servers written in the Java language were susceptible to enormous thread overhead, which resulted in both performance problems and lack of scalability.


By this time, you have the basic idea of how the reactor pattern works! The key component are the Selector, Channels (and buffers) and the handler. Let's investigate them one by one.

Channels and Buffers
Channels are like streams in the original I/O package. All data that goes anywhere (or comes from anywhere) must pass through a Channel object. A Buffer is a container object. All data that is sent to a channel must first be placed in a buffer; likewise, any data that is read from a channel is read into a buffer.

A Buffer is an object, which holds some data, that is to be written to or that has just been read from. The addition of the Buffer object in NIO marks one of the most significant differences between the new library and original I/O. In stream-oriented I/O, you wrote data directly to, and read data directly from, Stream objects.

In the NIO library, all data is handled with buffers. When data is read, it is read directly into a buffer. When data is written, it is written into a buffer. Anytime you access data in NIO, you are pulling it out of the buffer.

The most commonly used kind of buffer is the ByteBuffer. A ByteBuffer allows get/set operations (that is, the getting and setting of bytes) on its underlying byte array. (There are other buffers as well. CharBuffer ShortBuffer, IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer). *NOTE: StringBuffer was added in Java 5 and it's not even part of nio package.

Basic Example on reading data from a Channel.

//getting the channel.
FileInputStream fin = new FileInputStream( "readandshow.txt" );
FileChannel fc = fin.getChannel();

//creating a buffer.
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
fc.read( buffer );

You'll notice that we didn't need to tell the channel how much to read into the buffer. Each buffer has a sophisticated internal accounting system that keeps track of how much data has been read and how much room there is for more data.

Writing to a file.
FileOutputStream fout = new FileOutputStream( "writesomebytes.txt" );
FileChannel fc = fout.getChannel();

//create a buffer, and put some data in it.
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i=0; i<100; ++i) {
    buffer.put( i );
}

//The flip() method 
//prepares the buffer to have the 
//newly-read data written to another channel
buffer.flip();

//write data of the buffer.
fc.write( buffer );
Selector The central object in asynchronous I/O is called the Selector. A Selector is where you register your interest in various I/O events, and it is the object that tells you when those events occur. Example:
Selector selector = Selector.open();

//another way of getting selector instance.
Selector selector = SelectorProvider.provider().openSelector();
Handler The handler are your worker threads. They are responsible for the data that you read, and also for writing your data. You can pre-define a thread pool to handle all your request. There's nothing fancy about the handler. Check the link I provided below, for detailed example. Now that you are familiar with Selectors, Channels, buffers and Selector, we need to tie them together. But first, to accept connection from a client, you need a ServerSocketChannel. ServerSocketChannel is the nio version of ServerSocket that uses channeling and buffering methodology. Example:
// Create a new non-blocking server socket channel
serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);

// Bind the server socket to the specified address and port
// NOTE: HOST_ADDRESS is a type InetAddress and PORT is an int.
InetSocketAddress isa = new InetSocketAddress(HOST_ADDRESS, PORT);
serverChannel.socket().bind(isa);

//registering the ServerSocketChannel to the selector.
SelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );

The first argument to register() is always the Selector. The second argument, OP_ACCEPT, here specifies that we want to listen for accept events -- that is, the events that occur when a new connection is made. This is the only kind of event that is appropriate for a ServerSocketChannel.

Note the return value of the call to register(). A SelectionKey represents this registration of this channel with this Selector. When a Selector notifies you of an incoming event, it does this by supplying the SelectionKey that corresponds to that event. The SelectionKey can also be used to de-register the channel.

I'm sure by this time, you are ready to see a working sample code to implement this whole theory. I thought of writing an example, but this site did it very well. http://rox-xmlrpc.sourceforge.net/niotut/

Monday, June 06, 2011

Java Concurrency Utilities: using Semaphore

If you haven't done much of multi-threaded programming with Java 5, I am sure when you are ask of how prevent concurrent problems when 2 threads is accessing your data, you would think of synchronizing code, by making the method synchronized.

public class SyncCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

Perhaps, you would probably also come up with an idea, instead of synchronizing a method, you would only synchronized a block of code.

    public void increment() {
        synchronized(c) {
            c++;
        }
    }

But with the concurrency API of java 5, they have added solutions for common threads requirements. In particular, the have added "Semaphore".

A Semaphore controls access to shared resource using a counter. If the counter has a value greater than zero, then access is allowed. If it is zero, then access is denied. What the counter is counting are permits that allow access to the shared resource. Ergo, to access the resource, a thread must be granded a permit from the semaphore.

Semaphore has two constructor:

Sempahore(int num)
Semaphore(int num, boolean how)

num specifies the initial permit count. The num parameter, specifies the number of threads that can access a shared resource at any one time. If the value of num is one, then only one thread can access the resource at any one time. By setting the how to true, you can ensure that waiting threads are granted a permit in the order in which they request access.

To acquire permit, call the acquire() method, which has these two forms:

void acquire() throws InterruptedException
void acquire(int num) throws InterruptedException

To release a permit, call release(), which has these two forms:

void release()
void release(int num)

The first form releases one permit. The second form releases the number of permits.

To use a semaphore to control access to a resource, each thread that wants to use that resource must first call acquire() before accessing the resource. When the thread is done with the resource, it must call release().

import java.util.concurrent.*;

class SemaphoreDemo {

    public static void main(String args[]) {
        //instantiate a Semaphore with value 1. Meaning, 1 thread can aquire permit at a time.
        Semaphore sem = new Semaphore(1);
      
        //instantiate 2 threads to access a shared resource at the same time.
        new IncThread(sem, "A");
        new DecThread(sem, "B");
    }

}

// A shared resource.
class Shared {
    static int count = 0;
}

class IncThread implements Runnable {
    String name;
    Semaphore sem;

    IncThread(Semaphore s, String n) {
        sem = s;
        name = n;
        new Thread(this).start();
    }

    public void run() {
        try {
        //acquiring the permit.
            sem.acquire();
            System.out.println(name + "gets a permit.");
            for( int i=0; i < 5; i++ ) {
                Shared.count++;
                System.out.println(name + ":" + Shared.count);
                Thread.sleep(10);
            }
            } catch (InterruptedException exc) {
               System.out.println(exc);
            }
        //releasing the permit.
        System.out.println(name + "releases the permit.");
        sem.release();
    }
}

class DecThread implements Runnable {
    String name;
    Semaphore sem;

    DecThread(Semaphore s, String n) {
        sem = s;
        name = n;
        new Thread(this).start();
    }

    public void run() {
        try {
            sem.acquire();
            System.out.println(name + "gets a permit.");
            for(int i=0; i < 5; i++ ) {
                Shared.count--;
               System.out.println(name + ":" + Shared.count);
            }
        } catch (InterruptedException exc) {
            System.out.println(exc);
        }
        System.out.println(name + "releases the permit.");
        sem.release();
    }
}


Notice that in the run methods, there are no synchronized keywords define. That is because, the semaphore actually implements it internally making it synchronized as you acquire for the lock.

Without the use of Semaphore, accesses to Shared.count by both threads would have occurred simultaneously, and the increments and decrements would be intermixed.

Monday, May 23, 2011

new try-catch in java

As we have experienced this, it is difficult to correctly close resources. For example, if you open a file or a socket, it is easy to forget to close it. Your code can easily ran out of file handles if not properly taken care of.
To make things easier, Java 7 introduced the new "try with resources" syntax. It automatically closes any AutoCloseable resources referenced in the try statement. For example, instead of manually closing streams ourselves, we can simply do this:

import java.io.*;

public class AutomaticResourceClosing {
  public static void main(String[] args) throws IOException {
    try (
      PrintStream out = new PrintStream (
          new BufferedOutputStream(
              new FileOutputStream("foo.txt")))
    ) {
      out.print("Unable to close resource");
    }
  }
}


Take note that there is never a semicolon at the end of the "try ()" declaration.

You can read more about other features by going to Java.net site ( http://jdk7.java.net/ ).

Thursday, November 11, 2010

TDD with javascript, JQuery, QUnit and Maven

I recently attended a Test Driven Development (TDD) training by Brett Schuchert of ObjectMentor.com and find it really useful! With TDD your code maintenance and evolution are easier and regression testing is less likely to have bugs because it prevents bugs from happening in the first place.

But what is TDD exactly? The instructor defined it as a "design practice". It uses tests as mechanism for discovery and feedback. He also added that TDD is not always the right thing to do. It depends on your application and requirements.

I was surprised to know that TDD idea has been around since late 50's. The original Mercury Rocket Project uses TDD.

The training inspired me and had me started looking on the how to apply TDD in javascript. The instructor advised some framework such as jsunit, which is good, but since our FEDs (Frontend developers) uses JQuery, I have to find a framework that has less learning curve and easy to use.

I searched and found out about Qunit (http://docs.jquery.com/Qunit). QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery project to test its code and plugins but is capable of testing any generic JavaScript code (and even capable of testing JavaScript code on the server-side).

Qunit is cool! But I have to integrate it with our maven project. I want our "maven build" to break if javascript unit test fails. (like how JUnit works ).

After further research, I found Rhino. Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Given these 2 technologies, I configured maven to use qunit and Rhino to do javascript unit testing, and here's how I did it. ( If you have a better solution or comments, please let me know. )

One thing to keep in mind, when using this combo is that, you have to separate your javascript calculation logic from DOM-manipulation logic. You can extract them to a function or to an object, and unit test them separately. Use selenium to test the DOM-manipulation part. The reason being is that, you are executing javascript without the browser, and DOM-manipulation logic is easier to test using Selenium.

Here's an example on how to do it.

1) adder.js - This file is where you put the functions that you want to test.

//function that adds.
function adder(x,y) {
    return x + y;
}

2) adderTest.js - This file is your unitTest.
test("Adding numbers works", function() {
        expect(2);
        ok(adder, "function exists");
        equals(4, adder(2, 2), "2 + 2 = 4");
            }
);

3) suite.js - This file is your suite. It can contain many test.js files.

load("src/main/webapp/WEB-INF/js/qunit/qunit.js");

QUnit.init();
QUnit.config.blocking = false;
QUnit.config.autorun = true;
QUnit.config.updateRate = 0;
QUnit.log = function(result, message) {
    if(result == false) {
        print("FAILED: " + message);
        java.lang.System.exit(0);
    }else {
       print("PASS: " + message) ;
   }

};

load("src/main/webapp/WEB-INF/js/adder.js");
load("src/main/webapp/WEB-INF/js/adderTest.js");


NOTE:
a) Make sure you have downloaded qunit, and put it in your js directory. It is being referenced by suite.js
b) since I am using Maven 2, the path should starts from your base directory. (In my setup, it's in src/main/webapp/WEB-INF/js)

4) Add a dependency on Rhino and a maven plugin in your pom.xml:

...
<dependency>
   <groupid>rhino</groupid>
    <artifactid>js</artifactid>
    <version>1.7R1</version>
</dependency></pre>

...

<plugin>
    <groupid>org.codehaus.mojo</groupid>
    <artifactid>exec-maven-plugin</artifactid>
    <version>1.1</version>
    <executions>
        <execution>
        <phase>test</phase>
        <goals>
            <goal>java</goal>
        </goals>
        </execution>
    </executions>
    <configuration>
        <mainclass>org.mozilla.javascript.tools.shell.Main</mainclass>
        <arguments>
            <argument>-opt</argument>
            <argument>-1</argument>
            <argument>${basedir}/src/main/webapp/WEB-INF/js/suite.js</argument>
        </arguments>
    </configuration>
</plugin>
 



Now, when you execute "mvn test", it will execute the test suite, and run your test cases. Try adding this line in your addTest.js, and make sure to update the expect() method call.

equals(10,newAddition(5,0), "5 + 0 = 5");


making it:
test("Adding numbers works", function() {
     expect(3); //  <-- change to 3.
     ok(adder, "function exists");
        equals(4, adder(2, 2), "2 + 2 = 4");
        equals(10,adder(5,0), "5 + 0 = 5");
            }
);
);
It will break your maven build and tell you:

PASS: function exists
PASS: <span class="test-message">2 + 2 = 4</span>
FAILED: <span class="test-message">5 + 0 = 5</span>

Thursday, October 07, 2010

Pragmatic unit testing with JUnit

Here's a great slides about JUnit, Hamcrest, Parameterized Testing, JUnit Rules (Verifier, Timeout, etc), and also about naming classes.

Friday, September 10, 2010

Friday, August 27, 2010

implementing fastinfoset using CXF

I recently experimented with FastInfoset (FI) and I got it working using CXF. FastInfoset is a standard that specifies a binary encoding format for XML Information set. It aims to provide more efficient serialization than text-base XML format.

One can think of FI as gzip for XML, though FI aims to optimize both document size and processing performance, whereas gzip optimizes only the size. While the original formatting is lost, no information is lost in the conversion from XML to FI and back to XML.

The java implementation of FI is available as part of GlassFish project. ( https://fi.dev.java.net/ ).


1) In your pom.xml make sure you get the cxf version 2.2.7 or later (Thanks to Daniel and Igor for fixing the bug promptly) and add FI dependency:

<dependency>
<groupId>sun-fi</groupId>
<artifactId>FastInfoset</artifactId>
<version>1.2.2</version>
</dependency>

....

<repository>
<id>fastinfoset</id>
<url>http://repository.jboss.org/maven2</url>
</repository>


2) in your service add this annotation.

@Produces({"application/xml","application/fastinfoset" })


3) in your configuration, add the interceptor, customTypes for the JAXBElementProvider and define it in your service:


<bean id="fastInfosetOutInterceptor" class="org.apache.cxf.interceptor.FIStaxOutInterceptor" />
<bean id="fastInfosetInInterceptor" class="org.apache.cxf.interceptor.FIStaxInInterceptor" />

<util:list id="customTypes">
<value>application/xml</value>
<value>application/fastinfoset</value>
</util:list>

<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
<property name="produceMediaTypes" ref="customTypes" />
<property name="consumeMediaTypes" ref="customTypes" />
</bean>


<!-- JAX-RS endpoint configuration -->
<jaxrs:server id="sampleService" address="/">
<jaxrs:serviceBeans>
<ref bean="sampleServiceBean" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jaxbProvider" />
</jaxrs:providers>
<jaxrs:outInterceptors>
<ref bean="fastInfosetOutInterceptor" />
</jaxrs:outInterceptors>
<jaxrs:inInterceptors>
<ref bean="fastInfosetInInterceptor" />
</jaxrs:inInterceptors>
</jaxrs:server>


4) When testing, make sure you add Accept header variable with value “Application/fastinfoset”, before hitting the endpoint. (Using the browser will not work).

TO TEST:
curl -H "Accept: Application/fastinfoset" http://localhost:8080/services/samples/getSample?id=9
SampleResponse{??version@1????Samples????ResponseMetadata???Service???Name?Foo????URL?http://foo????Hostname?

You can also add a FireFox Add-on called “Poster”

Thursday, August 13, 2009

Groovy Closure vs. javascript closure

Coming from a javascript and java background, i've learned to use the javascript closure to its full advantage, but when we used groovy (on grails) for our new system, I was surprise that the concept of closure in groovy is different.

The definition of closure in groovy (from groovy.codehaus.org) is that, a groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. It has some special properties like implicit variables, support for currying and support for free variables (which we'll see later on). We'll ignore the nitty gritty details for now (see the formal definition if you want those) and look at some simple examples.

GROOVY CODE:

def myclosure = { println "hello world!" }

println "Executing the Closure:"
myclosure() //prints "hello world!"



The javascript closure is a functionality that marks a variable, that it will be use later. So even when it goes out of scope, the data is saved in the memory. Here's an example:



function SayHelloTo(name) {
var greeting = 'Hello ' + name;
var display = function() { alert(greeting); }
return display;
}

var greet = new SayHelloTo("Aidan Thor");
greet();




This is simply defining a method with a local variable called "greeting" and another method inside called display, then it returns that method.

When you instantiate "SayHelloTo", and execute it ( "greet()"), you would think that it will throw an error, because "greeting" is out of scope, but actually it will not throw an error, because the method created a closure (knowing that "greeting" will be called later).

Wednesday, July 29, 2009

MVP with GWT

MVP stands for Model View Presenter. It is a front end architecture that separates your model (data object) and the view via presenter.

A detailed description can be found in this link (http://www.martinfowler.com/eaaDev/uiArchs.html) written by Martin Fowler. The post is focused on why it's appropriate to use MVP than MVC in GWT project, and how to implement it.

It is tough to decide whether to use MVP or MVC, because both designs solve the problem. One good example that separates the two is that with MVC, it's always the controller's responsibility to handle keyboard and mouse events, while with MVP the GUI component itself initially handle the user's input, and delegate the interpretation of that input to the presenter. (Consider Struts or Spring MVC vs. Flex/Flash ).



A good friend of mine said that MVP is particularly interesting in the context of GWT when doing TDD (Test Driven Development) or just thorough testing all round. The reason is that testing widgets and widget interactions is generally slow because you need to create a UI environment (hosted mode or web mode usually) to run your tests in. By moving your application logic into the Presenter, you end up with code that can be tested fairly fast (with mock widgets). Since the widgets are simple there's less to go wrong in this harder/slower to test area.



In my opinion, the richer your client framework is (e.g. Flex/Flash, Silverlight ) the more you should favor MVP.

Here are the steps you need to do in building MVP compliant project.


1) Define a Page object. The page object represents a web page. You can even make it more granular by defining a Form object.



public class Page extends Composite implements PageView {
private presenter;

public Page() {
presenter = new PagePresenter(this);
TextArea ta = new TextArea();
ta.setCharacterWidth(80);
ta.setVisibleLines(50);
add(ta);

Button b = new Button("Comment", new ClickHandler() {
public void onClick(ClickEvent event) {
presenter.submitComment(ta.getValue());
}
});
add(b);

}
//This method is defined in PageView, and its being called
//by the presenter.
public void updateView(String text) {
Label commentLabel = new Label(text);
add(commentLabel);
}

}


Your page contains the presenter object, and it implements PageView.

2) Define your PageView interface. The PageView acts as a conduit between Page and the Presenter.


public interface PageView {

public void updateView(String text);

}


3) Define your Presenter object. The presenter is the class that contains all the business logic. It has reference to the services.


public class PagePresenter {

private PageView pageView;


public PagePresenter(PageView pageView ) {
this.pageView = pageView;
}

//You can use HasClickHandlers, Hastext or HasHTML, but I prefer just passing the
// data, if you dont need any other functionalities.
public void submitComment(String comment) {
if(comment != null) {
service.submitComment(comment);
//Do service calls here. When done, call
//pageView.updateView()
}
}
}

Sunday, May 31, 2009

what's on GWT2.0 ??

Here are a few things that I was able to capture about GWT 2.0 during google i/o 2009.

with GWT 2.0, they have added RunAsync functionality. RunAsync gives you the ability to split your javascript into chunks of files. Which allows you, not to load the entire JS from the start.

They have added ClientBundle functionality. ClientBundle includes ImageBundle, ResourceBundle and CssResource (The killer feature). ImageBundle combines individual images into a single image in multiple dimensions. Simply lining up images left-to-right to create an image strip is sufficient. This will make fewer HTTP round-trips. This is what the code looks like:


Interface MyBundle extends ClientBundle {
public static final MyBundle INSTANCE = GWT.create(MyBundle.class);

@Source(“smiley.gif”)
ImageResource smileyImage();

@Source(“frowny.png”)
ImageResource frownlyImage();

@Source(“app_config.xml”)
TextResource appConfig();

@Source(“wordlist.txt”)
ExternalTextResource wordlist();

@Source("my.css")
public CssResource css();

@Source("config.xml")
public TextResource initialConfiguration();

@Source("manual.pdf")
public DataResource ownersManual();
}

This is how you would use it:

Window.alert(MyResources.INSTANCE.css().getText());
Frame myFrame = new Frame(MyResources.INSTANCE.ownersManual().getURL());
TextResource configs = MyBundle.INSTANCE. InitialConfiguration();
String configXml = configs.getText();
Document doc = XMLParser.parse(configXml);


The CSSResource compiles CSS with an enhanced syntax. It defines and uses constants in CSS. E.g.

@define myBorder 8px;
@define myColor #FDD;
.error-border { border:myBorder solid:myColor; }

It also uses conditions for user agent, locale or anything.

/* Runtime evaluation in a static context */
@if (com.module.Foo.staticBooleanFunction()) {
... css rules ...
}

/* Compile-time evaluation */
@if {
... css rules ...
}
@if user.agent safari gecko1_8 { ... }
@if locale en { ... }

/* Negation is supported */
@if !user.agent ie6 opera { ... }


GWT 2.0 have updated sets of Panel that fix the Layout. The example given is the new and improve DockPanel. It doesn’t run javascript during resize. Constraints-based layout similar to Cocoa on OSX.

GWT2.0 have added option in the compiler is: -XdisableClassMetaData. Calling obj.getClass() or clazz.getName() forces class objects and their names to be generated into javascript. It has Size, speed and obscurity benefits.

GWT2.0 added options in the compiler is: -XdisableCastChecking. Nobody actually catches ClassCastException in app code. (I hope you are not doing this):


Void makeItQuak(Animal animal) {
Try {
((Quaker) animal).quak();
}catch(ClassCastException c ) {
Window.alert(“doesn’t quak!”);
}


The above example generates a call like this (compiled JS)

DynamicCast(animal, 2).quak();


But when the flag is turned on, you only get this:

animal.quak();

How does this help you? In real-world (and very large) google app:
-1% script size reduction
-10% speed improvement in performance-sensitive code.


GWT have added RPC blacklist. Tell the RPC subsystem to skip types that you know aren’t ever sent across the wire:

<extend-configuration-property name="”rpc.blacklist”" value="”com.example.client.WidgetList”">


-Added Client side stackTrace on some browsers.
Throwable#getStackTrace() actually does something sometimes )


-Added interfaces on JavaScript Overlay Types.

Wednesday, May 20, 2009

adding whitelist or blacklist option in maven GWT

If you are using Maven GWT plugin and find yourself lost in adding the whitelist or blacklist option in the configuration, do not worry, because it is not supported.

At first, I thought it's just another configuration tag, so i added:

<configuration>
<whitelist></whitelist>

But it didn't work. The solution is to add it in the runTarget tag. like this:

<properties>
<whitelist>" ^http[:][/][/]sample[.]net"</whitelist>
</properties>

<runtarget>com.sample.app/Sample.html -whitelist ${whitelist}</runtarget>


I hope this helps.

Monday, May 18, 2009

4 steps to add facebook connect (xfbml) to google web toolkit (GWT) app

Adding facebook connect (XFBML) to your Google web toolkit (GWT) application


This is a fast track tips on how to add facebook connect to your GWT based application.



Step 1: add a facebook application.
If you don't have the facebook application. Just login to facebook and search for the word "developer" in the search field of the menu bar.

http://screencast.com/t/43OHbcLl9

select developer and add/install it. Select "Set Up New Application" , select an application name, select agree then save changes.
The next page is the application configuration. take note of your API Key, because you will be using it. In the left menu bar, select "Connect".
in the connect URL, add your URL. (e.g. http://localhost:8888/com.sample.facebookApp/ ). localhost will work, because facebook connect will not
ping your server.



Step 2: adding the facebook connect library
open your .html file and add the facebook connect name space and the javscript library.


<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

...

<body>
</body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript">

Facebook said that its faster to add the script tab below the closing body tag.




Step 3: add Cross Domain Communication Channel in your GWT app.

create a file called "xd_receiver.html" or download the file from http://www.somethingtoputhere.com/xd_receiver.htm and save it to the
public diretory of your google web toolkit app. You will reference this file later in your code.


Step 4: adding the code in your EntryPoint.


a) Add a static final String called FB_API_KEY and XD_RECEIVER_URL.


public static final String FB_API_KEY = "YOUR_KEY_FROM_FROM_YOUR_FACEBOOK_APP";
public static final String XD_RECEIVER_URL = "/xd_receiver.html";


b) build init method. This method initialize the facebook connect in your app. You should call this method in your onModuleLoad()


private static native String initFacebook(String apiKey, String xd_receiver_url)
/*-{
$wnd.FB_RequireFeatures(["XFBML"], function(){
$wnd.FB.Facebook.init(apiKey, xd_receiver_url);
});
}-*/;


c) Define the loginHandler. The login handler gets executed after a user login has login to facebook connect. This method should be called
in your onModuleLoad().


private native void defineFbLoginHandler() /*-{
var fbConn = this;
$wnd.facebookConnectLogin = function() {
//The "@com.sample.facebookApp.XfbmlPrototype" is the fully qualified name of your GWT app EntryPoint.
//The renderFriendsList is the method that will be executed after you login. (aka. login handler).

@com.sample.facebookApp.XfbmlPrototype::SESSION_KEY = $wnd.FB.Facebook.apiClient.get_session().session_key;
fbConn.@com.sample.facebookApp.XfbmlPrototype::onLoginHandler()();
}
}-*/;

public void onLoginHandler() {
Window.alert("Login is successful!!");
//You can start adding XFBML comments here, like welcome notes, friend selector, etc.
}


d) define a parseDomTree method. Since facebook XFBML is not standard, you need to execute a method for them to render.


private static native void parseDomTree() /*-{
$wnd.FB.XFBML.Host.parseDomTree();
}-*/;


e) define your login button.


private Widget makeFbLoginButton() {
String fblogin = "";
HTML html = new HTML(fblogin);
return html;
}


As you can see, in the onlogin we point it to "facebookConnectLogin()". This method is define in defineFbLoginHandler() method we created in step c.




To sum it all up, your onModuleLoad() method will look like this:


public void onModuleLoad() {
FlowPanel loginPanel = new FlowPanel();
RootPanel.get().add(loginPanel);

Widget fbLoginButton = makeFbLoginButton();
loginPanel.add(fbLoginButton);

initFacebook(FB_API_KEY, XD_RECEIVER_URL);
defineFbLoginHandler();
}


Take note that facebook widgets doesn't render in Google Hosted mode. I tried DeferredCommand but it doesn't work. Make sure to compile and test it in a
browser.

Here's the link to all the facebook connect tags that are available: http://wiki.developers.facebook.com/index.php/XFBML

These are the books that I recommend:
1) GWT in Practice
2) GWT in Action
3) Google Web Toolkit Applications (Paperback)

Monday, February 16, 2009

busy life

It's been a year since my last post. I've been very busy working on a project that involves GWT, Grails and Android. Part of it, is that I got so busy with my personal life too.

With regards to the technology I'm using, it seems to me that there are lots of documentations, tutorials in the internet available already. So it doesn't make sense for me to post some introduction on these technologies since they can easily be found.

Although, I will post some methodology and technique that I find interesting when I get a chance.

Monday, February 04, 2008

Wicket IndicatingOrderByBorder component

Wicket have form components that displays a busy icon (like progress bar) whenever a button is clicked. They are the IndicatingAjaxButton, IndicatingAjaxFallbackLink, IndicatingAjaxLink and IndicatingAjaxSubmitButton objects.

What is not provided though is the indicating orderByBorder component. What is OrderByBorder in the first place? It's a component to use, if you want to sort your SortableDataProvider component.

Using the api OrderByBorder does the job well if your data is not big. But if you are sorting huge amount of data, its better to "Ajaxify" it. (For more information about Sorting Data View you can read it here: http://wicketstuff.org/wicket13/repeater/ ).

Here's the customize code for making your own Ajax OrderByBorder:


class IndicatingOrderByBorder extends AjaxFallbackOrderByBorder implements IAjaxIndicatorAware {

private final WicketAjaxIndicatorAppender indicatorAppender = new WicketAjaxIndicatorAppender();
private Form contactListForm;

public IndicatingOrderByBorder(String id, String property, ISortStateLocator
stateLocator, DataView dataView, Form contactListForm) {
super(id, property, stateLocator);
this.contactListForm = contactListForm;
add(indicatorAppender);
}

@Override
protected void onAjaxClick(AjaxRequestTarget target) {
target.addComponent(contactListForm);
}

public String getAjaxIndicatorMarkupId() {
return indicatorAppender.getMarkupId();
}
}


To learn that basic, you can read these books:
1) Pro Wicket
2) Wicket In Action (release date: July 2008)

Wednesday, December 05, 2007

Wicket HTML Table implementation

This is how you implement an html table using Wicket framework. For those of you who are new to wicket, Wicket is a component-oriented Java web application framework. It’s very different from action-/request-based frameworks like Struts, WebWork, or Spring MVC where form submission ultimately translates to a single action. In Wicket, a user action typically triggers an event on one of the form components, which in turn responds to the event through strongly typed event listeners. (See wicket.apache.org).

This example shows how you render an html table that display person's data. (e.g. first name, last name and age ).

1) First you need to define your HTML.


<form wicket:id="personListForm">
<table width="100%" border="0" >
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
<tr wicket:id="personList">
<td wicket:id="firstName">[first]</td>
<td wicket:id="lastName">[last]</td>
<td wicket:id="email">[email]</td>
</tr>
</table>
</form>



2) In your java code where you have to define the form. You will need the following:

a) Define a dataProvider - You can implement the IDataProvider interface, and define its functions. Normally, the IDataProvider is an object
that has access to your backend service.

b) Define a model - You can implement IModel, or you can use the subclasses available. ContactDetachableModel, DetachableContactModel, StringResourceModel.
Why can't we just use the POJO directly from the backend service? Well, wicket will sometimes serialized the object to save memory when you move from one page to the other, and go back. All
object that you will need to display, have to be wrapped/implemented IModel.




//This is the POJO that you retrieve from your service.
class Person implements Serializable {
private static final long serialVersionUID = 5934872279937101444L;
private String firstName;
private String lastName;
private String email;

//access methods here.
//getters and setters not define.

}


A detachable modelin Wicket is a model that can get rid of a large portion of its state to reduce the amount of memory it takes up and to make it cheaper to serialize when replicating it in a clustered environment. When an object is in the detached state, it contains only somevery minimal nontransient state such as an object ID that can be used to reconstitute the object from a persistent data store. When a detached object is attached, some logic in the object uses this minimal state to reconstruct the full state of the object. This typically involves restoring fields from persistent storageusing a database persistence technology


//This is the Wicket Model
public class DetachablePersonModel extends LodableDechableModel {
//make it transient, so that it will not get serialized.
private transient Person person;

@Override
public Object getObject() {
return this.person;
}
...

}



public class PersonDataProvider implements IDataProvider {

public Iterator<Person> iterator(int first, int count) {
Iterator<Person> iterator = null;
iterator = getPersonService().retrieveEntirePerson(first,count);
return iterator;
}

//Your model is used here.
public IModel model(Object object) { return new DetachablePersonModel((Person)object); }

public int size() {
int size = 0;
try {
size = getPersonService().retrieveEntirePerson().size();
} catch (ServiceException e) { //implement exception here.}
return size;
}

}


c) Define a DataView - Data views aim to make it very simple to populate your repeating view from a database by utilizing IDataProvider to act as an interface between the database and the dataview.


Normally, you will implement DataView as an anonymous class, or an inner class, because the chances of reusing the class is minimal.


//define as inner class

private class PersonDataView extends DataView {

...
@Override
protected void populateItem(Item item) {
Person person = (Person) item.getModelObject();
item.setModel(new CompoundPropertyModel(person));
item.add(new Label("firstName"));
item.add(new Label("lastName"));
item.add(new Label("emal"));

}
}


3) This is how you would define it in your page.


final Form persontListForm = new Form("personListForm");
final PersonDataProvider personDataProvider = new PersonDataProvider();
final DataView personDataView = new PersonDataView("personList", personDataProvider);
personDataView.setItemsPerPage(5);
persontListForm.add(contactListDataView);



For information regarding the objects used in this example visit:

http://people.apache.org/~tobrien/wicket/apidocs/index.html


Main wicket site:

wicket.apache.org

Tuesday, November 20, 2007

JavaScript Function Closure

Coming from a C++/JAVA background, it was hard for me to assimilate the concept of Function Closure in JavaScript. Now that I understand it, I'd like to share it here with you. Seriously, it's best explained by example than description. Here's an example.


var thingsToDo = {};

function initializeThingsToDo() {
var food= {
name: "Ramen",
type: "Tokatsu"
};
thingsToDo.eat = function() {
alert("I'm going to eat: " + food.name);
}
}

//Execute
initializeThingsToDo();
thingsToDo.eat();


Okay, what did I do here? First, I created an empty (global) Object called "thingsToDo", then I added a global function called "initializeThingsToDo". Inside this function I defined food object. I referenced the global object "thingsToDo" and attached a dynamic function called "eat" in the object.

After the code definitions, I ran the global function initializeThingsToDo, and called the method thingsToDo.eat().

I know you would say that this is crazy because when I ran thingsToDo.eat(), the method uses the food object but it's already out of scope.


//Execute
initializeThingsToDo();
thingsToDo.eat(); // When this is executed,
// the food object is already out of scope!


Na ah?! Not in JavaScript. You see, when you run the code, JavaScript will create a closure to the food object. After that, it saves it in the memory. The interpreter knows that it will be used for later. (It doesn't deallocate the food object in the memory. )

The power of function closure is well executed when you use AJAX. When you define your AJAX callback function, it gets called asynchronously. It creates a closure and call the objects/functions when it's ready.

If you are not familiar with JavaScript Object and Functions, you can read these links:

Java vs. JavaScript object
JavaScript usign Prototype.js
JavaScript Function

Monday, November 05, 2007

JavaScript function/procedure using Prototype.js framework

Prior to web2.0 and AJAX, I only use javascript for front end validation and some front end calculations.

When I started using Prototype.js, I learned a lot more about javaScript, particulary with functions/procedure.

If you are a java programmer, you probably write functions the traditional way.

e.g.
function sayHello() {
return "hello there!";
}

But there's an alternative. You can define functions this way:

var sayHello = function() {
return "hello there!";
}

Here we declared a global variable called sayHello, to which we have assigned a value. The value is, in this case, an anonymous function defined using the function() keyword.

Take note, that the effect of both ways are the same. (The second one is similar to C/C++ pointer to a function. wink-wink ).

In JavaScript, a Function is a first-class object that exists in its own right, unlike the method of an object in an object-oriented language.

To give an example about Function being a first-class object, let me explain about how to call the functions.

To call a function, you would use parenthesis.
e.g.

sayHello();

if you dont put the "()" it will return a reference to a function. You use that if you want to assign another name to call your function.

var sayHelloFxn = sayHello;

How does javascript function deal with input parameters? Consider this example

var animalCreator = function(species,color) {
return { species:species, color:color }
}


I created a function that returns a object (HashMap or associative array depending on how you want to call it ). What happened if I do call it like this?

1) var whale = animalCreator("mammal" );
2) var frog = animalCreator("amphibian", "green");
3) var eagle = animalCreator("bird", "white", "bald eagle" );

You would probably think that 1) and 3) will generate error. According to the declaration of the function "animalCreator" it accepts two arguments, called species and color. It is obviously designed to be called with two arguments, but in JavaScript (and unlike Java or C/C++/C#) this is nothing more than a guideline.

For 1), since there's only one argument, the second one will be set to null. and for 3) we pass a third argument. That will simply be ignored.

Okay, so much for function call. Let me explain about function as first-class object and how function changes its context. I know its weird, but the function object itself has its own function. You can use Function.call() or Function.apply() to execute a function.
e.g.

var food = { meal:"bread and egg", drink: "green tea" };
var person = {
meal:"bacon and rice",
drink: "coffee",
eat: function () {
return "I'd like to eat " + this.meal + " and drink " + this.drink;
}
};

1) person.eat();
2) person.eat.call(food);


Here we define 2 objects (food and person). Person has a function called "eat". The first one will return:

I'd like to eat bacon and rice and drink coffee.

while the second one, since you are using call, and passing an object as an argument. The function context will use the context of food. It will return:

I'd like to eat bread and egg and drink green tea.

As you noticed, the "this" changes context. This concept is very important in javaScript, because this is unlike java and C/C++/C#.

The apply() method operates similarly, except that it expects all arguments to the function invocation to be bundled as an array that is passed in as the second argument to apply(). Subsequent arguments are ignored.

Function Closures

What is function closures?

Friday, November 02, 2007

Free Directory Assistance?

If you need a phone number of a certain establishment you normally dial 411. It cost you about $1 (depending on your cellphone carrier).

411 is old school now. There's a way to get this information (and more) for free. Call 1-800-GOOG-411 or 1-800-466-4411, and you can ask not only for the numbers, but even for address, direction, etc. You can also request to deliver it to you via SMS (text message).

Kudos to Google!

Now what are you waiting for? Try it out! and save it in your phone's contact!

Check video below for more information.