Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, April 3, 2008

Key Points for Choosing the Best framework

The question which majority of we developers ask always is “Which framework should I use for my application?” or “Which framework is the best to use?”

The answer to these questions always comes in as “it depends” because requirements differ project wise. It might not be the case that the project which you might be working on will be requiring the same framework used in the prior projects. Requirements vary all the time and the framework which comes very close for implementing the specified tasks would be the best framework for you.

Having said that it is important to list down the key points on why you choose a particular framework. It is never a good reason to choose a framework just because others say it is cool. Let us focus on the key points for deciding a framework. Keep in mind, I am not trying to impose the usage of suggested framework for any particular project. This is a topic of general discussion in case where you might be eager to try out a new framework but are stuck to the choice of framework to start from.

The key points which might help you to make your choice are (not in any particular order):

  • Popularity
    • Helps in getting acquainted quickly (eg: Groovy)
  • Market
    • Easier to find jobs (eg: Struts)
  • Convenience
    • Should not take a huge learning curve (eg: Tapestry)
  • Time to implement
    • Should make the task get completed quickly
  • Scope
    • Should be pluggable with other frameworks (eg: Spring)
  • Documentation
    • Most important without which you will get stuck easily
  • Forums
    • The more big the community the easier is your work done
  • Bug tracking
    • If at all you tend to go deep, ticketing support should be present
  • Reference Books
    • Essential since online searching can eat up your time
  • Light weight
    • Complex ones will do no good if is not used much (eg: EJB 2.x)
  • Robust
    • There should not be any known bugs for the features you want to implement
  • Features

These are the 12 key points which I feel are very important when I look forward to work on a self project or am willing to learn a new framework. It is not necessary that all the 10 will be satisfied by one single framework. So it would be more beneficial to make a subset of these key points for shortlist your choice of frameworks based on your project.

How to finalize on a particular framework?

First, decide on comparing 2 to 3 frameworks at the max. The more you have in mind, the more confusion it will create. Plan out which features you want to implement for the given set of requirements. Do an exhaustive search on Google whether the features are provided by the frameworks you have in mind. Give points out of 10 for each of the subset key points. Compare the frameworks for the same subset of key points.

This will help you to make a matrix out of your choices and will further make it much easier to finalize your choice since now you would be sure of the reasons you are making a decision.

What are your key points when you first think when you pick a framework to work upon? It would be an interesting discussion to follow up. How did you shortlist your framework for learning or working on a project?

Tag handler interfaces in Custom Tag

Tag handler interfaces

The tag handlers must implement Tag , BodyTag , or IterationTag interfaces. These interfaces are contained in the javax.servlet.jsp.tagext package.

Tag handler methods defined by these interfaces are called by the JSP engine at various points during the evaluation of the tag.

Tag interface
The Tag interface defines the basic protocol between a tag handler and JSP container. It is the base interface for all tag handlers and declares the main lifecycle methods of the tag.

  • The setPageContext() method is called first by the container. The pageContext implicit object of the JSP page is passed as the argument.
  • The setParent() method is called next, which sets the parent of the tag handler.
  • For each attribute of the custom tag, a setter method is invoked next.
  • The doStartTag() method can perform initializations. It returns the value EVAL_BODY_INCLUDE or SKIP_BODY .
  • The doEndTag() method can contain the cleanup code for the tag. It returns the value EVAL_PAGE or SKIP_PAGE .
  • The release() method is called when the tag handler object is no longer required.

IterationTag interface
The IterationTag interface extends Tag by defining one additional method that controls the reevaluation of its body.

  • IterationTag provides a new method: doAfterBody() .
  • If doStartTag() returns SKIP_BODY , the body is skipped and the container calls doEndTag() .
  • If doStartTag() returns EVAL_BODY_INCLUDE , the body of the tag is evaluated and included, and the container invokes doAfterBody() .
  • The doAfterBody() method is invoked after every body evaluation to control whether the body will be reevaluated.
  • If doAfterBody() returns IterationTag.EVAL_BODY_AGAIN , then the body will be reevaluated. If doAfterBody() returns Tag.SKIP_BODY , then the body will be skipped and doEndTag() will be evaluated instead.

BodyTag interface
The BodyTag interface extends IterationTag by defining additional methods that let a tag handler manipulate the content of evaluating its body:

  • The doStartTag() method can return SKIP_BODY , EVAL_BODY_INCLUDE , or EVAL_BODY_BUFFERED .
  • If EVAL_BODY_INCLUDE or SKIP_BODY is returned, then evaluation happens as in IterationTag .
  • If EVAL_BODY_BUFFERED is returned, setBodyContent() is invoked, doInitBody() is invoked, the body is evaluated, doAfterBody() is invoked, and then, after zero or more iterations, doEndTag() is invoked. The doAfterBody() element returns EVAL_BODY_AGAIN or EVAL_BODY_BUFFERED to continue evaluating the page and SKIP_BODY to stop the iteration.

A class named Class

A class named Class

It might seem strange to have "a class named Class" (maybe no more so than creating an object of class Object, I guess). But java.lang.Class has been around since the earliest days of Java; at least JDK 1.0, so I guess most of these uses were planned even then

 

 

The Reflection API

The Reflection API

Uses of Reflection

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

Extensibility Features

An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.

Class Browsers and Visual Development Environments

A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.

Debuggers and Test Tools

Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

Drawbacks of Reflection

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

Performance Overhead

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Security Restrictions

Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

Exposure of Internals

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

 

Finding Out About Methods of a Class using reflection

One of the most valuable and basic uses of reflection is to find out what methods are defined within a class. To do this the following code can be used:

 

   import java.lang.reflect.*;

 

   public class method1 {

      private int f1(

       Object p, int x) throws NullPointerException

      {

         if (p == null)

            throw new NullPointerException();

         return x;

      }

       

      public static void main(String args[])

      {

         try {

           Class cls = Class.forName("method1");

       

            Method methlist[]

              = cls.getDeclaredMethods();

            for (int i = 0; i < methlist.length;

               i++) { 

               Method m = methlist[i];

               System.out.println("name

                 = " + m.getName());

               System.out.println("decl class = " +

                              m.getDeclaringClass());

               Class pvec[] = m.getParameterTypes();

               for (int j = 0; j < pvec.length; j++)

                  System.out.println("

                   param #" + j + " " + pvec[j]);

               Class evec[] = m.getExceptionTypes();

               for (int j = 0; j < evec.length; j++)

                  System.out.println("exc #" + j

                    + " " + evec[j]);

               System.out.println("return type = " +

                                  m.getReturnType());

               System.out.println("-----");

            }

         }

         catch (Throwable e) {

            System.err.println(e);

         }

      }

   }

 

how to invoke a method wihout knowing its method name? Dynamic Method Invocation

A new methodology - Dynamic Method Invocation

If you have a Method descriptor, you can invoke that method on any object of a class that contains it. Just call the Method's invoke() method passing the object (you can pass null if you're invoking a static method), and the argument list packed as an array of Object. Assume you are given class X containing this method:

 
public void work(int i, String s) {
            System.out.printf("Called: i=%d, s=%s%n", i, s);
}

To find and invoke this method dynamically, given an instance of it called "x", all you need to do is:

 
            Class clX = x.getClass();
 
            // To find a method, need array of matching Class types.
            Class[] argTypes = { int.class, String.class };
 
            // Find a Method object for the given method.
            Method worker = clX.getMethod("work", argTypes);
 
            // To invoke the method, need the invocation
            // arguments, as an Object array.
            Object[] theData = { 42, "Chocolate Chips" };
 
            // The last step: invoke the method.
            worker.invoke(x, theData);

By itself this is a bit tedious to code, but it is background for the next few sections.

Wednesday, April 2, 2008

ASPECTJ - AOP

ASPECTJ – AOP

Some aspects of system implementation, such as logging, error handling, standards enforcement and feature variations are notoriously difficult to implement in a modular way. The result is that code is tangled across a system and leads to quality, productivity and maintenance problems. AspectJ is a seamless aspect-oriented extension to the Java programming language that enables clean modularization of these 'crosscutting concerns'. For the best AspectJ development experience, the AspectJ Development Tools (AJDT) project provides Eclipse platform based tool support for AOSD with AspectJ

WebWork

WebWork

 

WebWork is a Java-based web application framework developed by OpenSymphony. It was developed with the specific intention of improving developer productivity and code simplicity. WebWork is built on top of XWork, which provides a generic command pattern framework as well as an Inversion of Control container.

WebWork provides robust support for building reusable UI templates, such as form controls, UI themes, internationalization, dynamic form parameter mapping to JavaBeans, robust client and server side validation, etc.

 

 

WebWork has been designed and implemented with a specific set of goals, that are very important for users of it. They are as follows:

  1. Web Designer never has to touch Java code.
  2. Create multiple "Web Skins" for a application
  3. Change Look and Feel
  4. Change Layout on a given Web Page
  5. Change Flow among Web Pages
  6. Move *existing* data elements from one page to another
  7. Integrate with various backend infrastructures
  8. Reuse components
  9. Perform internationalization (i18n) of a web application
  10. Keep the API small and to the point
  11. Ability to learn WebWork fast, by making all the fancier features optional
  12. Allow the developer to choose how to implement as much as possible, while providing default implementations that work well in most cases [1]

El expressions not recoginzed ? see tips below

Check below 2 points:

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

 

1) web.xml should not have It should NOT have this

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

 

Rather it should have,

<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 

2) other way is <%@ page isELIgnored="false" %>

That will fix it for this page. Fixing the web.xml should fix it for all pages.

 

 

The Struts-to-Spring Migration-Steps and Logical Mapping

This article helps developers who want to migrate their Struts applications to Spring MVC understand the logical mapping between the two frameworks and how to transform Struts applications into Spring MVC applications. Application developers with good Struts skills also will learn how key Struts concepts relate to Spring MVC concepts. Finally, this article should help architects understand and estimate the migration paths from Struts to Spring. To fully appreciate the subjects discussed, readers should have a working knowledge of the Struts framework.

The article is divided into two main parts:

  1. Logical mapping between the basic concepts of the Struts and Spring MVC frameworks
  2. Essential recommendations for migration alternatives

 

 

 

Logical Mapping: Similar Yet Different Frameworks

Struts and Spring are fundamentally similar implementations of the Model View Controller (MVC) architectural pattern. They are both intended primarily for the Model 2 type of development (see Related Resources in the left column), which is based on the core J2EE components servlet and JSP. Developers familiar with Struts should make the conceptual transition from one framework to the other rather easily. Both frameworks have clearly delineated boundaries for the components that serve the roles of the View, Controller, and, in the case of Spring, Model.

Similarities stop at the implementation level. The Struts design is based on concrete inheritance, meaning that each custom action has to be in an inheritance hierarchy of the Struts Action component. Because Spring controllers are interfaces, any component can play the role of the controller. This gives application designers more flexibility in the design of components.

At the framework component level, Struts requires use of Struts-specific objects, such as Form Beans (static or dynamic), Actions, Action Mappings, Action Forwards, and Request Processors. Spring MVC is more flexible, as all its major components are defined as interfaces.

Struts Is a Web Framework Only

Struts addresses only the presentation aspects of application development. On the other hand, Spring MVC is an integral part of the Spring framework, which fully integrates Spring with the rest of the frameworks that manage business components as well as other aspects of Spring enterprise development.

Now let’s look at the frameworks’ components in more detail.

Struts Actions Are Roughly Spring Controllers

In Struts, Actions are core "processing" objects of the framework. They play the role of controllers in the MVC pattern. Spring's alternative to Struts Actions is the Controller interface. In other words, Controllers process user input and dispatch to view components in Spring. The most significant differences between the Struts Action and the Spring Controller are that Actions are abstract classes and Controllers are interfaces. In order to be configured as a Spring MVC controller, an object would need only to implement the following method:

 
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) 

  

  
       throws Exception;

This design (also known as "design by interface") minimizes the coupling between the application and the framework itself. Also, it gives the architect greater flexibility in the design of the Controllers. With this in mind, the simplest intermediary transition step from Struts to Spring is to rewrite Actions so they implement the Controller interfaces and reuse the existing code. This allows incremental removal of all the Struts dependencies while keeping the application operational.

Spring offers other Action alternatives as well. A number of framework-supplied Controller implementations match the most common Web application tasks. Some of the supplied Controllers match the more specialized Struts Actions with which you may be familiar. For instance, if you use DispatchActions, MultiActionControllers and the more elaborate AbstractWizardFormControllers will be helpful. About a dozen different Controller implementations come with Spring MVC, so it is well worth exploring their purposes and how they can replace your Struts mechanisms.

No Action Forms

One of the biggest and the most positive differences in the Spring framework is that it has no specialized ActionForm objects. The framework supports binding of HTTP form values directly into POJOs (Plain Old Java Objects). This feature greatly simplifies application maintenance by limiting the number of classes to create and maintain.

In this case, the migration would mean dropping form beans and using domain objects directly. However, this is not a mandatory step since you can still use Form Bean objects as a map between the form inputs and domain objects. In Spring MVC, special-purpose Controllers that extend the AbstractFormController implementation support form-backed beans. The custom subclasses of the AbstractFormController use these form-backed (Command) Beans as form objects. Again, no strict requirements define these beans. A Command object can be any subclass of the java.lang.Object.

ActionForwards vs. ModelAndView

In Struts ActionMapping, objects are pointers into presentation resources (Actions, JSPs, Tiles, HTML files, etc.). The closest component in Spring MVC to ActionMapping is the ModelAndView interface. Spring Controllers return implementations of the ModelAndView interface, which like a Controller can be custom implemented. Or, if appropriate, you can use the ModelAndView implementation supplied by Spring MVC.

As the name implies, ModelAndView objects have Model and View components. Model components contain the business object to be displayed via the View component. Depending on the scenario, ModelAndView implementations may not have any Model components included. They may simply forward into some form of an actual View component (JSP, XSLT, Tiles, HTML, XML, etc.). As with Controller implementations, I strongly recommend researching Spring MVC-supplied implementations of the Model and View interfaces and View Resolvers.

Custom JSP Tags

Spring MVC relies on the expressive power of the standard JSP tag libraries. Unlike Struts, Spring MVC does not supply separate tag libraries for HTML, logic, or bean processing. It offers only a small tag library (Spring) that enables binding of Command objects into Web forms. You should use standard template libraries (JSTL) for all other tasks.

Validation

If you use Commons Validator in Struts, you may be able to completely reuse it in Spring. Spring 1.2 does not officially support the Commons-based validation framework, but the "sandbox" version of Spring MVC supports the reuse of validation definitions written in Commons Validator markup (validator.xml and validation-rules.xml). In any case, do not throw away your XML files with validation declarations. They could be reusable in Spring.

 

 

 

Error and Validation Messages

More good news! Spring recognizes Struts message bundles in an identical format. In order to reuse your existing Message resources within Spring MVC, you just configure it as messageSource in the Spring MVC configuration file as follows:

 
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
       <property name="basename">
              <value>resources.ApplicationResources</value>
       </property>
</bean>       

Also, you would need to use it, like your Controllers, as a messageSource property in your Controller implementations. No other changes are required.

Dispatcher Servlet

Spring MVC has its own version of the Request Processor/Action Servlet. It is DispatcherServlet, which is mapped to a group of URL expressions. To understand the concept of the Dispatcher Servlet, look at how Controllers are configured in Spring MVC.

Configuration Files

As a Struts user, you are used to having at least one struts-config.xml file (or more if you are using modules) that holds all the forwards, action mappings, form definitions, and plug-in declarations. In Spring MVC, all the Web application-related controller declarations are configured as Spring Beans. One or more Dispatcher Controllers dispatch all requests for the Web resources to the appropriate Controllers. For instance, if you want to remap your ".do" application into a Spring MVC application, you register the following servlet mapping in the web.xml of your application (I am not actually recommending that you use .do as an extension. Leave “.do” as a Struts-only convention.):

 
<servlet>
       <servlet-name>applicationDispatcher</servlet-name>    
       <servlet-class>
              org.springframework.web.servlet.DispatcherServlet
       </servlet-class>
       <load-on-startup>1</load-on-startup>
</servlet>
 
        ...
 
<servlet-mapping>
       <servlet-name>applicationDispatcher</servlet-name>
       <url-pattern>*.do</url-pattern>
</servlet-mapping>   

Now you have a Spring configuration file (applicationDispatcher-servlet.xml) with your Spring MVC Controller declarations. Note the “-servlet.xml” suffix for the applicationDispatcher file. It is a Spring MVC convention that enables DispatcherServlet to auto-load Spring MVC mapping files.

Mapping Web actions to the appropriate controllers in Spring MVC is quite easy. It is done in the same "wiring" fashion as the rest of the Spring application. The following example shows how to forward URL expression /showCatalog.do into a Controller showCatalog:

 
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
       <property name="mappings">
              <props>
                    <prop key="/showCatalog.do">showCatalog</prop>
              </props>
       </property>
</bean>

The Controller showCatalog would be configured as another bean implemented by a class that implements Controller interfaces. In this example, showCatalog is nothing more than a simple forwarding controller that forwards URL requests to a ModelAndView component named catalog:

 
<bean id="showCatalog" name="showCatalog"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
       <property name="viewName" value="catalog"/>     
</bean>       

 

 

 

Transition Paths from Struts to Spring MVC

There are three approaches to migrating Struts applications to Spring MVC. Some architects will gradually migrate the applications; others will choose to completely abandon the Struts framework and perform a complete rewrite. The approaches are outlined below and ordered according to the migration’s completeness.

1. Spring Enabling of Struts Components

For those who want to migrate slowly, the first—and completely painless—step is to enable Struts Actions as Spring Beans. This is a simple process, and the Spring documentation details it well. It does not require any changes to the existing Struts code, but it enables Struts Controller components, Actions, to be treated as Spring Beans. In this process, Actions inherit the nature of the Spring Beans and, therefore, start looking a lot like Spring Controllers.

Slow and step-wise migration is possible with this process. Each Action could be replaced one at a time by the Spring Controllers without rewriting the application at once and interrupting the existing Web sequences.

2. Spring with Tiles

Another alternative, fully supported by the Spring framework, is to replace Struts Controllers and related components (Actions, Form Beans, etc.) with Spring MVC components while keeping Tiles as the pure “view” framework. Spring MVC does not have a specific alternative to Tiles, so architects may decide to keep their investments in Tiles and make them work through Spring MVC.

The one serious disadvantage of this approach is that you will effectively maintain two diverse Web frameworks in your Web application, which could result in a greater maintenance burden and training effort.

3. Complete Migration

Complete migration would mean total replacement of all the components of the Struts framework with Struts MVC. At the end of the process, no Struts-specific components would remain in the application.

 

12 BENEFITS of Spring MVC over Struts

1. Spring provides a very clean division between controllers, JavaBean models, and views.

2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.

3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.

5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

8. No ActionForms. Bind directly to domain objects

9. More testable code (validation has no dependency on Servlet API)

10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.

11. Spring has a well defined interface to business layer

12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)

java.util.Properties VS HashMap

java.util.Properties

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

 

Properties is a special case of Hashtable, holding only Strings as keys and values

The Properties can be saved to a stream or loaded from a stream

Each key and its corresponding value in the property list is a string.

 

Properties inherits from Hashtable- 
java.lang.Object
  extended byjava.util.Dictionary
      extended byjava.util.Hashtable
          extended byjava.util.Properties

 

 Object

setProperty(String key, String value)
          Calls the Hashtable method put.

 

 

 

 

HashMap:

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

 

Both entries are object not string and it has rich set of Collection Handling API

 

put(Object key, Object value)
          Associates the specified value with the specified key in this map.