Friday, April 11, 2008

Struts 2 Custom Validators

Struts 2 allows the use of Custom validators through the @CustomValidator annotation. The @CustomValidator annotation takes two mandatory parameters, type and message
  • type: Refers to the "name" given to the validator in the validators.xml file.
  • message: Message to be displayed when this validator fails.
A custom validator can be implemented by extending the FieldValidatorSupport, or alternatively the ValidatorSupport classes. The following sample builds on the example built in the previous post, Struts 2 Validaton: Annotations.

To run this sample, follow these steps... There's More

  1. Create a simple struts project as described in the previous example, Struts 2 Validation : Annotations
  2. Create the new validator by extending the FieldValidatorSupport class
    package validators;

    import com.opensymphony.xwork2.validator.ValidationException;
    import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

    public class NumberFieldValidator extends FieldValidatorSupport {

    public void validate(Object object) throws ValidationException {
    String fieldName = getFieldName();
    Object value = this.getFieldValue(fieldName, object);

    if (!(value instanceof String)) {
    return;
    }

    String str = ((String) value).trim();
    if (str.length() == 0) {
    return;
    }

    try {
    Double.parseDouble(str);
    }catch(NumberFormatException nfe) {
    addFieldError(fieldName, object);
    return;
    }
    try {
    Integer.parseInt(str);
    }catch(NumberFormatException nfe) {
    addFieldError(fieldName, object);
    return;
    }

    }
    }
    NumberFieldValidator.java
    • The custom validator may extend the FieldValidatorSupport or the ValidatorSupport classes.
    • The FieldValidatorSupport class extends ValidatorSupport to add field specific information to the Field.
    • The is numeric check is performed by trying to convert the input string to Integer or Double and catching any exception.
    • The addFieldError method is used add any failed validations to the list of errors to be displayed.
    • The getFieldName and getFieldValue methods are implemented in the superclasses to retrieve the field name and field value for the field beign validated.
  3. Declare the new custom validator in the validators.xml file. The validators.xml file must be in the classpath of the application.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator Config 1.0//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
    <validators>
    <validator name="numericField" class="validators.NumberFieldValidator"/>
    </validators>
    validators.xml

    Note: The name attribute of the validator must match the type attribute of the @CustomValidator Annotation used in the Action class.
  4. Add the additional check to the Action class setPrice() method.
     @RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
    @CustomValidator(type = "numericField", message = "Price must be a number")
    public void setPrice(String price) {
    this.price = price;
    }
    AddTransactionAction.java

    Note: the type attribute of the @CustomValidator Annotation must match the name of the validator as defined in the validators.xml file.

Struts 2 Validation : Annotations

In a previous post, I described how to use validations in Struts 2, using XML validation rules. 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.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>struts2Validation</display-name>
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
    </filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    WEB-INF/web.xml
  4. Create the input JSP
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Add Transaction</title>
    </head>
    <body>
    <s:form action="addTransaction" validate="true" method="post">
    <s:fielderror />
    <table>
    <tr>
    <td>Symbol</td>
    <td><s:textfield name="symbol"></s:textfield></td>
    </tr>
    <tr>
    <td>Type</td>
    <td><s:select name="type" list="#{'':'Select One', 'BUY':'Buy','SELL':'Sell','BUY_COVER':'Buy to Cover','SELL_SHORT':'Sell Short'}">
    </s:select></td>
    </tr>
    <tr>
    <td>Date</td>
    <td><s:textfield name="date" ></s:textfield></td>
    </tr>
    <tr>
    <td>Number of Shares</td>
    <td><s:textfield name="numberOfShares"></s:textfield></td>
    </tr>
    <tr>
    <td>Price</td>
    <td><s:textfield name="price"></s:textfield></td>
    </tr>
    <tr>
    <td>Commission</td>
    <td><s:textfield name="comission"></s:textfield></td>
    </tr>
    <tr>
    <td>Notes</td>
    <td><s:textfield name="notes"></s:textfield></td>
    </tr>
    <tr>
    <td colspan="2"> <s:submit name="submit" value="submit"></s:submit>
    <s:submit name="submitNoValidate" value="submit without validation" method="noValidation"></s:submit> </td>

    </tr>
    </table>
    </s:form>
    </body>
    </html>
    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
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Transaction Added</title>
    </head>
    <body>
    <s:bean name="actions.AddTransactionAction" id="addTransaction" ></s:bean>
    <table>
    <tr>
    <td colspan="2">The following transaction has been added to your portfolio</td>
    </tr>
    <tr>
    <td>Symbol</td>
    <td><s:label name="symbol" value="%{symbol}" /></td>
    </tr>
    <tr>
    <td>Type</td>
    <td><s:label name="type" value="%{type}" />
    </td>
    </tr>
    <tr>
    <td>Date</td>
    <td><s:label name="date" value="%{date}"/></td>
    </tr>
    <tr>
    <td>Number of Shares</td>
    <td><s:label name="numberOfShares" value="%{numberOfShares}"></s:label></td>
    </tr>
    <tr>
    <td>Price</td>
    <td><s:label name="price" value="%{price}"></s:label></td>
    </tr>
    <tr>
    <td>Commission</td>
    <td><s:label name="comission" value="%{comission}"></s:label></td>
    </tr>
    <tr>
    <td>Notes</td>
    <td><s:label name="notes" value="%{notes}"></s:label></td>
    </tr>
    </table>
    </body>
    </html>
    done.jsp
  6. Create the Action class
    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;
    }
    }
    AddTransactionAction.java

    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
      <validators>
      <field name="numberOfShares">
      <field-validator type="requiredstring">
      <message>Number of Share is required</message>
      </field-validator>
      </field>
      </validators>
    • 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
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

    <struts>
    <package name="struts2Validation" extends="struts-default">
    <action name="addTransaction"
    class="actions.AddTransactionAction">
    <result name="success">done.jsp</result>
    <result name="input">transactions.jsp</result>
    </action>
    </package>
    </struts>
    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

Tuesday, April 01, 2008

Integrating Struts 2.0 and tiles

I am currently evaluating some web frameworks for a pet project and was trying to implement Struts 2 with tiles. Neither the Sturts 2 website, nor the tiles website gave an easy way to integrated Struts 2 and tiles. It took me a while to get them to work together. This post describes a way I figured out how to integrate Struts 2 with tiles. Struts 2 provides a plugin for integrating tiles 2. This plugin is included in the complete bundle (struts-2.x.x.x-all.zip). The following are are the steps needed to integrate struts2 with tiles.
Skip to Sample Code
  1. Download the struts complete bundle from the struts 2 website
  2. Download tiles 2 from tiles 2 website
  3. Download the tiles dependencies from the jakarta commons site
    • Commons BeanUtils 1.7.0 or above
    • Commons Digester 1.8 or above
    • Commons Logging 1.1 or above
  4. Create the layout page, and related files (except the layout, all the other files are basic jsps )
    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <table width="100%" height="100%">
    <tr height="20%">
    <td colspan="2" align="center" bgcolor="skyblue">
    <tiles:insertAttribute name="header" /></td>
    </tr>
    <tr>
    <td bgcolor="cyan" width="75%"><tiles:insertAttribute name="body" /></td>
    </tr>
    <tr height="20%">
    <td colspan="2" align="center" bgcolor="skyblue"><tiles:insertAttribute name="footer" /></td>
    </tr>
    </table>
    </body>
    </html>
  5. Create the HelloWorld Action class
    package example;

    import com.opensymphony.xwork2.ActionSupport;

    public class HelloWorld extends ActionSupport {

    public String execute() throws Exception {
    System.out.println("Hello World");
    return SUCCESS;
    }
    }
  6. Configure the Web Deployment descriptor by adding a tiles listener to the web.xml file of your web application.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>tilesTest</display-name>
    <listener>
    <listener-class>
    org.apache.struts2.tiles.StrutsTilesListener
    </listener-class>
    </listener>
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
    </filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
  7. Configure struts to work with tiles, this can be done by either
    1. Extending the sturts package from "tiles-default"
      <package name="tilesTest" extends="tiles-default">
    2. OR
    3. Declaring a new "result-type", tiles, that will map to "org.apache.struts2.views.tiles.TilesResult"
      <result-types>
      <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
      </result-types>
  8. Set the type of the results in the package to "tiles"
    <result name="success" type="tiles">helloworld.home</result>

    struts.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

    <struts>
    <package name="tilesTest" extends="struts-default">
    <result-types>
    <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>
    <action name="helloWorld" class="example.HelloWorld">
    <result name="success" type="tiles">helloworld.home</result>
    </action>
    </package>
    </struts>
    Note that the result "helloword.home" must match the definition name in tiles.xml file.

  9. Create definitions for tiles in WEB-INF/tiles.xml file.
    <!DOCTYPE tiles-definitions PUBLIC
    "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
    "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
    <tiles-definitions>
    <definition name="helloworld.home" template="/layouts/layout.jsp">
    <put-attribute name="header" value="/layouts/header.jsp" />
    <put-attribute name="body" value="/index.html" />
    <put-attribute name="footer" value="/layouts/footer.jsp" />
    </definition>
    </tiles-definitions>
  10. The following is a list of jar files used for this example (copied to the WEB-INF/lib directory)
    • commons-beanutils.jar
    • commons-digester-1.8.jar
    • commons-logging-1.1.1.jar
    • freemarker-2.3.8.jar
    • ognl-2.6.11.jar
    • struts2-core-2.0.11.1.jar
    • struts2-tiles-plugin-2.0.11.1.jar
    • tiles-api-2.0.5.jar
    • tiles-core-2.0.5.jar
    • tiles-jsp-2.0.5.jar
    • xwork-2.0.4.jar
  11. This example was implemented on tomcat 6.0.16, with Java 5 update 11

Friday, March 28, 2008

BlazeDS for Java-Flex communication

BlazeDS is a server-based Java remoting and web messaging technology that enables communication between back-end Java applications and Adobe Flex applications running in the browser. In this post, I describe a way (may not be the best) I was able to successfully to build a simple application using BlazeDS and Flex. The application is build using eclipse and ant, rather than using FlexBuilder. Following are the main steps that you have to follow to implement the example.
  1. Install tomcat
  2. Install Flex sdk
  3. Download BlazeDS web application.
  4. Create tomcat user with manager permisison
  5. Create dynamic web project in eclipse
  6. Create java file
  7. Create mxml file
  8. Update the config files in the WEB-INF/flex directory of the web application
  9. Copy flexTasks.tasks to the root directory.
  10. Create build file
  11. Copy catalina-ant.jar and flextasks.jar into ant lib directory, add them to ant runtime in eclipse.
  12. Build application using ant
Skip to Sample Code: Moving the mouse over the bolded code parts shows additional information
  1. Install tomcat: This example was implemented on Tomcat 6.0.16
  2. Install Flex sdk: You can download the flex sdk from here The example was implemented on Flex 3.0.0
  3. Download BlazeDS:Download the BlazeDS web application from here
  4. Create tomcat user with manager permisison: In the TOMCAT_HOME/tomcat-users.xml, add the following line
    <role rolename="manager"/>
    <user username="abhi" password="abhi" roles="manager"/>
  5. Create dynamic web project in eclipse by importing the BlazeDS Web application war file.
  6. Create java fileThe java class simply echoes the data input in the textbox shown in the browser.
    package hello;
    public class HelloWorld {

    public String sayHelloTo(String str) {
    System.out.println("Hello " + str);
    return "Hello " + str;
    }
    }
  7. Create mxml fileThe mxml file simply shows a text box and a submit button. A label will be displayed below the textbox with the word "Hello" appended to the input text.
    <?xml version="1.0" encoding="utf-8"?> 
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" viewSourceURL="srcview/index.html">
    <mx:Script>
    <![CDATA[

    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;


    [Bindable]
    private var helloResult:String;
    private function sayHelloTo():void {
    ro.sayHelloTo(inputText.text);
    }
    private function resultHandler(event:ResultEvent):void
    {

    helloResult = event.result as String;
    }

    ]]>
    </mx:Script>
    <mx:RemoteObject id="ro" destination="helloworld" result="resultHandler(event)" />
    <mx:HBox width="100%">
    <mx:TextInput id="inputText"/>
    <mx:Button label="Submit" click="sayHelloTo()"/>
    </mx:HBox>
    <mx:Label text="{helloResult}"/>
    </mx:Application>
    Note: Defining the remote object enables you to make calls to the remote Java classes as if they are local action script classes.
  8. Update the configuration files For this example, you only have to update one config file, WEB-INF/flex/remoting-config.xml, to add a new destination, the HelloWorld class.
    <?xml version="1.0" encoding="UTF-8"?>
    <service id="remoting-service"
    class="flex.messaging.services.RemotingService">

    <adapters>
    <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
    </adapters>

    <default-channels>
    <channel ref="my-amf"/>
    </default-channels>

    <destination id="helloworld">
    <properties>
    <source>hello.HelloWorld</source>
    </properties>
    </destination>



    </service>
  9. Copy flexTasks.tasks to the root directory.
  10. Create build fileThe ant build file uses two flex specific tasks, mxmlc to compile the mxml file and html-wrapper to create a html wrapper that contains the created swf file.
    <project name="helloWorldServer" default="build" basedir=".">

    <!-- ===================== Property Definitions =========================== -->

    <property file="build.properties" />
    <property file="${user.home}/build.properties" />


    <!-- ==================== File and Directory Names ======================== -->

    <property name="app.name" value="helloWorldServer" />
    <property name="app.path" value="/${app.name}" />
    <property name="app.version" value="0.1-dev" />
    <property name="build.home" value="${basedir}/build" />
    <property name="catalina.home" value="C:/unzipped/apache-tomcat-6.0.16" />
    <property name="dist.home" value="${basedir}/dist" />
    <property name="docs.home" value="${basedir}/docs" />
    <property name="manager.url" value="http://localhost:8080/manager" />
    <property name="src.home" value="${basedir}/src" />
    <property name="web.home" value="${basedir}/WebContent" />
    <property name="manager.username" value="abhi" />
    <property name="manager.password" value="abhi" />
    <property name="FLEX_HOME" value="C:/Adobe/Flex" />
    <property name="APP_ROOT" value="${basedir}/WebContent" />



    <!-- ==================== External Dependencies =========================== -->

    <!-- ==================== Compilation Classpath =========================== -->

    <path id="compile.classpath">
    <fileset dir="${catalina.home}/bin">
    <include name="*.jar" />
    </fileset>
    <pathelement location="${catalina.home}/lib" />
    <fileset dir="${catalina.home}/lib">
    <include name="*.jar" />
    </fileset>

    </path>

    <!-- ================== Custom Ant Task Definitions ======================= -->


    <taskdef resource="org/apache/catalina/ant/catalina.tasks" classpathref="compile.classpath" />
    <taskdef resource="flexTasks.tasks" classpath="c:/ant/lib/flexTasks.jar" />

    <!-- ==================== Compilation Control Options ==================== -->

    <property name="compile.debug" value="true" />
    <property name="compile.deprecation" value="false" />
    <property name="compile.optimize" value="true" />



    <!-- ==================== All Target ====================================== -->

    <target name="all" depends="clean,build" description="Clean build and dist directories, then compile" />



    <!-- ==================== Clean Target ==================================== -->

    <target name="clean" description="Delete old build and dist directories">
    <delete dir="${build.home}" />
    <delete dir="${dist.home}" />
    </target>



    <!-- ==================== Compile Target ================================== -->

    <target name="build" depends="prepare" description="Compile Java sources">

    <!-- Compile Java classes as necessary -->
    <mkdir dir="${build.home}/WEB-INF/classes" />
    <javac srcdir="${src.home}" destdir="${build.home}/WEB-INF/classes" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}">
    <classpath refid="compile.classpath" />
    </javac>

    <!-- Copy application resources -->
    <copy todir="${build.home}/WEB-INF/classes">
    <fileset dir="${src.home}" excludes="**/*.java" />
    </copy>

    </target>



    <!-- ==================== Dist Target ===================================== -->

    <target name="dist" depends="build,javadoc" description="Create binary distribution">

    <!-- Copy documentation subdirectories -->
    <mkdir dir="${dist.home}/docs" />
    <copy todir="${dist.home}/docs">
    <fileset dir="${docs.home}" />
    </copy>

    <!-- Create application JAR file -->
    <jar jarfile="${dist.home}/${app.name}-${app.version}.war" basedir="${build.home}" />

    <!-- Copy additional files to ${dist.home} as necessary -->

    </target>

    <!-- ==================== Flex targets ==================================== -->

    <target name="appcompile" depends="install">
    <mxmlc file="${APP_ROOT}/helloWorld.mxml" context-root="/helloWorldServer" keep-generated-actionscript="true" services="${web.home}/WEB-INF/flex/services-config.xml" output="${catalina.home}/webapps/${app.name}/helloWorld.swf">
    <compiler.library-path dir="${FLEX_HOME}/frameworks" append="true">
    <include name="${web.home}/WEB-INF/lib/" />
    </compiler.library-path>
    <load-config filename="${FLEX_HOME}/frameworks/flex-config.xml" />
    <source-path path-element="${FLEX_HOME}/frameworks" />
    </mxmlc>

    </target>

    <target name="createHtmlWrapper" depends="appcompile">
    <html-wrapper application="${APP_ROOT}/helloWorld.mxml" output="${catalina.home}/webapps/${app.name}" swf="helloWorld" />
    </target>



    <!-- ==================== Install Target ================================== -->

    <target name="install" depends="build" description="Install application to servlet container">

    <deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="file://${build.home}" />

    </target>


    <!-- ==================== Javadoc Target ================================== -->

    <target name="javadoc" depends="build" description="Create Javadoc API documentation">

    <mkdir dir="${dist.home}/docs/api" />
    <javadoc sourcepath="${src.home}" destdir="${dist.home}/docs/api" packagenames="*">
    <classpath refid="compile.classpath" />
    </javadoc>

    </target>



    <!-- ====================== List Target =================================== -->

    <target name="list" description="List installed applications on servlet container">

    <list url="${manager.url}" username="${manager.username}" password="${manager.password}" />

    </target>


    <!-- ==================== Prepare Target ================================== -->

    <target name="prepare">

    <!-- Create build directories as needed -->
    <mkdir dir="${build.home}" />
    <mkdir dir="${build.home}/WEB-INF" />
    <mkdir dir="${build.home}/WEB-INF/classes" />


    <!-- Copy static content of this web application -->
    <copy todir="${build.home}">
    <fileset dir="${web.home}" />
    </copy>

    <!-- Copy external dependencies as required -->
    <mkdir dir="${build.home}/WEB-INF/lib" />

    <!-- Copy static files from external dependencies as needed -->
    <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->

    </target>


    <!-- ==================== Reload Target =================================== -->

    <target name="reload" depends="build" description="Reload application on servlet container">

    <reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" />

    </target>


    <!-- ==================== Remove Target =================================== -->

    <target name="remove" description="Remove application on servlet container">

    <undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" />

    </target>
    </project>
  11. Addtional ant configuration: Copy catalina-ant.jar and flextasks.jar into ant lib directory, add them to ant runtime in eclipse.
  12. To build and install the file, simply run the createHtmlWrapper target in ant
References
  • The ant build file was created using the base build.xml file available on apache tomcat website.
  • The config files are used as is available with the BlazeDS service.

Thursday, August 23, 2007

Monday, August 20, 2007

Handling Security with Ajax, DWR and Acegi

This is an extension of a previous post that described how to secure your method calls using Acegi security. Here, I will go through how to secure your Asynchronous calls, using the same example with some modifications to include Ajax calls using Direct Web Remoting (DWR).
  1. Create the example project as shown in "Spring security with Acegi Security Framework". This will be the starting point.
  2. Create the SecureDAO object.
    package test;

    public class SecureDAO {
    public String create() {
    System.out.println("Create");
    return "create";
    }

    public String read() {
    System.out.println("read");
    return "read";
    }

    public String update() {
    System.out.println("update");
    return "update";
    }
    }
  3. Update the applicationContext.xml file to include the security definitions by adding the following bean definitions as shown below
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

    <beans>

    <bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
    <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor
    </value>
    </property>
    </bean>

    <bean id="httpSessionContextIntegrationFilter" class="org.acegisecurity.context.HttpSessionContextIntegrationFilter"/>

    <bean id="logoutFilter" class="org.acegisecurity.ui.logout.LogoutFilter">
    <constructor-arg value="/index.jsp"/>
    <constructor-arg>
    <list>
    <ref bean="rememberMeServices"/>
    <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler"/>
    </list>
    </constructor-arg>
    </bean>

    <bean id="authenticationProcessingFilter" class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="authenticationFailureUrl" value="/login.jsp?errorId=1"/>
    <property name="defaultTargetUrl" value="/"/>
    <property name="filterProcessesUrl" value="/j_acegi_security_check"/>
    <property name="rememberMeServices" ref="rememberMeServices"/>
    </bean>

    <bean id="securityContextHolderAwareRequestFilter" class="org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter"/>

    <bean id="rememberMeProcessingFilter" class="org.acegisecurity.ui.rememberme.RememberMeProcessingFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="rememberMeServices" ref="rememberMeServices"/>
    </bean>

    <bean id="anonymousProcessingFilter" class="org.acegisecurity.providers.anonymous.AnonymousProcessingFilter">
    <property name="key" value="changeThis"/>
    <property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
    </bean>

    <bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint">
    <bean class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl" value="/login.jsp"/>
    <property name="forceHttps" value="false"/>
    </bean>
    </property>
    <property name="accessDeniedHandler">
    <bean class="org.acegisecurity.ui.AccessDeniedHandlerImpl">
    <property name="errorPage" value="/denied.jsp"/>
    </bean>
    </property>
    </bean>

    <bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="accessDecisionManager">
    <bean class="org.acegisecurity.vote.AffirmativeBased">
    <property name="allowIfAllAbstainDecisions" value="false"/>
    <property name="decisionVoters">
    <list>
    <bean class="org.acegisecurity.vote.RoleVoter"/>
    <bean class="org.acegisecurity.vote.AuthenticatedVoter"/>
    </list>
    </property>
    </bean>
    </property>
    <property name="objectDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /secure/admin/**=ROLE_ADMIN
    /secure/**=IS_AUTHENTICATED_REMEMBERED
    /**=IS_AUTHENTICATED_ANONYMOUSLY
    </value>
    </property>
    </bean>

    <bean id="rememberMeServices" class="org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices">
    <property name="userDetailsService" ref="userDetailsService"/>
    <property name="tokenValiditySeconds" value="1800"></property>
    <property name="key" value="changeThis"/>
    </bean>

    <bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
    <list>
    <ref local="daoAuthenticationProvider"/>
    <bean class="org.acegisecurity.providers.anonymous.AnonymousAuthenticationProvider">
    <property name="key" value="changeThis"/>
    </bean>
    <bean class="org.acegisecurity.providers.rememberme.RememberMeAuthenticationProvider">
    <property name="key" value="changeThis"/>
    </bean>
    </list>
    </property>
    </bean>

    <bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
    <property name="userDetailsService" ref="userDetailsService"/>
    <property name="userCache">
    <bean class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
    <property name="cache">
    <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
    <property name="cacheManager">
    <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
    </property>
    <property name="cacheName" value="userCache"/>
    </bean>
    </property>
    </bean>
    </property>
    </bean>

    <bean id="userDetailsService" class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">
    <property name="userProperties">
    <bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="/WEB-INF/users.properties"/>
    </bean>
    </property>
    </bean>

    <bean id="loggerListener" class="org.acegisecurity.event.authentication.LoggerListener"/>

    <bean id="methodSecurityInterceptor" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
    <property name="authenticationManager">
    <ref bean="authenticationManager" />
    </property>
    <property name="accessDecisionManager">
    <bean class="org.acegisecurity.vote.AffirmativeBased">
    <property name="allowIfAllAbstainDecisions" value="false" />
    <property name="decisionVoters">
    <list>
    <bean class="org.acegisecurity.vote.RoleVoter" />
    <bean class="org.acegisecurity.vote.AuthenticatedVoter" />
    </list>
    </property>
    </bean>
    </property>
    <property name="objectDefinitionSource">
    <value>
    test.SecureDAO.*=IS_AUTHENTICATED_REMEMBERED
    test.SecureDAO.u=ROLE_ADMIN
    </value>
    </property>
    </bean>


    <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="interceptorNames">
    <list>
    <value>methodSecurityInterceptor</value>
    </list>
    </property>
    <property name="beanNames">
    <list>
    <value>secureDAO</value>
    </list>
    </property>
    </bean>

    <bean id="secureDAO" class="test.SecureDAO" />
    </beans>
  4. Update the Web deployment descriptor to forward DWR requests to the DWR Servlet
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>DWRSpring</display-name>
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
    <display-name>SpringListener</display-name>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
    <filter-name>Acegi Filter Chain Proxy</filter-name>
    <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
    <init-param>
    <param-name>targetClass</param-name>
    <param-value>org.acegisecurity.util.FilterChainProxy</param-value>
    </init-param>
    </filter>

    <filter-mapping>
    <filter-name>Acegi Filter Chain Proxy</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
    <init-param>
    <param-name>debug</param-name>
    <param-value>true</param-value>
    </init-param>
    </servlet>

    <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    </web-app>

  5. In the DWR configuration file, set the creator to Spring
    <!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
    "http://www.getahead.ltd.uk/dwr/dwr10.dtd">
    <dwr>
    <allow>
    <convert match="java.lang.Exception" converter="exception"/>
    <create creator="spring" javascript="secureDAO">
    <param name="beanName" value="secureDAO"/>
    </create>
    </allow>
    </dwr>
    Note:
    • The converter is used to convert the Java exception to Javascript exception.
  6. The main change will be made to the secure/authenticatedusers.jsp file. This will use DWR to make Ajax requests. Here is the code for the file
    <%@ page import="org.acegisecurity.context.SecurityContextHolder"%>
    <html>
    <head>

    <script type='text/javascript' src='/DWRSpring/dwr/interface/secureDAO.js'></script>
    <script type="text/javascript" src="../dwr/engine.js"> </script>
    <script type="text/javascript" src="../dwr/util.js"> </script>
    <script>
    dwr.engine.setErrorHandler(errorHandlerFn);
    function update() {
    var name = dwr.util.getValue("method");
    switch(name) {
    case "create":
    secureDAO.create(callBackFn)
    break;
    case "read":
    secureDAO.read(callBackFn);
    break;
    case "update":
    secureDAO.update(callBackFn);
    break;
    }

    }

    function callBackFn(str) {
    dwr.util.setValue("selectedAction","Server Returned : " + str);
    }

    function errorHandlerFn(message, exception) {
    dwr.util.setValue("selectedAction", "Error : " + message);
    }
    </script>

    </head>
    <body>
    <h1>Welcome: <%=SecurityContextHolder.getContext().getAuthentication().getName()%></h1>
    <p><a href="../">Home</a>
    <form name="testForm" action=""><select name="method" onchange="update()">
    <option value=""></option>
    <option value="create">create</option>
    <option value="read">read</option>
    <option value="update">update</option>
    </select></form>

    <div id="selectedAction"></div>
    <p><a href="../j_acegi_logout">Logout</a></p>
    </body>
    </html>
    Note:
    • The classes that are exposed through DWR will be available through the /WEB_APP_NAME/dwr/interface/JAVASCRIPT_NAME.js files.
      <script type='text/javascript' src='/DWRSpring/dwr/interface/secureDAO.js'></script>
    • The setErrorhandler call sets the global error handling function.
      dwr.engine.setErrorHandler(errorHandlerFn);
      Alternatively, the error handling function can be set for individual method calls (as described in DWR documentationa
      Remote.method(params, {
      callback:function(data) { ... },
      errorHandler:function(errorString, exception) { ... }
      });
    • util.js file contains utility functions for getting and setting values for the document elements.
  7. Make sure you have the following Jar files in your classpath:
    • acegi-security-1.0.3.jar
    • ant-junit.jar
    • cglib-nodep-2.1_3.jar
    • commons-codec-1.3.jar
    • commons-logging.jar
    • dwr.jar
    • ehcache-1.2.3.jar
    • jstl.jar
    • spring.jar
    • standard.jar

Wednesday, May 09, 2007

OpenJDK and JavaFX

Java is now completely open source. The JDK source code is now available through the OpenJDK project. According to the marketing manager of the OpenJDK project Rich Sands, Developers can,
... learn how the JDK is put together, fix that bug that's been 
driving you nuts, join the conversations in the mailing lists,
start or participate in projects to improve the implementation.
It's good to see that the governing body consists of not just Sun employees.

On a related note, Sun has announced the new JavaFX product family. Following Adobe's Flex, and Microsoft's Silverlight, JavaFX script is another product for building rich internet applicaitons. JavaFX Mobile is a complete mobile operating and application environment built around Java and Linux. JavaFX Mobile includes support for Java ME applications and other standard Java APIs.

Popular Posts