Tuesday, July 31, 2007

Class Declarations and Modifiers

Most Java programmers think they know all about how modifiers works.
For some of them its true, but for others - its not.
So, just to make sure you are on the right side, i decided to write a short brief about them.

Be aware that this article talk about modifiers of class - not on members!

Lets start with a few simple rules:

  • only one public class per source file.
  • if there is a public class in source file - the name of file must be the same as the class.
  • package statement must be the first line of code.
  • imports statements should be between package statement and class statement.

There are two modifiers types:

  • Access modifiers: public, protected, private.
  • Non-access modifiers ( final,abstract,strictfp).

Access modifiers:

In effect access means visibility.
if class A cant access class B, it means that A cannot see class B.
A cannot use class B in any way.

there are 4 access modifiers:


  1. default
  2. private
  3. protected
  4. public

Default access
Class with default access is a declaration of class without any modifiers.
it means "package level" access.
only classes from same package can access or extend this class.
for example: if class A as default access, then only classes in same package as A, can access class A.

Protected access
Only inner classes can have protected access modifier.
Class with protected access can be access by classes in same package or in a case of inner classes, the protected inner class can be access by extending classes of main class.
for example: if class A has inner protected class B, then if class C extends class A, class C will be able to access class B even if class C is not in the same package as class A and B.

private access
Only inner classes can have private access modifier.
Class with private access can be access only by containing class.
extension classes cannot access this class.

Public access
Class with public access is a class that all classes can access and extends from (unless class is final). no matter if class is in another package or if its a class of a third party. access is allowed.


Non-access modifiers :

class declaration can be changed by non access modifier in addition to access modifiers.
this declarations will result some behavior.

there are a few non-access modifiers for class:

  • final
  • abstract
  • static
  • strictfp

final
when declaring a class as final - it means that this class cannot be extended by anyone. no matter what is the access modifier - this class will never be extended. this restriction could be very useful in case of security reasons and so on.

abstract
when declaring a class as abstract - it means that no one can create an instance of this class, and this class should be extended by other classes. it means that this class is meant to be extend, the opposite of final modifier. abstract class can have abstract methods as well, but for us, is not the issue.

static
when declaring a class as static the class is defined as nested top-level class.

this class is a inner class . A nested top-level class is just like any other top-level class except that it is declared within another class or interface.

strictfp
Marking a class as strictfp means that any method code in the class will
conform to the IEEE 754 standard rules for floating points.

This was a short brief about class modifiers.
I hope i didn't miss anything about it.
I will publish a soon as possible a short brief about members modifiers.

Monday, July 30, 2007

Spring HTTP Remoting - How ?

preface:
Spring give us few ways to communicate between client and server.
One of these ways is by using http remoting.
Http remoting is a way to invoke remote methods on server.
Spring http remoting uses Http protocol in order to achive that goal.

When do we need it?
When we want our server to expose services to clients.
say we want to expose service who gives us collection of some application users.

How we do it?
Server will expose service using simple independent interface:
public interface userService{
public Collection getAllUsers();
}

As you can see the interface can be independent, and no need to extend from nothing.

Then, we will implement this interface:
public class UserServiceImpl implements UserService{
public Collection getAllUsers() {
//do implementation...
}
}

Client - need to have only the interface in its class path.
Serevr - need to have both interface and implementing class in its classpath.

So, client is unknow with the implementation, only with the interface - like we wish for.

In order to make it work, we will use Spring HTTP Remoting.
Spring Http remoting uses the standard Java serialization mechanism to expose services through HTTP.

Exposing server service:
first, we will create simple bean using spring. the bean will be the service implementation:
< id="userService" class="example.UserServiceImpl">

then, we will expose the service with name "/UserService">
< name="">/UserService"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
< name="service" ref="userService">
< name="serviceInterface" value="example.UserService">
< /bean >

Configuration of web.xml (only once for all services):
< /servlet &gt
< servlet-name &gt remoting < / servlet-name &gt
< servlet-class &gt org.springframework.web.servlet.DispatcherServlet < / servlet-class &gt
< /servlet >

<>
remoting < / servlet-name >
/remoting/* < /url-pattern >
< /servlet-mapping >


Linking the service at the client side:
< id="">userServiceProxy"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean" >
< name="serviceUrl" value="">/UserService"/ >
< name="serviceInterface" value="">UserService"/ >
< /bean >

Then, in order to invoke service:
UserService service = (UserService) appContext.getBean("userServiceProxy");
Collection allUsers = service.getAllUsers();


And.. thats it. service will be invoked on server and client will get the results.

So, how it works ?


  1. The userServiceProxy bean that we created is a proxy.
  2. When method is being called, the proxy takes the method and its arguments and creates org.springframework.remoting.support.RemoteInvocation object. this object holds the information about the method invoked, like method name and which arguments given to method (and more).
  3. The RemoteInvocation object is serialiezed and pushed into an http request to url we declared in "serviceUrl" property of proxy ("http://host:8080/remoting/UserService").
  4. When request reachs server, the url is mapped by us in web.xml and will be dispatch to a spring servlet.
  5. The RemoteInvocation object is deserialized, and by using reflaction the method is being executed - on server.
  6. Then org.springframework.remoting.support.RemoteInvocationResult object will be created. this object will hold the result of execution or the exception if accured.
  7. The RemoteInvocationResult object will serialized and phushed into an HTTP response.
  8. Client will get the response, and will deserialize RemoteInvocationResult object.
  9. If the RemoteInvocationResult object holds an exception - it will be thrown, else the value of method will be returned.

So as you can see, using Spring http is very easy to use and to understand. spring give us a way to make remote invocation transparent for us, and we can use services as they were on our client.

This mechanism can be extended and give us more abilities, like adding attributes on request and so on... i hope i will find the time to represent these abilities in the near futher.

Monday, July 23, 2007

Java Dynamic Proxy, simple yet powerfull!

What is Proxy?

Proxy is a well know design pattern.
Proxy is an object how encapsulate another object .

Say we have some interface, and some implementations. the implementations are real subject implementations. each implementation doing concrete operation. lets say that we want to add some behavior to all implementations, without touching each implementation code. for example, we would like to write to log before and after each operation invocation. the simplest way is to use one abstract class for all implementation to extend from, and by using some template methods we can achieve this goal. but, using abstract class has its limitations:

  • if we have an object how implements two interfaces, and we want to extends some behavior for both interfaces - we cannot do that using two different abstract class.
  • each implementation should extends the abstract class,so the implementations are now "dirty" and if one of the implementations is a third party code - we cannot do that.

so, whats is the solution ?

Proxy !

We can create some new object called MyProxy.

MyProxy will implement the interface and hold a private member of interface type (called target object). the implementation of proxy will be to delegate each method to invoke the targets methods implementation, so this proxy can hold all know implementation of interface, and invoke concrete implementations.

Now, we can add behaviors like log writing, just before and after we delegate the method to target implementation.

As you can understand now, we don't have any limitations we had using abstract classes, and we are free to add any behavior we like.


What is dynamic Proxy?
Dynamic proxy is a proxy we create at runtime. no need to write a proxy object how implements the interface. we can create implementation of some interface at runtime, and encapsulate from user that he is not using his concrete implementation, and add a behaviors as we wish.

How can we do it ?
Using JDK dynamic proxy.

The object java.lang.reflect.Proxy is a dynamic proxy how can create for us proxies for a given interfaces at runtime.

first we will need to implement java.lang.reflect.InvocationHandler interface:

public MyHandler extends java.lang.reflect.InvocationHandler{

T target;

public myHandler (T target){

this.target = target.

}

Object invoke(Object proxy, Method method,Object[] args) {

//do before

method.invoke(target,args);

//do after

}

}

Now we can create proxy for any interface that we wish to add this behavior. say we want to create proxy for Foo interface encapsulating FooImpl:

Foo implementation = new FooImpl();

Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] Foo.class } , new MyHandler(implementation));

now when we execute f.someMethod() will will execute FooImpl implementation with extra behavior.

This is a simple example of using proxies to achieve extended behaviors. Proxy can be use for a lot of other use cases like security check points, lazy loading of data, and many more.

So, use it, but do not over use it!

Hashing with java : HashCode & Equals, is that obvious?

Hash code and equals. If you ask java developers what it is, you will get a simple answer to so called simple question.
- “Equals is how we determine the object uniqueness“
- “Hash code is an numeric value representing object state”

So, is the answer is that simple?

The answer to that is yes and no. the general goal of these basic methods is obvious, but some developers might get it wrong.

I hope now you wondering why.

Let us use a simple example
-------------------------------------
public class Person {

private String name;
private String address;


public Person(String name, String address) {
this.name = name;
this.address = address;
}


public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

-------------------------------------
Now we make an assumption.
Two persons can have the same name but not on same addreres.
So, equivalence of Person object is name + address.

lets add equals method:
-------------------------------------
public boolean equals(Object obj) {
//return true if adress and name are the same in both objects

}

-------------------------------------

After adding equals method we must add hashCode:
-------------------------------------
public int hashCode(Object obj) {
//return hash code using adress and name are the same in both objects
}

-------------------------------------

Now, say we want to hold a Set of Persons :
-------------------------------------
Set mySet = new HashSet();
Person madonna= new Person("Madonna","LA");
Person bart = new Person("Bart simpson","NY");

mySet.add(madonna);

mySet.add(bart);



madonna.hashCode() //say the value is 2
bart.hashCode() //say the value is 4

mySet.size() // will give 2.

mySet.contains(madonna) // true

mySet.contains(bart) // true

-------------------------------------



As you can see, equals and hashCode did the work for us in this case.
But.. let us continue:
-------------------------------------
bart.setAddress("California"); // bart moved to Califronia.


mySet.contains(madonna) //true.
mySet.contains(bart) //FALSE !!!

-------------------------------------

We got false when asking if Bart exists in set because we changed the value of hash code of his Person object while he is in a set.


mySet is holding Bart under is old hashcode : 4.
We changed Barts address, so his hashCode now is not 4 any more.
so, when we will ask the set if Bart exists, the set will not find Bart any more due to the hashCode change we made by mistake.

So, how we can implement hashCode and equals?
  • equals should define equivalence not uniqueness
  • hash code and equals always should be implement together.
  • if equals is true between two object, they should return same hash code.
  • if two object return same hash code they don't have to be equals.
  • equals and hash code fields should be based on immutable fields who cant changed during life cycle of an application.

So, we need to add another field to person : id. this field will be immutable, and both hash code and equals will be based on his value.

So, dont forget, equals and hashCode are very easy but yet, very tricky.