Sunday 27 February 2011

Classloaders in java

Problems in java.util.Observable

Consider Observable pattern.

The way its implemented in java is full of flaws.

1. Observable is a class, not an interface, and worse, it doesn’t even implement an interface. Unfortunately, the java.util.Observable implementation has a number of problems that limit its usefulness and reuse. That’s not to say it doesn’t provide some utility, but there are some large potholes to watch out for. So from design point of view its bad in 2 ways:

   A) Because Observable is a class, you have to subclass it. That means you can’t add on the Observable behavior to an existing class that already extends another superclass. This limits its reuse potential (and isn’t that why we are using patterns in the first place?).
   B) Because there isn’t an Observable interface, you can’t even create your own implementation that plays well with Java’s built-in Observer API. Nor do you have the option of swapping out the java.util implementation for another (say, a new, multithreaded implementation).

2. Observable may serve your needs if you can extend java.util.Observable. On the other hand, you may need to roll your own implementation as we did at the beginning of the chapter. In either case, you know the Observer Pattern well and you’re in a good position to work with any API that makes use of the pattern.

3. If you look at the Observable API, the setChanged() method is protected. So what? Well, this means you can’t call setChanged() unless you’ve subclassed Observable. This means you can’t even create an instance of the Observable class and compose it with your own objects, you have to subclass. The design violates a second design principle here…favor composition over inheritance.

Java memory model

http://www.cs.umd.edu/users/pugh/java/memoryModel/
This is v.good material to follow java memory model.

Saturday 26 February 2011

CXF hello world tutorial

This example shows how to make cxf web service.

Get the bean ready:
package com.company.auth.bean;

import java.io.Serializable;
import java.util.Set;

public class Employee implements Serializable {

private static final long serialVersionUID = 1L;
private String gid;
private String lastName;
private String firstName;
private Set<String> privileges;

public Employee() {}

public Set<String> getPrivileges() {
return privileges;
}

public void setPrivileges(Set<String> privileges) {
this.privileges = privileges;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getGid() {
return gid;
}

public void setGid(String gid) {
this.gid = gid;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public boolean isUserInRole(String role) {
if(privileges == null) { return false; }
else { return privileges.contains(role); }
}

}

First off, you need to download Apache CXF and drop the necessary .jars in your WEB-INF/lib directory:
aopalliance-1.0.jar
commons-logging-1.1.jar
cxf-2.0-incubator.jar
geronimo-activation_1.1_spec-1.0-M1.jar (or Sun’s Activation jar)
geronimo-annotation_1.0_spec-1.1.jar (JSR 250)
geronimo-javamail_1.4_spec-1.0-M1.jar (or Sun’s JavaMail jar)
geronimo-servlet_2.5_spec-1.1-M1.jar (or Sun’s Servlet jar)
geronimo-ws-metadata_2.0_spec-1.1.1.jar (JSR 181)
jaxb-api-2.0.jar
jaxb-impl-2.0.5.jar
jaxws-api-2.0.jar
jetty-6.1.5.jar
jetty-util-6.1.5.jar
neethi-2.0.jar
saaj-api-1.3.jar
saaj-impl-1.3.jar
spring-core-2.0.4.jar
spring-beans-2.0.4.jar
spring-context-2.0.4.jar
spring-web-2.0.4.jar
stax-api-1.0.1.jar
wsdl4j-1.6.1.jar
wstx-asl-3.2.1.jar
XmlSchema-1.2.jar
xml-resolver-1.2.jar

The first thing which needed to be done was to create the service interface. The service interface defines which methods the web service client will be able to call. It’s pretty standard Java with just two JWS (Java Web Service) annotations thrown in:

package com.company.auth.service;

import javax.jws.WebService;
import javax.jws.WebParam;
import com.company.auth.bean.Employee;

@WebService
public interface AuthService {
Employee getEmployee(@WebParam(name="gid") String gid);
}

The @WebParam annotation is in fact optional, but highly recommended since it will make like easier for the end consumers of your service. Without it, your parameter would be named arg0 making it less clear what parameters your service actually takes.

Implementing the actual service comes next:

package com.company.auth.service;

import javax.jws.WebService;

import com.company.auth.bean.Employee;
import com.company.auth.dao.EmployeeDAO;

@WebService(endpointInterface = "com.company.auth.service.AuthService", serviceName = "corporateAuthService")
public class AuthServiceImpl implements AuthService {

public Employee getEmployee(String gid) {
EmployeeDAO dao = new EmployeeDAO();
return dao.getEmployee(gid);
}

}

I then had to tell Spring (which is used by CXF) where to find my Java classes. I created the following cxf.xml file inside my package directory (com/company/auth/service):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxws

  http://cxf.apache.org/schemas/jaxws.xsd">

<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint id="auth"
implementor="com.company.auth.service.AuthServiceImpl"
address="/cxfAuth"/>
</beans>

Finally, I updated my WEB-INF/web.xml file to let CXF know where my cxf.xml file was and define the CXF servlet:
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<display-name>Auth Manager</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/company/auth/service/cxf.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>

The final step is to build the client. This was very easy when compared to getting the server up and running because I was able to simply swipe the code from the Apache CXF documentation. So, without further ado:

package com.company.auth.client;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.company.auth.bean.Employee;
import com.company.auth.service.AuthService;

public final class Client {

private Client() {
}

public static void main(String args[]) throws Exception {

JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(AuthService.class);
factory.setAddress("http://localhost:7001/authManager/services/cxfAuth");
AuthService client = (AuthService) factory.create();

Employee employee = client.getEmployee("0223938");
System.out.println("Server said: " + employee.getLastName() + ", " + employee.getFirstName());
System.exit(0);

}

}

Thursday 24 February 2011

Java Serialization : Introduction

Introduction

Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object.

Note : Note that its ‘primary purpose’ is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again, but sometimes people use java serialization as a replacement for database, which is not our main motive. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.

You can see this tutorial for quick tutorial.

Overview

Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object. But when deserializing the object, the deserializer must know by some protocol how to deserialize. Here protocol means, understanding between serializing person and de-serializing person.

Implementation

For an object to be serialized, it must be an instance of a class that implements either the Serializable or Externalizable interface in java.io. Serializable is type of marker interface. Both interfaces only permit the saving of data associated with an object's variables. They depend on the class definition being available to the Java Virtual Machine at reconstruction time in order to construct the object.


The Serializable interface relies on the Java runtime default mechanism to save an object's state. Writing an object is done via the writeObject() method in the ObjectOutputStream class (or the ObjectOutput interface). Writing a primitive value may be done through the appropriate write<datatype>() method.

Reading the serialized object is accomplished using the readObject() method of the ObjectInputStream class, and primitives may be read using the various read<datatype>() methods.
What about other objects that may be referred to by the object we are serializing? For instance, what if our object is a Frame containing a set of (AWT) Panel and TextArea instance variables? Using the Serializable interface, these references (and their associated data) also are converted and written to the stream. All state information necessary to reconstruct our Frame object and any objects that it references gets stored together.
If those other objects or their formats weren't stored, our reconstructed Frame would contain null object references, and the content of those Panels and TextAreas would be gone. Plus, any methods that rely on the existence of the Panels or TextAreas would throw exceptions.
The Externalizable interface specifies that the implementing class will handle the serialization on its own, instead of relying on the default runtime mechanism. This includes which fields get written (and read), and in what order. The class must define a writeExternal() method to write out the stream, and a corresponding readExternal() method to read the stream. Inside of these methods the class calls ObjectOutputStream writeObject(), ObjectInputStream readObject(), and any necessary write<datatype>() and read<datatype>() methods, for the desired fields.
 

Hiding Data From Serialization

Sometimes you may wish to prevent certain fields from being stored in the serialized object. The Serializable interface allows the implementing class to specify that some of its fields do not get saved or restored. This is accomplished by placing the keyword transient before the data type in the variable declaration. For example, you may have some data which is confidential and can be re-read from a master file later (as opposed to saving it with the serialized object). Or you decide (wisely) to preserve the privacy of file references by declaring any such variables as transient. Otherwise, all fields automatically get written without any additional effort by the class.
In addition to those fields declared as transient, static fields are not serialized (written out), and so cannot be deserialized (read back in).
Another way to use Serializable, and control which fields get written, is to override the writeObject() method of the Serializable interface. Inside of this method, you are responsible for writing out the appropriate fields. If you take this approach, you will want to override readObject() as well, to control the restoration process. This is similar to using Externalizable, except that interface requires writeExternal() and readExternal().
For the Externalizable interface, since both writeExternal() and readExternal() must be declared public, this increases the risk that a rogue object could use them to determine the format of the serialized object. For this reason, you should be careful when saving object data with this interface.
It is worth considering the amount of security you need for any objects that you serialize. When reading them back in, all of the normal Java security checks (such as the bytecode verifier) are in effect. You can define certain values within the class that should remain intact in serialized objects. Perhaps they should contain a specific value, or a value within a particular range. You can easily check the value of any numeric variable read in from a serialized object, especially if you know that only a portion of the available range for that data type is used by your variable.
You can also encrypt the outgoing data stream. The implementation is up to you, and don't forget to decrypt the object format when reading it back in.

Versioning

Example of serialization:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class SerializationBox implements Serializable {

private byte serializableProp = 10;

public byte getSerializableProp() {
return serializableProp;
}
}

public class SerializationSample {

public static void main(String args[]) throws IOException,
FileNotFoundException, ClassNotFoundException {

SerializationBox serialB = new SerializationBox();
serialize("serial.out", serialB);
SerializationBox sb = (SerializationBox) deSerialize("serial.out");
System.out.println(sb.getSerializableProp());
}

public static void serialize(String outFile, Object serializableObject)
throws IOException {
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializableObject);
}

public static Object deSerialize(String serilizedObject)
throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(serilizedObject);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}
}

Format of a Serialized Object 
Conclusion
Adding object persistence to Java applications using serialization is easy. Serialization allows you to save the current state of an object to a container, typically a file. At some later time, you can retrieve the saved data values and create an equivalent object. Depending on which interface you implement, you can choose to have the object and all its referenced objects saved and restored automatically, or you can specify which fields should be saved and restored. Java also provides several ways of protecting sensitive data in a serialized object, so objects loaded from a serialized representation should prove no less secure than those classes loaded at application startup. Versioning provides a measure of the backward compatibility of class versions. The code needed to add serialization to your application is simple and flexible.

Some acronyms in java

JLS - Java Language Specification

Java Native methods

The Java native method is a great way to gain and merge the power of C or C++ programming into Java. To use Java as a scientific and high performance language, when efficient native Java compilers are not fully implemented, use native method can boost the performance to at least the speed of C compiled code.

1. Write the Java Code (Native Methods)

2. Compile the java code

Use the Java compiler to compile the Java class that you created in the previous step. At this time, you should also compile the main Java application that you wrote to test the native method.

3. Create the .h File

4. Create a Stubs File

5. Write the C Function

6: Create a Dynamically Loadable Library (Native Methods)

7. Run your application

 refer java docs for diagram and details.

4. Create a Stubs File

In addition to the .h file that you generated in the previous step, you must also use javah to generate a stub file. The stub file contains C code that provides the glue that holds the Java class and its parallel C structure together. To generate a stub file use javah's -stubs option. Again remember to run javah on the Java class.
By default, javah will place the resulting stub file in the same directory as the .class file. You can use the -d option to force javah to put the generated stub file in a different directory.
Similar to the .h file that javah generates, the name of the stubs file is the class name with .c appended to the end. In the "Hello World!" example that you've been working with throughout this lesson, the stub file is called HelloWorld.c : 

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <StubPreamble.h>

/* Stubs for class HelloWorld */
/* SYMBOL: "HelloWorld/displayHelloWorld()V", Java_HelloWorld_displayHelloWorld_stub */
stack_item *Java_HelloWorld_displayHelloWorld_stub(stack_item *_P_,struct execenv *_EE_) {
extern void HelloWorld_displayHelloWorld(void *);
(void) HelloWorld_displayHelloWorld(_P_[0].p);
return _P_;
}

For the moment, all you really need to know about the stub file is that you will later compile it into the dynamically loadable library that you create in Step 6: Create a Dynamically Loadable Library.

Generating a Stub


UNIX
% javah -stubs HelloWorld
DOS shell (Windows 95/NT)
C:\> javah -stubs HelloWorld

3. Create the .h File

In this step, you use the javah utility program to generate a C header file (a .h file) from the HelloWorld Java class. The header file defines a structure that represents the HelloWorld class on the C side, and provides a C function definition for the implementation of the native method displayHelloWorld() defined in that class.
Run javah now on the HelloWorld class that you created in the previous steps. For example, on UNIX you would issue the following command to your favorite shell tool.
% javah HelloWorld
By default, javah places the new .h file in the same directory as the .class file. You can tell javah to place the header files in a different directory with the -d option. The name of the header file is the Java class name with a .h appended to the end of it. For example, the command shown above will generate a file named HelloWorld.h.
eg. Content of javah file:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <native.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld

typedef struct ClassHelloWorld {
char PAD; /* ANSI C requires structures to have a least one member */
} ClassHelloWorld;
HandleTo(HelloWorld);

extern void HelloWorld_displayHelloWorld(struct HHelloWorld *);
#endif

The Class Structure

Look at the header file. Notice that it contains a struct definition for a structure named ClassHelloWorld. The members of this structure parallel the members of the corresponding Java class; that is to say, the fields in the struct correspond to instance variables in the class. But since HelloWorld doesn't have any instance variables, there is just a place holder in the structure. You can use the members of the struct to reference class instance variables from your C functions.

The Function Definition

In addition to the C structure that mimics the Java class, you will also notice a C function signature that looks like this:
extern void HelloWorld_displayHelloWorld(struct HHelloWorld *);
This is the definition for the C function that you will write in Step 5: Write the C Function that provides the implementation for the HelloWorld class's native method displayHelloWorld(). You must use this function signature when you write the implementation for the native method. If HelloWorld contained any other native methods, their function signatures would appear here as well. The name of the C function that implements the native method is derived from the package name, the class name, and the name of the Java native method. Thus, the native method displayHelloWorld() within the HelloWorld class becomes HelloWorld_displayHelloWorld(). In our example, there is no package name because HelloWorld is in the default package.
You will notice that the C function accepts a single parameter even though the native method defined in the Java class accepted none. You can think of the parameter as the "this" variable in C++. Our example ignores the "this" parameter. However, the next lesson, , describes how to access the data in the "this" parameter.

5. Write the C Function

Now, you can finally get down to the business of writing the implementation for the native method in C.
The function that you write must have the same function signature as the one you generated with javah into the HelloWorld.h file in Step 3: Create the .h File. The function signature generated for the HelloWorld class's displayHelloWorld() native method looks like this:
extern void HelloWorld_displayHelloWorld(struct HHelloWorld *);
Here's our implementation for HelloWorld_displayHelloWorld() which can be found in the file named HelloWorldImp.c.
#include &lt;StubPreamble.h&gt;
#include "HelloWorld.h"
#include &lt;stdio.h&gt;

void HelloWorld_displayHelloWorld(struct HHelloWorld *this) {
printf("Hello World!\n");
return;
}
As you can see, the implementation for HelloWorld_displayHelloWorld() is straightforward: the function uses the printf() function to display the string "Hello World!" and then returns. This file includes 3 C header files:
  • StubPreamble.h which provides enough information to the C code to interact with the Java runtime system. When writing native methods, you must always include this file in your C source files.
  • The .h file that you generated in Step 3: Create the .h File. This file contains the C structure that represents the Java class for which we are writing the native method and the function definition for the native method you are writing in this step.
  • The code snippet above also includes stdio.h because it uses the printf() function.

Running javah


UNIX
% javah HelloWorld
DOS shell (Windows 95/NT)
C:\> javah HelloWorld

Compiling Java Code


UNIX
% javac HelloWorld.java
% javac Main.java
DOS shell (Windows 95/NT)
C:\> javac HelloWorld.java
C:\> javac Main.java
Macintosh
[PENDING: Macintosh instructions]

1. Write the Java Code (Native Methods)

The following Java code segment defines a class named HelloWorld that has one method and a static code segment.
class HelloWorld {
public native void displayHelloWorld();

static {
System.loadLibrary("hello");
}
}

Define a Native Method

You can tell that the implementation for the HelloWorld class's displayHelloWorld() method is written in another programming language because of the native keyword that appears as part of its method definition:
public native void displayHelloWorld();
This method definition provides only the method signature for displayHelloWorld() and does not provide any implementation for it. The implementation for displayHelloWorld() is provided in a separate C language source file. The method definition for displayHelloWorld() also indicates that the method is a public instance method, accepts no arguments and returns no value. For more information about arguments to and return values from native methods see .
Like other methods, native methods must be defined within a Java class.

Load the Library

The C code that implements displayHelloWorld must be compiled into a dynamically loadable library (you will do this in Step 6: Create a Dynamically Loadable Library) and loaded into the Java class that requires it. Loading the library into the Java class maps the implementation of the native method to its definition. The following static code block from the HelloWorld class loads the appropriate library, named hello. The runtime system executes a class's static code block when it loads the class.
static {
System.loadLibrary("hello");
}
The loadLibrary() method is part of the System class.

Create the Main Program

In a separate source file, named Main.java, create a Java application that instantiates HelloWorld and calls the displayHelloWorld() native method.
class Main {
public static void main(String args[]) {
new HelloWorld().displayHelloWorld();
}
}
As you can see from the code sample above, you call a native method in the same manner as you call a regular method: just append the name of the method to the end of the object name with a period ('.'). A matched set of parentheses, ( and ), follow the method name and enclose any arguments to pass into the method. The displayHelloWorld() method doesn't take any arguments.

6: Create a Dynamically Loadable Library (Native Methods)

Remember in Step 1: Write the java Class that you use this method call to load a dynamically loadable library named hello into your program at runtime.
System.loadLibrary("hello");
Now you are ready to create the dynamically loadable library. Use the C compiler to compile the C source code created in the previous steps, HelloWorld.c and HelloWorldImp.c, into a dynamically loadable library named hello.

Cost associated with reflections in java

Reflection is v.powerful and useful, but comes at some cost:
  • You lose all the benefits of compile-time type checking, including exception checking. If a program attempts to invoke a nonexistent or inaccessible method reflectively, it will fail at run time unless you've taken special precautions.
  • The code required to perform reflective access is clumsy and verbose. It is tedious to write and difficult to read.
  • Performance suffers

Type of classes

There can be many classification of classes:
1. Final
Base Class,
Derived Class
Value classes

Monday 21 February 2011

Removing file extension java code

Armstrong Number Java Program

An Armstrong Number is one in which the sum of the individual numbers raised to the power of the number of words in that number is equal to that particular number itself. For example 1 raised to the power 1 is equal to 1, so it is an Armstrong Number. Again 153, implies 1 raised to the power 3, 5 raised to the power 3, and then 3 raised to the power 3 are added, then it gives 153 again, so it is also an Armstrong Number.
The Java Code is given below:-
////////////////////////////////////
package developer;
import java.util.Scanner;
public class ArmstrongNumber {
static double finalValue = 0;
public static void main(String[] args) {
int valueTaker = 0;
System.out.println("Enter a number to be checked for Armstrong Number: ");
Scanner armstScan = new Scanner(System.in);
if(armstScan.hasNextInt())
{
valueTaker = armstScan.nextInt();
}
StringBuffer sb = new StringBuffer().append(valueTaker);
double lengthSBKeeper = sb.length();
for(int lengthKeeper = 0; lengthKeeper < sb.length(); lengthKeeper++)
{
double zxc = Integer.parseInt(sb.substring(lengthKeeper, lengthKeeper+1));
finalValue = Math.pow(zxc, lengthSBKeeper) + finalValue;
}
if(finalValue == valueTaker)
{
System.out.println("The entered number "+valueTaker+" is an Armstrong Number");
}
else
{
System.out.println("The entered number is not an Armstrong Number");
}
}
}
///////////////////////////////////////

SCJP Useful Resources