Thursday, November 29, 2012

ant build with junit my code


<project name="" default="" basedir=".">

<property file="environment.properties" prefix="env" />
<property file="build.properties" prefix="build" />
<property name="root" location="${basedir}/WebContent" />
<path id="classpath">
<fileset dir="${env.web-inf.lib.dir}" includes="*.jar"/>
<fileset dir="${env.build.lib.dir}" includes="*.jar"/>
<fileset dir="${env.web-inf.lib.dir}" includes="*.zip"/>
<pathelement path="${env.classes.dir}"/>
</path>

<target name="clean-war-directory">
<delete dir="${env.war.base.dir}"/>
</target>

<target name="create-war-directory" depends="clean-war-directory">
<mkdir dir="${env.war.web-inf.dir}"/>
<mkdir dir="${env.war.jsp.dir}"/>
<mkdir dir="${env.war.tag.dir}"/>
<mkdir dir="${env.war.classes.dir}"/>
<mkdir dir="${env.war.lib.dir}"/>
<mkdir dir="${env.war.conf.dir}"/>
<mkdir dir="${env.war.css.dir}"/>
<mkdir dir="${env.war.images.dir}"/>
<mkdir dir="${env.war.javascript.dir}"/>
<mkdir dir="${env.war.src.dir}"/>
<mkdir dir="${env.war.meta-inf.dir}"/>
<mkdir dir="${env.war.flows.dir}"/>
</target>

<target name="create-bin-directory">
<mkdir dir="${env.classes.dir}"/>
</target>

<target name="copy-war-files-into-directory" depends="">
<copy todir="${env.war.jsp.dir}" preservelastmodified="true" overwrite="true">
<fileset dir="${env.jsp.dir}" includes="**/*.jsp"/>
<fileset dir="${env.jsp.dir}" includes="**/*.inc"/>
</copy>
   <copy todir="${env.war.tag.dir}" preservelastmodified="true" overwrite="true">
<fileset dir="${env.tag.dir}" includes="**/*.tag"/>
</copy>
<copy todir="${env.war.images.dir}" overwrite="true">
<fileset dir="${env.images.dir}" includes="**/*"/>
</copy>
<copy todir="${env.war.css.dir}" overwrite="true">
<fileset dir="${env.css.dir}" includes="**/*.css"/>
</copy>
<copy todir="${env.war.javascript.dir}" overwrite="true">
<fileset dir="${env.javascript.dir}" includes="**/*"/>
</copy>
<copy todir="${env.war.web-inf.dir}" overwrite="true">
<fileset dir="${env.web-inf.dir}" includes="*.*"/>
</copy>
<copy todir="${env.war.meta-inf.dir}" overwrite="true">
<fileset dir="${env.meta-inf.dir}" includes="**/*"/>
</copy>
<copy todir="${env.war.lib.dir}" overwrite="true">
<fileset dir="${env.web-inf.lib.dir}" includes="**/*.class"/>
</copy>
<copy todir="${env.war.conf.dir}" overwrite="true">
<fileset dir="${env.conf.dir}" includes="**/*.xml"/>
</copy>
<copy todir="${env.war.flows.dir}" overwrite="true">
<fileset dir="${env.flows.dir}" includes="**/*"/>
   </copy>
<copy todir="${env.war.classes.dir}" overwrite="true">
<fileset dir="${env.classes.dir}" includes="**/*.class"/>
<fileset dir="${env.source.dir}" includes="**/*.properties"/>
</copy>
<copy todir="${env.war.src.dir}" overwrite="true">
<fileset dir="${env.source.dir}" includes="**/*.java"/>
</copy>
<copy todir="${env.war.lib.dir}">
<fileset dir="${env.web-inf.lib.dir}">
<include name="*.jar"/>
</fileset>
</copy>
<copy todir="${env.war.base.dir}" preservelastmodified="true" overwrite="true">
<fileset dir="${env.welcomefile.dir}" includes="*.jsp"/>
</copy>
</target>

<target name="compile" depends="create-war-directory,create-bin-directory">
    <javac source="1.6" destdir="${env.classes.dir}" classpathref="classpath" debug="true" optimize="false">
<src path="${env.source.dir}"/>
</javac>
  </target>
  <target name="create-manifest">
  <tstamp>
      <format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
  </tstamp>
  <manifest file="${root}/META-INF/MANIFEST.MF">
  <attribute name="App-Name" value="${env.app.name}"/>
  <attribute name="Built-Timestamp" value="${TODAY}"/>      
  <attribute name="Built-Date" value="${env.build.date}"/>
  <attribute name="Built-By" value="${env.user.name}"/>
  <attribute name="Implementation-Version" value="${env.build.version}"/>
     <attribute name="Issue-fixed" value="${env.issue.fixed}"/>
  </manifest>
  <echo message= "Manifest Updated" />
  </target>
<target name="create-war" depends="compile,create-manifest,copy-war-files-into-directory,test,delete-test-class">
<war basedir="${env.war.base.dir}" webxml="${env.web-inf.dir}/web.xml" destfile="${build.war.file}" manifest="${env.war.meta-inf.dir}/MANIFEST.MF">
<exclude name="WEB-INF/lib/servlet-api-2.3.jar"/>
<exclude name="WEB-INF/lib/jaxb-api-2.1.jar"/>
<exclude name="WEB-INF/lib/jaxb-impl-2.1.7.jar"/>
<exclude name="WEB-INF/lib/xercesImpl.jar"/>
</war>
</target>
<target name="create--war" depends="create-war">
<delete dir="${env.war.base.dir}"/>
<delete dir="${env.classes.dir}"/>
</target>

<property name="testdir" location="test" />
<property name="full-compile" value="true" />
<path id="classpath.test">
<fileset dir="${env.web-inf.lib.dir}" includes="*.jar"/>
<fileset dir="${env.build.lib.dir}" includes="*.jar"/>
  <pathelement location="${env.test.classes.dir}" />
  <pathelement location="${env.classes.dir}" />
 </path>
 <target name="clean-test" >
 <delete verbose="${full-compile}">
  <fileset dir="${testdir}" includes="**/*.class" />
 </delete>
 </target>
 <target name="compile-junit" depends="clean-test">
  <javac source="1.6" srcdir="${testdir}" destdir="${env.test.classes.dir}" >
  <classpath refid="classpath.test"/>
  </javac>
 </target>
 <target name="test" depends="compile-junit">
 <junit haltonfailure="yes" >
<classpath refid="classpath.test" />
<formatter type="brief" usefile="false" />
<batchtest>
<fileset dir="${testdir}">
<include name="**/*Test*.java"/>
</fileset>
</batchtest>
 </junit>
 </target>
<target name="delete-test-class">
 <delete verbose="${full-compile}">
 <fileset dir="${testdir}" includes="**/*.class" />
 </delete>
</target>


</project>

Friday, August 31, 2012

jquery mobile dialog transparent

http://tqcblog.com/2012/04/19/transparent-jquery-mobile-dialogs/


The basic approach to fixing the dialogs is:
  • Make the dialog overlay transparent
  • When opening a dialog, add the class ui-dialog-background to the previous page that prevents it from being hidden
  • remove the class when the dialog closes
For multi page sites you will also need to set the data-dom-cache attribute on the background page to prevent it being removed from the DOM while still visible.
.ui-dialog-background {
opacity: 0.5;
display: block !important;
-webkit-transition: opacity 0.5s ease-in;
}
.ui-dialog-background.pop.in {
opacity: 1;
-webkit-transition: opacity 0.5s ease-in;
}
.ui-dialog {
min-height: 100% !important;
background: transparent !important;
}
$(function() {
    $('div[data-role="dialog"]').live('pagebeforeshow', function(e, ui) {
ui.prevPage.addClass("ui-dialog-background ");
});
    $('div[data-role="dialog"]').live('pagehide', function(e, ui) {
$(".ui-dialog-background ").removeClass("ui-dialog-background ");
});
});

Saturday, August 4, 2012

jquery mobile properties and methods


PROPERTIES

PROPERTIES
version = 1.1.1
ns =
subPageUrlKey = ui-page
activePageClass = ui-page-active
activeBtnClass = ui-btn-active
focusClass = ui-focus
ajaxEnabled = true
hashListeningEnabled = true
linkBindingEnabled = true
defaultPageTransition = fade
maxTransitionWidth = false
minScrollBack = 250
touchOverflowEnabled = false
defaultDialogTransition = pop
loadingMessage = loading
pageLoadErrorMessage = Error Loading Page
loadingMessageTextVisible = false
loadingMessageTheme = a
pageLoadErrorMessageTheme = e
autoInitializePage = true
pushStateEnabled = true
ignoreContentEnabled = false
orientationChangeEnabled = true
buttonMarkup = [object Object]
keyCode = [object Object]
nsNormalizeDict = [object Object]
browser = [object Object]
ajaxBlacklist = false
transitionHandlers = [object Object]
transitionFallbacks = [object Object]
path = [object Object]
base = [object Object]
urlHistory = [object Object]
dialogHashKey = &ui-state=dialog
allowCrossDomainPages = false
navreadyDeferred = [object Object]
zoom = [object Object]
METHODS
silentScroll ()
nsNormalize ()
getInheritedTheme ()
closestPageData ()
enhanceable ()
hijackable ()
haveParents ()
getScreenHeight ()
widget ()
media ()
gradeA ()
page ()
defaultTransitionHandler ()
getMaxScrollForTransition ()
focusPage ()
getDocumentUrl ()
getDocumentBase ()
_bindPageRemove ()
loadPage ()
changePage ()
dialog ()
collapsible ()
collapsibleset ()
navbar ()
listview ()
checkboxradio ()
button ()
textinput ()
slider ()
selectmenu ()
fixedtoolbar ()
showPageLoadingMsg ()
hidePageLoadingMsg ()
initializePage ()
_handleHashChange () 

Sunday, February 19, 2012

Annotations

Many APIs require a fair amount of boilerplate code. For example, in order to write a JAX-RPC web service, you must provide a paired interface and implementation. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible.
Other APIs require “side files” to be maintained in parallel with programs. For example JavaBeans requires a BeanInfo class to be maintained in parallel with a bean, and Enterprise JavaBeans (EJB) requires a deployment descriptor. It would be more convenient and less error-prone if the information in these side files were maintained as annotations in the program itself.
The Java platform has always had various ad hoc annotation mechanisms. For example the transient modifier is an ad hoc annotation indicating that a field should be ignored by the serialization subsystem, and the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used. As of release 5.0, the platform has a general purpose annotation (also known as metadata) facility that permits you to define and use your own annotation types. The facility consists of a syntax for declaring annotation types, a syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations, and an annotation processing tool.
Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.
Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.
Typical application programmers will never have to define an annotation type, but it is not hard to do so. Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes theinterface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives,StringClassenums, annotations, and arrays of the preceding types. Methods can have default values. Here is an example annotation type declaration:
/**
 * Describes the Request-For-Enhancement(RFE) that led
 * to the presence of the annotated API element.
 */
public @interface RequestForEnhancement {
    int    id();
    String synopsis();
    String engineer() default "[unassigned]"; 
    String date();    default "[unimplemented]"; 
}
Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as publicstatic, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:
@RequestForEnhancement(
    id       = 2868724,
    synopsis = "Enable time-travel",
    engineer = "Mr. Peabody",
    date     = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
An annotation type with no elements is termed a marker annotation type, for example:
/**
 * Indicates that the specification of the annotated API element
 * is preliminary and subject to change.
 */
public @interface Preliminary { }
It is permissible to omit the parentheses in marker annotations, as shown below:
@Preliminary public class TimeTravel { ... }
In annotations with a single element, the element should be named value, as shown below:
/**
 * Associates a copyright notice with the annotated API element.
 */
public @interface Copyright {
    String value();
}
It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, as shown below:
@Copyright("2002 Yoyodyne Propulsion Systems")
public class OscillationOverthruster { ... }
To tie it all together, we'll build a simple annotation-based test framework. First we need a marker annotation type to indicate that a method is a test method, and should be run by the testing tool:
import java.lang.annotation.*;

/**
 * Indicates that the annotated method is a test method.
 * This annotation should be used only on parameterless static methods.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. The first (@Retention(RetentionPolicy.RUNTIME)) indicates that annotations with this type are to be retained by the VM so they can be read reflectively at run-time. The second (@Target(ElementType.METHOD)) indicates that this annotation type can be used to annotate only method declarations.
Here is a sample program, some of whose methods are annotated with the above interface:
public class Foo {
    @Test public static void m1() { }
    public static void m2() { }
    @Test public static void m3() {
        throw new RuntimeException("Boom");
    }
    public static void m4() { }
    @Test public static void m5() { }
    public static void m6() { }
    @Test public static void m7() {
        throw new RuntimeException("Crash");
    }
    public static void m8() { }
}
Here is the testing tool:
import java.lang.reflect.*;

public class RunTests {
   public static void main(String[] args) throws Exception {
      int passed = 0, failed = 0;
      for (Method m : Class.forName(args[0]).getMethods()) {
         if (m.isAnnotationPresent(Test.class)) {
            try {
               m.invoke(null);
               passed++;
            } catch (Throwable ex) {
               System.out.printf("Test %s failed: %s %n", m, ex.getCause());
               failed++;
            }
         }
      }
      System.out.printf("Passed: %d, Failed %d%n", passed, failed);
   }
}
The tool takes a class name as a command line argument and iterates over all the methods of the named class attempting to invoke each method that is annotated with the Test annotation type (defined above). The reflective query to find out if a method has a Test annotation is highlighted in green. If a test method invocation throws an exception, the test is deemed to have failed, and a failure report is printed. Finally, a summary is printed showing the number of tests that passed and failed. Here is how it looks when you run the testing tool on the Foo program (above):
$ java RunTests Foo
Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom 
Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash 
Passed: 2, Failed 2
While this testing tool is clearly a toy, it demonstrates the power of annotations and could easily be extended to overcome its limitations.

Static Import

In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:
double r = Math.cos(Math.PI * theta);
In order to get around this, people sometimes put static members into an interface and inherit from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it: the Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class's use of the static members of another class is a mere implementation detail. When a class implements an interface, it becomes part of the class's public API. Implementation details should not leak into public APIs.
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:
import static java.lang.Math.PI;
or en masse:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.
So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

Varargs

In past releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used theMessageFormat class to format a message:
Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
     + "{0,number,integer}.", arguments);
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, theMessageFormat.format method now has this declaration:
    public static String format(String pattern,
                                Object... arguments);
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position. Given the new varargs declaration for MessageFormat.format, the above invocation may be replaced by the following shorter and sweeter invocation:
String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
    + "{0,number,integer}.",
    7, new Date(), "a disturbance in the Force");
There is a strong synergy between autoboxing and varargs, which is illustrated in the following program using reflection:
// Simple test framework
public class Test {
    public static void main(String[] args) {
        int passed = 0;
        int failed = 0;
        for (String className : args) {
            try {
                Class c = Class.forName(className);
                c.getMethod("test").invoke(c.newInstance());
                passed++;
            } catch (Exception ex) {
                System.out.printf("%s failed: %s%n", className, ex);
                failed++;
            }
        }
        System.out.printf("passed=%d; failed=%d%n", passed, failed);
    }
}
This little program is a complete, if minimal, test framework. It takes a list of class names on the command line. For each class name, it instantiates the class using its parameterless constructor and invokes a parameterless method called test. If the instantiation or invocation throws an exception, the test is deemed to have failed. The program prints each failure, followed by a summary of the test results. The reflective instantiation and invocation no longer require explicit array creation, because the getMethod and invoke methods accept a variable argument list. The program also uses the new printf facility, which relies on varargs. The program reads much more naturally than it would without varargs.
So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printffacility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

Enums

In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;
This pattern has many problems, such as:
  • Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
  • No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
  • Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.
It is possible to get around these problems by using the Typesafe Enum pattern (see Effective Java Item 21), but this pattern has its own problems: It is quite verbose, hence error prone, and its enum constants cannot be used in switch statements.
In 5.0, the Java™ programming language gets linguistic support for enumerated types. In their simplest form, these enums look just like their C, C++, and C# counterparts:
enum Season { WINTER, SPRING, SUMMER, FALL }
But appearances can be deceiving. Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems mentioned above, it allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand arbitrary changes in the enum type.
Here is an example of a playing card class built atop a couple of simple enum types. The Card class is immutable, and only one instance of each Card is created, so it need not override equals or hashCode:
import java.util.*;

public class Card {
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
        SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    private final Rank rank;
    private final Suit suit;
    private Card(Rank rank, Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public String toString() { return rank + " of " + suit; }

    private static final List<Card> protoDeck = new ArrayList<Card>();

    // Initialize prototype deck
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                protoDeck.add(new Card(rank, suit));
    }

    public static ArrayList<Card> newDeck() {
        return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
    }
}
The toString method for Card takes advantage of the toString methods for Rank and Suit. Note that the Card class is short (about 25 lines of code). If the typesafe enums (Rank and Suit) had been built by hand, each of them would have been significantly longer than the entire Card class.
The (private) constructor of Card takes two parameters, a Rank and a Suit. If you accidentally invoke the constructor with the parameters reversed, the compiler will politely inform you of your error. Contrast this to the int enum pattern, in which the program would fail at run time.
Note that each enum type has a static values method that returns an array containing all of the values of the enum type in the order they are declared. This method is commonly used in combination with thefor-each loop to iterate over the values of an enumerated type.
The following example is a simple program called Deal that exercises Card. It reads two numbers from the command line, representing the number of hands to deal and the number of cards per hand. Then it creates a new deck of cards, shuffles it, and deals and prints the requested hands.
import java.util.*;

public class Deal {
    public static void main(String args[]) {
        int numHands = Integer.parseInt(args[0]);
        int cardsPerHand = Integer.parseInt(args[1]);
        List<Card> deck  = Card.newDeck();
        Collections.shuffle(deck);
        for (int i=0; i < numHands; i++)
            System.out.println(deal(deck, cardsPerHand));
    }

    public static ArrayList<Card> deal(List<Card> deck, int n) {
         int deckSize = deck.size();
         List<Card> handView = deck.subList(deckSize-n, deckSize);
         ArrayList<Card> hand = new ArrayList<Card>(handView);
         handView.clear();
         return hand;
     }
}

$ java Deal 4 5
[FOUR of HEARTS, NINE of DIAMONDS, QUEEN of SPADES, ACE of SPADES, NINE of SPADES]
[DEUCE of HEARTS, EIGHT of SPADES, JACK of DIAMONDS, TEN of CLUBS, SEVEN of SPADES]
[FIVE of HEARTS, FOUR of DIAMONDS, SIX of DIAMONDS, NINE of CLUBS, JACK of CLUBS]
[SEVEN of HEARTS, SIX of CLUBS, DEUCE of DIAMONDS, THREE of SPADES, EIGHT of CLUBS]
Suppose you want to add data and behavior to an enum. For example consider the planets of the solar system. Each planet knows its mass and radius, and can calculate its surface gravity and the weight of an object on the planet. Here is how it looks:
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}
The enum type Planet contains a constructor, and each enum constant is declared with parameters to be passed to the constructor when it is created.
Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):
    public static void main(String[] args) {
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
Your weight on PLUTO is 11.703031
The idea of adding behavior to enum constants can be taken one step further. You can give each enum constant a different behavior for some method. One way to do this by switching on the enumeration constant. Here is an example with an enum whose constants represent the four basic arithmetic operations, and whose eval method performs the operation:
public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    // Do arithmetic op represented by this constant
    double eval(double x, double y){
        switch(this) {
            case PLUS:   return x + y;
            case MINUS:  return x - y;
            case TIMES:  return x * y;
            case DIVIDE: return x / y;
        }
        throw new AssertionError("Unknown op: " + this);
    }
}
This works fine, but it will not compile without the throw statement, which is not terribly pretty. Worse, you must remember to add a new case to the switch statement each time you add a new constant toOperation. If you forget, the eval method with fail, executing the aforementioned throw statement
There is another way give each enum constant a different behavior for some method that avoids these problems. You can declare the method abstract in the enum type and override it with a concrete method in each constant. Such methods are known as constant-specific methods. Here is the previous example redone using this technique:
public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}
Here is a sample program that exercises the Operation class. It takes two operands from the command line, iterates over all the operations, and for each operation, performs the operation and prints the resulting equation:
    public static void main(String args[]) {
        double x = Double.parseDouble(args[0]);
        double y = Double.parseDouble(args[1]);
        for (Operation op : Operation.values())
            System.out.printf("%f %s %f = %f%n", x, op, y, op.eval(x, y));
    }

$ java Operation 4 2
4.000000 PLUS 2.000000 = 6.000000
4.000000 MINUS 2.000000 = 2.000000
4.000000 TIMES 2.000000 = 8.000000
4.000000 DIVIDE 2.000000 = 2.000000
Constant-specific methods are reasonably sophisticated, and many programmers will never need to use them, but it is nice to know that they are there if you need them.
Two classes have been added to java.util in support of enums: special-purpose Set and Map implementations called EnumSet and EnumMapEnumSet is a high-performance Set implementation for enums. All of the members of an enum set must be of the same enum type. Internally, it is represented by a bit-vector, typically a single long. Enum sets support iteration over ranges of enum types. For example given the following enum declaration:
    enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
you can iterate over the weekdays. The EnumSet class provides a static factory that makes it easy:
    for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY))
        System.out.println(d);
Enum sets also provide a rich, typesafe replacement for traditional bit flags:
    EnumSet.of(Style.BOLD, Style.ITALIC)
Similarly, EnumMap is a high-performance Map implementation for use with enum keys, internally implemented as an array. Enum maps combine the richness and safety of the Map interface with speed approaching that of an array. If you want to map an enum to a value, you should always use an EnumMap in preference to an array.
The Card class, above, contains a static factory that returns a deck, but there is no way to get an individual card from its rank and suit. Merely exposing the constructor would destroy the singleton property (that only a single instance of each card is allowed to exist). Here is how to write a static factory that preserves the singleton property, using a nested EnumMap:
private static Map<Suit, Map<Rank, Card>> table =
    new EnumMap<Suit, Map<Rank, Card>>(Suit.class);
static {
    for (Suit suit : Suit.values()) {
        Map<Rank, Card> suitTable = new EnumMap<Rank, Card>(Rank.class);
        for (Rank rank : Rank.values())
            suitTable.put(rank, new Card(rank, suit));
        table.put(suit, suitTable);
    }
}

public static Card valueOf(Rank rank, Suit suit) {
    return table.get(suit).get(rank);
}
The EnumMap (table) maps each suit to an EnumMap that maps each rank to a card. The lookup performed by the valueOf method is internally implemented as two array accesses, but the code is much clearer and safer. In order to preserve the singleton property, it is imperative that the constructor invocation in the prototype deck initialization in Card be replaced by a call to the new static factory:
    // Initialize prototype deck
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                protoDeck.add(Card.valueOf(rank, suit));
    }
It is also imperative that the initialization of table be placed above the initialization of protoDeck, as the latter depends on the former.
So when should you use enums? Any time you need a fixed set of constants. That includes natural enumerated types (like the planets, days of the week, and suits in a card deck) as well as other sets where you know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, and the like. It is not necessary that the set of constants in an enum type stay fixed for all time. The feature was specifically designed to allow for binary compatible evolution of enum types.

Autoboxing



As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValuemethod. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
The following example illustrates autoboxing and unboxing, along with generics and the for-each loop. In a mere ten lines of code, it computes and prints an alphabetized frequency table of the words appearing on the command line.
import java.util.*;

// Prints a frequency table of the words on the command line
public class Frequency {
   public static void main(String[] args) {
      Map<String, Integer> m = new TreeMap<String, Integer>();
      for (String word : args) {
          Integer freq = m.get(word);
          m.put(word, (freq == null ? 1 : freq + 1));
      }
      System.out.println(m);
   }
}

java Frequency if it is to be it is up to me to do the watusi
{be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}
The program first declares a map from String to Integer, associating the number of times a word occurs on the command line with the word. Then it iterates over each word on the command line. For each word, it looks up the word in the map. Then it puts a revised entry for the word into the map. The line that does this (highlighted in green) contains both autoboxing and unboxing. To compute the new value to associate with the word, first it looks at the current value (freq). If it is null, this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to the number of prior occurrences and puts that value into the map. But of course you cannot put an int into a map, nor can you add one to an Integer. What is really happening is this: In order to add 1 to freq, it is automatically unboxed, resulting in an expression of type int. Since both of the alternative expressions in the conditional expression are of type int, so too is the conditional expression itself. In order to put this int value into the map, it is automatically boxed into an Integer.
The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats. An Integer expression can have a null value. If your program tries to autounbox null, it will throw a NullPointerException. The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. Finally, there are performance costs associated with boxing and unboxing, even if it is done automatically.
Here is another sample program featuring autoboxing and unboxing. It is a static factory that takes an int array and returns a List of Integer backed by the array. In a mere ten lines of code this method provides the full richness of the List interface atop an int array. All changes to the list write through to the array and vice-versa. The lines that use autoboxing or unboxing are highlighted in green:
// List adapter for primitive int array
public static List<Integer> asList(final int[] a) {
    return new AbstractList<Integer>() {
        public Integer get(int i) { return a[i]; }
        // Throws NullPointerException if val == null
        public Integer set(int i, Integer val) {
            Integer oldVal = a[i];
            a[i] = val;
            return oldVal;
        }
        public int size() { return a.length; }
    };
}
The performance of the resulting list is likely to be poor, as it boxes or unboxes on every get or set operation. It is plenty fast enough for occasional use, but it would be folly to use it in a performance critical inner loop.
So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

The For-Each Loop

Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and cancels them:
void cancelAll(Collection<TimerTask> c) {
    for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
        i.next().cancel();
}
The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:
void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}
When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)
Here is a common mistake people make when they are trying to do nested iteration over two collections:
List suits = ...;
List ranks = ...;
List sortedDeck = new ArrayList();

// BROKEN - throws NoSuchElementException!
for (Iterator i = suits.iterator(); i.hasNext(); )
    for (Iterator j = ranks.iterator(); j.hasNext(); )
        sortedDeck.add(new Card(i.next(), j.next()));
Can you spot the bug? Don't feel bad if you can't. Many expert programmers have made this mistake at one time or another. The problem is that the next method is being called too many times on the “outer” collection (suits). It is being called in the inner loop for both the outer and inner collections, which is wrong. In order to fix it, you have to add a variable in the scope of the outer loop to hold the suit:
// Fixed, though a bit ugly
for (Iterator i = suits.iterator(); i.hasNext(); ) {
    Suit suit = (Suit) i.next();
    for (Iterator j = ranks.iterator(); j.hasNext(); )
        sortedDeck.add(new Card(suit, j.next()));
}
So what does all this have to do with the for-each construct? It is tailor-made for nested iteration! Feast your eyes:
for (Suit suit : suits)
    for (Rank rank : ranks)
        sortedDeck.add(new Card(suit, rank));
The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:
// Returns the sum of the elements of a
int sum(int[] a) {
    int result = 0;
    for (int i : a)
        result += i;
    return result;
}
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

Generics



When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.
Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.
Here is a simple example taken from the existing Collections tutorial:
// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); )
      if (((String) i.next()).length() == 4)
        i.remove();
}
Here is the same example modified to use generics:
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
    for (Iterator<String> i = c.iterator(); i.hasNext(); )
      if (i.next().length() == 4)
        i.remove();
}
When you see the code <Type>, read it as “of Type”; the declaration above reads as “Collection of String c.” The code using generics is clearer and safer. We have eliminated an unsafe cast and a number of extra parentheses. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness.
To paraphrase Generics Specification Lead Gilad Bracha, when we declare c to be of type Collection<String>, this tells us something about the variable c that holds true wherever and whenever it is used, and the compiler guarantees it (assuming the program compiles without warnings). A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks whether the programmer is right only at run time.
While the primary use of generics is collections, there are many other uses. “Holder classes,” such as WeakReference and ThreadLocal, have all been generified, that is, they have been retrofitted to make use of generics. More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:
<T extends Annotation> T getAnnotation(Class<T> annotationType); 
This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:
Author a = Othello.class.getAnnotation(Author.class);
Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation.
Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code. There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.
The java.util.Collections class has been outfitted with wrapper classes that provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers. These “checked collection wrappers” are very useful for debugging. Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:
Set<String> s = new HashSet<String>();
with this declaration:
Set<String> s = Collections.checkedSet(new HashSet<String>(), String.class);
the collection will throw a ClassCastException at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem.
You should use generics everywhere you can. The extra effort in generifying code is well worth the gains in clarity and type safety. It is straightforward to use a generic library, but it requires some expertise to write a generic library, or to generify an existing library. There is one caveat: You may not use generics (or any other Tiger features) if you intend to deploy the compiled code on a pre-5.0 virtual machine.
If you are familiar with C++'s template mechanism, you might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit “template metaprogramming.”
There is much more to learn about generics. See the Generics Tutorial.

Monday, January 9, 2012


Developing a Spring Framework MVC application step-by-step using NetBeans and GlassFish

Authors







Overview


1. What's covered


2. Prerequisite software


3. The application we are building


1. Basic Application and Environment Setup


1.1. Create the NetBeans Spring project


1.2. Create 'index.jsp'


1.3. Deploy the application to GlassFish


1.4. Check the application works


1.5. Download the Spring Framework


1.6. Modify 'web.xml' in the 'WEB-INF' directory


1.7. Copy libraries to 'WEB-INF/lib'


1.8. Create the Controller


1.9. Write a test for the Controller


1.10. Create the View


1.11. Compile and deploy the application


1.12. Try out the application


1.13. Summary


2. Developing and Configuring the Views and the Controller


2.1. Configure JSTL and add JSP header file


2.2. Improve the controller


2.3. Decouple the view from the controller


2.4. Summary


3. Developing the Business Logic


3.1. Review the business case of the Inventory Management System


3.2. Add some classes for business logic


3.3. Summary


4. Developing the Web Interface


4.1. Add reference to business logic in the controller


4.2. Modify the view to display business data and add support for message bundle


4.3. Add some test data to automatically populate some business objects


4.4. Add the message bundle


4.5. Adding a form


4.6. Adding a form controller


4.7. Summary


5. Implementing Database Persistence


5.1. Create database startup script


5.2. Create table and test data scripts


5.3. Run scripts and load test data


5.4. Create a Data Access Object (DAO) implementation for JDBC


5.5. Implement tests for JDBC DAO implementation


5.6. Summary


6. Integrating the Web Application with the Persistence Layer


6.1. Modify service layer


6.2. Fix the failing tests


6.3. Create new application context for service layer configuration


6.4. Add transaction and connection pool configuration to application context


6.5. Final test of the complete application


6.6. Summary


A. Build Scripts

 

Overview

This document is a step-by-step guide on how to develop a web application from scratch using the Spring Framework.
Only a cursory knowledge of Spring itself is assumed, and as such this tutorial is ideal if you are learning or investigating Spring. Hopefully by the time you have worked your way through the tutorial material you will see how the constituent parts of the Spring Framework, namely Inversion of Control (IoC), Aspect-Oriented Programming (AOP), and the various Spring service libraries (such as the JDBC library) all fit together in the context of a Spring MVC web application.
Spring provides several options for configuring your application. The most popular one is using XML files. This is also the traditional way that has been supported from the first release of Spring. With the introduction of Annotations in Java 5, we now have an alternate way of configuring our Spring applications. The new Spring 2.5 release introduces extensive support for using Annotations to configure a web application.
This document uses the traditional XML style for configuration. We are working on an "Annotation Edition" of this document and hope to publish it in the near future.
Please note that we are not going to cover any background information or theory in this tutorial; there are plenty of books available that cover the areas in depth; whenever a new class or feature is used in the tutorial, forward pointers to the relevant section(s) of the Spring reference documentation are provided where the class or feature is covered in depth. 

1. What's covered

The following list details all of the various parts of the Spring Framework that are covered over the course of the tutorial.
·         Inversion of Control (IoC)
·         The Spring Web MVC framework
·         Data access with JDBC
·         Unit and integration testing
·         Transaction management 

2. Prerequisite software

The following prerequisite software and environment setup is assumed. You should also be reasonably comfortable using the following technologies.
·     Java SDK 1.5/1.6
·     Ant 1.7
·     Spring Netbeans Module Release 1.1
·     GlassFish V2 UR1
·     NetBeans 6.0
NetBeans IDE 6.0 Full Pack (http://www.netbeans.org) provides an excellent environment for web application development. The Ant build scripts are omitted from this discussion as they are automatically generated by the IDE. The Spring plugin module for NetBeans should be installed prior to start of this project,
You may of course use pretty much any variation or version of the above software. If you want to use IntelliJ instead of NetBeans or Jetty instead of GlassFish, then many of the tutorial steps will not translate directly to your environment but you should be able to follow along anyway. 

3. The application we are building

The application we will be building from scratch over the course of this tutorial is a very basic inventory management system. This inventory management system is severely constrained in terms of scope; find below a use case diagram illustrating the simple use cases that we will be implementing. The reason why the application is so constrained is so that you can concentrate on the specifics of Spring Web MVC and Spring, and not the finer details of inventory management.


Use case diagram of the inventory management system
We will start by setting up the basic project directory structure for our application, downloading the required libraries, setting up our Ant build scripts, etc. The first step gives us a solid foundation on which to develop the application proper in parts 23, and 4.
Once the basic setup is out of the way, Spring itself will be introduced, starting with the Spring Web MVC framework. We will use Spring Web MVC to display the inventoried stock, which will involve writing some simple Java classes and some JSPs. We will then move onto introducing persistent data access into our application, using Spring's Simple JDBC support.
By the time we have finished all of the steps in the tutorial, we will have an application that does basic inventory management, including listing stock and permitting the price increase of such stock.