Tag: WebService

Resteasy and JPA with Hibernate as Provider in JBoss AS7

Hi,

The Java Persistence Architecture API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification as a replacement for the EJB 2 CMP Entity Beans specification. JPA is now considered the standard industry approach for Object to Relational Mapping (ORM) in the Java Industry.

JBoss also provides feature to deploy JAX-RS based applications including package “org.jboss.resteasy.*”. Here in this example we will see how to integrate the Resteasy wtih JPA. In this process we will see how to use various annotations like @XmlRootElement, @ApplicationPath @Entity @PersistenceContext etc.. A Quick tour on JAX-RS Reference Guide will be better.

The JBoss Application Server JPA subsystem implements the JPA 2.0 container-managed requirements. JPA Applications use the Hibernate (core) 4.0 persistence provider, that is included with JBoss AS. Hibernate 4 is packaged with the AS and is the default persistence provider. The JPA 2.0 Specifications can be found in the following link: http://jcp.org/aboutJava/communityprocess/pfd/jsr317/index.html

A Best reference for JPA features inside JBoss AS7 can be foun in the following link: JPA Reference Guide

However in this current emo we will just create a Simple JPA persistence unit and then we will try to insert some employee detils insie the DataBase using the JAX-RS as frontend. So basically this is just as a startup.

In this example we will mainly focus on following points

Point-1). For Web Applications we should put the “persistence.xml” file inside “${WEB_APPLICATION}/WEB-INF/classes/META-INF/persistence.xml”
For EJB Applications we should put the “persistence.xml” file inside “${EJB_JAR}/META-INF”

Point-2). To inject the EntityManager inside our Web Components we can use the annotation @javax.persistence.PersistenceContext(unitName=”name”)

Point-3). How to use the JAX-RS resteasy implementations and various annotations associated with it.

<<< I S S U E >>>: I tried to use the @javax.ejb.EJB annotation to inject an Enterprise Java Bean inside Rest Easy component but it did not work Like @EJB(lookup=”jndiName”) , which need to be checked (May be it’s work as designed). But it worked fine inside a Servlet in another case.

Server Side Configuration

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.CR1” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). In order to get more details on how to create MySQL DataSource in JBoss AS7 you can refer to the following article: http://middlewaremagic.com/jboss/?p=872
Create a DataSource inside “${JBOSS_HOME}/standalone/configuration/standalone-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:datasources:1.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="H2DS" enabled="true">
                    <connection-url>
                        jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
                    </connection-url>
                    <driver>
                        h2
                    </driver>
                    <security>
                        <security-domain>
                            encrypted-ds
                        </security-domain>
                    </security>
                </datasource>


                <!-- Below is the DataSource Configuration which we added for our JPA TestCase-->
                <datasource jndi-name="java:/MySqlDS" pool-name="MySqlDS_Pool" enabled="true" jta="false" use-ccm="false">
                    <connection-url>
                        jdbc:mysql://localhost:3306/testDB
                    </connection-url>
                    <driver-class>
                        com.mysql.jdbc.Driver
                    </driver-class>
                    <driver>
                        mysql-connector-java-5.1.13-bin.jar
                    </driver>
                    <security>
                        <user-name>someDBUserName</user-name>
                        <password>someDBPassword</password>
                    </security>
                </datasource>
                <!-- Above is the DataSource we created on MySQL Database -->


                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>
                            org.h2.jdbcx.JdbcDataSource
                        </xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

Point-3). Restart your JBoss AS7 from inside “/home/userone/jboss-as-7.1.0.CR1/bin” directory as following:

.
 ./standalone.sh -c standalone-full.xml
.

Developing JPA Part Of the Test Case

Step1). Create a directory somewhere in your filesystem like “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” where we will be placing our source codes and JSPs.

Step2). Now first of all we will create an Entity “Employee.java” as following inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory. NOTICE: we used the annotation “@XmlRootElement”

package jpa;
import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@Entity
@Table(name="Employee")
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private Integer empno;
	private String ename;

        public Employee() {
    	 System.out.println("[Employee] Employee Object Created. "+this);
        }

	public Integer getEmpno() {
                System.out.println("[Employee] getEmpno() called on "+this);
		return this.empno;
	}

	public void setEmpno(Integer empno) {
                System.out.println("[Employee] setEmpno("+empno+") called on "+this);
		this.empno = empno;
	}

	public String getEname() {
                System.out.println("[Employee] getEname() called on "+this);
		return this.ename;
	}

	public void setEname(String ename) {
                System.out.println("[Employee] setEname("+ename+") called on "+this);
		this.ename = ename;
	}

}

Step3). Now we will create a Simple Stateless SessionBean remote Interface “EmployeeServiceRemote.java” inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

package jpa;
import java.util.Collection;
import javax.ejb.Remote;
@Remote

public interface EmployeeServiceRemote{
  public void doAction();
  public Employee createEmployee(Integer id, String name);
  public void removeEmployee(Integer id);
  public Employee findEmployee(Integer id);
  public Collection<Employee> findAllEmployees() ;

}

Step4). Now we will Stateless Session Bean class “EmployeeService.java” by implementing the interface “EmployeeServiceRemote.java”. Place this file as well inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

package jpa;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class EmployeeService implements EmployeeServiceRemote {
  @PersistenceContext(unitName="EmployeeService")
  EntityManager em;

  public EmployeeService() {
	  System.out.println("n[EmployeeService] EmployeeService Created. this: "+this);
  }

  public Employee createEmployee(Integer id, String name) {
    Employee emp = new Employee();
    emp.setEmpno(id);
    emp.setEname(name);
    em.persist(emp);
    emp = findEmployee(id);
    System.out.println("n[EmployeeService] Inside createEmployee() findEmployee result: "+emp+"t this: "+this);
    em.flush();
    return emp;
  }

  public void removeEmployee(Integer id) {
    System.out.println("n[EmployeeService] Inside removeEmployee("+id+") this: "+this);
    Employee emp = findEmployee(id);
    if (emp != null) {
      em.remove(emp);
    }
  }

  public Employee findEmployee(Integer id) {
    System.out.println("n[EmployeeService] Inside findEmployee("+id+") this: "+this);
    return em.find(Employee.class, id);
  }

  @SuppressWarnings("unchecked")
  public Collection<Employee> findAllEmployees() {
    System.out.println("n[EmployeeService] Inside findAllEmployees() this: "+this);
    Query query = em.createQuery("SELECT e FROM Employee e");
    return (Collection<Employee>) query.getResultList();
  }

  public void doAction(){
  }
}

Step5). Now we will write the “persistence.xml” file inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
	xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
	<persistence-unit name="EmployeeService"> <!-- transaction-type="JTA" -->
		<jta-data-source>java:/MySqlDS</jta-data-source>
		<class>jpa.Employee</class>
		<properties>
			<property name="hibernate.hbm2ddl.auto" value="create-drop" />
                        <property name="hibernate.show_sql" value="true" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
		</properties>
	</persistence-unit>
</persistence>

NOTE: We need to make sure that this “persistence.xml” file goes inside the “${war.name}/WEB-INF/classes/META-INF” directory of our WAR file.
Due to the property “hibernate.hbm2ddl.auto” the Employee table will be automatically created in the database as soon as we deploy the application on JBoss and will be automatically droped as soon as we undeploy our application. Valid values for this property are “validate | update | create | create-drop”

Developing JAX-RS Part Of the Test Case

Step6). Now we will write a simple “index.jsp” page to just provide a some input forms so that a user can enter the employee name and id details , Place this file as well inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

<html>
<head>
<title>JPA With Rest Demo In JBoss AS7</title>
</head>
<body>

<h1>Add An Employee</h1>
   <table border="10%">
      <form action="services/create" method="post">
         <TR><TD>Enter Employee ID </TD><TD> <input name="empno" type="text" value="" /> </TD></TR>
         <TR><TD>Enter Employee Name </TD><TD> <input name="empname" type="text" value="" /> </TD></TR>
         <TR><TD><input type="submit" value="Add Employee" /></TD><TD> <input type="reset" value="Clear" /></TD></TR>
      </form>
    </table>

<h1>Remove An Employee</h1>
   <table border="10%">
     <form action="services/removeemployee" method="post">
         <TR><TD>Enter Employee ID </TD><TD> <input name="empno" type="text" value=""/> </TD></TR>
         <TR><TD></TD><TD><input type="submit" value="Remove Employee" /></TD></TR>
   </form>
    </table>

<h1>Find An Employee</h1>
   <table border="10%">
      <form action="services/findemployee" method="post">
         <TR><TD>Enter Employee ID </TD><TD> <input name="empno" type="text" value=""/> </TD></TR>
         <TR><TD></TD><TD><input type="submit" value="Find Employee" /></TD></TR>
      </form>
    </table>

<h1>Find All Employees</h1>
   <a href="services/findall">Find All Employees</a>  

</body>
</html>

Step7). We will write the “MyRestService.java” inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” as following in order to insert the details entered by the user in previous index.jsp page.

package rest;
import java.util.Collection;

//Rest related imports
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

// EJB Related imports
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ejb.EJB;
import jpa.Employee;
import jpa.EmployeeServiceRemote;

@ApplicationPath("/services")
@Path("/")
public class MyRestService extends Application
{
   /* ::::NOTE::::
        The Following Injection is not Working which need to be checked. So Here i am doing the old style lookup for the EJB.

        @EJB(lookup="java:global/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote")
        jpa.EmployeeServiceRemote remote;
   */

  jpa.EmployeeServiceRemote remote;
  public MyRestService()
     {
       try{
            InitialContext ctx=new InitialContext();
            remote = (EmployeeServiceRemote) ctx.lookup("java:global/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote");
          }
       catch(NamingException ne) 
          {
            System.out.println("n[MyRestService]NamingException: "+ne);
            ne.printStackTrace();
          }
     }


  @POST
  @Path("/create")
  @Produces(MediaType.APPLICATION_XML)  
  @Consumes("application/x-www-form-urlencoded")
  public Employee createEmployee(@FormParam("empno") Integer id, @FormParam("empname") String name) 
    {
        System.out.println("n[MyRestService]jpa.EmployeeServiceRemote remote = "+remote);
        Employee emp=null;
        if(remote!=null)
           emp=remote.createEmployee(id,name);
        else
          {
           emp=new Employee();
           emp.setEname(name);
           emp.setEmpno(id);
          }
        return emp;
    }        


  @POST
  @Path("/removeemployee")
  @Consumes("application/x-www-form-urlencoded")
  @Produces(MediaType.TEXT_HTML)  
  public String removeEmployee(@FormParam("empno") Integer id) 
    {
        System.out.println("n[MyRestService]Inside removeEmployee("+id+") this: "+this);
        remote.removeEmployee(id);
        return "Emplloyee Removed with Id: "+id;
    }


  @POST
  @Path("/findemployee")
  @Produces(MediaType.APPLICATION_XML)  
  @Consumes("application/x-www-form-urlencoded")
  public Employee findEmployee(@FormParam("empno") Integer id) 
    {
        System.out.println("n[MyRestService]Inside findEmployee("+id+") this: "+this);
        Employee emp=remote.findEmployee(id);
        return  emp;
    }


  @GET
  @Produces(MediaType.APPLICATION_XML)  
  @Path("/findall")
  public Collection<Employee> findAllEmployees() 
   {
       System.out.println("n[MyRestService]Inside findAllEmployees() this: "+this);
       Collection<Employee> collection=remote.findAllEmployees();
       return collection;
   }
}

Step8). As this is going to be a WebApplication so we will provide a simple default “web.xml” file inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

</web-app>

Building and deploying the Application

Step9). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deploy our web application on the JBoss AS7.1 CR1 Server, so write the following “build.xml” file inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” directory.

<project name="JPA_BASIC_Demo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="JPA_With_JAXRS_BASIC_Demo.war" />
 
   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>
   </path>
 
        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}/WEB-INF/classes/META-INF"/>
        </target>
 
        <target name="build" depends="init">
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy todir="${tmp.dir}/WEB-INF/classes">
                <fileset dir="${src.dir}" includes="**/*.java"/>
           </copy>
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy file="${src.dir}/web.xml" tofile="${tmp.dir}/web.xml"/>

           <!-- Make Sure that the persistence.xml file is placed inside "${war.name}/WEB-INF/classes/META-INF" directory -->
           <copy file="${src.dir}/persistence.xml" tofile="${tmp.dir}/WEB-INF/classes/META-INF/persistence.xml"/>

           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>
 
        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step10). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step11). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” and then run the ant to build the webservice. by running the command “ant”

[userone@localhost JPA2_JAXRS_And_Hibernate4_On_AS7]$ ant
Buildfile: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build.xml

init:
   [delete] Deleting directory /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build
    [mkdir] Created dir: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build
    [mkdir] Created dir: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp
    [mkdir] Created dir: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes/META-INF

build:
    [javac] /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build.xml:25: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 4 source files to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes
     [copy] Copying 4 files to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes/META-INF
      [jar] Building jar: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/JPA_With_JAXRS_BASIC_Demo.war
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build

deploy:
     [echo] *******************  Deploying the WAR file JPA_With_JAXRS_BASIC_Demo.war *********************
     [echo] ********** build/JPA_With_JAXRS_BASIC_Demo.war to //home/userone/jboss-as-7.1.0.CR1/standalone/deployments **********
     [copy] Copying 1 file to //home/userone/jboss-as-7.1.0.CR1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

Step12). Now you will see the following kind of output on your JBoss AS7.1 console which means the application is deployed successfully:

20:21:15,570 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) Starting deployment of "JPA_With_JAXRS_BASIC_Demo.war"
20:21:15,589 INFO  [org.jboss.jpa] (MSC service thread 1-2) JBAS011401: Read persistence.xml for EmployeeService
20:21:15,598 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-3) JNDI bindings for session bean named EmployeeService in deployment unit deployment "JPA_With_JAXRS_BASIC_Demo.war" are as follows:

	java:global/JPA_With_JAXRS_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:app/JPA_With_JAXRS_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:module/EmployeeService!jpa.EmployeeServiceRemote
	java:global/JPA_With_JAXRS_BASIC_Demo/EmployeeService
	java:app/JPA_With_JAXRS_BASIC_Demo/EmployeeService
	java:module/EmployeeService

20:21:15,617 INFO  [org.jboss.jpa] (MSC service thread 1-6) JBAS011402: Starting Persistence Unit Service 'JPA_With_JAXRS_BASIC_Demo.war#EmployeeService'
20:21:15,619 INFO  [org.hibernate.ejb.Ejb3Configuration] (MSC service thread 1-6) HHH000204: Processing PersistenceUnitInfo [
	name: EmployeeService
	...]
20:21:15,628 INFO  [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (MSC service thread 1-6) HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
20:21:15,635 INFO  [org.hibernate.dialect.Dialect] (MSC service thread 1-6) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
20:21:15,635 INFO  [org.hibernate.engine.jdbc.internal.LobCreatorBuilder] (MSC service thread 1-6) HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
20:21:15,636 INFO  [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (MSC service thread 1-6) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
20:21:15,636 INFO  [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (MSC service thread 1-6) HHH000397: Using ASTQueryTranslatorFactory
20:21:15,643 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (MSC service thread 1-6) HHH000227: Running hbm2ddl schema export
20:21:15,643 INFO  [stdout] (MSC service thread 1-6) Hibernate: drop table if exists Employee
20:21:15,645 INFO  [stdout] (MSC service thread 1-6) Hibernate: create table Employee (empno integer not null, ename varchar(255), primary key (empno))
20:21:15,768 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (MSC service thread 1-6) HHH000230: Schema export complete
20:21:15,776 INFO  [org.jboss.web] (MSC service thread 1-4) registering web context: /JPA_With_JAXRS_BASIC_Demo
20:21:15,788 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "JPA_With_JAXRS_BASIC_Demo.war"

Step13). Now access the WebApplication like following :
http://localhost:8080/JPA_With_JAXRS_BASIC_Demo/

JPA_With_JAXRS


.
.
Thanks 🙂
Middleware Magic Team


Sending Attachment using MTOM on spring-cxf webservice in JBoss AS7

Hi,

Awaited “jboss-as-7.1.0.CR1” is released recently. So here we are going to test a WebService to receive an attachment from a WebService client using MTOM in JBoss AS7.1 CR1. In this sample we will see how to develop a Simple Apache CXF based webService with the help of Spring framework and then how to use MTOM (Message Transmission Optimization Mechanism).

Benifit of MTOM? The efficiency claims of MTOM only refers to the size of the messages sent across the wire. Since SOAP uses XML, any binary data in the SOAP message will have to be encoded as text. This is usually done using Base64 encoding which increases the size of the binary data by 33%. MTOM provides a way to send the binary data in its original binary form, avoiding any increase in size due to encoding it in text. MTOM does not address the efficiency of serializing or deserializing the messages. More details about MTOM can be found in the following link: http://en.wikipedia.org/wiki/Message_Transmission_Optimization_Mechanism

More informations about the CXF Spring Client can be found in the following link:
http://cxf.apache.org/docs/writing-a-service-with-spring.html

Highlights of Article

Point-1). In this example we are going to use “jboss-as-7.1.0.CR1” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). We will see how to use the “cxf-servlet.xml” file and where to place it.

Point-3). How to use the Spring “ApplicationContext” and “ClassPathXmlApplicationContext” to initialize the jaxws based beans for Service client.

Point-4). As the client is going to use spring features to access the web service so we will need to make sure that “spring-2.5.6.jar” jar is present in the client classpath. This jar can be downloaded from the following link:
http://repo1.maven.org/maven2/org/springframework/spring/2.5.6/spring-2.5.6.jar

Point-5). How to send binary attachments to WebService from a Client using MTOM. And How to configure MTOM in our Service and Client communication.

Point-6). Discuss some possible BUGs with the “org.jboss.ws.tools.ant.WSProvideTask” of JBoss AS7.
.

Developing Spring CXF WebService

Step1). Create a Directory somewhere in your filesystem like “/home/userone/Spring_MTOM_Service/” and then create “src” directory inside “/home/userone/Spring_MTOM_Service/”.

Step2). Create a class “Picture.java” using the standard XML binding annotations. And make sure that you define the @javax.xml.bind.annotation.XmlMimeType for your DataHandler. More information about DataHandler can be found in the following link:
http://docs.oracle.com/javase/6/docs/api/javax/activation/DataHandler.html#DataHandler(java.lang.Object, java.lang.String)

package ws;
import javax.activation.DataHandler;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAttribute;

@XmlType
public class Picture {

    @XmlMimeType("application/octet-stream")
    protected DataHandler pictureDataHandler;
    protected String title;

  public String getTitle() 
    { 
       return title; 
    }

  public void setTitle(String title) 
    {
       this.title = title; 
    }

  public DataHandler getPictureDataHandler() 
    {
       System.out.println("[Picture] picture = "+this);
       return pictureDataHandler; 
    }
/*
  public void setPictureDataHandler(DataHandler pictureData) 
    { 
       System.out.println("nsetPictureDataHandler() method invoked with pictureData = "+pictureData);
       System.out.println("[Picture] picture = "+this);
       System.out.println("[Picture] pictureData.getContentType() = "+pictureData.getContentType());
       this.pictureDataHandler = pictureDataHandler; 
    }
*/
}

( ( ( ( ( I S S U E – 1 ) ) ) ) ):
If you will notice in above code i have commented the “setPictureDataHandler” method because if i dont comment it then i get the following exception, Which looks like an issue with JBoss AS7.1 CR1 and i get the following exception while running org.jboss.ws.tools.ant.WSProvideTask ANT task:

[wsprovide] Caused by: org.apache.cxf.service.factory.ServiceConstructionException
[wsprovide] 	at org.apache.cxf.jaxb.JAXBDataBinding.initialize(JAXBDataBinding.java:292)
[wsprovide] 	at org.apache.cxf.service.factory.AbstractServiceFactoryBean.initializeDataBindings(AbstractServiceFactoryBean.java:86)
[wsprovide] 	at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.buildServiceFromClass(ReflectionServiceFactoryBean.java:444)
[wsprovide] 	at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.buildServiceFromClass(JaxWsServiceFactoryBean.java:682)
[wsprovide] 	at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.initializeServiceModel(ReflectionServiceFactoryBean.java:507)
[wsprovide] 	at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.create(ReflectionServiceFactoryBean.java:241)
[wsprovide] 	at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.create(JaxWsServiceFactoryBean.java:202)
[wsprovide] 	at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createEndpoint(AbstractWSDLBasedEndpointFactory.java:101)
[wsprovide] 	at org.apache.cxf.frontend.AbstractServiceFactory.createService(AbstractServiceFactory.java:78)
[wsprovide] 	... 26 more
[wsprovide] Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
[wsprovide] Class has two properties of the same name "pictureDataHandler"
[wsprovide] 	this problem is related to the following location:
[wsprovide] 		at public javax.activation.DataHandler ws.Picture.getPictureDataHandler()
[wsprovide] 		at ws.Picture
[wsprovide] 		at private ws.Picture ws.jaxws_asm.UploadPictureAttachment.arg1
[wsprovide] 		at ws.jaxws_asm.UploadPictureAttachment
[wsprovide] 	this problem is related to the following location:
[wsprovide] 		at protected javax.activation.DataHandler ws.Picture.pictureDataHandler
[wsprovide] 		at ws.Picture
[wsprovide] 		at private ws.Picture ws.jaxws_asm.UploadPictureAttachment.arg1
[wsprovide] 		at ws.jaxws_asm.UploadPictureAttachment

( ( ( ( ( I S S U E – 2 ) ) ) ) ):
If i declare the @XmlMimeType(“application/octet-stream”) Just above the method “public DataHandler getPictureDataHandler()” then without having the “setPictureDataHandler” method the code compiles FINE using org.jboss.ws.tools.ant.WSProvideTask ANT task, but in the run time when inside the webservice when i call Picture.getPictureDataHandler() it returns NULL inside “SpringCXFMtom.java” service. Where as the setPictureDataHandler(dataHandler) works fine.

Step3). Now we will write the Web Service Endpoint Interface “SpringCXFMtomIntf.java” inside “/home/userone/Spring_MTOM_Service/src” as following:

package ws;
import javax.jws.WebService;
@WebService
public interface SpringCXFMtomIntf
  {
      public String uploadPictureAttachment(String pictureName,ws.Picture picture);
  }

Step4). Now we will provide the WebService Implementation class “SpringCXFMtom.java” inside “/home/userone/Spring_MTOM_Service/src” as following:

package ws;
import javax.jws.WebService;
import javax.jws.WebMethod;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.activation.DataHandler;
import java.io.IOException;
import java.io.File;
import javax.xml.ws.RequestWrapper;


@WebService(name="SpringCXFMtomService", endpointInterface = "ws.SpringCXFMtomIntf",targetNamespace="http://ws/")
public class SpringCXFMtom implements SpringCXFMtomIntf
  {
      @WebMethod(operationName="uploadPictureAttachment")
      @RequestWrapper(localName = "uploadPictureAttachment", targetNamespace = "http://ws/", className = "ws.UploadPictureAttachment")
      public String uploadPictureAttachment(String pictureName,ws.Picture picture)
        {
            String uploadLocation=System.getProperty("jboss.server.log.dir");
            byte b[];
            FileOutputStream fout=null;
            InputStream in = null;
            try{
                  System.out.println("[SpringCXFMtom] uploadPictureAttachment() invoked.");
                  System.out.println("[SpringCXFMtom] picture = "+picture);
                  picture.setTitle(pictureName);
                  System.out.println("picture.getTitle() = "+picture.getTitle());
                  System.out.println("trying to get dataHandler");
                  DataHandler dataHandler=picture.getPictureDataHandler();

                  if(dataHandler!=null)
                    {
                        System.out.println("Got dataHandler: "+dataHandler);

  	                in = dataHandler.getInputStream();
	                if(in != null) 
                          {
                             System.out.println("InputStream NOT NULL");
                             File file=new File(uploadLocation+"/"+pictureName);
                             fout=new FileOutputStream(file);

                             int n=0;
                             while((n=in.read())!=-1)
                               {
                                    fout.write(n);
                               }
                             fout.close();
                             in.close();
	                  }
                       else
                         {
                             System.out.println("InputStream IS NULL");
                         }                             
                    }
                   else
                     {
                         System.out.println("nnPlease check Why the dataHandler is NULL.");
                     }
               }
             catch(Exception e)
               {
                   System.out.println("nt Unable to Upload File on directory: "+uploadLocation+"/"+pictureName);
                   e.printStackTrace();
                   if(in!=null)
                     {
                        try{   in.close(); }catch(Exception ee){ ee.printStackTrace(); }
                     }
                   if(fout!=null)
                     {
                        try{   fout.close(); }catch(Exception ee){ ee.printStackTrace(); }
                     }
               }
                       
            return "File Uploaded on JBoss AS7 Server Location: "+uploadLocation+"/"+pictureName;
        }
  }

Step4). We will write the “web.xml” inside “/home/userone/Spring_MTOM_Service/src” as following (practically this file is almost empty):

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

</web-app>

Step5). We will write the “cxf-servlet.xml” inside “/home/userone/Spring_MTOM_Service/src” to define “jaxws:endpoint” and it’s implementation class along with the MTOM enablement details as following:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  http://cxf.apache.org/jaxws  http://cxf.apache.org/schemas/jaxws.xsd">

       <jaxws:endpoint 
              id="mtomService" 
              implementor="ws.SpringCXFMtom" 
              address="http://localhost:8080/HelloWorld">
              <jaxws:properties>
                     <entry key="mtom-enabled" value="true"/>
              </jaxws:properties>
       </jaxws:endpoint>
 
</beans>

NOTE: We need to make sure that this “cxf-servlet.xml” file is present inside the “WEB-INF” diectory of our service. NOTICE we enabled MTOM using the properties key=”mtom-enabled” value=”true”

Developing Spring CXF based Client

Step6). Now we will write the WebService Client “Test_CXF_Client.java” inside “/home/userone/Spring_MTOM_Service/src” using CXF standard code as following :

package client;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
public class Test_CXF_Client
  {
     public static void main(String ar[]) throws Exception
      {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"client-beans.xml"});
        SpringCXFMtomIntf client = (SpringCXFMtomIntf) context.getBean("testClient");
        System.out.println("ntGot Client: "+client);         

        DataHandler dataHandler=null;
        String attachmentName=ar[0];
        String attachmentFile=ar[1];
        Picture picture=null;

        dataHandler=new DataHandler(new java.net.URL(ar[1]));
        System.out.println("nt dataHandler.getContentType() = "+dataHandler.getContentType());

        picture=new Picture();
        picture.setTitle(attachmentName);        
        picture.setPictureDataHandler(dataHandler);

        String result=client.uploadPictureAttachment(attachmentName,picture);
        System.out.println("ntclient.uploadPictureAttachment(attachmentName,picture): "+result);                
      }
  }

Step7). We will create the “client-beans.xml” XML file inside “/home/userone/Spring_MTOM_Service/src” directory as following. (This file name may be anything)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <jaxws:client id="testClient"
                  serviceClass="client.SpringCXFMtomIntf"
                  address="http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom">
                  <jaxws:properties>
                     <entry key="mtom-enabled" value="true"/>
                  </jaxws:properties>
    </jaxws:client>
</beans>

NOTE: The file name “client-beans.xml” may be anything but we need to make sure that this file is present in the client classpath.

NOTE: client-beans.xml file should be written only when you have run the wsconsume anttask to generate Client side artifacts for your WebService, Because the classes like “client.SpringCXFServiceIntf” will be generated at client side only after generating the client side artifacts.

NOTE: We enabled MTOM using the properties key=”mtom-enabled” value=”true”

Step8). As our weservice client is going to use the spring features to access the web service so we will need to make sure that the following JAR is present in the client classpath and place it inside “/home/userone/Spring_MTOM_Service/src” directory. This file can be downloaded from the following link:
http://repo1.maven.org/maven2/org/springframework/spring/2.5.6/spring-2.5.6.jar

Building, Deploying and Testing

Step9). As everything is done so we will write a ant build script in order to build/deploy/run and test the WebService and Basic Authentication, So create a file “build.xml” inside “/home/userone/Spring_MTOM_Service/” as following:

<project name="JBoss_Service" default="post-deploy">
<property name="jboss.home" value="/home/userone/boss-as-7.1.0.CR1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="war.tmp.name" value="Spring_CXF_MTOM_Service_Demo" />
<property name="war.name" value="Spring_CXF_MTOM_Service_Demo.war" />
<property name="src.dir" value="src" />
<property name="client.src.dir" value="${basedir}/clientSrc" />
<property name="output.dir" value="build" />
<property name="client.dir" value="${basedir}/clientStuff" />
<property name="client.jar.name" value="Spring_CXF_MTOM_Client.jar" />
 
   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
   </path>

   <path id="client.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
     <fileset dir="${src.dir}">
        <include name="**/spring-2.5.6.jar"/>
        <!-- This Jar is needed at client side and can be downloaded from the following link -->
        <!-- http://repo1.maven.org/maven2/org/springframework/spring/2.5.6/spring-2.5.6.jar -->
     </fileset>  
     <fileset dir="${client.dir}">
        <include name="*.jar"/>
     </fileset>  
   </path>

   <taskdef name="wsprovide" classname="org.jboss.ws.tools.ant.WSProvideTask">
       <classpath refid="jboss.classpath"/>
   </taskdef>

   <taskdef name="wsconsume" classname="org.jboss.ws.tools.ant.WSConsumeTask">
       <classpath refid="jboss.classpath"/>
   </taskdef>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <mkdir dir="${output.dir}/${war.tmp.name}/META-INF"/>
           <mkdir dir="${output.dir}/${war.tmp.name}/WEB-INF/classes"/>
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}"/>

       <javac srcdir="${src.dir}" destdir="${output.dir}/${war.tmp.name}/WEB-INF/classes"  includes="*.java" excludes="Test_CXF_Client.java">
       	        <classpath>
	            <pathelement location="${output.dir}/${war.tmp.name}/WEB-INF/classes"/>
	            <path refid="jboss.classpath"/>
	        </classpath>
       </javac>
        </target>
	 
    <target name="build" depends="init">

        <copy todir="${output.dir}/${war.tmp.name}/WEB-INF">
	  <fileset dir="${basedir}/src">
	      <include name="web.xml"/>
	      <include name="cxf-servlet.xml"/>
	  </fileset>
	</copy>   
       <wsprovide
        	fork="false"
        	keep="true"
        	destdir="${output.dir}/${war.tmp.name}/WEB-INF/classes"
        	resourcedestdir="${output.dir}/${war.tmp.name}/WEB-INF/wsdl"
        	sourcedestdir="${output.dir}"
        	genwsdl="true" 
        	verbose="true"
                classpath="${output.dir}/${war.tmp.name}/WEB-INF/classes"
        	sei="ws.SpringCXFMtom">
            	<classpath>
                	  <pathelement path="${output.dir}/${war.tmp.name}/WEB-INF/classes"/>
            	</classpath>
      </wsprovide>
      <jar jarfile="${output.dir}/${war.name}" basedir="${output.dir}/${war.tmp.name}" compress="true" />  
      <delete dir="${output.dir}/${war.tmp.name}" /> 
    </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying   *********************" />  
            <echo message="********** ${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
        </target>
  
        <target name="post-deploy" depends="deploy">
            <echo message="*******************  NOTE  *********************" />
            <echo message="***** You should be able to access your WSDL using Browser now *****" />
            <echo message="                http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom?wsdl          " />
        </target>  

        <target name="client">
             <delete dir="${client.dir}" />
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom?wsdl"
                      wsdl="http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom?wsdl">
            </wsconsume>
            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" />  
            <zip destfile="${client.dir}/${client.jar.name}" 
                 update="true"> 
                 <fileset dir="${src.dir}"> 
                       <include name="client-beans.xml" /> 
                 </fileset> 
            </zip> 
       </target>

        <target name="run" depends="client">
            <javac srcdir="${src.dir}" destdir="${client.dir}"  includes="Test_CXF_Client.java" classpathref="client.classpath"/>
            <java classname="client.Test_CXF_Client"  >
	        <classpath>
	            <pathelement location="${client.dir}"/>
	            <path refid="client.classpath"/>
	        </classpath>
                <arg line="one.jpg file:///home/jsenshar/Desktop/DELETE/one.jpg"/>
            </java>
        </target>  

</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script is to point to your own JBoss AS7 directory home directory.

Step10). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step11). Run the command “ant” or “ant post-deploy” which will internally build the WebService and deploy it inside the JBoss AS7 standalone profile.

[userone@localhost Spring_MTOM_Service]$ ant
Buildfile: /home/userone/Spring_MTOM_Service/build.xml
Buildfile: /home/userone/Spring_MTOM_Service/build.xml

init:
   [delete] Deleting directory /home/userone/Spring_MTOM_Service/build
    [mkdir] Created dir: /home/userone/Spring_MTOM_Service/build
    [mkdir] Created dir: /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo/META-INF
    [mkdir] Created dir: /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo/WEB-INF/classes
   [delete] Deleting directory /home/userone/Spring_MTOM_Service/clientStuff
    [mkdir] Created dir: /home/userone/Spring_MTOM_Service/clientStuff
    [javac] /home/userone/Spring_MTOM_Service/build.xml:49: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 3 source files to /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo/WEB-INF/classes

build:
     [copy] Copying 2 files to /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo/WEB-INF
[wsprovide] Generating from endpoint: ws.SpringCXFMtom
[wsprovide] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
[wsprovide] log4j:WARN Please initialize the log4j system properly.
[wsprovide] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[wsprovide] java2ws -s /home/userone/Spring_MTOM_Service/build -classdir /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo/WEB-INF/classes -d /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo/WEB-INF/wsdl -verbose -wsdl -cp ::::::: -wrapperbean -createxsdimports ws.SpringCXFMtom
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide] 
[wsprovide] /home/userone/Spring_MTOM_Service/build/ws/jaxws/UploadPictureAttachment.java:25: cannot find symbol
[wsprovide] symbol  : class Picture
[wsprovide] location: package ws
[wsprovide]     private ws.Picture arg1;
[wsprovide]               ^
[wsprovide] /home/userone/Spring_MTOM_Service/build/ws/jaxws/UploadPictureAttachment.java:35: cannot find symbol
[wsprovide] symbol  : class Picture
[wsprovide] location: package ws
[wsprovide]     public ws.Picture getArg1() {
[wsprovide]              ^
[wsprovide] /home/userone/Spring_MTOM_Service/build/ws/jaxws/UploadPictureAttachment.java:39: cannot find symbol
[wsprovide] symbol  : class Picture
[wsprovide] location: package ws
[wsprovide]     public void setArg1(ws.Picture newArg1)  {
[wsprovide]                           ^
[wsprovide] 3 errors
      [jar] Building jar: /home/userone/Spring_MTOM_Service/build/Spring_CXF_MTOM_Service_Demo.war

deploy:
     [echo] *******************  Deploying   *********************
     [echo] ********** Spring_CXF_MTOM_Service_Demo.war to /home/userone/boss-as-7.1.0.CR1/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/boss-as-7.1.0.CR1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

post-deploy:
     [echo] *******************  NOTE  *********************
     [echo] ***** You should be able to access your WSDL using Browser now *****
     [echo]                 http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom?wsdl          

BUILD SUCCESSFUL
Total time: 4 seconds

( ( ( ( ( I S S U E – 3 ) ) ) ) ):
Even if you see that there are some exceptions while compiling the WebService using “org.jboss.ws.tools.ant.WSProvideTask” that “UploadPictureAttachment.java” is not compiling properly and seeing many compilation errors…But i ignored these errors still everything was OK. And the service deployed Successfully.

Step12). As soon as the service is deployed on JBoss AS7 you will see the following kind of output in the JBoss console :

22:19:47,218 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) Starting deployment of "Spring_CXF_MTOM_Service_Demo.war"
22:19:47,258 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-5) Add Service
 id=ws.SpringCXFMtom
 address=http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom
 implementor=ws.SpringCXFMtom
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://ws/}SpringCXFMtomService
 portName={http://ws/}SpringCXFMtomServicePort
 wsdlLocation=null
 mtomEnabled=false
22:19:47,259 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-5) register: jboss.ws:context=Spring_CXF_MTOM_Service_Demo,endpoint=ws.SpringCXFMtom
22:19:47,266 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-5) Creating Service {http://ws/}SpringCXFMtomService from class ws.SpringCXFMtomIntf
22:19:47,285 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-5) Setting the server's publish address to be http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom
22:19:47,292 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-5) WSDL published to: file:/home/userone/boss-as-7.1.0.CR1/standalone/data/wsdl/Spring_CXF_MTOM_Service_Demo.war/SpringCXFMtomService.wsdl
22:19:47,295 INFO  [org.jboss.as.webservices] (MSC service thread 1-1) JBAS015539: Starting service jboss.ws.endpoint."Spring_CXF_MTOM_Service_Demo.war"."ws.SpringCXFMtom"
22:19:47,301 INFO  [org.jboss.web] (MSC service thread 1-3) registering web context: /Spring_CXF_MTOM_Service_Demo
22:19:47,312 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018565: Replaced deployment "Spring_CXF_MTOM_Service_Demo.war" with deployment "Spring_CXF_MTOM_Service_Demo.war"

Step13). Now run the command “ant run” in your shell prompt to run the WebService client to access the WebService operation. “ant run” command will automatically build the client side artifacts using the “wsconsume” ant task as well and then it will run the client:

[userone@localhost CXFTimeoutClientDemo]$ ant run
Buildfile: /home/userone/Spring_MTOM_Service/build.xml

client:
   [delete] Deleting directory /home/userone/Spring_MTOM_Service/clientStuff
[wsconsume] Consuming wsdl: http://localhost:8080/Spring_CXF_MTOM_Service_Demo/SpringCXFMtom?wsdl
[wsconsume] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
[wsconsume] log4j:WARN Please initialize the log4j system properly.
[wsconsume] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
      [jar] Building jar: /home/userone/Spring_MTOM_Service/clientStuff/Spring_CXF_MTOM_Client.jar
      [zip] Updating zip: /home/userone/Spring_MTOM_Service/clientStuff/Spring_CXF_MTOM_Client.jar

run:
    [javac] /home/userone/Spring_MTOM_Service/build.xml:121: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 1 source file to /home/userone/Spring_MTOM_Service/clientStuff
      log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
      log4j:WARN Please initialize the log4j system properly.
      log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
      
      	Got Client: org.apache.cxf.jaxws.JaxWsClientProxy@7b5c9f9d
      
      	 dataHandler.getContentType() = image/jpeg
      
      	client.uploadPictureAttachment(attachmentName,picture): File Uploaded on JBoss AS7 Server Location: /home/userone/boss-as-7.1.0.CR1/standalone/log/one.jpg

BUILD SUCCESSFUL
Total time: 9 seconds

Note: Above 3 Issues need to be fixed.

As everything is working fine and we are able to upload a file on the Server.

BUT still as mentioned in the above article that there are 3 Issues which need to be checked by JBoss Folks seems there is something is broken with the WSProvide task while compiling the “javax.xml.bind.annotation.XmlMimeType;” annotations.

.
.
Thanks 🙂
MiddlewareMagic Team


Developing Spring based CXF WebService in JBoss AS7

Hi,

C O N G R A T U L A T I O N S …Awaited “jboss-as-7.1.0.CR1” is released recently. So here we are going to test a Simple WebService in JBoss AS7.1 CR1. In this sample we will see how to develop a Simple Apache CXF based webService with the help of Spring. Also we will see how to use a Simple Spring WebService Client to reduce the code at the client side and the utilize the beans feature provided by the Spring.

More informations about the CXF Spring Client can be found in the following link:
http://cxf.apache.org/docs/writing-a-service-with-spring.html

Highlights of Article

Point-1). In this example we are going to use “jboss-as-7.1.0.CR1” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). We will see how to use the cxf-servlet.xml file.

Point-3). How to use the Spring ApplicationContext and ClassPathXmlApplicationContext to initialize the jaxws based beans for Service client.

Point-4). As the client is going to use spring features to access the web service so we will need to make sure that “spring-2.5.6.jar” jar is present in the client classpath. This jar can be downloaded from the following link:
http://repo1.maven.org/maven2/org/springframework/spring/2.5.6/spring-2.5.6.jar

Developing Spring CXF WebService

Step1). Create a Directory somewhere in your filesystem like “/home/userone/CXF_Spring_Demo/” and then create “src” directory inside “/home/userone/CXF_Spring_Demo/”.

Step2). Now we will write the Web Service Endpoint Interface “Spring_CXF_Service_Intf.java” inside “/home/userone/CXF_Spring_Demo/src” as following:

package ws;
import javax.jws.WebService;

@WebService
public interface Spring_CXF_Service_Intf
  {
      public String sayHello(String name);
  }

Step4). Now we will provide the WebService Implementation class “Spring_CXF_Service.java” inside “/home/userone/CXF_Spring_Demo/src” as following:

package ws;
import javax.jws.WebService;

@WebService(endpointInterface = "ws.Spring_CXF_Service_Intf")
public class Spring_CXF_Service implements Spring_CXF_Service_Intf
  {
      public String sayHello(String name)
        {
            System.out.println("[Spring_CXF_Service] sayHello("+name+") invoked.");
            return "Hello World !!! Mr. "+name;
        }
  }

Step4). We will write the “web.xml” inside “/home/userone/CXF_Spring_Demo/src” as following (practically this file is almost empty):

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

</web-app>

Step5). We will write the “cxf-servlet.xml” inside “/home/userone/CXF_Spring_Demo/src” to define “jaxws:endpoint” and it’s implementation class details as following:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

        <!--
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
        -->

        <!-- In My case i am putting "cxf-servlet.xml" inside WEB-INF directory -->
	<jaxws:endpoint 
	  id="cxfSpringServiceHelloWorld" 
	  implementor="client.SpringCXFService" 
	  address="/Spring_CXF_Service" />
	  
</beans>

NOTE: We need to make sure that this “cxf-servlet.xml” file is present inside the “WEB-INF” diectory of our service.

Developing Spring CXF based Client

Step6). Now we will write the WebService Client “Test_CXF_Client.java” inside “/home/userone/CXF_Spring_Demo/src” using CXF standard code as following :

package client;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test_CXF_Client
  {
     public static void main(String ar[]) throws Exception
      {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"client-beans.xml"});
        SpringCXFServiceIntf client = (SpringCXFServiceIntf) context.getBean("testClient");
        System.out.println("ntGot Client: "+client);         
        System.out.println("ntclient.sayHello(Middleware Magic): "+client.sayHello("Middleware Magic"));                
      }
  }

Step7). We will create the “client-beans.xml” XML file inside “/home/userone/CXF_Spring_Demo/src” directory as following. (This file name may be anything)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <jaxws:client id="testClient"
                  serviceClass="client.SpringCXFServiceIntf"
                  address="http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service" />
</beans>

NOTE: The file name “client-beans.xml” may be anything but we need to make sure that this file is present in the client classpath.
NOTE: client-beans.xml file should be written only when you have run the wsconsume anttask to generate Client side artifacts for your WebService, Because the classes like “client.SpringCXFServiceIntf” will be generated at client side only after generating the client side artifacts.

Step8). As our weservice client is going to use the spring features to access the web service so we will need to make sure that the following JAR is present in the client classpath and place it inside “/home/userone/CXF_Spring_Demo/src” directory. This file can be downloaded from the following link:
http://repo1.maven.org/maven2/org/springframework/spring/2.5.6/spring-2.5.6.jar

Building, Deploying and Testing

Step9). As everything is done so we will write a ant build script in order to build/deploy/run and test the WebService and Basic Authentication, So create a file “build.xml” inside “/home/userone/CXF_Spring_Demo/” as following:

<project name="JBoss_Service" default="post-deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="war.tmp.name" value="Spring_CXF_Service_Demo" />
<property name="war.name" value="Spring_CXF_Service_Demo.war" />
<property name="src.dir" value="src" />
<property name="client.src.dir" value="${basedir}/clientSrc" />
<property name="output.dir" value="build" />
<property name="client.dir" value="${basedir}/clientStuff" />
<property name="client.jar.name" value="Spring_CXF_Client.jar" />
 
   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
   </path>

   <path id="client.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
     <fileset dir="${src.dir}">
        <include name="**/spring-2.5.6.jar"/>
        <!-- This Jar is needed at client side and can be downloaded from the following link -->
        <!-- http://repo1.maven.org/maven2/org/springframework/spring/2.5.6/spring-2.5.6.jar    -->
     </fileset>  
     <fileset dir="${client.dir}">
        <include name="*.jar"/>
     </fileset>  
   </path>

   <taskdef name="wsprovide" classname="org.jboss.ws.tools.ant.WSProvideTask">
       <classpath refid="jboss.classpath"/>
   </taskdef>

   <taskdef name="wsconsume" classname="org.jboss.ws.tools.ant.WSConsumeTask">
       <classpath refid="jboss.classpath"/>
   </taskdef>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <mkdir dir="${output.dir}/${war.tmp.name}/META-INF"/>
           <mkdir dir="${output.dir}/${war.tmp.name}/WEB-INF/classes"/>
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}"/>
        </target>
	 
    <target name="build" depends="init">
       <javac srcdir="${src.dir}" destdir="${output.dir}/${war.tmp.name}/WEB-INF/classes"  includes="*.java" excludes="Test_CXF_Client.java" classpathref="jboss.classpath"/>
        <copy todir="${output.dir}/${war.tmp.name}/WEB-INF">
	  <fileset dir="${basedir}/src">
	      <include name="web.xml"/>
	      <include name="cxf-servlet.xml"/>
	  </fileset>
	</copy>   
       <wsprovide
        	fork="false"
        	keep="true"
        	destdir="${output.dir}"
        	resourcedestdir="${output.dir}/${war.tmp.name}/WEB-INF/wsdl"
        	sourcedestdir="${output.dir}"
        	genwsdl="true" 
        	verbose="true"
        	sei="ws.Spring_CXF_Service">
            	<classpath>
                	  <pathelement path="${output.dir}/${war.tmp.name}/WEB-INF/classes"/>
            	</classpath>
      </wsprovide>
      <jar jarfile="${output.dir}/${war.name}" basedir="${output.dir}/${war.tmp.name}" compress="true" />  
      <delete dir="${output.dir}/${war.tmp.name}" />
    </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying   *********************" />  
            <echo message="********** ${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
        </target>
  
        <target name="post-deploy" depends="deploy">
            <echo message="*******************  NOTE  *********************" />
            <echo message="***** You should be able to access your WSDL using Browser now *****" />
            <echo message="                http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service?wsdl          " />
        </target>  

        <target name="client">
             <delete dir="${client.dir}" />
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service?wsdl"
                      wsdl="http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service?wsdl">
            </wsconsume>
            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" />  
            <zip destfile="${client.dir}/${client.jar.name}" 
                 update="true"> 
                 <fileset dir="${src.dir}"> 
                       <include name="client-beans.xml" /> 
                 </fileset> 
            </zip> 
       </target>

        <target name="run" depends="client">
            <javac srcdir="${src.dir}" destdir="${client.dir}"  includes="Test_CXF_Client.java" classpathref="client.classpath"/>
            <java classname="client.Test_CXF_Client"  >
	        <classpath>
	            <pathelement location="${client.dir}"/>
	            <path refid="client.classpath"/>
	        </classpath>
                <arg value="http://localhost:8080/Spring_CXF_Service_Demo"/>
            </java>
        </target>  

</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script is to point to your own JBoss AS7 directory home directory.

Step10). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step11). Run the command “ant” or “ant post-deploy” which will internally build the WebService and deploy it inside the JBoss AS7 standalone profile.

[userone@localhost CXFTimeoutClientDemo]$ ant
Buildfile: /home/userone/CXF_Spring_Demo/build.xml

init:
   [delete] Deleting directory /home/userone/CXF_Spring_Demo/build
    [mkdir] Created dir: /home/userone/CXF_Spring_Demo/build
    [mkdir] Created dir: /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo/META-INF
    [mkdir] Created dir: /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo/WEB-INF/classes
   [delete] Deleting directory /home/userone/CXF_Spring_Demo/clientStuff
    [mkdir] Created dir: /home/userone/CXF_Spring_Demo/clientStuff

build:
    [javac] Compiling 2 source files to /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo/WEB-INF/classes
     [copy] Copying 2 files to /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo/WEB-INF
[wsprovide] Generating from endpoint: ws.Spring_CXF_Service
[wsprovide] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
[wsprovide] log4j:WARN Please initialize the log4j system properly.
[wsprovide] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[wsprovide] java2ws -s /home/userone/CXF_Spring_Demo/build -classdir /home/userone/CXF_Spring_Demo/build -d /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo/WEB-INF/wsdl -verbose -wsdl -cp ::::::: -wrapperbean -createxsdimports ws.Spring_CXF_Service
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide] 
      [jar] Building jar: /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo.war
   [delete] Deleting directory /home/userone/CXF_Spring_Demo/build/Spring_CXF_Service_Demo

deploy:
     [echo] *******************  Deploying   *********************
     [echo] ********** Spring_CXF_Service_Demo.war to /home/userone/jboss-as-7.1.0.CR1/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.CR1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

post-deploy:
     [echo] *******************  NOTE  *********************
     [echo] ***** You should be able to access your WSDL using Browser now *****
     [echo]                 http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service?wsdl          

BUILD SUCCESSFUL
Total time: 5 seconds

Step12). As soon as the service is deployed on JBoss AS7 you will see the following kind of output in the JBoss console :

12:27:16,426 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) Starting deployment of "Spring_CXF_Service_Demo.war"
12:27:16,479 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-4) Add Service
 id=ws.Spring_CXF_Service
 address=http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service
 implementor=ws.Spring_CXF_Service
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://ws/}Spring_CXF_ServiceService
 portName={http://ws/}Spring_CXF_ServicePort
 wsdlLocation=null
 mtomEnabled=false
12:27:16,479 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-4) register: jboss.ws:context=Spring_CXF_Service_Demo,endpoint=ws.Spring_CXF_Service
12:27:16,491 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-4) Creating Service {http://ws/}Spring_CXF_ServiceService from class ws.Spring_CXF_Service_Intf
12:27:16,533 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-4) Setting the server's publish address to be http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service
12:27:16,548 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-4) WSDL published to: file:/home/userone/jboss-as-7.1.0.CR1/standalone/data/wsdl/Spring_CXF_Service_Demo.war/Spring_CXF_ServiceService.wsdl
12:27:16,550 INFO  [org.jboss.as.webservices] (MSC service thread 1-1) JBAS015539: Starting service jboss.ws.port-component-link
12:27:16,555 INFO  [org.jboss.as.webservices] (MSC service thread 1-1) JBAS015539: Starting service jboss.ws.endpoint."Spring_CXF_Service_Demo.war"."ws.Spring_CXF_Service"
12:27:16,571 INFO  [org.jboss.web] (MSC service thread 1-7) registering web context: /Spring_CXF_Service_Demo
12:27:16,594 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018565: Replaced deployment "Spring_CXF_Service_Demo.war" with deployment "Spring_CXF_Service_Demo.war"

Step13). Now run the command “ant run” in your shell prompt to run the WebService client to access the WebService operation. “ant run” command will automatically build the client side artifacts using the “wsconsume” ant task as well and then it will run the client:

[userone@localhost CXFTimeoutClientDemo]$ ant run
Buildfile: /home/userone/CXF_Spring_Demo/build.xml

client:
   [delete] Deleting directory /home/userone/CXF_Spring_Demo/clientStuff
[wsconsume] Consuming wsdl: http://localhost:8080/Spring_CXF_Service_Demo/Spring_CXF_Service?wsdl
[wsconsume] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
[wsconsume] log4j:WARN Please initialize the log4j system properly.
[wsconsume] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
      [jar] Building jar: /home/userone/CXF_Spring_Demo/clientStuff/Spring_CXF_Client.jar
      [zip] Updating zip: /home/userone/CXF_Spring_Demo/clientStuff/Spring_CXF_Client.jar

run:
     [javac] Compiling 1 source file to /home/userone/CXF_Spring_Demo/clientStuff
      log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
      log4j:WARN Please initialize the log4j system properly.
      log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
      
      	Got Client: org.apache.cxf.jaxws.JaxWsClientProxy@6ed3199e
      
      	client.sayHello(Middleware Magic): Hello World !!! Mr. Middleware Magic

BUILD SUCCESSFUL
Total time: 9 seconds

.
.
Thanks
MiddlewareMagic Team


Copyright © 2010-2012 Middleware Magic. All rights reserved. |