Thursday, December 30, 2010

Intercepting Filter

Presentation-tier request handling mechanism receives different type of requests. They require various type of processing such as authentication checking, validation checking, modifying, auditing. Therefore, preprocessing and post processing  of a client request is required. In the normal scenario, we can do this by conditional checks and with a invaild check, abort the request. But this is not a good solution because, we have to change the code according to the type of request. Therefore, the best solution is to add and remove components, these specific components complete specific filtering actions.
    Therefore, when a client send a request, FilterManager manages the needed filters according to the order. It is the FilterChain with appropriate filters. It is an ordered collection of independent filters. The Filter chain coordinates their processing that are mapped to a target. The target is the resource that client requests.

Sunday, December 26, 2010

Apache Maven-What is a POM?

The fundamental unit of work in Maven is POM, Project Object Model. It is a XML file containing the project and configuration details used by Maven to build the project. When executing a task, Maven looks for the POM in the current directory to get needed configuration information such as project dependencies, the plugins, goals and the build profiles. POM contains other information such as project version, description, developers and mailing lists.
The Super POM is Maven's default POM. All POMs we create extend the Super POM and Super POM is inherited by the POMs. Minimum requirements for a POM are the project root, modelVersion, groupId, artifactId, version. Here is a example of a POM file with minimum requirements.

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1</version>
</project>

If the configuration details are not specified, Maven will use their defaults.  Here, with the minimum requirements, repositories are not defined. Therefore, when it is built, it will inherit the repositories configuration from Super POM.

If we want to add an another artifact to our project, my-app, it will be something like this.

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-module</artifactId>
  <version>1</version>
</project>

If we want to make the my-app project the parent of newly created artifact, we have to edit the newly created artifact module's pom file as below to include the parent's section.

<project>
  <parent>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-app</artifactId>
    <version>1</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-module</artifactId>
  <version>1</version>
</project>

Wednesday, December 22, 2010

EntityManager

EntityManager manages entities. The javax.persistence.EntityManager instances represent the entity manager. Each EntityManager instance is associated with a persistent context. A persistence context defines the scope under which particular entity instances are created, persisted, and removed and it is a set of managed entity instances that exist in a particular data source. The EntityManager interface defines the methods that are used to interact with the persistence context like creating and removing persistent entity instances, finding entities by the entity’s primary key, and allowing queries to be run on entities.

Container-Managed Entity Managers


EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. The Java EE container manages the life cycle of container-managed entity managers.

To obtain an EntityManager instance, inject the entity manager into the application component:

@PersistenceContext
EntityManager em;

Application-Managed Entity Managers

The persistence context is not propagated to application components, and the life cycle of EntityManager instances is managed by the application. Applications create EntityManager instances using the createEntityManager method of javax.persistence.EntityManagerFactory.
To obtain an EntityManager instance, you first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation:

@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();

The EntityManager.find method is used to look up entities in the data store by the entity’s primary key.

@PersistenceContext
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
    Customer cust = em.find(Customer.class, custID);
    cust.getOrders().add(newOrder);
    newOrder.setCustomer(cust);
}

Managing an Entity Instance’s Life Cycle

The four states of an entity instance are new, managed, detached and removed. New entity instances have no persistent identity and are not yet associated with a persistence context. Managed entity instances have a persistent identity and are associated with a persistence context. Detached entity instances have a persistent identify and are not currently associated with a persistence context. Removed entity instances have a persistent identity, are associated with a persistent context, and are scheduled for removal from the data store.

By invoking the persist method or by a cascading persist operation invoked from related entities that have the cascade=PERSIST or cascade=ALL elements set in the relationship annotation, new entity instances become managed and persistent. The entity’s data is stored to the database when the transaction associated with the persist operation is completed. Managed entity instances are removed by invoking the remove method, or by a cascading remove operation invoked from related entities that have the cascade=REMOVE or cascade=ALL elements set in the relationship annotation.

Creating Queries

The EntityManager.createQuery and EntityManager.createNamedQuery methods are used to query the data store using Java Persistence query language queries. The createQuery method is used to create dynamic queries.

public List findWithName(String name) {
return em.createQuery(
    "SELECT c FROM Customer c WHERE c.name LIKE :custName")
    .setParameter("custName", name)
    .setMaxResults(10)
    .getResultList();
}

The createNamedQuery method is used to create static queries.

@NamedQuery(
    name="findAllCustomersWithName",
    query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)


@PersistenceContext
public EntityManager em;
...
customers = em.createNamedQuery("findAllCustomersWithName")
    .setParameter("custName", "Smith")
    .getResultList();

Log4j

Log4j is an open source project that allows the developers to control which log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files. The advantages of the logging are providing a precise context about a run of the application, the generation of the logging output requires no human intervention, log output can be saved in persistent medium. The drawback of logging is slowing down the application.

Log4j has three main components. They are loggers, appenders and layouts. These three components are used to log messages according to message type and level and to control at run time how these messages are formatted and when they are reported. The advantage of logging API than System.out.println(); is it's ability to disable certain log statements while allowing others to print unhindered( logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria ).

The root logger is the top of the logger hierarchy. It always exists and cannot be retrieved by name. Logger.getRootLogger method retrives the root of hierarchy. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. Some methods in the logger class are stated below.
    public void trace(Object message);
    public void debug(Object message);
    public void info(Object message);
    public void warn(Object message);
    public void error(Object message);
    public void fatal(Object message);
    public void log(Level l, Object message);

Loggers may be assigned levels. They are TRACE, DEBUG, INFO, WARN, ERROR and FATAL defined in the org.apache.log4j.level class. We can define our own level by subclassing the Level class. Root logger has an asigned level. If a logger is not assigned a level, it inherits from the ancestors. Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal  and log.By definition, the printing method determines the level of a logging request. A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy.  The order of the levels is DEBUG < INFO < WARN < ERROR < FATAL. Calling the getLogger method with the same name will always return a reference to the exact same logger object.

Appenders and Layouts

Log4j allows logging requests to print to multiple destinations. An output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS,  NT Event Loggers, and remote UNIX Syslog daemons. The addAppender method adds an appender to a given logger. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy.

Output format can be customized using a layout with an appender. The layout formats the logging request according to the user's wishes and an appender sends the formatted output to its destination.

PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output:176 [main] INFO  org.foo.Bar - Located nearest gas station.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.

Sunday, December 12, 2010

Hibernate

Hibernate is an Open Source persistence technology. Hibernate maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduces the development time. It is most useful with object-oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.

Features of Hibernate
  •     Hibernate provides full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
  •     Filters for working with temporal (historical), regional or permissioned data.
  •     Enhanced Criteria query API: with full support for projection/aggregation and subselects.
  •     Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.
  •     Hibernate is Scalable: Hibernate has high performance and due to its dual-layer architecture can be used in the clustered environments.
  •     Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.
  •     Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.

      In Hibernate, Java classes represent the table in the database and then map the instance variable in the class with the columns in the stabase. Then Hibernate can perform the operations like select, insert, update and delete by automatically creating the quiries.

Hibernate architecture has three main components:
  1. Connection Management: provides efficient management of the database connections. 
  2. Transaction management: provides the ability to the user to execute more than one database statements at a time.
  3. Object relational mapping: technique of mapping the data representation from an object model to a relational data model and is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Plain Old Java Objects (POJOs) classes are used to map to the database table and configure the variables to map to the database column.A xml file is used to map  Object to the  table in the database. Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows application to create the Hibernate Session by reading the configuration from hibernate.cfg.xml file.  Then the save method on session object is used to save the contact information to the database:

Spring

Spring framework is an open source technology and helps to simplify the developed of enterprise applications in Java technologies.

Features of Spring Framework:

  • Transaction Management: A generic abstraction layer for transaction management allows the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy
  • Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.
  • AOP Framework: Spring is best AOP framework
  • MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality.

Spring Architecture

Spring is well-organized architecture consisting  of seven modules. Modules in the Spring framework are:

   1. Spring AOP
            To provide declarative enterprise services, especially as a replacement for EJB declarative services.
            To allow users to implement custom aspects, complementing their use of OOP with AOP

   2. Spring ORM
      The ORM package that is related to the database access,  provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
       
   3. Spring Web
      The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC.
        
   4. Spring DAO
      The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
        
   5. Spring Context
      This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
       
   6. Spring Web MVC
      This is the Module which provides the MVC implementations for the web applications.
       
   7. Spring Core
      This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic

Two way to configure Spring IOC container

a) xml file: The bean configuration is defined in xml file and then instruct the Spring to use the xml file to configure the beans.

b) Annotation: The @configuration spring annotation can also be used to configure the Spring IOC container. Here programmer add the @configuration to the Java class and this class is considered as special configuration class. The @Bean  tag is used to define the bean, and the Spring framework executes the method and then register the object returned. By default the name of the method is used as the bean name.

XML Bean-Injection

InjectClass.java
class InjectClass {

    private String name;
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Name: " , this.name);
    }
}

InjectClass is the java class. It has overided the toString() method.

XML file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="mybean"   class="InjectClass"
      p:name="XML Bean-Injection">
    </beans>

xmlns:p="http://www.springframework.org/schema/p":-Namespace:"p" that cannot be validated.

<bean id="mybean"  class="InjectClass">:- Here "InjectClass" is the name of the bean class which would be referred in the xml file with the id "mybean".

The xml file declares the spring bean "mybean" . The <bean .../> tag is used to declare a bean in the xml file. The xml file is used to configure the spring run-time environment. Spring framework manages the beans in our program.



import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
    public static void main(String[] args) {
        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
                "context.xml"));
        InjectClass demo = (InjectClass) beanFactory.getBean("mybean");
        System.out.println(demo);
    }
}


XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml")): creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document

new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded.

Friday, December 10, 2010

A start to Apache Camel

Camel is an open-source, Java-based project that helps the user to implement many of the design patterns in the Enterprise Integration Patterns book. When we talk about the the term endpoint, in client-server communication, the client is one end point and the server is another endpoint. An endpoint might refer to an address, such as a host:port pair for TCP-based communication, or it might refer to a software entity that is contactable at that address.

Some examples of the Camel-supported endpoint technologies are JMS queue, web service,  file, FTP server, email address, POJO (plain old Java object).

In camel based applications, endpoints are created and connected with routes. Camel defines a Java interface called Endpoint. Each Camel-supported endpoint has a class that implements this Endpoint interface.

A CamelContext object represents the Camel runtime system. You typically have one CamelContext object in an application. After creating a CamelContext object, we can add end points and routes to connect the end points.

Invoking the start() operation on the CamelContext object, starts Camel-internal threads that are used to process the sending, receiving and processing of messages in the endpoints.Invoke the stop() operation on the CamelContext object stops all the endpoints and Camel-internal threads. CamelTemplate class is a thin wrapper around the CamelContext class. It has methods that send a Message or Exchange to an endpoint. Therefore, messages can be sent to source endpoints, messages will move along routers.

Components are used to create the endpoints. As an example, if we take JmsComponent class(implements Component), JmsComponent.createEndpoint() creates an instance of the JmsEndpoint class (which implements the Endpoint interface). In the application-level, CamelContext.getEndpoint() finds the desired Component object and then invokes createEndpoint() on it.

myCamelContext.getEndpoint("pop3://john.smith@mailserv.example.com?password=myPassword");

The parameter to getEndpoint is a URI. URI prefix(the part before :) is Component. CamelContext object maintains a mapping from names of components(pop3) to Component objects. CamelContext object invokes createEndpoint("pop3://john.smith@mailserv.example.com?password=myPassword") on that MailComponent object. The createEndpoint() operation splits the URI into its component parts and uses these parts to create and configure an Endpoint object.

Message,Exchange and Processor

Message interface is an abstraction for a single message(request, reply or exception message). There are concrete classes that implement Message interface for each Camel supported communication technologies. The Exchange interface is an abstraction for an exchange of messages, that is, a request message and its corresponding reply or exception message. In Camel terminology, the request, reply and exception messages are called in, out and fault messages. There are also concrete classes that implement the Exchange interface for each Camel-supported communications technology.

The processor interface represents the process of a message. The classses that implement Processor interface  provides support for a design pattern. For an example, ChoiceProcessor implements the message router pattern, FilterProcessor class which discards messages that do not satisfy a stated condition.

Routes, RouteBuilders and Java DSL

A route is the step-by-step movement of a Message from an input queue, through decision making (such as filters and routers) to a destination queue(if any). Camel provides two ways for an application developer to specify routes, XML file and Java DSL (domain-specific language). Java DSL is a class library that looks like DSL with JAVA

Wednesday, December 8, 2010

Java Concurrency with Newly Added Features in JavaSE 5

Java concurrency helps developers to work with multi-threaded programs using features like Thread, synchronized and volatile. Threads communicate by calling a method of another thread. Some thread coordination methods are start, join and interrupt. A deadlock occurs when there is more than one thread, each waiting for the resource held by another. Starvation occurs when a thread holds a lock when some other starve without any progress. Wait/notify methods are used when one thread needs to signal when other thread waits till the condition is met.

A race condition occurs when more than one thread is performing actions on shared resources and several outcomes can exist with the order of the actions from each thread. Therefore, locking establishes the guarantee of the orderings. The monitor in every object provide mutual exclusion access to critical sections of code. Critical section is specified by marking as synchronized in a method or code block. Only one thread is allowed to enter the critical section for a particular monitor. Other threads have to wait for the monitor to be released.

java.util.concurrent.locks packages has a standard Lock interface. ReentrantLock implementation dublicated the functionality of the synchronized keyword with functionlity to obtain information about the state of lock. ReadWriteLock interface and ReentrantReadWrite Lock implementation define pair of locks for reading and writing. volatile modifier marked in a field indicate that the changes to that field must be seen by all subsequent reads by other threads.

java.util.concurrent package inculdes data structures designed for concurrent use. Use of these data structures gives better performances than using a synchoronized wrapper around an unsynchronized collection. As an example, CopyOnWriteArrayList is a thread-safe ArrayList where each modification of the data structure results in a new internal copy of the data. Queue acts as a "first in first out(FIFO)" adding elements in one end and removing from other end. BlockingQueue interface extends Queue and provide additional functionality how to handle the scenario where a queue may be full. Deque supports adding and removing from both ends, not adding from one end and removing from other end.

There are several classes for multi-thread communication such as CyclicBarrier, CountDownLatch, Semaphore and Exchanger. In task execution using a pool of workers, Executor and more ExecutorService interfaces define the contract for a component  that can execute tasks.