Sunday, November 25, 2007

Getting started with JPA and Hibernate

jboss-EJB-3.0_Embeddable_ALPHA_9

  • hibernate-all

  • thirdparty-all.jar

  • jboss-ejb3-all.jar



hibernate-annotations-3.3.0.GA

  • hibernate-annotations.jar



hibernate-3.2.5.GA

  • hibernate3.jar



hibernate-entitymanager-3.3.1.GA

  • hibernate-entitymanager.jar



EntityManager Interface - hibernate-all.jar
EntityManagerFactory Interface - hibernate-all.jar

EntityManagerImpl - hibernate-entitymanager.jar
EntityManagerFactoryImpl - hibernate-entitymanager.jar

Note: the current hibernate-all.jar is not compatible with the latest hibernate GA release and therefore, hibernate-all.jar should come after hibernate-annotations.jar in the jar export order. Otherwise it will throw NoSuchMethodError.

Saturday, September 1, 2007

Using M2Eclipse

M2Eclipse is a great tool. It made developer's life much easier for using Maven2 with eclipse WTP.

1. Install M2Eclipse from http://m2eclipse.codehaus.org/update/

2. Create a webapp project using maven

3. Create a dynamic web project with eclipse using the same project name.

4. Fix web content folder, src/main/java and src/test/java folders.

5. add m2 dependencies in j2ee dependencies for the project.

6. ready for hot deploy.

Friday, August 31, 2007

Use Maven2 with Eclipse WTP

Maven verion: 2.0.7
Eclipse Version: 3.3.0
Build id: I20070625-1500

The following is how I setup a maven web project that can be hot deployed using eclipse WTP.

1. Create maven web project

mvn archetype:create
-DgroupId=[your projects group id]
-DartifactId=[your project's artifact id]
-DarchetypeArtifactId=maven-archetype-webapp

ref

2. Create dynamic web project in eclipse

Replace maven generated WEB-INF and META_INF with eclipse generated WEB-INF and META-INF

3. Create M2_REPO variable in eclipse and point it to ~/m2/repository

4. Create src/main/java and src/main/test folder

5. Point eclipse source folder to src/main/java and src/main/test folders.

6. Delete eclipse WTP default WebContent folder.

7. Switch to navigaton view and modify org.eclipse.wst.common.component file
i.e.

<?xml version="1.0" encoding="UTF-8"?>
< project-modules id="moduleCoreId" project-version="1.5.0">
< wb-module deploy-name="MyWebApp">
< wb-resource deploy-path="/" source-path="/src/main/webapp"/>
< wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
< wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/java"/>
< property name="context-root" value="MyWebApp"/>
< property name="java-output-path" value="build/classes"/>
< /wb-module>
< /project-modules>

8. Modify pom.xml file and add the following plugin configuration

< build>
< finalName>MyWebApp</finalName>
< plugins>
< plugin>
< groupId>org.apache.maven.plugins</groupId>
< artifactId>maven-eclipse-plugin</artifactId>
< configuration>
< buildoutputdirectory>src/main/webapp/WEB-INF/classes
< /buildoutputdirectory>
< downloadsources>true</downloadsources>
< /configuration>
< /plugin>
< /plugins>
< /build>

9. Add dependent libraries to the pom.xml

10. run mvn eclipse:eclipse

Friday, August 17, 2007

Architectural view of Web Applications

The main concepts of MVC

  • The model handles application and business logic

  • The view handles presentation logic

  • The controller accepts and interprets keyboard and mouse input.


The motivation behind MVC was to separate the model code from its presentation. The model code does not contain any UI information, but it broadcasts notification of any state changes to dependents, which are typically views.
This scheme provides a good separation between these three layers but suffers from two weaknesses.

  • It has a simplistic view of the model and does not account for any difference between application logic (for example, flow of control and coordination of multiple Web pages) and business logic.

  • Most rich-client libraries and windowing system combine the view and controller functions in a single widget, making the logical separation into view and controller less userful.


MVC framework has evolved.

Controller: object handling application logic.
Model:business objects.

Controller
Input Controller


The input controller is a central feature. There is a single input controller for all pages in a Web application. The input controller parses input, determines the parameter-passing mechanisms, extracts any necessay information from the request, cooperates with the application controller to determine the next operatioin (typically called an action), and invokes that action in the correct context. By having a single component as an input controller, any knowledge of HTTP or naming conventions is localized at the request level. This reduces the amount of code duplication and the total size of code. Note that the input controller component is typicaly a servlet, and there may be one instance for accessing the application over HTTP via a regular Web browser and another instance for mobile applications using a Wireless Application Protocol (WAP) enabled device.


Application Controller


The application controller is typically a regular Java object. It coordinates logic related to the application flow, handles errors, maintains longer-term state, and determines which view to display. Application controllers typically need a mapping orequests to the application objects that manage the flow. Most frameworks maintain these mappings in complex XML configuration files.

Tuesday, July 24, 2007

Install Eclipse WTP build 2.0 and JadClipse

Eclipse WTP build 2.0 requires Java 1.5 installed.

To install JadClipse, first follow the instructions on this page.

Note: make sure the class files you want to decompile is on your classpath.

Thursday, July 12, 2007

Java 101

ArrayList and LinkedList

Speed


  • An ArrayList is backed by a primitive Object array. Because of that, an ArrayList is much faster than a LinkedList for random access.

  • The standard binary search algorithm starts by checking the search key against the value in the middle of the list. If the middle value is too high, then the upper half of the list is eliminated. However, if the middle value is too low, then the lower half of the list if ignored.

  • LinkedList is a bad choice in this situation. The binary search algorithm inherently uses random access, and LinkedList does not support fast random access. The time to do a random access in a LinkedList is proportional to the size of the list. By comparison, random access in an ArrayList has a fixed time.

  • If you have lots of element inserting and deleting, LinkedList is a better choice.

  • When an element is added to the beginning of an ArrayList, all of the existing elements must be pushed back, which means a lot of expensive data movement and copying. By contrast, adding an element to the beginning of a LinkedList simply means allocating an internal record for the element and then adjusting a couple of links. Adding to the beginning of a LinkedList has fixed cost, but adding to the beginning of an ArrayList has a cost that's proportinal to the list size.


Space

  • LinkedList class has a private internal class defined like this:
    private static class Entry {
    Object element;
    Entry next;
    Entry previous;
    }
    Each Entry object references a list element, along with the next and previous elements in the LinkedList -- in other words, a doubly-linked list. A LinkedList of 1000 elements will have 1000 Entry objects linked together, referencing the actual list elements. There is a significant space overhead in a LinkedList structure, given all these Entry objects.

  • An ArrayList has a backing Object array to store the elements. This array starts with a capacity of 10. When the array needs to grow, the new capacity is computed as:
    newCapacity = (oldCapacity *3)/2 +1

  • Notice that the array capacity grows each time by about 50%. This means that if you have an ArrayList with a large number of elements, there will be a significant amount of space wasted at the end. This waste is intrinsic to the way ArrayList works. If there was no spare capacity, the array would have to be reallocated for each new element, and performance would suffer dramatically. Changing the growth strategy to be more aggressive (such as doubling the size at each reallocation) would result in slightly better performance, but it would waste more space.


Summary

  • Appending elements to the end of a list has a fixed averaged cost for both ArrayList and LinkedList. For ArrayList, appending typically involves setting an internal array location to the element reference. but occasionally results in the array being reallocated. For LinkedList, the cost of uniform and involves allocating an internal Entry object.

  • Inserting or deleting elements in the middle of an ArrayList implies that the rest of the list must be moved. Inserting or deleting elements in the middle of a LinkedList has fixed cost.

  • A LinkedList does not support efficient random access.

  • An ArrayList has space overhead in the form of reserve capacity at the end of the list. A LinkedList has significant space overhead per element.

  • Sometimes a Map structure is a better choice than a List.




ref

Sunday, June 24, 2007

Maven 101

Project Object Model (POM) is the fundamental unit of work in Maven. It is an xml file that contains information about the project and configuration details used by Maven to build the project.
build directory -> target
source directory -> src/main/java
test source directory -> /src/main/test
The goals or plugins are now configured in the pom.xml. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.
Configuration that can be specified in the POM are:

  • project dependencies

  • plugins

  • goals

  • build profiles

  • project version

  • description

  • developers

  • mailing lists


The minimum requirement for a POM are the following:

  • project root

  • modelVersion

  • groupId

  • artifactId

  • version


Project: the top level element in all Maven pom.xml files
modelVersion This element indicates what version of the object model this POM is using.
groupId: This element indicates the unique identifier of the organization or group that created the project. The groupId is one of the key identifiers of aproject and is typically based on the fully qualified domain name of your organization.
artifactId: this element indicates the unique base name of the primary artifact being generated by this project. The primary artifact for a project is typically a JAR file.
Introduction to the Standard Directory Layout
Having a common directory layout would allow for users familiar with one Maven project to immediately feel at home in another Maven project. The advantages are analogous to adopting a site-wide look and feel.
src/main/java: Application/Library sources
src/main/resources: Application Library resources
src/main/filters: Resource filter files
src/main/assembly: Assembly descriptors
src/main/config: Configuration files
src/main/webapp: Web application sources
src/test/java: Test sources
src/test/resources: Test resources
src/test/filters: Test resource filter files
src/site: Site

Introduction to Repositories
A repository in Maven is used to hold build artifacts and dependencies of varying types.
There are strictly only two types of repositories: local and remote.
The local repository refers to a copy on your own installation that is a chache of the remote downloads, and also contains the temporary build artifacts that you have not yet released.
The remote repository refer to any other type of repository, accessed by a variety of protocols such as file://and http://. These repositories might be truely remote repository set up by a third party to provide their artifacts for downloading. Other "remote" repositories may be internal repositories set up on a file or HTTP server within your company, used to share private artifacts between development teams and for releases.
$mvn archetype:create -DgroupId=mavenbook -DartifactId=my-app
archetype:create is called a Maven "goal". The plugin is the prefix "archetype" and the the goal is to "create". -Dname=value pairs are arguments.
A phase is a step in what Maven calls the "build lifecycle".

ref

Maven war plugin
The default resource directory for all maven2 projects is src/main/resources which will end up in target/classes and in WEB-INF/classes in the war.

src/main/resources -> target/classes
src/main/resources -> WEB-INF/classes (war file)

ref

Maven2 step by step

Friday, June 8, 2007

Domain Model

Implementing a Domain Model

Business concerns should be separated from the crosscutting concerns (such as transactions, persistence and authorization) - leakage of concerns.

Domain model implementation is such an important piece of code that it shouldn't depend on other Java APIs. For example, code in the domain model shouldn't perform JNDI lookups or call the database via the JDBC API.This alows you to reuse the domain model implementation virtualy anywhere. Most importantly, it makes it easy to unit test the domain model outside of any application server or other managed environment.

Transparent persistence means a complete separation of concerns between the persistent classes of the domain model and the persistence logic itself, where the persistent classes are unware of - and have no dependency to - the persistence mechanism.

Hibernate compares the objects by value - not by object identify - to determine if the property's persistent state needs to be updated. For example, the following getter method won't result in unnecessay SQL UPDATEs:

public String getFirstname() {
return new String (firstname);
}

However, there is one very important exception. Collections are compared by identify!
The following code should be avoided:

public void setNames(List namesList) {
names = (String[]) namesList.toArray();
}

public List getNames() {
return Arrays.asList(names);
}

It is recommended practice to use one mapping file per persistent class. The convention is to give the file the same name as the mapped class, appending an hbm suffix: for example, Category.hbm.xml.

Property and class mappings

Hibernate uses reflection to determine the Java type of the property and therefore the type name can be omitted.

hbm2ddl tool can be used to generate database schema.
not-null attribute should be used to report illegal null property values without going to the database.



Detection of illegal null values is mainly useful for providing sensible exceptions
at development time. It isn’t intended for true data validation, which is outside
the scope of Hibernate.

Derived properties

The value of a derived property is calculated at runtime by evaluation of an expression. You define the expression using the formula attribute. For example

formula="TOTAL + TAX_RATE * TOTAL"
type="big_decimal"/>

The given SQL formula is evaluated every time the entity is retrieved from the database.

Identify versus equality
Object identity, ==, is a notion defined by the Java virtual machine. Two object references are identical if they point to te same memory location.

On the other hand, object equality is a notion defined by classes that implement the equals() method, sometims also referred to as equivalencee. Equivalence means that two different (non-identical) objects have the same value.

Database identify - Objects stored in a relational database are identical if they represent the same row, or equivalently, share the same table and primary key value.

Wednesday, June 6, 2007

Shell Scripting

At login time

Your login shel consults /etc/profile which is owned by root,
your home ~/.bash_profile which is owned by yourself,
the /etc/bashrc which is owned by root and your home ~/.bashrc which owned by yourself.

Each time a new shell is started

It executes the /etc/bashrc and ~/.bashrc.

Notice that starting a new shell without logging out and in again (a child process) means that the shell has no need to run the profile files again.

Useful command combination

Count number of files in subdirectories
find . -type -f | wc -l

Monday, June 4, 2007

Java Major and Minor Versions

Java compiler
major version: 47
classes compiled by jdk 1.3

major version: 48
classes compiled by jdk 1.4

major version: 49
classes compiled by jdk 1.5

Compiled by Ant javac

major version: 47
target= 1.3

major version: 48
target = 1.4

major version: 49
target = 1.5

classes compiled by a newer version of jdk can not be run by an older version of jvm without specifically specifying the targeted source version.

Friday, June 1, 2007

Web Application Deployment Descriptor

All servlet containers that are compliant with the 2.3 servlet specification are required to support the following types of deployment information:

Initialization parameters
Session configuration
Servlet declarations
Servlet mappings
Application lifecycle listener classes
Filter definitions and mappings
Welcome file list
Error pages

Optional:

Tag library mappings
JNDI References

When a web application is installed in a container, the container is responsible for assigning a ServletContext to it. There is a single instance of a ServletContext object for each web application depolyed in a container.

The ServletContext provides an external view of the web container environment for a servlet. A servlet can use the ServletContext object to gain access to external resources, log events, and store attributes and objects that other servlet instances in the same context can access. It's essentially an application-scope shared resource.

Because a servlet is associated with a specific web application, all requests that begin with a specific request path (known as the context path) are routed to the web application associated with that servlet. Servlets associated with the default application have an empty string ("") as the context path.




Application events provide notifications of a change in state of the servlet context (Each web application uses its own servlet context) or of an HTTP session object.

You write event listener classes that respond to these changes in state, and you configure and deploy them in a Web applicatioin. The servlet container generates events that cause the event listener classes to do something. In other words, the servlet container calls the methods on a user's event listener class.

Monday, May 14, 2007

Java Concurrency

Process

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.

To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.

Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.

Thread
Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process - every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread - or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmers' point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads.

Preferred means of creating multthreaded application in J2SE5.0

Implement the Runnable interface and use build-in methods and classes to create Threads that execute the Runnables.

Runnables are executed by an object of a class that implements the Executor interface. An executor object typically creates and manages a group of threads called a thread pool.

ExecutorService's execute method creates a new Thread inside the ExecutorService to run the Runnable passed to it as an argument and transitions that Thread from the new state to the runnable state. Method execute returns immediately from each invocation - the program does not wait for each PrintTask to finish.

ExecutorService.shutdown() method will end each Thread in threadExecutor as soon as each finishes executing its Runnable.

If the program executed more than three Runnables, additional Threads would not be created, but rather an existing Thread would be reused when it completed the Runnable assigned to it.

The code in the method main executes in the main thread which is created by the JVM and executes the main method.

The code in the run method of PrintTask executes in the threads created by the ExecutorService. When method main terminates, the program itself continues running because there are still threads that are alive. The program will not terminate until its last thread completes execution.

ref

Sunday, May 13, 2007

Collections in Java

In the early days, java platform had only two basic classes:

java.util.Vector

java.util.Hashtable

Prior to java 5.0, the Collections Framework had two major drawbacks.

The collections were untyped and worked only with anonymous Objects instead of real types like Dates and Strings.This meant that you had to perform a type cast every time you took an object out of a collection. In theory, this broke Java's compile-time type safety.

The second problem was that, for practical reasons, collections could work only with objects and not with primitive types. This meant that any time you wanted to put a number or other primitive type into a collection you had to store it in a wrapper class first and, of course, unpack it later upon retrieving it. The combination of these factors made code working with collections less readable and more dangerous to boot.

Two biggest new features:

Generic types make it possible to have truly typesafe collections.

The introduction of autoboxing and unboxing of primitive types means that you can generally treat objects and primitives as equals as far as collections are concerned.

Java.util pachage:

Collection interface represents a container that holds other objects.
Map interface represents a group of key/value pairs.

java.util package (J2SE 5.0)


General Rules

ArrayList and LinkedList provide the array and linked list implementations of the List interface described earlier. ArrayList is satisfactory for most purposes but use LinkedList when you plan to do a lot of insertions or deletions at various points in the list.

HashSet and HashMap provide a good hash map implementation of the Set and Map interfaces. The LinkedHashSet and LinkedHashMap implementations combine the hash algorithm with a linked list that maintains insertion order of the elements. (Note that these linked collections are ordered, but not sorted collections.)

TreeSet and TreeMap maintain sorted collections using a tree data structure. In the case of TreeMap, it is the key values that are sorted. The sorting is accomplished by a comparator object. We'll discuss sorting later in this chapter.

Queue is implemented both by LinkedList (which implements both List and Queue) and PriorityQueue. A PriorityQueue's prioritization comes from a sorting order determined by a comparator supplied with its constructor. Elements that sort "least" or "lowest" have the highest priority. The various implementations of BlockingQueue mirror these for concurrency-aware queues.

Finally, IdentityHashMap is an alternate type of HashMap that uses object identity instead of object equality to determine which keys match which objects. Normally any two objects that test equal with equals( ) operate as the same key in a Map. With IdentityHashMap, only the original object instance retrieves the element.

We should also mention three specialized collections that we'll talk about later: EnumSet and EnumMap are specifically designed to work with Java enumerations. WeakHashMap uses weak references to cooperate with Java garbage collection.

Synchronized and Unsynchronized Collections

To create a synchronized versioin of any collection:

A threadsafe List:

List list = new ArrayList();
List syncList = Collections.synchronizedList(list);

Wednesday, May 9, 2007

Installing and deploying app for Axis 1.X

First of all, I have to say that it's a pain in the #@!$@# to deploy your class as webservices using Axis 1.x. Unless you have to do it, here is what I did.

Installing Axis

1. Copy webapps/axis directory from axis_unzip_folder/webapps/axis to web applications folder

2. Make sure the following jars are in the WEB-INF/lib folder

  • axis.jar

  • axis-ant.jar

  • commons-discovery-0.2.jar

  • commons-logging-1.0.4.jar

  • jaxrpc.jar

  • log4j-1.2.8.jar

  • log4j.properties

  • saaj.jar

  • wsdl4j-1.5.1.jar



3. Make sure that web.xml and server-config.wsdd is in your WEB-INF folder

4. Evalutate installation with happyaxis.jsp

ref

Deploying application

1. We have a piece of code

2. We want to take theexisting code, wrap it up as a Web service, and then deploy it to the Apache Axis system.

3. Once we have a running service on the server side, we will create java stubs that allow up to communicate with the service, only requiring the WSDL.

Here are the steps:

1. Java2WSDL: Generate the WSDL file for the given interface.

To run ant tasks for java2wsdl, make sure the following jars are in the classpath

1. axis.jar
2. axis-ant.jar
3. jaxrpc.jar
4. log4j.jar
5. saaj.jar
6. wsdl4j.jar


2. WSDL2Java: Generate the server side wrapper code, and stubs for easy client access.

Java stub classes/interfaces will be generated according to the wsdl specified.

3. classinterfaceSoapBindingImpl: Fill in wrapper to call the existing code.

4. Deploy the service to Apache Axis

Deploy the war folder/file onto application server
Run: java org.apache.axis.client.AdminClient
-p"7003" -h"localhost" -s"axis-test/servlet/AxisServlet" war\hello\deploy.wsdd

5. Write a client that uses the generated stubs, to easily access the web service.

HelloWorldService service = new HelloWorldServiceLocator();

HelloWorld hw = service.gethello();

Ref

Sunday, May 6, 2007

Axis

Axis is all about processing Messages

When the central Axis processing logic runs, a series of Handlers are each invoked. The particular order is determined by two factors:

  • Deployment Configuration

  • Client Engine or Server Engine


The object passed to each Handler invocation is a MessageContext

MessageContext contains

  • a "request" message

  • a "response" message

  • a bag of properties



Message path on the Server

Transport -> Global -> Service

Message path on the client

Client app -> Service -> Global -> Transport

Handlers are either transport-specific, service-specific, or global. The handlers of each of these three different kinds are combined together into Chains. So the overall sequence of Handlers comprises three Chains: transport, global, and service.

A Chain is a composite handler. It aggregates a collection of Handlers as well as implementing the Handler interface.

Axis supports scoping service objects (the actual Java objects which implement your methods) three ways. "Request" scope, the default, will create a new object each time a SOAP request comes in for your service. "Application" scope will create a singleton shared object to service all requests. "Session" scope will create a new object for each session-enabled client who accesses your service. To specify the scope option, you add a to your service like this (where "value" is request, session, or application):
<service name="MyService"... >
<parameter name="scope" value="value"/ >
...
</service >

Message Processing
A message is processed by passing through the appropriate Chains. A message context is used to pass the message and associated environment through the sequence of Handlers. The model is that Axis Chains are constructed offline by having Handlers added to them one at a time.

A Targeted Chain is a special kind of chain which may have any or all of: a request Handler, a pivot handler, and a response Handler.

A service is a special kind of Targeted Chain in which the pivot Handler is known as a "provider".

Axis has an abstract AxisEngine class with two concrete subclasses: AxisClient drives the client side handler chains and AxisServer drives the server side handler chains.

The EngineConfiguration interface is the means of configuring the Handler factories and global options of an engine instance. An instance of a concrete implementation of EngineConfiguration must be passed to the engine when it is created and the engine must be notified if the EngineConfiguration contents are modified.

WSDD is an XML grammar for deployment descriptors which are used to statically configure Axis engines.

Each handler needs configuration in terms of


  • the concrete class name of a factory for the Handler


  • a set of options for the handler


  • a lifecycle scope value which determins the scope of sharing of instances of the Handler.



Exceptions

RemoteExceptions map to SOAP Faults

Exceptions are represented as wsdl:fault elements

Axis will only send objects for which there is a registered Axis serializer.

WSDL2Java: Building stubs, skeletons, and data types from WSDL
Client-side bindings
% java org.apache.axis.wsdl.WSDL2Java (WSDL-file_URL)

type mapping


ref

Tuesday, April 24, 2007

Spring Injecting dependencies

The basic principle behind Dependency Injection (DI) is that objects define their dependencies (that is to say the other objects they work with) only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a factory method. Then, it is the job of the container to actually inject those dependencies when it creates the bean. This is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself being in control of instantiating or locating its dependencies on its own using direct construction of classes, or something like the Service Locator pattern.

It becomes evident upon usage that code gets much cleaner when the DI principle is applied, and reaching a higher grade of decoupling is much easier when beans do not look up their dependencies, but are provided with them (and additionally do not even know where the dependencies are located and of what actual class they are).

The BeanFactory supports both of these variants for injecting dependencies into beans it manages. (It in fact also supports injecting setter-based dependencies after some dependencies have already been supplied via the constructor approach.)

Bean dependency resolution generally happens as follows:

1.

The BeanFactory is created and initialized with a configuration which describes all the beans. (Most Spring users use a BeanFactory or ApplicationContext implementation that supports XML format configuration files.)
2.

Each bean has dependencies expressed in the form of properties, constructor arguments, or arguments to the static-factory method when that is used instead of a normal constructor. These dependencies will be provided to the bean, when the bean is actually created.
3.

Each property or constructor argument is either an actual definition of the value to set, or a reference to another bean in the container.
4.

Each property or constructor argument which is a value must be able to be converted from whatever format it was specified in, to the actual type of that property or constructor argument. By default Spring can convert a value supplied in string format to all built-in types, such as int, long, String, boolean, etc.


The Spring container validates the configuration of each bean as the container is created, including the validation that properties which are bean references are actually referring to valid beans. However, the bean properties themselves are not set until the bean is actually created. For those beans that are singleton-scoped and set to be pre-instantiated (such as singleton beans in an ApplicationContext), creation happens at the time that the container is created, but otherwise this is only when the bean is requested. When a bean actually has to be created, this will potentially cause a graph of other beans to be created, as its dependencies and its dependencies' dependencies (and so on) are created and assigned.

Circular dependencies

If you are using predominantly constructor injection it is possible to write and configure your classes and beans such that an unresolvable circular dependency scenario is created.

Consider the scenario where you have class A, which requires an instance of class B to be provided via constructor injection, and class B, which requires an instance of class A to be provided via constructor injection. If you configure beans for classes A and B to be injected into each other, the Spring IoC container will detect this circular reference at runtime, and throw a BeanCurrentlyInCreationException.

One possible solution to this issue is to edit the source code of some of your classes to be configured via setters instead of via constructors. Another solution is not to use constructor injection and stick to setter injection only.

You can generally trust Spring to do the right thing. It will detect mis-configuration issues, such as references to non-existent beans and circular dependencies, at container load-time. It will actually set properties and resolve dependencies as late as possible, which is when the bean is actually created. This means that a Spring container which has loaded correctly can later generate an exception when you request a bean if there is a problem creating that bean or one of its dependencies. This could happen if the bean throws an exception as a result of a missing or invalid property, for example. This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost of some upfront time and memory to create these beans before they are actually needed, you find out about configuration issues when the ApplicationContext is created, not later. If you wish, you can still override this default behavior and set any of these singleton beans to lazy-initialize (that is not be pre-instantiated).

Finally, if it is not immediately apparent, it is worth mentioning that when one or more collaborating beans are being injected into a dependent bean, each collaborating bean is totally configured prior to being passed (via one of the DI flavors) to the dependent bean. This means that if bean A has a dependency on bean B, the Spring IoC container will totally configure bean B prior to invoking the setter method on bean A; you can read 'totally configure' to mean that the bean will be instantiated (if not a pre-instantiated singleton), all of its dependencies will be set, and the relevant lifecycle methods (such as a configured init method or the IntializingBean callback method) will all be invoked.

ref

Wednesday, April 18, 2007

Wildcards v.s. Generic Methods

Wildcards

void printCollection(Collection c) {
for (Object e : c) {
System.out.println(e);
} // ok

Collection c = new ArrayList ();
c.add(new Object()); //compile time error

Since we don’t know what the element type of c stands for, we cannot add objects
to it.

interface Collection {

public boolean containsAll(Collection c);
public boolean addAll(Collection c);
}

We could have used generic methods here instead:

interface Collection {
public boolean containsAll(Collection c);
public boolean addAll(Collection c);
// hey, type variables can have bounds too!
}

In both containsAll and addAll, the type parameter T is used only once. The return type doesn't depend on the type parameter, nor does any other argument to the method (in this case, there simply is only one argument). This tells us that the type argument is being used for polymorphism; its only effect is to allow a variety of actual argument types to be used at different invocation sites. If that is the case, one should use wildcards. Wildcards are designed to support flexible subtyping, which is what we're trying to express here.

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency. A generic method should not be used.

Use both generic methods and wildcards in tandem.

Class Collections {
public static void copy(List dest, list src) {...}
}



Saturday, April 14, 2007

Generics in Java

Generics are about abstraction. Generics let you create classes and methods that work in the same way on different types of objects.

Array types in Java have an inheritance relationship that allows this kind of aliasing to occur:

Date [ ] dates = new Date[10];
Object [ ] objects = dates;
objects[0] = "not a date"; // Runtime ArrayStoreException;


However, arrays have runtime representations as different classes and they check themselves at runtime, throwing an ArrayStoreException in just this case. So, in theory, Java code is not guaranteed typesafe by the compiler if you use arrays in this way.

Why Isn't a List a List<object>"?

The reason gets back to the heart of the rationale for generics that we discussed in the introduction: changing APIs. In the simplest case, supposing an ObjectList type extends a DateList type, the DateList would have all of the methods of ObjectList and we could still insert Objects into it. Now, you might object that generics let us change the APIs, so that doesn't apply anymore. That's true, but there is a bigger problem. If we could assign our DateList to an ObjectList variable, we would have to be able to use Object methods to insert elements of types other than Date into it. We could alias the DateList as an ObjectList and try to trick it into accepting some other type:
    DateList dateList = new DateList( );
ObjectList objectList = dateList;
objectList.add( new Foo( ) ); // should be runtime error!

Thursday, April 12, 2007

Java Constructor Chain

The way how java constructors are chained has three parts and is applied repeatedly for each successive constructor that is invoked:

  • If the first statement of a constructor is an ordinary statement—i.e., not a call to this( ) or super( )—Java inserts an implicit call to super( ) to invoke the default constructor of the superclass. Upon returning from that call, Java initializes the instance variables of the current class and proceeds to execute the statements of the current constructor.

  • If the first statement of a constructor is a call to a superclass constructor via super( ), Java invokes the selected superclass constructor. Upon its return, Java initializes the current class's instance variables and proceeds with the statements of the current constructor.

  • If the first statement of a constructor is a call to an overloaded constructor via this( ), Java invokes the selected constructor, and upon its return, simply proceeds with the statements of the current constructor. The call to the superclass's constructor has happened within the overloaded constructor, either explicitly or implicitly, so the initialization of instance variables has already occurred.

Tuesday, April 10, 2007

Java ClassLoaders

Class loader delegation model is the graph of class loaders that pass loading requests to each other. The bootstrap class loader is at the root of this graph. Class loaders are created with a single delegation parent and looks for a class in the following places:
  • Cache
  • Parent
  • Self
Three standard class loaders:
  • bootstrap class loader (jre/lib)
  • extension class loader (jre/lib/ext)
  • system class loader (CLASSPATH)
Three phases of class loading
  • loading: locating the required class file
by searching through the respective classpaths and loading in the bytecode. Within the JVM, the loading process gives a very basic memory structure to the class object. Methods, fields, and other referenced classes are not dealt with at this stage. As a result, the class is not usable.

  • Linking is the most complicated of the three phases. It can be broken down into three main stages:
  • Bytecode verification. The class loader does a number of checks on the bytecodes of the class to ensure that it is well formed and well behaved.
  • Class preparation. This stage prepares the necessary data structures that represent fields, methods, and implemented interfaces that are defined within each class.
  • Resolving. In this stage, the class loader loads all the other classes referenced by a particular class. The classes can be referenced in a number of ways:
    - Superclasses
    - Interfaces
    - Fields
    - Method signatures
    - Local variables used in methods
  • initializing phase
Any static initializers contained within a class are executed. At the end of this phase, static fields are initialized to their default values.

At the end of these three phases, a class is fully loaded and is ready for use. Note that class loading can be performed in a lazy manner and therefore some parts of the class loading process may be done on first use of the class rather than at load time.

Explicit and Implicit loading

Explicit:
cl.loadClass() (cl instance of java.lang.ClassLoader)
Class.forName()

Articles
Part 1
Part 2
Part 3
Part 4

Thursday, April 5, 2007

Mac Short Key

Mac OS X offers a glorious assortment of predefined keystrokes for jumping to the most important locations on your Mac: your Home folder, the Applications folder, the Utilities folder, the Computer window, your iDisk, the Network window, and so on.

Better yet, the keystrokes are incredibly simple to memorize: Just press Shift- and the first letter of the location you want. Shift--H opens your Home folder, Shift--A opens the Applications folder, and so on. You learn one, you've learned 'em all.

The point here is that Shift-, in Tiger, means places.

The other system-wide key combo, Option-, means functions. For example, Option--D hides or shows the Dock, Option--H is the Hide Others command, Option--+ magnifies the screen (if you've turned on this feature), Option--Esc brings up the Force Quit dialog box, and so on. Consistency is always nice.

Tuesday, March 27, 2007

Comparing Stateless and Stateful Session Beans

Upon startup, WebLogic Server automatically creates and populates the free pool with the quantity of instances you specify in the bean's initial-beans-in-free-pool deployment element in the weblogic-ejb-jar.xml file. By default, initial-beans-in-free-pool is set to 0.

If you configure a pool, WebLogic Server will service method calls with an EJB instance from the free pool, if one is available. The EJB remains active for the duration of the client's method call. After the method completes, the EJB instance is returned to the free pool. Because WebLogic Server unbinds stateless session beans from clients after each method call, the actual bean class instance that a client uses may be different from invocation to invocation.

If all instances of an EJB class are active and max-beans-in-free-pool has been reached, new clients requesting the EJB class will be blocked until an active EJB completes a method call. If the transaction times out (or, for non-transactional calls, if five minutes elapse), WebLogic Server throws a RemoteException for a remote client or an EJBException for a local client.

Note: The maximum size of the free pool is limited by the value of the max-beans-in-free-pool element, available memory, or the number of execute threads.

When an application requests a bean instance from the free pool, there are three possible outcomes:

  • An instance is available in the pool. WebLogic Server makes that instance available and your application proceeds with processing.
  • No instance is available in the pool, but the number of instances in use is less then max-beans-in-free-pool. WebLogic Server allocates a new bean instance and gives it to you.
  • No instances are available in the pool and the number of instances in use is already max-beans-in-free-pool. You application must wait until either your transaction times out or a bean instance that already exists in the pool becomes available.
bea docs

Thursday, March 22, 2007

Threads in Java

Synchronization:
Locking is about coordinating the activities of two or more threads, so they can work together and not collide in their use of the same address space. Synchronization makes sure only one thread at a time can perform certain activities that manupulate an object.

In Java
Every Class has a lock
Every instance has a lock.

To synchronize a method:
synchronized void say () {/*do sth*/ }
Because say() is an instance method, a thread has to acquire the lock on the particular instance before it can invoke the say() method.
If say() were a class (static) method instead of an instance method, we could still mark it as synchronized. But in this case as there is no instance object involved, the lock would be on the class object itself

Monday, February 5, 2007

Import and Export Oracle Database

Use Oracle utility tool
exp username/password file=dbexp log=dbexp.log

will export all the objects belong to the user.

Friday, February 2, 2007

http sniffer

I found two very good http debugging tools for windows and mac

windows:
Fiddler
mac:
HTTP Scoop

Friday, January 19, 2007

Setup CVS Server on Mac OS X 10.4

I just setup the cvs server on mac. Here are the steps:

Configuring the CVS repository


sudo mkdir /usr/local/cvsroot/

sudo cvs -d /usr/local/cvsroot/ init
or
setup environment variable:
CVSROOT=/usr/local/cvsroot
and
export CVSROOT

Password CVS access using xinetd
create a file cvspserver in /etc/xinetd.d
service cvspserver
{
disable = no
socket_type = stream
wait = no user = root
server = /usr/bin/cvs
server_args = -f --allow-root=/usr/local/cvsroot
pserver groups = yes flags = REUSE
}

Restarting xinetd
cat /var/run/xinetd.pid and grab the id (i.e. 285)
sudo kill -HUP id (i.e. 285)
sudo /System/Library/StartupItems/IPServices/IPServices start

Create a file called passwd in /usr/local/cvsroot/CVSROOT/
create a encrypted password:
perl -e 'print crypt "password", "sa"'
in the passwd file, put down
username:encryptedpassword

Setup client connection like this
:pserver:username@domain:/usr/local/cvsroot

then you're done!