Wednesday, January 28, 2009

Using the Validator with a Non-Struts Application


the Validator was originally designed for use with the Struts framework. However, because of its flexible design, there's no direct coupling to any Struts components, and you're free to use it in ordinary Java applications as well. There are, however, some steps that you'll have to take in order to make the Validator easier to digest.

You can utilize the same configuration files as in Web- based applications. This is another advantage of using the Validator framework. The Struts framework finds and loads these files based on the addition of the plug-in mentioned earlier. However, in non-Struts applications, the manner in which these configuration files are discovered and loaded must be done manually. This is typically done at application startup using the following method calls:

ValidatorResources resources = new ValidatorResources();

InputStream rules = ValidateExample.class.getResourceAsStream("validator-rules.xml");

ValidatorResourcesInitializer.initialize(resources, in);

InputStream forms = ValidateExample.class.getResourceAsStream("validation.xml");

ValidatorResourcesInitializer.initialize(resources, forms);

This snippet of code creates a new instance of a
ValidatorResources class and initializes it based on the two Validator configuration files. The ValidatorResources object can then be used throughout your application to validate the configured JavaBeans.

how to validate your beans using the Validator:

// Suppose we already had a CheckoutForm object created and populated
CheckoutForm form = new CheckoutForm();

// Create a validator with the checkoutForm
Validator validator = new Validator(resources, "checkoutForm");

// Tell the validator which bean to validate against.
validator.addResource(Validator.BEAN_KEY, form);

// Validate the checkoutForm object and store the validation results

ValidatorResults results = validator.validate();

you can see that the name of the JavaBean checkoutForm is being passed to the constructor of the Validator class. This is necessary so that the Validator instance knows which set of validation rules to use against the bean.

As you can see, using the Validator with non-Struts applications is a little less automatic, but still provides a more flexible solution. The other benefit is that it keeps the validation rules out of the source code and in external configuration files. This can save time when customization of your application is a vital aspect of your business.






Creating Your Own Validators in Struts

Even though the Validators provided by the framework cover many of the validation rules that Web applications require, there are special needs that will require you to create your own rules. Fortunately, the Validator framework is easily extensible and the effort to do so is minimal.

To create your own validator, just create a Java class that implements your special validation rule. For example, suppose you needed a rule to validate that a user was the legal drinking age; this might be necessary to purchase alcoholic beverages online. You could possibly use one of the existing validation rules, but it would be more obvious to create a rule to validate that the user meets the required drinking age. The Java class might look something like the one in Example:

import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.util.StrutsValidatorUtil;

public class NewValidator implements Serializable{

public static boolean validateDrinkingAge( Object bean,
ValidatorAction va,
Field field,
ActionErrors errors, HttpServletRequest request) {

String value = null;
if (isString(bean)) {
value = (String) bean;
} else {
value =
ValidatorUtil.getValueAsString(bean, field.getProperty());
}
String sMin = field.getVarValue("drinkingAge");

if (!GenericValidator.isBlankOrNull(value)) {
try {
int iValue = Integer.parseInt(value);
int drinkingAge = Integer.parseInt(sMin);

if ( iValue < drinkingAge ){
errors.add(field.getKey(),
StrutsValidatorUtil.getActionError(request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(),
StrutsValidatorUtil.getActionError(request, va, field));
return false;
}
}
return true;
}

private static boolean isString(Object o) {
if (o == null) {
return (true);
}
return (String.class.isInstance(o));
}


After you create the new Validator, you simply add it to
the list of existing Validators in the validation-rules.xml
file. Once that's done, you can use the new Validator just
like it was one of the "basic validators."



Tuesday, January 27, 2009

About Serialization

Serialization:
Serialization is the process of persisting the state of an object.
In Java serializing an object involves encoding its state in a structured way within a byte array. Once an object is serialized, the byte array can be manipulated in various ways; it can be written to a file, sent over a network or RMI, or persisted within a database as a BLOB.

The serialization process encodes enough information about the object type within the byte stream, allowing the original object to be easily recreated upon deserialization, at a later point in time.
Serialization and Deserialization is same as marshaling and unmarshaling in C/C++.

Where to keep serialized object:

Serialization is a highly versatile mechanism it should be addressed by storing the state in relational or object databases. It does not have transaction management and concurrency control. Nor does it provide any typical database features like indexed access, caching and a query language.

Serializing static variables:

Variables declared as static members are not considered part of the state of an object because they are shared by all instances of that class. Classes which need to preserve the value of static members during serialization should save and restore these values explicitly using private void readObject(ObjectInputStream) and private void writeObject(ObjectOutputStream).

Advantages and Disadvantages:

The advantages of serialization are:
It is easy to use and can be customized.
The serialized stream can be encrypted, authenticated and compressed, supporting the needs of secure Java computing.
Serialized classes can support coherent versioning and are flexible enough to allow gradual evolution of your application's object schema.
Serialization can also be used as a mechanism for exchanging objects between Java and C++ libraries, using third party vendor libraries within C++.
Many vital technologies that rely upon serialization, including RMI, JavaBeans and EJB.

Disadvantages:
It should ideally not be used with large-sized objects, as it offers significant overhead. Large objects also significantly increase the memory requirements of your application since the object input/output streams cache live references to all objects written to or read from the stream until the stream is closed or reset. Consequently, the garbage collection of these objects can be inordinately delayed.
Serializable interface does not offer fine-grained control over object access - although you can somewhat circumvent this issue by implementing the complex Externalizable interface, instead.
Since serialization does not offer any transaction control mechanisms, it is not suitable for use within applications needing concurrent access without making use of additional APIs.
Criteria for a class to be Serializable:
Have access to a no-argument constructor in its first non-serializable superclass
Identify non-serializable data members using the transient keyword or explicitly mark data members as serializable using the serialPersistentFields member.
My subclass implements Serializable but my superclass doesn't. Both subclass and superclass contain instance variables that need to be saved as part of the state of the subclass. Will serialization save the superclass fields for me?

When you serialize an object, the serialization mechanism works by chaining up the inheritance hierarchy, saving the sate of each Serializable superclass in turn. When serialization reaches the first non-serializable superclass, the serialization stops.

When deserializing, the state of this first non-serializable superclass is restored not from the stream, but by invoking that class' no-argument constructor. If the no-argument constructor is not adequate for your purposes, you must customize the serialization of your subclass with writeObject() and readObject() in order to write out and restore any information from the non-serializable superclass that you find necessary.

Externalizable instead of Serializable:

By implementing Externalizable yourself you can win performance at the cost of flexibility and extra code to maintain. If you implement Externalizable yourself you stream the data directly without the need for reflection which is used in the case of Serializable

Read and write serialized objects to and from a database:

If your RDBMS supports them, you can store serialized objects as BLOBs.
These are JDBC 2.0 features, but take a look at java.sql.Blob, ResultSet and PreparedStatement for more information.

Collections like Vector or a Hashtable:

Collections like Vector and Hashtable both implements Serializable and have been designed for serialization.
One thing to keep in mind is to watch out for is, that in order to serialize a collection like Vector or Hashtable, you must also be able to serialize all of the objects contained in these collections. Otherwise, the collection would not be able to be completely restored. Your program will throw a NotSerializableException unless all objects stored in the Vector or Hashtable are also serializable.

Other way to save the state of an object of a class which does not implement Serializable or Extenalizable

Write the value of each and every instance variable into the persistent storage. If there are 50 variables, you will have to store each of them individually. If some of the variables are object references, you will have to follow each reference and save the state of that object as well. You can do that, but it would be a proprietary solution and each class that wanted to read your object would also have to know all about your proprietary format.

Role of serialization in RMI:

RMI uses serialization as its basic and only mechanism for sending objects across a network.
If an object implements java.rmi.Remote, then the object's stub is serialized and sent to the client. If the object implements java.io.Serializable, then the object itself is serialized and sent.

Role of serialization in EJB:

A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You're invoking methods remotely from one JVM space 'A' on objects which are in JVM space 'B' -- possibly running on another machine on the network.
To make this happen, all arguments of each method call must have their current state plucked out of JVM 'A' memory, flattened into a byte stream which can be sent over a network connection, and then deserialized for reincarnation on the other end in JVM 'B' where the actual method call takes place.
If the method has a return value, it is serialized up for streaming back to JVM 'A.' Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.


Tuesday, January 20, 2009

The Meaning of Professional

The Meaning of "Professional"

So what does it mean to be a professional programmer? What does it mean to be a professional anything? Some definitions simply say to be a professional is "to make money from a skill," but true professionals also have a set of qualities often described as "professionalism." In my opinion, these qualities are: trustworthiness, teamwork, leadership, communication, constant updating of skills, an interest in minimizing risks and accountability. Each of these effect the professional programmer in certain ways.

Trustworthiness The concept of trustworthiness applies in several different ways for programmers. Can you be trusted with a job? To perform a task without someone checking up on you? Can you be trusted to ask for help when you need it?

If you're given clients' data or have signed a non-disclosure agreement, then you are being trusted to respect privacy. You are trusted to check license agreements on third party tools or libraries and to get licenses or permission as required. And like any professional you are trusted to simply do a good job.

Teamwork Will you genuinely cooperate with your team mates? Will you work to mutual advantage and not just your own? Can you trust your team to work with you? Can you do your share of the work and trust your team to do the rest? And can you accept your management (and sometimes even clients) as part of the team, everyone trying to get the same job done?

Leadership Showing leadership means both earning respect from others and knowing what to do with it. Recognize the skills of your team members, and make sure you can offer each person challenges and development without exceeding what they can cope with at a given time.

Leadership involves not always getting to do the "fun" parts of a project yourself (that scary "delegation" word). It also involves not asking anyone to do a task that you wouldn't be willing to do yourself. It's not just the managers and lead programmers who need to show leadership, it's any professional programmer. The best programmers to work with are the ones that know what's going on, not just their little tasks.

Communication Respecting the people you work with, and your clients, enough to really listen to them is a critical part of communication. Teamwork can't happen without good communication, nor can accountability.

Communication is critical for helping clients to produce usable specifications and feedback. Will you question whether the specs you are given really will serve the purpose that the client has in mind?

Communication skills help with making meetings timely and effective. A professional's communication is effective and to the point, whether in person, in email, on the phone or in written documents.

Documentation at first seems like a programmer-specific concern until you consider how many people require documentation in a serious project: other programmers need high level, API level and in-code documentation; managers need planning, progress, and bug documentation; lawyers need proof of what was done and when; and users need documentation on how to use the software.

Updating Skills Keeping your skills up to date involves staying aware of what's going on in your industry. What are the current ideas about methodologies like eXtreme Programming? What libraries and tools are out there that might support your project? What are the current refactoring tools? How about standards, file formats and protocols? Are you up to date with Unicode, XML, SQL, and all the other acronyms? Perhaps you're missing out on something if you're not. What platforms are your potential clients using? Should you be learning about cross platform development?

Basically you need to possess a genuine interest in your field, and to read broadly so you know what's out there and which areas to then read deeply about. You also need to accept that even (or should I say "especially") the very best programmers are still learning.

Minimizing Risks Familiarity with best practices, combined with a healthy dose of common sense, will take you a long way towards managing risks. Professional programmers keep track of known bugs or any other change they intend to make. Bugs are risks, and a simple database can prevent you having a product ship with bugs you'd simply forgotten.

Another risk that's often not properly considered is any and all changes to the source code. Source is your livelihood and any change can be a mistake. There's good software out there that will keep track of every revision of your source code and even help merge code that multiple people have changed.

Professional programmers are careful to do enough testing. A software company will generally have testers but the developers need to know how to get the most out of testers and also how to write their own unit and regression tests to make sure every change in behavior is noticed and checked by a human.

Keeping your code simple and well styled is another commonly overlooked way to manage risks. If anyone can look at the code and see right away what it does, you are far less likely to find bugs in it later, and you are less likely to have a junior programmer attempt to change something without understanding it first.

Another risk is the client changing their mind, or more often changing their specifications because they've realized it wasn't what they had in mind. Write your code to be modular and reusable and you won't have any trouble adapting it to changing needs.

Accountability Writing code for others is a responsibility. You need to make sure your software is reliable. You need to make sure you and the client truly understand the requirements and specifications. You need to have documentation of your work, all current and past bugs, your progress, any problems, signed-off milestones, and more. You are also required to know about some basic legal issues, like software licensing, the terms of your employment contract, and intellectual property law.


As you can see, there is a huge gap between "coding" and "professional programming." Most programming courses focus on the coding side of things, and the professional skills tend to be glossed over or not covered at all. I have found myself regularly teaching these skills to new co-workers, which highlighted the need for "professionalism skills training." Teaching my co-workers reminded me how much I enjoy teaching. I decided to teach more people by trying my hand at professional writing for a change.

These days I consider myself to be a professional programmer, though I am still discovering the depth and breadth of what exactly that means. Perhaps that ongoing exploration of programming and of professionalism is what makes this for me a career and not just a job.

Tuesday, January 13, 2009

Java 5 Features Esay to Development

Java 5 Features

java 5 has so many features these make development easy and faster.

1: Generics: In Java1.4 Collection work with Object class Type in this case you need to casting object from Collection Type object and this is unsafe. and 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.

How to Define Generics Type Collection in Java 5

List =new ArrayList();
Here ArrayList will contain only String Type object not any Other type.

2: Enhancement of Loop:
the enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. The enhanced for loop is the easiest of the new features to immediately incorporate in your code.

Suppose you have a collection of TechTip objects called RecentTips. You could use an enhanced for loop with the collection as follows:

Old forLoop:

public class OldForArray {
public static void main(String[] args){
int[] squares = {0,1,4,9,16,25};
for (int i=0; i< j =" 0;" squares =" {0,"> squares = new ArrayList();

private static void fillList() {
for (int i = 0; i < j="0;">To remove elements as you traverse collections
>To modify the current slot in an array or list
>To iterate over multiple collections or arrays

3: AutoBoxing: is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, double and Double, etc). The underlying code that is generated is the same, but autoboxing provides a sugar coating that avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types.

Int x = new Integer(2); no need of conversion.

4: Typesafe Enum: Enumerations are sets of closely related items. Enum type accept only
predefine type constant. enum is typesafe.
for example

public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is optional
}

Enum that overrides toString method.
A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found here
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.

@Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}

Enum with additional fields and custom constructor.
Enum constructors must be either private or package default, and
protected or public access modifier is not allowed. When custom
constructor is declared, all elements declaration must match that
constructor.public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}Enum that implements interfaces. Enum can implement any interfaces. All enum types implicitly implements java.io.Serializable, and java.lang.Comparable.public enum Color implements Runnable {
WHITE, BLACK, RED, YELLOW, BLUE;

public void run() {
System.out.println("name()=" + name() +
", toString()=" + toString());
}
}A sample test program to invoke this run() method:
for(Color c : Color.values()) {
c.run();
}Or,
for(Runnable r : Color.values()) {
r.run();
}

5:Varargs:

6: Static Import:

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.

6: Annotation: Java 5 introduces annotation types which can
be used to express metadata relating to program members in the
form of annotations. Annotations in Java 5
can be applied to package and type declarations (classes,
interfaces, enums, and annotations), constructors, methods,
fields, parameters, and variables. Annotations are specified in the
program source by using the @ symbol. For example,
the following piece of code uses the @Deprecated
annotation to indicate that the obsoleteMethod()
has been deprecated:
@Deprecated
public void obsoleteMethod() { ... }
Annotations may be marker annotations, single-valued annotations, or multi-valued annotations. Annotation types with no members or that provide default values for all members may be used simply as marker annotations, as in the deprecation example above. Single-value annotation types have a single member, and the annotation may be written in one of two equivalent forms:
@SuppressWarnings({"unchecked"})
public void someMethod() {...}
or
@SuppressWarnings(value={"unchecked"})
public void someMethod() {...}
Multi-value annotations must use the member-name=value syntax to specify annotation values. For example:
@Authenticated(role="supervisor",clearanceLevel=5)

public void someMethod() {...}












To Work with Eclipse TPTP follow the link:
http://www.eclipse.org/tptp/home/downloads/4.5.0/documents/quicktour/quick_tour.html

Monday, January 12, 2009

Object Clonning

Object Cloning: Java object is an Reference Type. there is no way to create a copy of an existing object's attribute in to new object.
when you create object like

String S=new String("Hello Friends");
and S1=S; in this case S1 is a new Object not copy of an existing Object.

There is a Special method called Clone() in Object Class which allow to create a copy to an existing object. for this purpose you need to implement Cloneable interface which is markup interface(no Method).
Java allow two kinds to Clonning:
1: Shallow Clonning: Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.

class CoffeeCup implements Cloneable {
private int innerCoffee;
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
// This should never happen
throw new InternalError(e.toString());
}

}

public void add(int amount) {
innerCoffee += amount;
}

public int releaseOneSip(int sipSize) {
int sip = sipSize;
if (innerCoffee < sipSize) {
sip = innerCoffee;
}
innerCoffee -= sip;
return sip;
}

public int spillEntireContents() {
int all = innerCoffee;
innerCoffee = 0;
return all;
}
}

class Example1 {
public static void main(String[] args) {

CoffeeCup original = new CoffeeCup();
original.add(75); // Original now contains 75 ml of coffee
CoffeeCup copy = (CoffeeCup) original.clone();
copy.releaseOneSip(25); // Copy now contains 50 ml of coffee

// Figure 15-1 shows the heap at this point in the program

int origAmount = original.spillEntireContents();
int copyAmount = copy.spillEntireContents();
System.out.println("Original has " + origAmount + " ml of coffee.");
System.out.println("Copy has " + copyAmount + " ml of coffee.");
}

}
2: Deep Clonning: Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
class CoffeeCup implements Cloneable {

private Coffee innerCoffee = new Coffee(0);

public Object clone() {
CoffeeCup copyCup = null;
try {
copyCup = (CoffeeCup) super.clone();
}
catch (CloneNotSupportedException e) {
// this should never happen
throw new InternalError(e.toString());
}
copyCup.innerCoffee = (Coffee) innerCoffee.clone();
return copyCup;
}

public void add(int amount) {
innerCoffee.add(amount);
}

public int releaseOneSip(int sipSize) {
return innerCoffee.remove(sipSize);
}

public int spillEntireContents() {
return innerCoffee.removeAll();
}
class Example3 {
public static void main(String[] args) {

CoffeeCup original = new CoffeeCup();
original.add(75); // original now contains 75 ml of coffee
CoffeeCup copy = (CoffeeCup) original.clone();
copy.releaseOneSip(25);
// Copy now contains 50 ml of coffee.
// Original still has 75 ml of coffee.

// Figure 15-3 shows the heap at this point in the program

int origAmount = original.spillEntireContents();
int copyAmount = copy.spillEntireContents();
System.out.println("Original has " + origAmount
+ " ml of coffee.");
System.out.println("Copy has " + copyAmount
+ " ml of coffee.");
}
}

}

When you invoke Clone() method it Should Either return
  1. return an Object reference to a copy of the object upon which it is invoked, or
  2. throw CloneNotSupportedException
How to Disallow Clonning of Object: do not implement Cloneable Interface

Drawbacks of Clonning: Object Clonning allow to programmer steeling an object