Friday, June 29, 2007

Confucius say

What the superior man seeks is in himself; What the small man seeks is in others
- Confucius

Tuesday, June 26, 2007

EJB 3.0

- Server-side component framework: Dividing functionality into independent and self-contained components that can interoperate with each other to assemble an application was deemed the best solution for building applications.

- Component vs. Object: Object-oriented languages/technoglogy by itself wasnot fully equipped to garner optimum levels of reuse.Components differ from objects in a substantial manner - they live in an independent existence. A component is a self-contained, reusable entity, it must be packaged with all the requisite artifacts.

- Simplicity in EJB 3.0 has been achieve:
a) No home and object interfaces are required. Pre EJB 3.0, need provide home interface (local/remote), EJB object interface (local/remote) and a bean class.
Home interface server as a factory for creating references to EJB object. SL session bean and message driven bean doesn't have state, can be create equally. SF session bean has a special create method in home interface to pass state, in 3.0, a special method can be defined in bean class to handle it, called by container before 1st business method invoked.
Object interface provide client view for an EJB, container provides implementation for it, i.e., the EJB Object. It delegate the business method call to bean class, whereas calling container middleware service before and after the method invocation. The problem is that bean class doesn't directly implement the object interfaces and developers should be extra careful in providing the implicit implementation to match the method signatures. (one solution is define a super business interface)
** Local interface passes parameter using pass-by-reference semantics, remote interface pass-by-reference
** For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request (bean in instace pool servers only for home methods such as create and findBy). while refering the EJB Object classes the container creates a separate instance for each client request.
In EJB 3.0, only a POJI business interface and a POJO directly implementation bean class needed, container will internally generate wrapper class, i.e., how the container inject middleware service before and after business method invocation is a container-specific detail and need not concern the EJB developer. Also, 2.+'s RemoteException in remote interface is removed, replaced with a EJBException which is unchecked RuntimeException and not need to be listed in the method signature.

b) No component interface is required
javax.ejb.SessionBean and javax.ejb.MessageDrivenBean to notify bean instance of variosu life cycle events such as ejbCreate(), ejbDestroy() are not enforced. You can use @interpectors annotation to add a callback class to handle them if needed.

c) Use of Java metadata annotation
It makes deployment descriptors redundant. If there is deployer, should still use DD to separate the responsibility.

d) Simplification of APIs for accessing bean's environment: don't have to rely on JNDI, dependency injection and EJBContext.lookup() available

- Session Bean
Components that contains logic for business processes, relatively short-lived object, lifetime equivalent of a session or request.

Three subTypes: SLSB, SFSB, and session bean as web service (2.1+)

SLSB: no conversational state. In EJB 2.+, bean instances are pooled (a few beans can server many clients) and reused, they are decoupled from EJB objects. For SL, the container dynamically reassign beans to client requests at the per-method level. The create(), remove() in home interface are for creating and destroying EJB objects, not bean instances which are managed by container in bean pool. (So from SL client code, operate on same EJB object may actually delegate to different bean; SF is different)

SFSB: hold conversational state spanning multiple method call. Same bean has to be used for same EJB object and client requests, meanwhile, need bean pooling, so activation/passivation are introduced.
** One of the most common programming mistakes in J2EE is to forget to explicitly destroy or remove session bean (SF) once they have been used, a big performance impact. Basically, what happens is that the SF bean will be passivated,a rather silly way of removing an bean from the container (or removed when session timeout). As you probably know, passivation is a very expensive operation, as it first serializes the bean, and then writes it to disk. In EJB 2.+, call remove() method in EJBObject interface; in EJB 3.0, add a method annotated with @remove in business interface, call it will tell container that the client doesn't need it anymore and can be destroyed.
** SFSB vs. Http Session object
SFSB has limited used in development should rarely be seen. Shopping cart as referenced example cannot satisfy the persistent failure. The primary intent of SFSBs is used in non-web system to track session-oriented state. In web system, should use HttpSession objects to store session-oriented state on behalf of a client. Applications that manage an HttpSession object and an SFSB for a single client wind up duplicating effort that does not need to be duplicated. only used in two cases: 1. system is expected to have a large number of concurrent clients, since SFSB has passivation/activation, implemented as HttpSession only hold one reference to a SFSB; 2. session-oriented objects need to receive notifications on the lifecycle of the transactions they participate in. SFSBs can implement the SessionSynchronization interface. (Arguable: different responsibility for web-tier against business tier, lower reusebility)

Session Bean as Web Service
Web service has not single implementation framework, a contract with WS only involve its interfaces (port), which defined in WSDL, and can be implemented in any language.
Web services = WSDL + SOAP + UDDI;

- Entities
Java Persistence Specification: provide standard ORM; not tie to J2EE container, can be used in J2SE env; define a service provider interface SPI

Entities vs. Session Bean: have persistent identity (PK), persistent state, not remotely accessible, different life cycle with application

- Entity bean (CMP & BMP)
passviation/activation Entity bean vs. SFSB:
SFSB passivation/activation uses object serialization to persist states, ejbActivated() and ejbPassivate() are called to restore/release the resources such as socket connection;
Entity bean passivation/activation is to transition bean into or out of instance pool. In activation, container associate bean with a specific EJB object and a specific primary key. call ejbActivate(), ejbLoad() in order, ejbActivate() is to acquire resource, and ejbLoad()read db data to bean state; In passivation, deassociate bean from EJBObject and PK, call ejbStore() and ejbPassivate() in order.
** container cannot passivate a bean when it is in a transaction

More methods: findXXX() in home interface and corresponding ejbFindXX() in bean class for BMP, findByPrimaryKey() is mandatory, others are custom finder; getPrimaryKey() in EntityContext to be used in bean ejbLoad() and ejbRemove() in bean, EJBObject has a getPrimaryKey() method to be used in client code. We have remove() in both EJBHome and EJBObject interface, the former one is only for entity bean that we can remove it without instantiated first.

EJB 2.0 CMP vs EJB 1.1 CMP
In EJB 1.1 CMP there was no defined standard for defining relationships, finder methods or local beans; EJB 2.0 CMP more clearly defines the roles of entity beans, includes standard query definition (EJB QL), local interfaces and abstract classes. The abstract class model require to declare abstract accessor methods, which is required by the EJB 2.0 specification to use Container Managed Relationships (CMR), the container will generate the code to implement the relationship into the accessor methods of the EJB wrapper object.

CMR (container managed relationship 1-1, 1-N, N-M)
It is to establish a relationship between two CMP entity beans
Multiplicity defined in deployment descriptor with
Navigability (uni-direction and bi-direction) is implied by the definition of abstract getter and setter method in one or both of the entity beans. Also, a is added to deployment descriptor.
** CMR fields (as opposed to CMP fields) cannot be initialized in ejbCreate() method because PK is not available atm, They can, however, be set in ejbPostCreate()

- Message Driven Bean
Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean

MOM - message-oriented middleware vs. RMI
.aynchrony, non-blocking request processing
.decoupling, message sender decouple from consumer
.reliability, guarantee delivery
.support for multiple senders and receiver, broadcast

Friday, June 22, 2007


- take control of compilation, packaging, testing, and deployment stages of the build process in a way that is portable, scalable, and often reusable.

- three levels: project (each build file), target (dependencies), task (extensible, e.g, javac, mkdir)

<-- target is to resolve dependencies, conditionally execution. e.g., -->
<target name="m.clean">
  <property name="cleaned" value="true"/>
<target name="m.compile">
  <javac destdir="..." ></javac>
  <antcall target="m.binding" />

<target name="m.binding" if="cleaned">
   <bind load="true"> ...</bind>

- DataTypes: Path, Fileset, Patternset, Filterset, ZipFilest, etc.

- Ant properties ${}
i. built in properties such as ant.file (the absolute path of the build file, can use ant.file.fgl-common-build where fgl-common-build is the project name of the build file which is included in the main build file)

ii. JVM system properties, e.g.,, java.home

iii. Set with 'property' task

<property name="build.debug" value="on"/> -- name/value pair
<property file="" /> -- load from properties file
<property name="src.dir" location="somedir" /> - refer to relative path

iv. load environment varialbe

<property environment="env" />

v. set property conditionally

<!-- if debug, set debugLevel to all; else lines only -->
<condition property="debugLevel" value="lines,vars,source" else="lines,source">
  <istrue value="${debug}"/>

all env vairables are loaded with prefix env such as env.CATALINA_HOME
Properties are immutable. A property define in build file doesn't override the one from property file. However, there are ways to break the immutability of property using <ant/>, <antcall>, <available> and -D command line operation. Among them, -D has the highest priority.

Tuesday, June 19, 2007

MBean definition

Java Management Extensions (JMX) is a Java technology that supplies tools for managing and monitoring applications, system objects, devices (e.g. printers) and service oriented networks. Those resources are represented by objects called MBeans (for Managed Bean).

MBean is a type of JavaBean, created with dependency injection. The MBean represents a resource running in the Java Virtual Machine such as an application, a J2EE technical service (transactional monitor, JDBC driver, ...), ... They can be used for getting and setting applications configuration (pull), for collecting statistics (pull) (e.g. performance, resources usage, problems, ...) and notifying events (push) (e.g. faults, state changes, ...)

Friday, June 15, 2007


- allow a smooth transition from machine-centric to human-centric coding, on bytecode level, it is java. It builds on the basic idea of Java platform with a different interpretation of code appearance.
- Groovy is a dynamic language: generating classes transparently at runtime and able to seemingly modify classes at runtime. Groovy doesn't generate bytecode that reflects method call directly, but does something like
getMetaClass().invokeMethod(this, "foo", EMPTY_PARAMA_ARRAY); That way, method calls are redirected through the object's MetaClass. The MetaClass can now do tricks with method invocations such as intercepting, redirecting, adding/removing methods at runtime, and so on.
- run Groovy classes inside JVM in two ways: precompiled mode (with groovyc compiler to generate *.class file, loaded with normal Java classloader) and direct mode (no *.class files are generated, but rather class objects, loaded with groovy classloader)
- treat everything as an object and all operators as method calls, hence improves the level of object orientation. autoboxing for primitive types, 1+1 is interpreted as
- closure needed in: iterator for collections, and using resource in safe manner.

Thursday, June 14, 2007


Spring is a lightweight inversion of control and aspect-oriented container framework.
- lightweight: size/overhead, and nonintrusive, app doesn't have dependencies on Spring specific classes
- inversion of control: object are passively given the dependencies instead of creating or looking for dependencies. beans loosely couple through interface.
- aspect-oriented: enable cohesive development by separating application business logic from system services (commonly referred to as cross-cutting concerns because they tend to cut across multiple components) such as auditing and transaction mgr.
- container: contains and managers the life cycle and config of app objects, creating associations between collaborating components (wiring beans)
- framework: config and compose complex app from simple component.

Common implementations of ApplicationContext:
- ClassPathXmlApplicationContext: load context definiton as xml from classpath
- FileSystemXmlApplicatonContext: load from file system
- XmlWebApplicationContext: load from xml contained within a web application

Tuesday, June 12, 2007

Java 5 Enum

Java 5 enum is a special type of class - subclass of java.lang.Enum. Java compiler transparently translate it. Each symbolic constant of enum is an instance of the class. The constructor must be private to avoid programmatically instantiation. It can also have private attribute and methods.

enum TrafficLight {RED, GREEN, BLUE; }
public class TrafficLight {
private final String color;
private TrafficLight(String color) { this.color = color; }

public static final TrafficLight GREEN = new TrafficLight(“GREEN”);

So,on the caller side:

TrafficLight tl = TrafficLight.RED;


enum TrafficLight {RED("stop"), GREEN("go"), BLUE("warn"); }

where the string is passed in as constructor parameter.

Also, since it is normally inside a file with other class, it cannot be declared as public in that case.

-Some common methods

public enum Shape { RECTANGLE, CIRCLE, LINE }
System.out.println(drawing); // Prints RECTANGLE, toString() will return name
System.out.println(drawing.ordinal()); // Prints 0 for RECTANGLE.
Shape drawing = Shape.valueOf("RECTANGLE"); // convert a string to Enum object

Reference Link