Thursday, December 25, 2008

Guicing JSF with Guice

Recently I read some of presentation of the WebBeans. This encourage me to learn JSF. When learning the JSF there are Managed Bean and I think I need some injection, Guice cross on my mind, so I search on the internet about integrating Guice and  JSF. Some of article and one project found, but none of fits on what I need and I want.

So I'm trying to learn how this JSF works so I can use Guice on it.

The case of login on a web page. User need to login to a web page using username and password. Below is the login bean

public class LoginBean {
    private String username;
    private String password;
    
    public String login() {
        return "success";
    }
    
    public void reset(ActionEvent event) {
        username = null;
        password = null;
    }
}

we need some logic when login button execute. So I add some logic.

public class LoginBean {
    private String username;
    private String password;
    
    @Inject
    private UserDao userDao;
    
    public String login() {
        User user = userDao.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            // we found the user on our d   atabase
            return "success";
        } else {
            // there is no user with specified username and password
            return "failed";
        }
    }
    
    public void reset(ActionEvent event) {
        username = null;
        password = null;
    }
}

The @Inject marked will be injected by the Guice injector. So we are going to create the Guice injection works. Mojarra, the JSF Resource Implementation, we can find com.sun.faces.spi.InjectionProvider, here are the injection will be held.

public class InjectionProvider {
    void inject(Object managedBean) throws InjectionProviderException;
    void invokePostConstruct(Object managedBean) throws InjectionProviderException;
    void invokePreDestroy(Object managedBean) throws InjectionProviderException;
}

We are iterested only on "inject" method, this are executed everytime the Managed Beans are about to use.

public class GuiceInjectionProvider implements InjectionProvider {
    private final Injector injector;
    
    public GuiceInjectionProvider() {
        // create injector
        injector = Guice.createInjector(new InMemoryModule());
    }
    
    public void inject(Object managedBean) throws InjectionProviderException {
        // inject managed beans
        injector.injectMembers(managedBean);
    }
    
    public void invokePostConstruct(Object managedBean)
            throws InjectionProviderException {
    }
    
    public void invokePreDestroy(Object managedBean) throws InjectionProviderException {
    }
}

Above are simple implementation for the injection, actually for now on we need the simple one. The creation of injection is on the constructor.

We already have the java class, now is the configuration part. Add context-param on web.xml




<context-param>
lt;param-name>com.sun.faces.injectionProvider</param-name>
<param-value>uudashr.guicejsf.guice.GuiceInjectionProvider</param-value>
</context-param>



It tells the mojarra to use custom injection provider.

Thursday, September 4, 2008

V8 Benchmark

Google Chrome is rock.
One things that make it a rock star is the JavaScript engine, "V8". Then I try to do a benchmark by opening http://code.google.com/apis/v8/run.html on different browser.

Here are the result:

Google Chrome 0.2.149.27
Score: 1362
DeltaBlue: 1543
Crypto: 1201
RayTrace: 1022
EarleyBoyer: 1820

Safari 3.1.2
Score: 165
DeltaBlue: 115
Crypto: 113
RayTrace: 194
EarleyBoyer: 296

Firefox 3.0.1
Score: 174
DeltaBlue: 204
Crypto: 110
RayTrace: 173
EarleyBoyer: 237

Opera 9.52
Score: 247
DeltaBlue: 160
Crypto: 110
RayTrace: 315
EarleyBoyer: 666

Well, where is the IE7?
When I open the URL on IE7, it shows alert window when the progress reach 33%, but I finally got the result.


Internet Exprorer 7
Score: 41
DeltaBlue: 18
Crypto: 36
RayTrace: 57
EarleyBoyer: 78

At first, the score is only 18, and I try it again, hoping a better result. It only can reach 40 to 41.

Well, IE7 has the slowest JavaScript engine. The browser war is started.

Wednesday, August 6, 2008

jEdit: Basic Setting of My Favourite Text Editor

Not much people knows jEdit is a great tools, most of I know it can compete with existing commercial and free Text Editor (or even Programmer's Editor), and the great thing it is multiplatform and open source, many people give contribution on jEdit.

I'll introduce best practice of using jEdit, it based on my needs as software developer.

You can download jEdit on www.jedit.org. Get the jEdit distribution and install it.
Start the jEdit, and you will see splash screen like this



Some platform such windows has jEdit server, it runs on the background, so there is no need to do initialize things again and when you need to open jEdit, it will start quicker.

This are the main screen



Since version version 4.3 pre 14 it has new splash screen and little fancy icons.
Straight to the point, what do programmers usually need is?
  1. Line numbers
  2. Indentations
  3. Shortcut to do things
Line numbers
To show line numbers, simply by click on menu bar: "Utilities -> Global Options..."
Alternative of this you can click "Global Options..." on the toolbar.
Select "gutter" on the left tree and check the "Line numbering" on the right view.

Indentations
Indentation has been set by default, but it use 8 as tab and indent width. I'm not conform with this options and usually use 4 as tab and indent width . On the same "Global Options..." dialog, select "Editing" on the left tree. Fill all the desirable value.

Shortcut
Programmers need to do things fast. So this are list of some usefull shortcut
  • Open... (ctrl + o)
  • New (ctrl + n), it will create new editor of new buffer. Buffer is just like tab.
  • Show Buffer Switcher (alt + back_quote), it just open the combo box, you can do this by clicking on the Buffer Switcher.
  • Go to Next Buffer (ctrl + page_down)
  • Go to Previous Buffer (ctrl + page_up)
  • Find... (ctrl + f)
  • Find next (ctrl + g)
  • Incremental search (ctrl + comma)
  • Hypersearch (ctrl + period), this will show list of all occurrence word on different view
  • Incremental search for selected word (alt + comma)
  • Hypersearch for selected word (alt + period), this will show list of all occurrence word on different view
Well, start using the free and powerful jEdit. It has many other functionality and you can make it more powerful by using plugins.

Thursday, May 29, 2008

ConcurrentHashMap

Why use the ConcurrentHashMap? The traditional synchronized HashMap or Hashtable, use a single lock to read and write. When you try to write new entry while other try to read the different entry, the locking happened. Shouldn't be like this. The simple implementation is using a N lock for N entries. The modification for entry X will be use the Y lock, where Y is lock for X. On ConcurrentHashMap, they use segmentation for the lock, they have 32 lock (or depends on the configuration). So a different write or read can be done concurrently without locking if they have a different lock/segment.

Wednesday, October 17, 2007

Why use log adapter (generic logging)

Long time ago I have a question "Why use common logging, why not use log4j?"
The answer is "Because you can use different log implementation".
Unsatisfying answer.
But past week ago I found SLF4J and I use it for jSMPP projects.

It comes answer that we are creating API/Component that might be use with application using unpredictable log implementation.

Saturday, September 8, 2007

Why I love jEdit

jEdit, this is an awsome programmer's text editor. Might some of people said that the user interface is ugly, but it's powerful, believe me.
Give it a try for some time range, try to find out "how do I do things in jEdit", try to see the available plugins.
Here is my favourit plugins:
  1. Buffer Tabs
  2. Project Viewer
  3. Open It (just assign shortcut here ctrl+shift+o, and set the refresh interval to 10 seconds, and automatic import path to project path)
  4. Sidekick
  5. Error List
  6. Plugins related to xml things
  7. Ruby plugins if you want to use Ruby application
  8. PHP Plugins if you want to develop PHP application
  9. SuperAbbreviations (this is cool)
The most great thing is free of charge.

Sunday, September 2, 2007

Value Object, Entity and Data Transfer Object

There are several type of object on Object Oriented Programming. There are a lot of misconception of those. Below is some explaination of some type such as Value Object, Entity and Value Object.

What is Value Object?

Value Object is not Entity. According to Martin Fowler http://www.martinfowler.com/ap2/valueObject.html "An object whose conceptual identity is based on a combination of values of its properties." So what was that? It's like Integer, Date, etc. When you want to do an equality those object to another it should compare all it's meaning properties.


public class Grade {
private Subject subject;
private float gradeValue;
....
public boolean equals(Object o) {
...
Grade other = (Grade)o;
// compare all the meaning objects
return subject.equals(subject) && gradeValue == other.gradeValue;
...
}
}

It might have more than one instance of Grade in memory. John has Grade and Brad has it too, we can check the equality by it's properties (subject and the gradeValue). They both might have the same grade.
Address class can be another good example. Lets say that a store have a lot of customers. Addess is composite of city, street, and floor. When we find some customers life on same place we might say they are on the same city, street and floor.

So what is Entity?

Entity might be POJO and Value Object "might" too. It recognized by their identity.

public class User {
private String username;
private String password;
private Group group;
....
public boolean equals(Object o) {
...
User other = (User)o;
return username.equals(other.username);
...
}
}


We only concern to username property as identity and ignore the other properties of User class (password, group). We can imagine entity is like a record on database table which has primary key.

So what is Data Transfer Object?

According to Martin Fowler http://www.martinfowler.com/eaaCatalog/dataTransferObject.html, DTO is "An object that carries data between processes in order to reduce the number of method calls.". The main idea is object that transfered in order to reduce method calls over the network. We can call it as Value Object or we can call it as Entity. When it does? It depends on how we compare the object - Value Object if based on it's properties or Entity if based on it's identity.

references:

Friday, July 27, 2007

TODO and FIXME notes

This may help if you developing software in team.
We may add comment on our code as notes for later changes/implementation.

public class Monitor {
public void doMonitor() {
// TODO implement this method
// FIXME create specific exception
throw new IllegalArgumentException("Not implemented yet");
}
public void process() {
// FIXME bugs ....
....
}
}

But when the source is already unified with other source code on the same team, ("TODO implement this method") we might ask "who write this notes? the system is on production state and there are still unimplemented code!" or another case is "FIXME find bugs ....", someone find bugs, but the original writer can read and say "thanks, you save my life by finding my bugs" but he/she didn't know who the one find the bugs.

So it might a good idea if we write a name on our comments


public class Monitor {
public void doMonitor() {
// TODO uudashr: implement this method
// FIXME uudashr: create specific exception
throw new IllegalArgumentException("Not implemented yet");
}
public void process() {
// FIXME uudashr: bugs ....
....
}
}

Monday, July 16, 2007

Reflection API

It started 2 years ago, when I have to develop a web based system using PHP.
I'm not a PHP expert, so I asked my friends who works as PHP Developer a question
"What are they usually need for developing system? What is the best framework did they
use?" So 2 frameworks comes, Eocene and Mojavi.

I'm trying to learn about Mojavi, and I have to learn so many things to start my
project. Oh my god. So I stopped and think "Why don't I learn the concepts, and create
the framework by myself, so I don't have to waste time to learn features and
regret if the framework didn't fit to me".
So I started my simple framework using OO on PHP.
The problem is "how can I handle with unexists class on code time, but exist on
run time?" Google comes to help and I found "reflection".
So there is reflection API on PHP as well.
After that I learn reflection on Java.

Here is an example of how to use reflection API.

package uudashr.reflection;

public class Example {
public void hello() {
System.out.println("This is hello method");
}

public String toString() {
return "This is example instance [from toString method]";
}
}

How to handle this simple class using reflection API? watch this.

package uudashr.reflection;

import java.lang.reflect.Method;

public class GettingClass {
public static void main(String[] args) {
testCreateInstance();

testExecutingMethod();
}

public static void testCreateInstance() {
try {
Class exampleClass = Class.forName("uudashr.reflection.Example");
Object obj = exampleClass.newInstance();
System.out.println(obj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

public static void testExecutingMethod() {
try {
Class exampleClass = Class.forName("uudashr.reflection.Example");

Object obj = exampleClass.newInstance();

Method helloMethod = exampleClass.getMethod("hello", null);
helloMethod.invoke(obj, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Monday, June 25, 2007

Eclipse - Generating code, constructors, getters, and setters

Sometimes we have to work with POJO, like when we work with Hibernate. The main problem is after we create all the member variables, we should create the getters and setters. To create N properties, it need N * 2 method (of getters and setters), that would be an extra job for your fingers. The same problem comes when we want to create a constructor that has parameter from the member variables . Thanks god, Eclipse come to save us.

Assume we have create UserProfile class.



Now we will create the constructor
"right click + source"
or
"alt + shift + s" on windows
or
"alt + cmd + s" on mac
then select
"Generate Constructor using Fields..."

Select all fields you need



and click OK, it should be like this



and let's generate the getter and setter, open the source menu like above, then select
"Generate Getters and Setters..."



"Select all" or what ever you need, then boom, Eclipse save your fingers.

Tuesday, June 19, 2007

How to download using curl

Hello, I'm new on Mac, previously I'm using MS Windows and I still use it on my office. The first thing when I'm using my mac is "Where is my free download manager, where I can perform resume on my download?". Nix platform already has great tools to download "curl". How do I download using curl.

When you want to download, you have to find the URL for an example "http://www.downloads.com/filetodownload.zip".
To start download you can type

curl -C - -O http://www.downloads.com/filetodownload.zip

You can cancel your download or there might be an network error found, we can resume the download as long the server support for the resuming.

just type the same command on the same directory

curl -C - -O http://www.downloads.com/filetodownload.zip

Thats it, the download will resume.

Pure Object Oriented Language

What is Object Oriented? Based on this article written by Bjarne Stroustrup on http://www.research.att.com/~bs/oopsla.pdf , "A language or technique is object-oriented if and only if it directly supports: [1] Abstraction - providing some form of classes and objects. [2] Inheritance - providing the ability to build new abstractions out of existing ones. [3] Run-time polymorphism - providing some form of run-time binding". So, when a language have this three of features, we can call it as an Object Oriented Language.

So what is pure Object Oriented Programming Language? Which one is it?
What do I ask above question?
Well, there is some discussion, and someone says that Java is not pure Object Oriented Language instead of C++. Wow, it's shocking statement. So lets the amazing Google help us, and I find this http://www.jvoegele.com/software/langcomp.html , where stated where object orientation of language can be separated by:
1. Pure
2. Hybrid
3. Multi-Paradigm
4. Add-On
5. Partial Support

In this articles, consideration of pure Object Oriented Language should support such of qualities of :
1. Encapsulation / Information Hiding
2. Inheritance
3. Polymorphism/Dynamic Binding
4. All pre-defined types are Objects
5. All operation performed by sending messages to Objects
6. All user-defined types are Objects

Well, Java and even C++ doesn't fit with above definition. The Eiffel, Smalltalk, and Ruby is the winner as pure Object Oriented languages.