Pages

Monday, August 3, 2009

Struts 2 Validation Annotation

This post will show how to use Annotation based validation in Struts 2. For this example I used the add transaction part of google's portfolio manager (noticed that they do not have validations over there). Struts 2 provides a number of validators for XML based validation rules. All of them have respective annotations defined and can be used in place of XML validation rules. In the example, we will use the @RequiredStringValidator, @RegexFieldValidator and also see how to parameterize messages when using annotations.

Follow these steps to implement the example ... There's more

1. Create a dynamic web project in Eclipse.
2. Copy the following jar files into the WEB-INF/lib directory, all these files are available with sturts download.
* struts2-core-2.0.11.1.jar
* xwork-2.0.4.jar
* freemarker-2.3.8.jar
* commons-logging-1.1.1.jar
* ognl-2.6.11.jar
3. Update your web deployment desciptor to include the sturts filter dispatcher.

WEB-INF/web.xml





4. Create the input JSP : transactions.jsp





Note: The method="noValidation" indicates to struts that on submission, the noValidation() method will be invoked on the AddTransactionAction class.

5. Create the output JSP : done.jsp





6. Create the Action class :AddTransactionAction.java

package actions;

import org.apache.struts2.interceptor.validation.SkipValidation;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import com.opensymphony.xwork2.validator.annotations.Validation;

@Validation
public class AddTransactionAction extends ActionSupport {

private String symbol;
private String type;
private String date;
private String numberOfShares;
private String price;
private String comission;
private String notes;


public String execute() throws Exception {
System.out.println("In Execute");

return SUCCESS;
}

@SkipValidation
public String noValidation() throws Exception {
System.out.println("In Novalidation");
return SUCCESS;
}


public String getSymbol() {
return symbol;
}

@RequiredStringValidator(type = ValidatorType.FIELD, message = "Symbol Required")
public void setSymbol(String symbol) {
this.symbol = symbol;
}


public String getType() {
return type;
}

@RequiredStringValidator(type = ValidatorType.FIELD, message = "Type Required")
public void setType(String type) {
this.type = type;
}


public String getDate() {
return date;
}

@RequiredStringValidator(type = ValidatorType.FIELD, message = "Date Required")
@RegexFieldValidator(type=ValidatorType.FIELD, message="",key="date.error.message", expression = "[0-9][0-9]/[0-9][0-9]/[1-9][0-9][0-9][0-9]")
public void setDate(String date) {
this.date = date;
}


public String getNumberOfShares() {
return numberOfShares;
}


@RequiredStringValidator(type = ValidatorType.FIELD, message = " Number of Shares Required")
public void setNumberOfShares(String numberOfShares) {
this.numberOfShares = numberOfShares;
}


public String getPrice() {
return price;
}

@RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
public void setPrice(String price) {
this.price = price;
}


public String getComission() {
return comission;
}

@RequiredStringValidator(type = ValidatorType.FIELD, message = "Comission Required")
public void setComission(String comission) {
this.comission = comission;
}


public String getNotes() {
return notes;
}


public void setNotes(String notes) {
this.notes = notes;
}
}



Note:
* The annotation @Validation is used to indicate that the current action might need validation. The validations on a method level can be skipped using the @SkipValidation annotation on the method.
* The method noValidations() uses the @SkipValidation annotation, you can see this when you click on "Submit without validation" in the JSP
* The @RequiredStringValidator annotation is used to indicate a Required Strint similar to the following xml rule

* On the date field, I used a @RegexFieldValidator annotation, so that the date field will be mandated to have a given format.
* Parameterized messages: You will notice that the message attribute of the @RegexFieldValidator is set to an empty string, while the key is set to a value. This is due to the fact that the message attribute is mandatory, and the key attribute is used to denote the message key from the properties files. The parameters can be retrieved in the properties files using the ${date} notation where the "date" variable is expected to available in the value stack.

7. Create a definition for the action in struts.xml





Note: The result with name "input" is because the validator returns the result to input when validation fails.
8. Create the properties file for messages

date.error.message=Date ${date} is not properly formatted.

package.properties

Note: In the properties file, ${date} is used to retrieve the "date" value from the value stack, this is the way Struts 2 supports parameterization.

9. Create the struts.properties file to set the theme to simple theme, so that you have more control how the UI components are laid out.

struts.ui.theme=simple

struts.properties

Thursday, July 23, 2009

Glassfish: Add Cluster Support

Start your domain
Command: asadmin start-domain domain1

You will see message:
Domain does not support application server clusters and other standalone instances.

Goto: http://localhost:4848/

Go to the Application Server tree node, on the right hand side, you will see the 'Add Cluster Support' button. Click on this button

The next page will show you the implication about this action. Click OK

You will see that the profile has been successfully upgraded and server restart is required

Now restart your server.

You will see message:
Domain supports application server clusters and other standalone instances.

Friday, July 10, 2009

JQuery

jQuery is a Open source JavaScript Library.

jQuery is easy to learn.

Fast, Easy to use, Easy-to-use AJAX (I love the $.ajaxSetup() function)
Nice Event handlers
CSS selectors


features:

* HTML element selections
* HTML element manipulation
* CSS manipulation
* HTML event functions
* JavaScript Effects and animations
* HTML DOM traversal and modification
* AJAX
* Utilities

Tuesday, May 5, 2009

Integrate Birt Report Engine To Your Application

Setup

1. Download Birt Runtime

2. Copy all the jars in the birt-runtime/ReportEngine/lib directory from the Report Engine download into your ApplicationRoot/WEB-INF/lib directory.

3. Create a directory named platform in your WEB-INF folder.

4. Copy the birt-runtime/Report Engine/plugins and birt-runtime/ReportEngine/configuration directories to the platform directory you just created.

5. Copy iText.jar to the platform/plugins/com.lowagie.itext/lib directory. If the directory does not exist, create it.

6. Copy servlet.jar into WEB-INF/lib

* BirtConfig.properties - Configuration properties for the Engine.Place it to /WEB-INF/classes folder
* BirtEngine.java - Class used to initialize the Report Engine.
* WebReport.java - The servlet that handles report generation on a GET command.
* Copy Database driver class to


BirtConfig.properties

logDirectory=c:/temp

logLevel=FINEST

BirtEngine.java

import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import javax.servlet.*;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;

public class BirtEngine {

private static IReportEngine birtEngine = null;

private static Properties configProps = new Properties();

private final static String configFile = "BirtConfig.properties";

public static synchronized void initBirtConfig() {

loadEngineProps();

}


public static synchronized IReportEngine getBirtEngine(ServletContext sc) {

if (birtEngine == null)
{

EngineConfig config = new EngineConfig();

if( configProps != null){

String logLevel = configProps.getProperty("logLevel");

Level level = Level.OFF;

if ("SEVERE".equalsIgnoreCase(logLevel))

{

level = Level.SEVERE;

} else if ("WARNING".equalsIgnoreCase(logLevel))

{

level = Level.WARNING;

} else if ("INFO".equalsIgnoreCase(logLevel))

{

level = Level.INFO;

} else if ("CONFIG".equalsIgnoreCase(logLevel))

{

level = Level.CONFIG;

} else if ("FINE".equalsIgnoreCase(logLevel))

{

level = Level.FINE;

} else if ("FINER".equalsIgnoreCase(logLevel))

{

level = Level.FINER;

} else if ("FINEST".equalsIgnoreCase(logLevel))

{

level = Level.FINEST;

} else if ("OFF".equalsIgnoreCase(logLevel))

{

level = Level.OFF;

}

config.setLogConfig(configProps.getProperty("logDirectory"), level);

}

config.setEngineHome("");

IPlatformContext context = new PlatformServletContext( sc );

config.setPlatformContext( context );

try

{

Platform.startup( config );

}

catch ( BirtException e )

{

e.printStackTrace( );

}


IReportEngineFactory factory = (IReportEngineFactory) Platform

.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );

birtEngine = factory.createReportEngine( config );

}

return birtEngine;

}

public static synchronized void destroyBirtEngine() {

if (birtEngine == null) {

return;

}

birtEngine.shutdown();

Platform.shutdown();

birtEngine = null;

}


public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}


private static void loadEngineProps() {

try {

//Config File must be in classpath

ClassLoader cl = Thread.currentThread ().getContextClassLoader();

InputStream in = null;

in = cl.getResourceAsStream (configFile);

configProps.load(in);

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

WebReport.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IReportEngine;


public class WebReport extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* Constructor of the object.

*/

private IReportEngine birtReportEngine = null;

protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );

public WebReport() {

super();

}


/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy();

BirtEngine.destroyBirtEngine();

}



/**

* The doGet method of the servlet.

*

*/

public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//get report name and launch the engine

resp.setContentType("text/html");

//resp.setContentType( "application/pdf" );

//resp.setHeader ("Content-Disposition","inline; filename=test.pdf");

String reportName = req.getParameter("ReportName");

ServletContext sc = req.getSession().getServletContext();

this.birtReportEngine = BirtEngine.getBirtEngine(sc);



//setup image directory

HTMLRenderContext renderContext = new HTMLRenderContext();

renderContext.setBaseImageURL(req.getContextPath()+"/images");

renderContext.setImageDirectory(sc.getRealPath("/images"));



logger.log( Level.FINE, "image directory " + sc.getRealPath("/images"));

System.out.println("stdout image directory " + sc.getRealPath("/images"));

HashMap contextMap = new HashMap();

contextMap.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext );

IReportRunnable design;

try

{

//Open report design

design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );

//create task to run and render report

IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );

task.setAppContext( contextMap );

//set output options

HTMLRenderOption options = new HTMLRenderOption();

options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);

//options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);

options.setOutputStream(resp.getOutputStream());

task.setRenderOption(options);

//run report

task.run();

task.close();

}catch (Exception e){
e.printStackTrace();
throw new ServletException( e );
}

}


/**

* The doPost method of the servlet.

*/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" ");
out.println(" ");
out.println(" Post does nothing");
out.println(" ");
out.println("");
out.flush();
out.close();

}



/**

* Initialization of the servlet.

*

* @throws ServletException if an error occure

*/

public void init() throws ServletException {

BirtEngine.initBirtConfig();

}

}

Friday, May 1, 2009

Frameworks Comparision



Ajax support


JSF: No Ajax support, use ICEfaces and Ajax4JSF

Stripes: No libraries, supports streaming results

Struts 2: Dojo built-in, plugins for GWT, JSON

Spring MVC: No libraries, use DWR

Tapestry: Dojo built-in in 4.1


Bookmarking and URLs
JSF does a POST for everything - URLs not even considered

Struts 2 has namespaces - makes it easy

Spring MVC allows full URL control

Tapestry still has somewhat ugly URLs


Validation

JSF has ugly default messages, but easiest to configure

Spring MVC allows you to use Commons Validator - a mature solution

Struts 2 uses OGNL for powerful expressions - clientside only works when specifying rules on Actions

Tapestry has very robust validation - good messages without need to customize

Stripes and Wicket do validation in Java - no client-side


Testability

Spring and Struts 2 allow easy testing with mocks (e.g. EasyMock, jMock, Spring Mocks)

JSF page classes can be easily tested and actually look a lot like Struts 2 actions

Struts 1 Vs Struts 2

Struts 1 Vs Struts 2

Action classes

Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.

An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.

Threading Model

Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.

Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

Servlet Dependency

Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked.

Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

Testability

A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1.

Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.

Harvesting Input

Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans.

Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects.

Expression Language

Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.

Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

Binding values into views

Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.

Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.

Type Conversion

Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance.

Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

Validation

Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects.

Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

Control Of Action Execution

Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle.

Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

Friday, April 24, 2009

JDBC using JNDI

public class dbConnection {

public void testConnection(){
String sql = "select * from emp"; // query

Connection con = null;
Statement stmt = null;
ResultSet rs = null;

InitialContext cxt = new InitialContext();
DataSource dataSource = (DataSource) cxt.lookup("jdbc/myEmpDB"); // "jdbc/myEmpDB"get JNDI JDBC connection
con = dataSource.getConnection();

// run sql objects
stmt = con.createStatement();
rs = stmt.executeQuery(sql);

while (rs.next()) {
System.out.println("Emp Name : "+rs.getString("employeeName")));
}
}
}

JDBC (Java Database Connectivity) with MySQL

public class dbConnection {

public void testConnection(){

String sql = "select * from emp"; // query
String conURL = "jdbc:mysql://localhost:3306/employeeDB"; // "employeeDB" is database name

Connection con = null;
Statement stmt = null;
ResultSet rs = null;

Class.forName("com.mysql.jdbc.Driver"); // create instance of mysql driver
con = DriverManager.getConnection(conURL);

stmt = con.createStatement();
rs = stmt.executeQuery(sql);

while (rs.next()) {
System.out.println("Emp Name : "+rs.getString("employeeName")));
}
}
}

Thursday, February 12, 2009

Jasper Report

  • Jasper Reports is an open-source Java reporting library.
  • 100% written in Java.
  • It compiles .jrxml (XML source) to .jasper (compiled) files, which in turn can be transformed into several output types including PDF, HTML, CSV, and XLS.
  • You can configure various data source: JDBC, EJB, POJO, Hibernate, XML.


Download Struts 2 Jasper Report Plugins

We need the following libraries: http://www.sourceforge.net/projects/jasperreports

  • jasperreports-version.jar
  • commons-*.jar
  • itext-version.jar
  • jdt-compiler.jar

Copy these libraries to your WEB-INF/lib directory

Code

Create Product JavaBean called Product.java

Create Action (MyJasperAction) which compiles and stream the datasource to jrxml which compiles and generate report.



public
class MyJasperAction extends ActionSupport {
 
    /** create List to use as our JasperReports dataSource. */
    private List myList;
 
    public String execute() throws Exception {
 
        Product p1 = new Product(new Long(1), "Sony Camera", "149.99");
        Product p2 = new Product(new Long(2), "Fuji Camera", "99.99");
 
        // Store product in our dataSource list (normally would come from database).
        myList = new ArrayList();
        myList.add(p1);
        myList.add(p2);
 
        // Normally we would provide a pre-compiled .jrxml file
        // or check to make sure we don't compile on every request.

try {

JasperCompileManager.compileReportToFile(

"myapp/reports/jasper_template.jrxml",

"myapp/reports/compiled_template.jasper");

} catch (Exception e) {

e.printStackTrace();

return ERROR;

}


        return SUCCESS;
    }
 
    public List getMyList() {
        return myList;
    }
}

Struts.xml

define the jasper result type manually in struts.xml


Monday, January 5, 2009

Jasper Reports Pagination

//IGNORE PAGINATION
// if (!format.equals(ReportFormat.PDF.toString()))
// parameters.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE); // IGNORE PAGINATION BEFORE JRFillManager.fillReport

//PAGINATION
//exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(0));
//JRVariable[] jrVariables jasperReport.getVariables();
// retrive PAGE_COUNT Variable for total page and perfor paging on that
Google
 

Java-Struts