WebService

RestEasy WebService & RestEasy Client with CDI injection in JBoss AS7


As we are already aware that JBossAS 7.1 is a Fully EE6 certified Application Server. It provides implementations of most needed features like “RestEasy WebService” And “CDI” injection. You might have already seen/read some of the demos of RestEast webservices in our previous articles. But here in this article we are going to focus on following points .

Point-1). How to developand use the JAX-RS resteasy implementations and various annotations associated with it on JBoss AS7.1.1.Final.

Point-2). How to use the CDI Injection of @javax.inject.Named Beans using @javax.enterprise.context.ApplicationScoped inside our RestEasy WebServices. And will see that why do we need “beans.xml” file.

Point-3). How and why to use the annotations like @javax.xml.bind.annotation.XmlRootElement.

Point-4). How to write a Pure RestEasy Standalone Client to access the RestEasy WebService.

The Source Code of this Demo can be Downloaded from the following link: “Github”
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/RestfulService_With_CDI_AS7

Writing RestEasy WebService with CDI Injection.

Step-1). Create a directory somewhere in your file system like “home/userone/RestfulService_With_CDI_AS7″ then in this directory create a “src” directory where we will place all our source codes and application components.

Step-2). Write a Simple Class “Customer.java” inside “home/userone/RestfulService_With_CDI_AS7/src” with the help of “@javax.xml.bind.annotation.XmlRootElement” annotation sothat its value can be represented as XML element in an XML document.

package test;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

	private int id;
	private String name;
	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
}

Step-3). As above write another Simple Class “Customers.java” inside “home/userone/RestfulService_With_CDI_AS7/src” with the help of “@javax.xml.bind.annotation.XmlRootElement” annotation sothat its value also can be represented as XML element in an XML document.

package test;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.*;
@XmlRootElement
public class Customers {

	private List customer;

	public List getCustomer() {
		return customer;
	}

	public void setCustomer(List customer) {
		this.customer = customer;
	}
}

Step-4). Now we will write “TestBean.java” inorder to populate it’s property “java.util.TreeMap” with the Customer Objects. Write the “TestBean.java” program inside “home/userone/RestfulService_With_CDI_AS7/src”

package beans;
import java.io.Serializable;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import java.util.TreeMap;
import test.Customer;

@Named
@ApplicationScoped
public class TestBean implements Serializable
   {
    private static final long serialVersionUID = 1L;
    private TreeMap customerMap;

    public TestBean()
         {
           System.out.println("\n\t TestBean which is CDI Bean instantiated.");
           customerMap=new TreeMap();
         }

    public TreeMap getCustomerMap()
         {
            System.out.println("\n\t[TestBean] getCustomerMap() called.");
            return customerMap;
         }

    public void setCustomerMap(TreeMap customerMap)
         {
           System.out.println("\n\t[TestBean] setCustomerMap(TreeMap) called.");
           this.customerMap = customerMap;
         }
   }

Step-5). As in the above TestBean we have used the @Named annotation and we have declared it’s scope as “ApplicationScoped” so now we will create a “beans.xml” file which is finally going to be placed inside “WEB-INF” directory of our webapplication for the CDI to wrok. So here we will need to create a file with name “beans.xml” inside “home/userone/RestfulService_With_CDI_AS7/src” as following:

*** NOTE: An application that uses CDI must have a file named beans.xml. The file can be completely empty (it has content only in certain limited situations), but it must be present.

<beans 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/beans_1_0.xsd">

</beans>

Step-6). In order to develop RestEasy WebService we should provide a class which extends “javax.ws.rs.core.Application” so write a Program “MyRestService.java” inside “home/userone/RestfulService_With_CDI_AS7/src” as following:

package ws.test;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("test")
public class MyRestService  extends Application {

}

Step-7). Now the Most important Step Here we will write a Class “CustomersResource.java” with the help of “javax.ws.rs.*” packages in order to process the Client Requests. so write a Program “CustomersResource.java” inside “home/userone/RestfulService_With_CDI_AS7/src” as following:

package test;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

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.servlet.ServletContext;
import javax.ws.rs.core.Context;
import javax.inject.Inject;

@Produces("application/xml")
@Path("customers")
public class CustomersResource {

        @Inject
        private beans.TestBean testBean;

	private TreeMap customerMap = new TreeMap();

	public CustomersResource() {
                System.out.println("[CustomerResource] Instantiated  "+this);
		Customer customer1 = new Customer();
		customer1.setId(1111);
		customer1.setName("CustomerOne");
		customer1.setAddress("Bombay, India");

		Customer customer2 = new Customer();
		customer2.setId(2222);
		customer2.setName("CustomerTwo");
		customer2.setAddress("Pune, India");

		Customer customer3 = new Customer();
		customer3.setId(3333);
		customer3.setName("CustomerThree");
		customer3.setAddress("Bangalore, India");

                customerMap.put(customer1.getId(),customer1);
                customerMap.put(customer2.getId(),customer2);
                customerMap.put(customer3.getId(),customer3);

                if(testBean!=null)
                    {
                       System.out.println("[CustomersResource] testBean NOT NULL "+testBean);
                       testBean.setCustomerMap(customerMap);
                    }
                else
                    {
                       System.out.println("[CustomersResource] testBean IS NULL");
                    }
	}

	@GET
	@Produces(MediaType.APPLICATION_XML)
	@Path("all")
	public Customers getCustomers() {
		List customers = new ArrayList();
		customers.addAll(testBean.getCustomerMap().values());
                Customers allCustomers=new Customers();
                allCustomers.setCustomer(customers);
                return allCustomers;
	}

	@GET
	@Path("{id}")
	public Customer getCustomer(@PathParam("id") int customerId) {
		return customerMap.get(customerId);
	}

	public String addDefaultCustomer(Customer customer) {
		customerMap.put(customer.getId(), customer);
		return "Customer ID: " +  customer.getId() +" Name: "+ customer.getName()+" Address: "+customer.getAddress();
	}

	@POST
	@Path("add")
	@Produces(MediaType.APPLICATION_XML)
	@Consumes("application/x-www-form-urlencoded")
	public Customer addCustomer(@FormParam("custId")int id,@FormParam("custName")String name,@FormParam("custAddress")String address) {
		Customer customer = new Customer();
                customer.setId(id);
                customer.setName(name);
                customer.setAddress(address);
                customerMap.put(customer.getId(),customer);
                testBean.setCustomerMap(customerMap);
		return customer;
	}

}

Step-8). Now we will write following kind of JSP file “index.jsp” inside “home/userone/RestfulService_With_CDI_AS7/src” in order to allow users to provide/enter the customer details.


    CDI Demo
<table border="10%">
<form action="test/customers/add" method="POST"></form>
<tbody>
<tr>
<td>Customer ID:</td>
<td> <input name="custId" type="text" /></td>
</tr>
<tr>
<td>Customer Name:</td>
<td> <input name="custName" type="text" /></td>
</tr>
<tr>
<td>Customer Address:</td>
<td> <input name="custAddress" type="text" /></td>
</tr>
<tr>
<td><input type="submit" value="Add Customer" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
</tbody>
</table>

Step-9). Now write the following kind of “web.xml” file inside “home/userone/RestfulService_With_CDI_AS7/src” directord make sure that you are using the web.xml 3.0 version XSD (web-app_3_0.xsd) declaration in your web.xml file as following


        javax.ws.rs.core.Application
        javax.ws.rs.core.Application

        javax.ws.rs.core.Application
        /*

Step-10). Now we will write the ANT “build.xml” file inside “home/userone/RestfulService_With_CDI_AS7″ directory in order to build and deploy and test our WebService .


           <!-- Need to place at lease one empty "beans.xml" file inside WEB-INF -->

Step-11). 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%
.

Step-12). Now once the PATH is set In the command/Shell prompt you can move inside the directory “home/userone/RestfulService_With_CDI_AS7″ and then run the ant to build/deploy the webservice. by running the command “ant”

[userone@localhost RestfulService_With_CDI_AS7]$ ant
Buildfile: build.xml

init:
   [delete] Deleting directory /userone/RestfulService_With_CDI_AS7/build
    [mkdir] Created dir: /userone/RestfulService_With_CDI_AS7/build
    [mkdir] Created dir: /userone/RestfulService_With_CDI_AS7/tmp

build:
    [mkdir] Created dir: /userone/RestfulService_With_CDI_AS7/tmp/WEB-INF/classes
    [javac] Compiling 5 source files to /userone/RestfulService_With_CDI_AS7/tmp/WEB-INF/classes
     [copy] Copying 1 file to /userone/RestfulService_With_CDI_AS7/tmp
     [copy] Copying 1 file to /userone/RestfulService_With_CDI_AS7/tmp
     [copy] Copying 1 file to /userone/RestfulService_With_CDI_AS7/tmp/WEB-INF/classes
     [copy] Copying 1 file to /userone/RestfulService_With_CDI_AS7/tmp/WEB-INF/classes
     [copy] Copying 1 file to /userone/RestfulService_With_CDI_AS7/tmp/WEB-INF
      [jar] Building jar: /userone/RestfulService_With_CDI_AS7/tmp/RestServiceWithCDI.war
     [copy] Copying 1 file to /userone/RestfulService_With_CDI_AS7/build

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

BUILD SUCCESSFUL
Total time: 2 seconds

Testing The RestEasy WebService from WebBrowser

Step-13). Once the WebService is deployed successfully you can access it using the following URL: “http://localhost:8080/RestServiceWithCDI//index.jsp” As following:

RestEasyWebService_CDI_Inserting Customer Data

If you want to access all the Customers Details then access te following URL “http://localhost:8080/RestServiceWithCDI/test/customers/all” :

RestEasyWebService_With_CDI_Retrieving all Customers Record

Writing and Testing a Pure RestEasy WebService Client

Step-13). Now we are going to use our own Standalone RestEasy WebService Client in order to access the WebService. So write program with name “RestEasyClient.java” inside “home/userone/RestfulService_With_CDI_AS7/src” directory as following:

package client;
import java.io.*;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;

public class RestEasyClient
{
      public static void main(String ar[]) throws Exception
       {
        String url="http://localhost:8080/RestServiceWithCDI/test/customers/all";
        MediaType mediaType=MediaType.APPLICATION_XML_TYPE;
        String result = "";

        try
        {
            ClientRequest request = new ClientRequest(url);
            request.accept(mediaType);
            ClientResponse response = request.get(String.class);
            if (response.getStatus() != 200)
            {
                System.out.println("***** BAD RESPONSE *****");
                throw new RuntimeException("Request Processing Failed with HTTP status: "+ response.getStatus());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getEntity().getBytes())));
            String output = null;
            while ((output = br.readLine()) != null)
            {
                result = result+output+"\n";
            }

            result=result.replaceAll("><",">\n<");
            System.out.println("\n\n********** RESULT **********\n"+result);
        }
        catch (Exception e)
        {
            System.err.println("\n\t Exception Occured: "+e);
            e.printStackTrace();
        }
    }
}

Step-14). Now run the command “ant client” in order compile and run the Client program from the following directory “home/userone/RestfulService_With_CDI_AS7″ as following:

[userone@localhost RestfulService_With_CDI_AS7]$ ant client
Buildfile: build.xml

client:
     [echo] *******************  Client Accessing RestEasy Service *********************
    [javac] Compiling 6 source files to /NotBackedUp/Downloads/RestfulService_With_CDI_AS7/build
     [java] log4j:WARN No appenders could be found for logger (org.jboss.resteasy.plugins.providers.DocumentProvider).
     [java] log4j:WARN Please initialize the log4j system properly.
     [java] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
     [java]
     [java]
     [java] ********** RESULT **********
     [java] <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     [java] <customers>
     [java] <customer>
     [java] <address>Bombay, India</address>
     [java] <id>1111</id>
     [java] <name>CustomerOne</name>
     [java] </customer>
     [java] <customer>
     [java] <address>Pune, India</address>
     [java] <id>2222</id>
     [java] <name>CustomerTwo</name>
     [java] </customer>
     [java] <customer>
     [java] <address>Bangalore, India</address>
     [java] <id>3333</id>
     [java] <name>CustomerThree</name>
     [java] </customer>
     [java] <customer>
     [java] <address>Pune, India</address>
     [java] <id>8888</id>
     [java] <name>MiddlewareMagic</name>
     [java] </customer>
     [java] </customers>
     [java] 

BUILD SUCCESSFUL
Total time: 3 seconds

.
.
Thanks :)
Middleware Magic Team


Apache CXF Service with Complex Type in JBoss AS7

Hi,

JBoss AS7 uses the JBossWS-CXF as default webservice provider which provides most of the features coming with Apache CXF (including WS-Security, WS-Policy, WS-Addressing, WS-ReliableMessaging, basic WS-Trust, MTOM) as well as common JBossWS stack features like endpoint metrics, record management, endpoint address rewrite, etc.

In this example we will see how we can use a Complex DataType inside our CXF Based WebService and how we can enable the client side Logging for the incoming and outgoing SOAP Request/Responses, which are most desired for trouble shooting and debugging purpose.

In this example we will mainly focus on following points

Point-1). How to use the JBoss Specific Tools to build the WebServices. The details of these tools like “wsconsume” and “wsprovide” are mentioned in the following link: https://docs.jboss.org/author/display/JBWS/JAX-WS+Tools

Point-2). Where we need to place the “log4j.properties fileat the client side in order to generate a separate Log file containing the SOAP request/response.

Point-3). How to use “org.apache.cxf.interceptor.LoggingInInterceptor” and “org.apache.cxf.interceptor.LoggingOutInterceptor” at client side.

Point-4). Here we are using JBoss AS7.1.0 CR1b which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads. I am using “jboss-as-7.1.0.CR1bb” in this demo.

Point-5). How to use the JAXB Annotations like “XmlAccessorType”, “XmlAccessType” and “XmlType” to define and use the Complex Datatypes inside our webservice using the “SOAPBinding.ParameterStyle.BARE”

Point-6). Source Code of this Demo is available at https://github.com/jaysensharma/MiddlewareMagicDemos

Developing Simple WebService

Step-1). Create a directory somewhere in your file system as “/home/userone/ComplexTypes_CXF_WebService_JBossAS7″ then create another directory “src” inside the “/home/userone/ComplexTypes_CXF_WebService_JBossAS7″.

Step-2). Write a simple webservice implementation pojo class “DemoCXF.java” as following inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7/src”:

package ws;
import javax.jws.WebParam;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService(name = "DemoCXF", serviceName ="DemoCXFService", portName ="DemoCXFPort", targetNamespace="http://test.org")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) 

public class DemoCXF
{
  @WebMethod()
  @WebResult(targetNamespace="http://test.org",name="updatedEmployee")
  public Employee processEmployeeSalary(@WebParam(partName = "employee", name = "employee", targetNamespace = "http://test.org")
        Employee emp, @WebParam(partName = "incrementAmount", name = "incrementAmount", targetNamespace = "http://test.org") Long incrementAmount)
  {
    System.out.println("[DemoCXF] Method Invoked....processEmployeeSalary");
    System.out.println("[DemoCXF] Before processing: "+emp);
    long incrementedSalary=emp.getEmpSalary()+incrementAmount;
    emp.setEmpSalary(incrementedSalary);
    System.out.println("[DemoCXF] After processing: "+emp);

    // Some Business Logic to Store the Employee's Updated Details in Database or Messaging System.

    return emp;
  }
}

Step-3). Write a simple Complex Type “Employee.java” as following inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7/src”:

package ws;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "employee", propOrder = {
    "empName",
    "empNo",
    "empSalary"
})

public class Employee
  {
    public String empName;
    public Long empNo;
    public Long empSalary;

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String value) {
        this.empName = value;
    }

    public Long getEmpNo() {
        return empNo;
    }

    public void setEmpNo(Long value) {
        this.empNo = value;
    }

    public Long getEmpSalary() {
        return empSalary;
    }

    public void setEmpSalary(Long value) {
        this.empSalary = value;
    }

  }

Step-4). Write the “web.xml” file to define the WebService as following inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7/src”

<?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">
  <servlet>
    <servlet-name>DemoCXF</servlet-name>
    <servlet-class>ws.DemoCXF</servlet-class>
  </servlet>  

  <servlet-mapping>
    <servlet-name>DemoCXF</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Step-5). Write the WebService client code “Test_CXF_Client.java” as following inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7/src”:

package client;
import java.net.URL;
import javax.xml.namespace.QName;

// Client side Logging related CXF APIs
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

public class Test_CXF_Client
  {
     public static void main(String ar[]) throws Exception
      {
        String WSDL_URL=ar[0]+"?wsdl";
        DemoCXFService service=new DemoCXFService(new URL(WSDL_URL));
        DemoCXF port=service.getDemoCXFPort();

        /* Following part of code is needed for client side Logging of Soap request/response */
        /* We need to make sure that we place the "log4j.properties" file inside clients classpath */
        Client client = ClientProxy.getClient(port);
        client.getInInterceptors().add(new LoggingInInterceptor());
        client.getOutInterceptors().add(new LoggingOutInterceptor());

        Employee emp=new Employee();
        emp.setEmpNo(1000L);
        emp.setEmpName("MiddlewaremagicEmployee");
        emp.setEmpSalary(6000L);

        System.out.println("\n\nBefore  EmpNo: "+emp.getEmpNo()+",  Name:"+emp.getEmpName()+",  Sal:"+emp.getEmpSalary());
        emp=port.processEmployeeSalary(emp,1000L);
        System.out.println("\n\nAfter   EmpNo: "+emp.getEmpNo()+",  Name:"+emp.getEmpName()+",  Sal:"+emp.getEmpSalary());
      }
  }

Step-5). As we are going to generate the client side logging in a separate log file at client side using CXF APIs so we will need to write a “log4j.properties” file as following inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7/src”:

# Direct log messages to a log file
log4j.rootLogger=INFO, WSClientAppender

log4j.appender.WSClientAppender=org.apache.log4j.ConsoleAppender
log4j.appender.WSClientAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.WSClientAppender.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

NOTE: In this example we are using the “ConsoleAppender” whihc means in the Clients Console (Shell Pormpt) we will be able to see the Incoming and Outgoing soap request/response.

Step-6). Now we will write simple ANT build script “build.xml” which will build / deploy and run the webservice & client as following inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7″:

<project name="JBoss_Complex_Service" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1b" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />

<property name="basedir" value="." />
<property name="war.dir" value="CXFComplexTypeDemoWAR" />
<property name="war.name" value="CXFComplexTypeDemo.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="DemoCXFClient.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="${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.dir}"/>
           <mkdir dir="${output.dir}/${war.dir}/META-INF"/>
           <mkdir dir="${output.dir}/${war.dir}/WEB-INF"/>
           <mkdir dir="${output.dir}/${war.dir}/WEB-INF/classes"/>
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}/META-INF"/>
        </target>

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

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

    </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying   *********************" />
            <echo message="********** ${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy file="${output.dir}/${war.name}" todir="${jboss.home}/standalone/deployments/"/>

            <echo message="*******************  Deployed Successfully   *********************" />
        </target>

        <target name="post-deploy" >
            <echo message="*******************  NOTE  *********************" />
            <echo message="***** You should be able to access your WSDL using Browser now *****" />
            <echo message="                http://localhost:8080/CXFComplexTypeDemo?wsdl          " />
        </target>  

        <target name="client" depends="post-deploy">
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}"/>
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="service.wsdl"
                      wsdl="http://localhost:8080/CXFComplexTypeDemo?wsdl">
            </wsconsume>

            <!-- We need to make sure that log4j.properties is present inside client's classpath-->
            <copy file="${src.dir}/log4j.properties" todir="${client.dir}" />

            <javac srcdir="${src.dir}" destdir="${client.dir}"  includes="Test_CXF_Client.java" classpathref="client.classpath">
	        <classpath>
	            <pathelement location="${client.dir}"/>
	            <path refid="client.classpath"/>
	        </classpath>
            </javac>

            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" /> 

            <!-- Cleaning Client Stuff Directory  -->
            <delete dir="${client.dir}/client"/>
            <delete file="${client.dir}/log4j.properties"/>
       </target>

        <target name="run" depends="client">
            <java classname="client.Test_CXF_Client" fork="true" >
	        <classpath>
	            <pathelement location="${client.dir}/DemoCXFClient.jar"/>
	            <path refid="client.classpath"/>
	        </classpath>
                <arg value="http://localhost:8080/CXFComplexTypeDemo"/>
            </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 to point to your own JBoss AS7 directory.

Point-7). Now Start your JBoss Profile as following from inside the directory “/home/userone/jboss-as-7.1.0.CR1b/bin”:

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

Step-8). 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%

Step-9). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/ComplexTypes_CXF_WebService_JBossAS7″ and then run the ant to build and deploy the WebService application on your JBoss Standalone full profile, by running the command “ant deploy”

[userone@localhost ComplexTypes_CXF_WebService_JBossAS7]$ ant deploy
Buildfile: build.xml

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

build:
    [javac] Compiling 2 source files to /home/userone/ComplexTypes_CXF_WebService_JBossAS7/build/CXFComplexTypeDemoWAR/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/ComplexTypes_CXF_WebService_JBossAS7/build/CXFComplexTypeDemoWAR/WEB-INF
[wsprovide] Generating from endpoint: ws.DemoCXF
[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/ComplexTypes_CXF_WebService_JBossAS7/build -classdir /home/userone/ComplexTypes_CXF_WebService_JBossAS7/build -d /home/userone/ComplexTypes_CXF_WebService_JBossAS7/build/CXFComplexTypeDemoWAR/WEB-INF/wsdl -verbose -wsdl -cp ::::::::: -wrapperbean -createxsdimports ws.DemoCXF
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide]
      [jar] Building jar: /home/userone/ComplexTypes_CXF_WebService_JBossAS7/build/CXFComplexTypeDemo.war

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

BUILD SUCCESSFUL
Total time: 5 seconds

As soon as the WebService will be deployed on the JBoss AS7 you will see the following kind of output on your JBoss Console (STDOUT):

15:53:37,164 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) Starting deployment of "CXFComplexTypeDemo.war"
15:53:37,203 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-5) Add Service
 id=DemoCXF
 address=http://localhost:8080/CXFComplexTypeDemo
 implementor=ws.DemoCXF
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://test.org}DemoCXFService
 portName={http://test.org}DemoCXFPort
 wsdlLocation=null
 mtomEnabled=false
15:53:37,204 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-5) register: jboss.ws:context=CXFComplexTypeDemo,endpoint=DemoCXF
15:53:37,213 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-5) Creating Service {http://test.org}DemoCXFService from class ws.DemoCXF
15:53:37,238 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-5) Setting the server's publish address to be http://localhost:8080/CXFComplexTypeDemo
15:53:37,247 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-5) WSDL published to: file:/home/userone/jboss-as-7.1.0.CR1b/standalone/data/wsdl/CXFComplexTypeDemo.war/DemoCXFService.wsdl
15:53:37,251 INFO  [org.jboss.as.webservices] (MSC service thread 1-8) JBAS015539: Starting service jboss.ws.endpoint."CXFComplexTypeDemo.war".DemoCXF
15:53:37,260 INFO  [org.jboss.web] (MSC service thread 1-8) registering web context: /CXFComplexTypeDemo
15:53:37,268 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018565: Replaced deployment "CXFComplexTypeDemo.war" with deployment "CXFComplexTypeDemo.war"

Step-10). Now we will try to compile and run the WebService Client application by running the command “ant run”

[userone@localhost ComplexTypes_CXF_WebService_JBossAS7]$ ant run
Buildfile: build.xml

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

client:
   [delete] Deleting directory /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff
    [mkdir] Created dir: /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff
[wsconsume] Consuming wsdl: http://localhost:8080/CXFComplexTypeDemo?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.
     [copy] Copying 1 file to /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff
    [javac] Compiling 1 source file to /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff
      [jar] Building jar: /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff/DemoCXFClient.jar
   [delete] Deleting directory /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff/client
   [delete] Deleting: /home/userone/ComplexTypes_CXF_WebService_JBossAS7/clientStuff/log4j.properties

run:
     [java] Feb 4, 2012 3:54:51 PM client.DemoCXFService <clinit>
     [java] INFO: Can not initialize the default wsdl from service.wsdl
     [java] 15:54:52,844  INFO ReflectionServiceFactoryBean:366 - Creating Service {http://test.org}DemoCXFService from WSDL: http://localhost:8080/CXFComplexTypeDemo?wsdl
     [java]
     [java]
     [java] Before  EmpNo: 1000,  Name:MiddlewaremagicEmployee,  Sal:6000
     [java] 15:54:53,275  INFO LoggingOutInterceptor:151 - Outbound Message
     [java] ---------------------------
     [java] ID: 1
     [java] Address: http://localhost:8080/CXFComplexTypeDemo
     [java] Encoding: UTF-8
     [java] Content-Type: text/xml
     [java] Headers: {Accept=[*/*], SOAPAction=[""]}
     [java] Payload:
            <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
             <soap:Body>
                  <ns2:employee xmlns:ns2="http://test.org">
                      <empName>MiddlewaremagicEmployee</empName>
                      <empNo>1000</empNo>
                      <empSalary>6000</empSalary>
                  </ns2:employee>
                  <ns2:incrementAmount xmlns:ns2="http://test.org">1000</ns2:incrementAmount>
              </soap:Body>
            </soap:Envelope>
     [java] --------------------------------------
     [java] 15:54:53,289  INFO LoggingInInterceptor:151 - Inbound Message
     [java] ----------------------------
     [java] ID: 1
     [java] Response-Code: 200
     [java] Encoding: UTF-8
     [java] Content-Type: text/xml;charset=UTF-8
     [java] Headers: {Content-Length=[268], content-type=[text/xml;charset=UTF-8], Date=[Sat, 04 Feb 2012 10:24:52 GMT], Server=[Apache-Coyote/1.1]}
     [java] Payload:
            <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
               <soap:Body>
                  <ns2:updatedEmployee xmlns:ns2="http://test.org">
                      <empName>MiddlewaremagicEmployee</empName>
                      <empNo>1000</empNo>
                      <empSalary>7000</empSalary>
                  </ns2:updatedEmployee>
               </soap:Body>
            </soap:Envelope>
     [java] --------------------------------------
     [java]
     [java]
     [java] After   EmpNo: 1000,  Name:MiddlewaremagicEmployee,  Sal:7000

BUILD SUCCESSFUL
Total time: 9 seconds

Step-11). The Generated WSDL File will look something like following :

http://localhost:8080/CXFComplexTypeDemo?wsdl

<?xml version='1.0' encoding='UTF-8'?><wsdl:definitions name="DemoCXFService" targetNamespace="http://test.org" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://test.org" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <wsdl:types>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://test.org" xmlns="http://test.org" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:complexType name="employee">
    <xs:sequence>
      <xs:element minOccurs="0" name="empName" type="xs:string"/>
      <xs:element minOccurs="0" name="empNo" type="xs:long"/>
      <xs:element minOccurs="0" name="empSalary" type="xs:long"/>
    </xs:sequence>
  </xs:complexType>
  <xs:element name="employee" nillable="true" type="employee"/>
  <xs:element name="incrementAmount" nillable="true" type="xs:long"/>
  <xs:element name="updatedEmployee" nillable="true" type="employee"/>
</xs:schema>
  </wsdl:types>
  <wsdl:message name="processEmployeeSalaryResponse">
    <wsdl:part element="tns:updatedEmployee" name="updatedEmployee">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="processEmployeeSalary">
    <wsdl:part element="tns:employee" name="employee">
    </wsdl:part>
    <wsdl:part element="tns:incrementAmount" name="incrementAmount">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="DemoCXF">
    <wsdl:operation name="processEmployeeSalary">
      <wsdl:input message="tns:processEmployeeSalary" name="processEmployeeSalary">
    </wsdl:input>
      <wsdl:output message="tns:processEmployeeSalaryResponse" name="processEmployeeSalaryResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="DemoCXFServiceSoapBinding" type="tns:DemoCXF">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="processEmployeeSalary">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="processEmployeeSalary">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="processEmployeeSalaryResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="DemoCXFService">
    <wsdl:port binding="tns:DemoCXFServiceSoapBinding" name="DemoCXFPort">
      <soap:address location="http://localhost:8080/CXFComplexTypeDemo"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

.
.
Thanks :)
Middleware Magic Team


Apache CXF Client Side Logging in JBoss AS7

Hi,

JBoss AS7 uses the JBossWS-CXF as default webservice provider which provides most of the features coming with Apache CXF (including WS-Security, WS-Policy, WS-Addressing, WS-ReliableMessaging, basic WS-Trust, MTOM) as well as common JBossWS stack features like endpoint metrics, record management, endpoint address rewrite, etc.

In this example we will see how we can enable the client side Logging for the incoming and outgoing SOAP Request/Responses, which are most desired for trouble shooting and debugging purpose.

In this example we will mainly focus on following points

Point-1). How to use the JBoss Specific Tools to build the WebServices. The details of these tools like “wsconsume” and “wsprovide” are mentioned in the following link: https://docs.jboss.org/author/display/JBWS/JAX-WS+Tools

Point-2). Where we need to place the “log4j.properties fileat the client side in order to generate a separate Log file containing the SOAP request/response.

Point-3). How to use “org.apache.cxf.interceptor.LoggingInInterceptor” and “org.apache.cxf.interceptor.LoggingOutInterceptor” at client side.

Point-4). Here we are using JBoss AS7.1.0 CR1b which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads. I am using “jboss-as-7.1.0.CR1b” in this demo.

Point-5). Source Code of this Demo is available at https://github.com/jaysensharma/MiddlewareMagicDemos

Developing Simple WebService

Step-1). Create a directory somewhere in your file system as “/home/userone/CXFClientSide_Logging_Demo” then create another directory “src” inside the “/home/userone/CXFClientSide_Logging_Demo”.

Step-2). Write a simple webservice implementation pojo class “DemoCXF.java” as following inside the directory “/home/userone/CXFClientSide_Logging_Demo/src”:


package ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.annotation.Resource;
import javax.xml.ws.WebServiceContext;
import java.util.Collection;

@WebService(name = "DemoCXF", serviceName ="DemoCXFService", portName ="DemoCXFPort", targetNamespace="http://test.org")

public class DemoCXF
{
  @Resource
  WebServiceContext ctx;

  @WebMethod()
  public String sayHello(String name)
  {
    System.out.println("\n\n\t Method Invoked....String sayHello("+name+")");
    return "Hello JBossAS7 User: "+name;
  }

  @WebMethod()
  public String getProperty(String propertyName)
  {
    System.out.println("\n\n\t Method Invoked....String getProperty(String propertyName)");
    return "RETURNED: "+(Collection) ctx.getMessageContext().values();
  }
}

Step-3). Write the “web.xml” file to define the WebService as following inside the directory “/home/userone/CXFClientSide_Logging_Demo/src”:

<?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">
  <servlet>
    <servlet-name>DemoCXF</servlet-name>
    <servlet-class>ws.DemoCXF</servlet-class>
  </servlet>  

  <servlet-mapping>
    <servlet-name>DemoCXF</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Step-4). Write the WebService client code “Test_CXF_Client.java” as following inside the directory “/home/userone/CXFClientSide_Logging_Demo/src”:


package client;
import java.net.URL;
import javax.xml.namespace.QName;

// Client side Logging related CXF APIs
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

public class Test_CXF_Client
  {
     public static void main(String ar[]) throws Exception
      {
        String WSDL_URL=ar[0]+"?wsdl";
        DemoCXFService service=new DemoCXFService(new URL(WSDL_URL));
        DemoCXF port=service.getDemoCXFPort();

        /* Following part of code is needed for client side Logging of Soap request/response */
        /* We need to make sure that we place the "log4j.properties" file inside clients classpath */
        Client client = ClientProxy.getClient(port);
        client.getInInterceptors().add(new LoggingInInterceptor());
        client.getOutInterceptors().add(new LoggingOutInterceptor()); 

        System.out.println("\n\t port.sayHello(\"MiddlewareMagic\") = "+port.sayHello("MiddlewareMagic"));
      }
  }

Step-5). As we are going to generate the client side logging in a separate log file at client side using CXF APIs so we will need to write a “log4j.properties” file as following inside the directory “/home/userone/CXFClientSide_Logging_Demo/src”:

# Direct log messages to a log file
log4j.rootLogger=INFO, WSClientAppender

log4j.appender.WSClientAppender=org.apache.log4j.RollingFileAppender
log4j.appender.WSClientAppender.File=/NotBackedUp/Downloads/CXFClientDemo/clientStuff/webserviceClient.log
log4j.appender.WSClientAppender.MaxFileSize=10MB
log4j.appender.WSClientAppender.MaxBackupIndex=3
log4j.appender.WSClientAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.WSClientAppender.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

NOTE: Make sure that you have defined the right Location for the Log File and the Directory must exist, which is defined in the above file property “log4j.appender.WSClientAppender.File”.

Step-6). Now we will write simple ANT build script “build.xml” which will build / deploy and run the webservice & client as following inside the directory “/home/userone/CXFClientSide_Logging_Demo”:

<project name="JBoss_Service" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1b" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />

<property name="basedir" value="." />
<property name="war.dir" value="CXFClientLoggingDemoWAR" />
<property name="war.name" value="CXFClientLoggingDemo.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="DemoCXFClient.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="${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.dir}"/>
           <mkdir dir="${output.dir}/${war.dir}/META-INF"/>
           <mkdir dir="${output.dir}/${war.dir}/WEB-INF"/>
           <mkdir dir="${output.dir}/${war.dir}/WEB-INF/classes"/>
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}/META-INF"/>
        </target>

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

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

    </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying   *********************" />
            <echo message="********** ${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy file="${output.dir}/${war.name}" todir="${jboss.home}/standalone/deployments/"/>

            <echo message="*******************  Deployed Successfully   *********************" />
        </target>

        <target name="post-deploy" >
            <echo message="*******************  NOTE  *********************" />
            <echo message="***** You should be able to access your WSDL using Browser now *****" />
            <echo message="                http://localhost:8080/CXFClientLoggingDemo?wsdl          " />
        </target>  

        <target name="client" depends="post-deploy">
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}"/>
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="service.wsdl"
                      wsdl="http://localhost:8080/CXFClientLoggingDemo?wsdl">
            </wsconsume>

            <!-- We need to make sure that log4j.properties is present inside client's classpath-->
            <copy file="${src.dir}/log4j.properties" todir="${client.dir}" />

            <javac srcdir="${src.dir}" destdir="${client.dir}"  includes="Test_CXF_Client.java" classpathref="client.classpath">
	        <classpath>
	            <pathelement location="${client.dir}"/>
	            <path refid="client.classpath"/>
	        </classpath>
            </javac>

            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" /> 

            <!-- Cleaning Client Stuff Directory -->
            <delete dir="${client.dir}/client"/>
            <delete file="${client.dir}/log4j.properties"/>
       </target>

        <target name="run" depends="client">
            <java classname="client.Test_CXF_Client" fork="true" >
	        <classpath>
	            <pathelement location="${client.dir}/DemoCXFClient.jar"/>
	            <path refid="client.classpath"/>
	        </classpath>
                <jvmarg value="-Dorg.apache.cxf.Logger=org.apache.cxf.common.logging.Log4jLogger" />
                <arg value="http://localhost:8080/CXFClientLoggingDemo"/>
            </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 to point to your own JBoss AS7 directory.

Step-7). Now Start your JBoss Profile as following from inside the directory “/home/userone/jboss-as-7.1.0.CR1/bin”:

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

Step-8). 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%

Step-9). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/CXFClientSide_Logging_Demo” and then run the ant to build and deploy the WebService application on your JBoss Standalone full profile, by running the command “ant deploy”

[userone@localhost CXFClientSide_Logging_Demo]$ ant deploy
Buildfile: build.xml

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

build:
    [javac] Compiling 1 source file to /home/userone/CXFClientSide_Logging_Demo/build/CXFClientLoggingDemoWAR/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CXFClientSide_Logging_Demo/build/CXFClientLoggingDemoWAR/WEB-INF
[wsprovide] Generating from endpoint: ws.DemoCXF
[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/CXFClientSide_Logging_Demo/build -classdir /home/userone/CXFClientSide_Logging_Demo/build -d /home/userone/CXFClientSide_Logging_Demo/build/CXFClientLoggingDemoWAR/WEB-INF/wsdl -verbose -wsdl -cp ::::::::: -wrapperbean -createxsdimports ws.DemoCXF
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide]
      [jar] Building jar: /home/userone/CXFClientSide_Logging_Demo/build/CXFClientLoggingDemo.war

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

BUILD SUCCESSFUL
Total time: 6 seconds

As soon as the WebService will be deployed on the JBoss AS7 you will see the following kind of output on your JBoss Console (STDOUT):

12:55:32,698 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) Starting deployment of "CXFClientLoggingDemo.war"
12:55:32,953 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-2) Add Service
 id=DemoCXF
 address=http://localhost:8080/CXFClientLoggingDemo
 implementor=ws.DemoCXF
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://test.org}DemoCXFService
 portName={http://test.org}DemoCXFPort
 wsdlLocation=null
 mtomEnabled=false
12:55:32,954 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-2) register: jboss.ws:context=CXFClientLoggingDemo,endpoint=DemoCXF
12:55:33,174 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-2) Creating Service {http://test.org}DemoCXFService from class ws.DemoCXF
12:55:33,482 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-2) Setting the server's publish address to be http://localhost:8080/CXFClientLoggingDemo
12:55:33,605 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-2) WSDL published to: file:/home/userone/jboss-as-7.1.0.CR1b/standalone/data/wsdl/CXFClientLoggingDemo.war/DemoCXFService.wsdl
12:55:33,613 INFO  [org.jboss.as.webservices] (MSC service thread 1-8) JBAS015539: Starting service jboss.ws.port-component-link
12:55:33,622 INFO  [org.jboss.as.webservices] (MSC service thread 1-3) JBAS015539: Starting service jboss.ws.endpoint."CXFClientLoggingDemo.war".DemoCXF
12:55:33,647 INFO  [org.jboss.web] (MSC service thread 1-7) registering web context: /CXFClientLoggingDemo
12:55:33,667 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "CXFClientLoggingDemo.war"

Step-10). Now we will try to compile and run the WebService Client application by running the command “ant run”

[userone@localhost CXFClientSide_Logging_Demo]$ ant run
Buildfile: build.xml

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

client:
   [delete] Deleting directory /home/userone/CXFClientSide_Logging_Demo/clientStuff
    [mkdir] Created dir: /home/userone/CXFClientSide_Logging_Demo/clientStuff
[wsconsume] Consuming wsdl: http://localhost:8080/CXFClientLoggingDemo?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.
     [copy] Copying 1 file to /home/userone/CXFClientSide_Logging_Demo/clientStuff
    [javac] Compiling 1 source file to /home/userone/CXFClientSide_Logging_Demo/clientStuff
      [jar] Building jar: /home/userone/CXFClientSide_Logging_Demo/clientStuff/DemoCXFClient.jar
   [delete] Deleting directory /home/userone/CXFClientSide_Logging_Demo/clientStuff/client
   [delete] Deleting: /home/userone/CXFClientSide_Logging_Demo/clientStuff/log4j.properties

run:
     [java] Feb 4, 2012 12:55:45 PM client.DemoCXFService <clinit>
     [java] INFO: Can not initialize the default wsdl from service.wsdl
     [java]
     [java] 	 port.sayHello("MiddlewareMagic") = Hello JBossAS7 User: MiddlewareMagic

BUILD SUCCESSFUL
Total time: 9 seconds

Step-11). Once the webservice is invoked successfully then you will be able to see the Client Side log file is generated in the location which is mentioned in the “log4j.properties” file…something like following:

12:55:46,418  INFO ReflectionServiceFactoryBean:366 - Creating Service {http://test.org}DemoCXFService from WSDL: http://localhost:8080/CXFClientLoggingDemo?wsdl
12:55:46,930  INFO LoggingOutInterceptor:151 - Outbound Message
---------------------------
ID: 1
Address: http://localhost:8080/CXFClientLoggingDemo
Encoding: UTF-8
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHello xmlns:ns2="http://test.org"><arg0>MiddlewareMagic</arg0></ns2:sayHello></soap:Body></soap:Envelope>
--------------------------------------
12:55:47,061  INFO LoggingInInterceptor:151 - Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml;charset=UTF-8
Headers: {Content-Length=[235], content-type=[text/xml;charset=UTF-8], Date=[Sat, 04 Feb 2012 07:25:46 GMT], Server=[Apache-Coyote/1.1]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHelloResponse xmlns:ns2="http://test.org"><return>Hello JBossAS7 User: MiddlewareMagic</return></ns2:sayHelloResponse></soap:Body></soap:Envelope>
--------------------------------------

Enabling Logging On JBoss Server Side

You can add the following System Property (-Dorg.apache.cxf.logging.enabled=true) on JBoss Configuration like “standalone-full.xml” as following:

<server xmlns="urn:jboss:domain:1.3">

    <extensions>
        <extension module="org.jboss.as.clustering.infinispan"/>
        <extension module="org.jboss.as.cmp"/>
       .
       .
       .
        <extension module="org.jboss.as.webservices"/>
        <extension module="org.jboss.as.weld"/>
    </extensions>

    <system-properties>
        <property name="org.apache.cxf.logging.enabled" value="true"/>
    </system-properties>

    <management>
        <security-realms>
       .
       .
        </security-realms>
   </management>

.
.
Thanks :)
Middleware Magic Team


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("\n\nPlease check Why the dataHandler is NULL.");
                     }
               }
             catch(Exception e)
               {
                   System.out.println("\n\t 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("\n\tGot 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("\n\t dataHandler.getContentType() = "+dataHandler.getContentType());

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

        String result=client.uploadPictureAttachment(attachmentName,picture);
        System.out.println("\n\tclient.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
     [java] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
     [java] log4j:WARN Please initialize the log4j system properly.
     [java] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
     [java]
     [java] 	Got Client: org.apache.cxf.jaxws.JaxWsClientProxy@7b5c9f9d
     [java]
     [java] 	 dataHandler.getContentType() = image/jpeg
     [java]
     [java] 	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("\n\tGot Client: "+client);
        System.out.println("\n\tclient.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
     [java] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
     [java] log4j:WARN Please initialize the log4j system properly.
     [java] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
     [java]
     [java] 	Got Client: org.apache.cxf.jaxws.JaxWsClientProxy@6ed3199e
     [java]
     [java] 	client.sayHello(Middleware Magic): Hello World !!! Mr. Middleware Magic

BUILD SUCCESSFUL
Total time: 9 seconds

.
.
Thanks
MiddlewareMagic Team


Getting WebService Statistics using JMX in JBoss AS7

Hi,

In this demonstration we will see how we can query the Statistics of a WebService deployed on JBoss using standard MBean code. In this example we will see that we need not to add any JAVA_OPTS in our JBoss configuration files in order to access these MBeans.

Here we will use a Sample webservice which will be deployed on JBoss AS7, for example you can refer to the following article to know how to deploy the WebService in JBoss: “http://middlewaremagic.com/jboss/?p=980” We will try to access the statistics of this webservice using our Standard JMX code. The statistics will include the following useful informations: “StartTime”, “StopTime”, “MinProcessingTime”, “AverageProcessingTime”, “MaxProcessingTime”, “RequestCount”..etc

JBoss side Configuration ( jboss-as-7.1.0.Beta1 )

Step1). Open the “/home/userone/jboss-as-7.1.0.Beta1/standalone/configuration/standalone-full.xml” file and edit the subsystem “urn:jboss:domain:jmx:1.1″ as following:

        <subsystem xmlns="urn:jboss:domain:jmx:1.1" show-model="true">
            <jmx-connector registry-binding="jmx-connector-registry" server-binding="jmx-connector-server"/>
        </subsystem>

Step2). Restart your JBoss Profile from “/home/userone/jboss-as-7.1.0.Beta1/bin” directory like following:

[userone@localhost bin]$ ./standalone.sh -c standalone-full.xml

Step3). Deploy your WebService on JBoss. For Testing you can use the webService mentioned in the following link:
http://middlewaremagic.com/jboss/?p=980

Step4). Now Somewhere in your filesystem write a Java Program “WebServiceMonitor.java” as following:

import java.util.Date;
import java.util.Hashtable;
import java.io.IOException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.MemoryMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;

public class WebServiceMonitor
{
    private static MBeanServerConnection connection;
    private static JMXConnector connector;
    public static void Connection(String hostname, String port) throws IOException
    {
        Integer portInteger = Integer.valueOf(port);
        Hashtable h = new Hashtable();
        JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+hostname+":"+port+"/jmxrmi");
        connector = JMXConnectorFactory.connect(address,null);
        connection = connector.getMBeanServerConnection();
        System.out.println("GOT THE MBeanServerConnection---SUCCESSFULLY");
    }

    private static void getServiceDetail(String contextRoot,String endPointName) throws Exception
    {
        ObjectName serviceRef=new ObjectName("jboss.ws:context="+contextRoot+",endpoint="+endPointName);
        String address=(String)connection.getAttribute(serviceRef, "Address");
        System.out.println("\t Address : "+address);
        Date startTime=(Date)connection.getAttribute(serviceRef, "StartTime");
        System.out.println("\t StartTime : "+startTime);
        Long minProcessingTime=(Long)connection.getAttribute(serviceRef, "MinProcessingTime");
        System.out.println("\t MinProcessingTime : "+minProcessingTime);
        Long maxProcessingTime=(Long)connection.getAttribute(serviceRef, "MaxProcessingTime");
        System.out.println("\t MaxProcessingTime : "+maxProcessingTime);
        Long totalProcessingTime=(Long)connection.getAttribute(serviceRef, "TotalProcessingTime");
        System.out.println("\t TotalProcessingTime : "+totalProcessingTime);
        Long requestCount=(Long)connection.getAttribute(serviceRef, "RequestCount");
        System.out.println("\t RequestCount : "+requestCount);
        Long responseCount=(Long)connection.getAttribute(serviceRef, "ResponseCount");
        System.out.println("\t ResponseCount : "+responseCount);
        Long faultCount=(Long)connection.getAttribute(serviceRef, "FaultCount");
        System.out.println("\t FaultCount : "+faultCount);
        Date stopTime=(Date)connection.getAttribute(serviceRef, "StopTime");
        System.out.println("\t StopTime : "+stopTime);
        Long averageProcessingTime=(Long)connection.getAttribute(serviceRef, "AverageProcessingTime");
        System.out.println("\t AverageProcessingTime : "+averageProcessingTime);
    }

    public static void main(String[] args) throws Exception
    {
    String hostname = args[0];
    String port = args[1];
    String contextRoot=args[2];
    String endPointName=args[3];
    Connection(hostname, port);
    System.out.println("------------------Getting Service Details------------------");
    System.out.println("jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS");
    System.out.println("-----------------------------------------------------------");
    getServiceDetail(contextRoot,endPointName);

    // ObjectName will be in the following format
    // "jboss.ws:context="+contextRoot+",endpoint="+endPointName
    //       Example:
    //       jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS
    }
}

Step5). Now we will write a simple Ant build script to build and execute the above program. So write an Ant build script “build.xml” file in the same directory where the above program is placed.

<project name="JBoss_Monitor" default="run">
<property name="jboss.home" value="/NotBackedUp/JBoss_All/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="base.dir" value="." />

   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>
   </path>

   <target name="run">
       <javac srcdir="${base.dir}" destdir="${base.dir}"  includes="WebServiceMonitor.java" classpathref="jboss.classpath"/>
       <java classname="WebServiceMonitor">
           <classpath>
              <pathelement location="${base.dir}"/>
              <path refid="jboss.classpath"/>
           </classpath>
           <arg line="localhost 1090  CXFTimeoutClientDemo Test_CXF_WS"/>
       </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.

Step6). 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%

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

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

run:
     [java] GOT THE MBeanServerConnection---SUCCESSFULLY
     [java] ------------------Getting Service Details------------------
     [java] jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS
     [java] -----------------------------------------------------------
     [java] 	 Address : http://localhost:8080/CXFTimeoutClientDemo
     [java] 	 StartTime : Tue Nov 29 01:17:23 BTT 2011
     [java] 	 MinProcessingTime : 8
     [java] 	 MaxProcessingTime : 15191
     [java] 	 TotalProcessingTime : 15310
     [java] 	 RequestCount : 3
     [java] 	 ResponseCount : 3
     [java] 	 FaultCount : 0
     [java] 	 StopTime : null
     [java] 	 AverageProcessingTime : 5103

BUILD SUCCESSFUL
Total time: 2 seconds

Step8). If you want to run the above program manually then you will need to run the following command

.
java WebServiceMonitor localhost 1090 CXFTimeoutClientDemo Test_CXF_WS
.

NOTE: Here we are passing 4 Arguments
“localhost” (Here our JBoss is running),
“1090″ (This is the jmx-connector-registry connector port of JBoss which is enabled in the step1),
“CXFTimeoutClientDemo” (This is the Context Root of our WebService Application)
“Test_CXF_WS” (This is the Endpoint Name of our WebService)
.
.
.
Thanks
MiddlewareMagic Team


CXF Client side Tuning Parameters and disabling Chunking in JBoss AS7

Hi,

JBoss AS7 provides support for Apache CXF 2.4.4, so in this demonstration we will see how to develop a Simple example of CXF webService. In this Example we see how to apply the different CXF specific settings pragmatically on the CXF Client code like setting “ReceiveTimeout”, “ConnectionTimeout” and enabling or disabling “Chunking”.

There are two ways of putting a body into an HTTP stream:

Standard streaming” way used by most browsers is to specify a Content-Length header in the HTTP headers. This allows the receiver to know how much data is coming and when to stop reading. The problem with this approach is that the length needs to be pre-determined. The data cannot be streamed as generated as the length needs to be calculated upfront. Thus, if chunking is turned off, we need to buffer the data in a byte buffer (or temp file if too large) so that the Content-Length can be calculated.

Chunked Streaming – with this mode, the data is sent to the receiver in chunks. Each chunk is preceded by a hexidecimal chunk size. When a chunk size is 0, the receiver knows all the data has been received. This mode allows better streaming as we just need to buffer a small amount, up to 8K by default, and when the buffer fills, write out the chunk.

In general, Chunked will perform better as the streaming can take place directly. HOWEVER, there are some problems with chunking:

Many proxy servers don’t understand it, especially older proxy servers. Many proxy servers want the Content-Length up front so they can allocate a buffer to store the request before passing it onto the real server.

Some of the older WebServices stacks also have problems with Chunking. Specifically, older versions of .NET.

NOTE: If you are getting strange errors (generally not soap faults, but other HTTP type errors) like following, when trying to interact with a service, try turning off chunking to see if that helps.

Caused by: org.jboss.soa.esb.UnmarshalException: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]
 at org.jboss.internal.soa.esb.addressing.helpers.EPRHelper.fromXMLString(EPRHelper.java:148)
 at org.jboss.internal.soa.esb.services.registry.JAXRRegistryImpl.findEPRs(JAXRRegistryImpl.java:292)
 ... 63 more

Caused by: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]
 at com.ctc.wstx.sr.StreamScanner.throwUnexpectedEOF(StreamScanner.java:661)
 at com.ctc.wstx.sr.BasicStreamReader.handleEOF(BasicStreamReader.java:2134)
 at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2040)
 at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1069)
 at org.jboss.internal.soa.esb.util.stax.StreamHelper.skipToStartElement(StreamHelper.java:317)
 at org.jboss.internal.soa.esb.addressing.helpers.EPRHelper.fromXMLString(EPRHelper.java:138)

More informations about the CXF Client Parameters you can refer to the following link:
http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html#ClientHTTPTransport%28includingSSLsupport%29-The%7B%7Bclient%7D%7Delement

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

Developing Simple WebApp CXFWebService

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

Step2). Now we will write the EJB3 webservice implementation class with name “Test_CXF_WS.java” inside “/home/userone/CXFTimeoutClientDemo/src” as following:

package ws;
package ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.annotation.Resource;
import javax.xml.ws.WebServiceContext;
import java.util.Collection;
import java.util.Date;
@WebService(name = "DemoCXFService", targetNamespace="http://test.org")
public class Test_CXF_WS
{
  @Resource
  WebServiceContext ctx;

  @WebMethod()
  public String getProperty(String propertyName)
  {
        System.out.println("\n\n\t Method Invoked....String getProperty(String propertyName)");
        for(int i=0;i<15;i++)
          {
             System.out.println("\n\t getProperty(String propertyName)  PROCESSING "+"\t"+new Date());
             try{  Thread.sleep(1000);  }
             catch(InterruptedException e){ e.printStackTrace(); }
          }
        return "RETURNED: "+(Collection) ctx.getMessageContext().values();
  }
}

Step3). We will write the “web.xml” inside “/home/userone/CXFTimeoutClientDemo/src” to define the servlet and servlet-mapping for our WebService as following:

<?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">
  <servlet>
    <servlet-name>Test_CXF_WS</servlet-name>
    <servlet-class>ws.Test_CXF_WS</servlet-class>
  </servlet>  

  <servlet-mapping>
    <servlet-name>Test_CXF_WS</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

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

package client;
import java.util.Date;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

public class Test_CXF_Client
  {
     public static void main(String ar[]) throws Exception
      {
        String ENDPOINT_URL=ar[0];

        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());

        factory.setServiceClass(DemoCXFService.class);
        factory.setAddress(ENDPOINT_URL);
        DemoCXFService service = (DemoCXFService) factory.create();

        Client client = ClientProxy.getClient(service);
        if (client != null) {
            HTTPConduit conduit = (HTTPConduit) client.getConduit();
            HTTPClientPolicy policy = new HTTPClientPolicy();

            /*
                ConnectionTimeout
                ================== Specifies the amount of time, in milliseconds, that the client will attempt to establish
                                   a connection before it times out. The default is 30000 (30 seconds).
                                   0 specifies that the client will continue to attempt to open a connection indefinitely.
             */
            /*
                ReceiveTimeout
                ==================Specifies the amount of time, in milliseconds, that the client will wait for
                                  a response before it times out. The default is 60000.
                                  0 specifies that the client will wait indefinitely.
             */
             /*
               Chunking is by default enabled in CXF webservices so we are disabling it.
             */

             policy.setConnectionTimeout(10000);
             policy.setReceiveTimeout(5000);
             policy.setAllowChunking(false);
            conduit.setClient(policy);
        }        

        System.out.println("\n\t service.getProperty(\"something\") invoked at : "+new Date());
        System.out.println("\n\t service.getProperty(\"something\") = "+service.getProperty("something"));
      }
  }

Step5). AS we are going to deploy the WebService in Exploded format inside the JBoss AS7 container so we will need to create and deploy a File with name “${AppName}.dodeploy” means in our case the filename will be “CXFTimeoutClientDemo.war.dodeploy”. Create this EMPTY file and place it inside “/home/userone/CXFTimeoutClientDemo/src” directory. For archived deployable applications this file is not required.

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

<project name="JBoss_Service" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.0.2.Final" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="java.home.dir" value="/home/userone/MyJdks/jdk1.6.0_05" />
<property name="basedir" value="." />
<property name="war.name" value="CXFTimeoutClientDemo.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="DemoCXF_Timeout_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="${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.name}"/>
           <mkdir dir="${output.dir}/${war.name}/META-INF"/>
           <mkdir dir="${output.dir}/${war.name}/WEB-INF"/>
           <mkdir dir="${output.dir}/${war.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.name}/WEB-INF/classes"  includes="*.java" excludes="Test_CXF_Client.java" classpathref="jboss.classpath"/>
        <copy todir="${output.dir}/${war.name}/WEB-INF">
	  <fileset dir="${basedir}/src">
	      <include name="web.xml"/>
	  </fileset>
	</copy>
       <wsprovide
        	fork="false"
        	keep="true"
        	destdir="${output.dir}"
        	resourcedestdir="${output.dir}/${war.name}/WEB-INF/wsdl"
        	sourcedestdir="${output.dir}"
        	genwsdl="true"
        	verbose="true"
        	sei="ws.Test_CXF_WS">
            	<classpath>
                	  <pathelement path="${output.dir}/${war.name}/WEB-INF/classes"/>
            	</classpath>
      </wsprovide>
    </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="The EMPTY '${war.name}.dodeploy' tells JBoss AS7 to deploy the application"/>
            <echo message="This file is needed if we want to deploy an exploded application in JBossAS7"/>
            <copy todir="${jboss.home}/standalone/deployments/">
	        <fileset dir="${basedir}/src">
	          <include name="${war.name}.dodeploy"/>
	        </fileset>
	    </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>

        <target name="post-deploy">
            <echo message="*******************  NOTE  *********************" />
            <echo message="***** You should be able to access your WSDL using Browser now *****" />
            <echo message="                http://localhost:8080/CXFTimeoutClientDemo?wsdl          " />
        </target>  

        <target name="client" depends="post-deploy">
             <delete dir="${client.dir}" />
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="service.wsdl"
                      wsdl="http://localhost:8080/CXFTimeoutClientDemo?wsdl">
            </wsconsume>
            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" />
       </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/CXFTimeoutClientDemo"/>
            </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.

Step7). 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%

Step8). 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: build.xml

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

build:
    [javac] Compiling 1 source file to /home/userone/CXFTimeoutClientDemo/build/CXFTimeoutClientDemo.war/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CXFTimeoutClientDemo/build/CXFTimeoutClientDemo.war/WEB-INF
[wsprovide] Generating from endpoint: ws.Test_CXF_WS
[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/CXFTimeoutClientDemo/build -classdir /home/userone/CXFTimeoutClientDemo/build -d /home/userone/CXFTimeoutClientDemo/build/CXFTimeoutClientDemo.war/WEB-INF/wsdl -verbose -wsdl -cp :::::::: -wrapperbean -createxsdimports ws.Test_CXF_WS
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide] 

deploy:
     [echo] *******************  Deploying   *********************
     [echo] ********** CXFTimeoutClientDemo.war to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
     [copy] Copying 4 files to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [copy] Copied 6 empty directories to 1 empty directory under /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] The EMPTY 'CXFTimeoutClientDemo.war.dodeploy' tells JBoss AS7 to deploy the application
     [echo] This file is needed if we want to deploy an exploded application in JBossAS7
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 4 seconds

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

02:20:41,193 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015003: Found CXFTimeoutClientDemo.war in deployment directory. To trigger deployment create a file called CXFTimeoutClientDemo.war.dodeploy
02:20:41,197 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) Starting deployment of "CXFTimeoutClientDemo.war"
02:20:41,304 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-5) Add Service
 id=Test_CXF_WS
 address=http://localhost:8080/CXFTimeoutClientDemo
 implementor=ws.Test_CXF_WS
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://test.org}Test_CXF_WSService
 portName={http://test.org}DemoCXFServicePort
 wsdlLocation=null
 mtomEnabled=false
02:20:41,304 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-5) register: jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS
02:20:41,312 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-5) Creating Service {http://test.org}Test_CXF_WSService from class ws.Test_CXF_WS
02:20:41,339 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-5) Setting the server's publish address to be http://localhost:8080/CXFTimeoutClientDemo
02:20:41,347 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-5) WSDL published to: file:/home/userone/jboss-as-7.1.0.Beta1/standalone/data/wsdl/CXFTimeoutClientDemo.war/Test_CXF_WSService.wsdl
02:20:41,372 INFO  [org.jboss.as.webservices] (MSC service thread 1-5) JBAS015539: Starting service jboss.ws.endpoint."CXFTimeoutClientDemo.war".Test_CXF_WS
02:20:41,383 INFO  [org.jboss.web] (MSC service thread 1-3) registering web context: /CXFTimeoutClientDemo
02:20:41,400 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 1) Deployed "CXFTimeoutClientDemo.war"

Step10). 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: build.xml

post-deploy:
 *******************  NOTE  *********************
 ***** You should be able to access your WSDL using Browser now *****

http://localhost:8080/CXFTimeoutClientDemo?wsdl

client:
] Deleting directory /home/userone/CXFTimeoutClientDemo/clientStuff
 Consuming wsdl: http://localhost:8080/CXFTimeoutClientDemo?wsdl
 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.
 Building jar: /home/userone/CXFTimeoutClientDemo/clientStuff/DemoCXF_Timeout_Client.jar

run:
 Compiling 1 source file to /home/userone/CXFTimeoutClientDemo/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.

 	 service.getProperty("something") invoked at : Sun Nov 27 02:23:49 IST 2011
 javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:194)
 	at org.apache.tools.ant.taskdefs.Java.run(Java.java:764)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:218)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:132)
 	at org.apache.tools.ant.taskdefs.Java.execute(Java.java:105)
 	at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
 	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 	at java.lang.reflect.Method.invoke(Method.java:597)
 	at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
 	at org.apache.tools.ant.Task.perform(Task.java:348)
 	at org.apache.tools.ant.Target.execute(Target.java:357)
 	at org.apache.tools.ant.Target.performTasks(Target.java:385)
 	at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
 	at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
 	at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
 	at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
 	at org.apache.tools.ant.Main.runBuild(Main.java:758)
 	at org.apache.tools.ant.Main.startAnt(Main.java:217)
 	at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)
 	at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)
 Caused by: javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:145)
 	at $Proxy36.getProperty(Unknown Source)
 	at client.Test_CXF_Client.main(Unknown Source)
 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 	at java.lang.reflect.Method.invoke(Method.java:597)
 	at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
 	at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
 	... 20 more
 Caused by: java.net.SocketTimeoutException: SocketTimeoutException invoking http://localhost:8080/CXFTimeoutClientDemo: Read timed out
 	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
 	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
 	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.mapException(HTTPConduit.java:1430)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1415)
 	at org.apache.cxf.io.CacheAndWriteOutputStream.postClose(CacheAndWriteOutputStream.java:47)
 	at org.apache.cxf.io.CachedOutputStream.close(CachedOutputStream.java:194)
 	at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
 	at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:648)
 	at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
 	at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
 	at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:533)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:463)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:366)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:319)
 	at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:88)
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)
 	... 28 more
 Caused by: java.net.SocketTimeoutException: Read timed out
 	at java.net.SocketInputStream.socketRead0(Native Method)
 	at java.net.SocketInputStream.read(SocketInputStream.java:129)
 	at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
 	at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
 	at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
 	at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
 	at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
 	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1072)
 	at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1541)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1493)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1401)
 	... 40 more
 --- Nested Exception ---
 javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:145)
 	at $Proxy36.getProperty(Unknown Source)
 	at client.Test_CXF_Client.main(Unknown Source)
 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 	at java.lang.reflect.Method.invoke(Method.java:597)
 	at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
 	at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
 	at org.apache.tools.ant.taskdefs.Java.run(Java.java:764)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:218)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:132)
 	at org.apache.tools.ant.taskdefs.Java.execute(Java.java:105)
 	at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
 	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 	at java.lang.reflect.Method.invoke(Method.java:597)
 	at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
 	at org.apache.tools.ant.Task.perform(Task.java:348)
 	at org.apache.tools.ant.Target.execute(Target.java:357)
 	at org.apache.tools.ant.Target.performTasks(Target.java:385)
 	at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
 	at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
 	at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
 	at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
 	at org.apache.tools.ant.Main.runBuild(Main.java:758)
 	at org.apache.tools.ant.Main.startAnt(Main.java:217)
 	at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)
 	at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)
 Caused by: java.net.SocketTimeoutException: SocketTimeoutException invoking http://localhost:8080/CXFTimeoutClientDemo: Read timed out
 	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
 	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
 	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.mapException(HTTPConduit.java:1430)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1415)
 	at org.apache.cxf.io.CacheAndWriteOutputStream.postClose(CacheAndWriteOutputStream.java:47)
 	at org.apache.cxf.io.CachedOutputStream.close(CachedOutputStream.java:194)
 	at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
 	at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:648)
 	at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
 	at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
 	at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:533)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:463)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:366)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:319)
 	at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:88)
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)
 	... 28 more
 Caused by: java.net.SocketTimeoutException: Read timed out
 	at java.net.SocketInputStream.socketRead0(Native Method)
 	at java.net.SocketInputStream.read(SocketInputStream.java:129)
 	at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
 	at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
 	at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
 	at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
 	at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
 	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1072)
 	at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1541)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1493)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1401)
 	... 40 more
 Java Result: -1

NOTE: You are seeing the above “java.net.SocketTimeoutException: Read timed out” because the client has set “RecieveTimeout” as 5-Seconds where as the Webservice for loop will process the operation in 15 Seconds.

.
.
Thanks
MiddlewareMagic Team


Basic Authentication in WebApp Based CXF WebService JBoss AS7

Hi,

JBoss AS7 provides support for Apache CXF 2.4.4, so in this demonstration we will see how to develop a Simple Non-EJB CXF webService with Basic Authentication enabled. In this Example we will using the jboss-web.xml file to map the security-domain defined inside our “standalone-full.xml” file and we will write the “web.xml” manually to define the Basic Authentication and role mapping.

If you want to see how to avoid writing the deployment descriptors like jboss-web.xml, by using JBoss Specific annotations then you can refer to the following article: http://middlewaremagic.com/jboss/?p=958 (EJB based CXF WebService with Basic Authentication in JBoss AS7)

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

Configuring “security-domain” inside the “standalone-full.xml” file

Here we will first create a security-domain inside the security subsystem “/home/userone/jboss-as-7.1.0.Beta1/standalone/configuration/standard-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:security:1.1">
            <security-domains>
                <security-domain name="other" cache-type="default">
                    <authentication>
                        <login-module code="UsersRoles" flag="required"/>
                    </authentication>
                </security-domain>
                <security-domain name="jboss-web-policy" cache-type="default">
                    <authorization>
                        <policy-module code="Delegating" flag="required"/>
                    </authorization>
                </security-domain>
                <security-domain name="jboss-ejb-policy" cache-type="default">
                    <authorization>
                        <policy-module code="Delegating" flag="required"/>
                    </authorization>
                </security-domain>

                <!--****************************************************************-->
                <!-- Following Part is added Here for Our CXF Application security -->
                <security-domain name="cxfservice-security-domain" cache-type="default">
                    <authentication>
                        <login-module code="UsersRoles" flag="required">
                            <module-option name="usersProperties" value="cxfservice-users.properties"/>
                            <module-option name="rolesProperties" value="cxfservice-roles.properties"/>
                            <module-option name="unauthenticatedIdentity" value="nobody"/>
                        </login-module>
                    </authentication>
                </security-domain>
            </security-domains>
        </subsystem>

NOTE: the properties files “cxfservice-users.properties” and “cxfservice-roles.properties” we will later add inside our CXFBasedEJB3 Service Jar file.

Developing Simple WebApp CXFWebService

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

Step2). Create a property file with name “cxfservice-roles.properties” inside “/home/userone/CXFTimeoutClientDemo/src” as following:

userone=TestRole

Step3). Create a property file with name “cxfservice-users.properties” inside “/home/userone/CXFTimeoutClientDemo/src” as following:

userone=passwordone

Step4).Now we will write the EJB3 webservice implementation class with name “Test_CXF_WS.java” inside “/home/userone/CXFTimeoutClientDemo/src” as following:

package ws;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(name = "DemoCXFService", targetNamespace="http://test.org")
public class Test_CXF_WS
{
  @WebMethod()
  public String sayHello(String name)
  {
        System.out.println("\n\n\t Method Invoked sayHello() ...  Hello, "+name);
        return "Hello Mr, "+name;
  }
}

Step5). We will write the “web.xml” inside “/home/userone/CXFTimeoutClientDemo/src” to define the BASIC Authentication and secured resources as following:

<?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">
  <servlet>
    <servlet-name>Test_CXF_WS</servlet-name>
    <servlet-class>ws.Test_CXF_WS</servlet-class>
  </servlet>  

  <servlet-mapping>
    <servlet-name>Test_CXF_WS</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>  

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>MySecureResources</web-resource-name>
            <description>Some Description</description>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>TestRole</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
    </login-config>
    <security-role>
        <role-name>TestRole</role-name>
    </security-role>
</web-app>

Step6). We will write the “jboss-web.xml” inside “/home/userone/CXFTimeoutClientDemo/src” to map the security-domain defined in the “standalone-full.xml” file as following:

<jboss-web>
    <security-domain>java:/jaas/cxfservice-security-domain</security-domain>
</jboss-web>

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

package client;
import java.util.Date;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import javax.xml.ws.BindingProvider;

public class Test_CXF_Client
  {
     public static void main(String ar[]) throws Exception
      {
        String ENDPOINT_URL=ar[0];
        String BASIC_USER="userone";
        String BASIC_PWD="passwordone";

        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

        factory.setServiceClass(DemoCXFService.class);
        factory.setAddress(ENDPOINT_URL);
        DemoCXFService service = (DemoCXFService) factory.create();

        BindingProvider bp = (BindingProvider)service;
        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, BASIC_USER);
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, BASIC_PWD);

        System.out.println("\n\t service.sayHello(\"MiddlewareMagic\") invoked at : "+new Date());
        System.out.println("\n\t service.sayHello(\"MiddlewareMagic\") = "+service.sayHello("MiddlewareMagic"));
      }
  }

Step8). AS we are going to deploy the WebService in Exploded format inside the JBoss AS7 container so we will need to create and deploy a File with name “${AppName}.dodeploy” means in our case the filename will be “CXF_BasicAuthDemo.war.dodeploy”. Create this EMPTY file and place it inside “/home/userone/CXFTimeoutClientDemo/src” directory.

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

<project name="JBoss_Service" default="post-deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="java.home.dir" value="/home/userone/MyJdks/jdk1.6.0_05" />
<property name="basedir" value="." />
<property name="war.name" value="CXF_BasicAuthDemo.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="DemoCXF_BasicAuth_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="${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.name}"/>
           <mkdir dir="${output.dir}/${war.name}/META-INF"/>
           <mkdir dir="${output.dir}/${war.name}/WEB-INF"/>
           <mkdir dir="${output.dir}/${war.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.name}/WEB-INF/classes"  includes="*.java" excludes="Test_CXF_Client.java" classpathref="jboss.classpath"/>
        <copy todir="${output.dir}/${war.name}/WEB-INF">
	  <fileset dir="${basedir}/src">
	      <include name="web.xml"/>
	      <include name="jboss-web.xml"/>
	  </fileset>
	</copy>
       <wsprovide
        	fork="false"
        	keep="true"
        	destdir="${output.dir}"
        	resourcedestdir="${output.dir}/${war.name}/WEB-INF/wsdl"
        	sourcedestdir="${output.dir}"
        	genwsdl="true"
        	verbose="true"
        	sei="ws.Test_CXF_WS">
            	<classpath>
                	  <pathelement path="${output.dir}/${war.name}/WEB-INF/classes"/>
            	</classpath>
      </wsprovide>
        <copy todir="${output.dir}/${war.name}/WEB-INF/classes">
	  <fileset dir="${basedir}/src">
	      <include name="*.properties"/>
	  </fileset>
	</copy>
    </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="The EMPTY '${war.name}.dodeploy' tells JBoss AS7 to deploy the application"/>
            <echo message="This file is needed if we want to deploy an exploded application in JBossAS7"/>
            <copy todir="${jboss.home}/standalone/deployments/">
	        <fileset dir="${basedir}/src">
	          <include name="${war.name}.dodeploy"/>
	        </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://userone:passwordone@localhost:8080/CXF_BasicAuthDemo/Test_CXF_WSService?wsdl" />
            <echo message="            " />
            <echo message="            " />
            <echo message="RMEMBER *** Syntax: " />
            <echo message="http://BasicUsername:BasicPassword@localhost:8080/CXF_BasicAuthDemo/Test_CXF_WSService?wsdl" />
            <echo message="and then save it in your file system with following name:" />
            <echo message="${src.dir}/META-INF/wsdl/CXFBasicAuthService.wsdl "/>
            <echo message="And then run the ' ant client' To generate client artifacts" />
            <echo message="************************************************" />
        </target>

        <target name="client">
             <delete dir="${client.dir}" />
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="service.wsdl"
                      wsdl="${src.dir}/META-INF/wsdl/CXFBasicAuthService.wsdl">
            </wsconsume>
            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" />
       </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/CXF_BasicAuthDemo"/>
            </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.

Step9). 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%

Step10). 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: build.xml

init:
   [delete] Deleting directory /home/userone/CXFTimeoutClientDemo/build
    [mkdir] Created dir: /home/userone/CXFTimeoutClientDemo/build
    [mkdir] Created dir: /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war
    [mkdir] Created dir: /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/META-INF
    [mkdir] Created dir: /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/WEB-INF
    [mkdir] Created dir: /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/WEB-INF/classes
   [delete] Deleting directory /home/userone/CXFTimeoutClientDemo/clientStuff
    [mkdir] Created dir: /home/userone/CXFTimeoutClientDemo/clientStuff

build:
    [javac] Compiling 1 source file to /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/WEB-INF/classes
     [copy] Copying 2 files to /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/WEB-INF
[wsprovide] Generating from endpoint: ws.Test_CXF_WS
[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/CXFTimeoutClientDemo/build -classdir /home/userone/CXFTimeoutClientDemo/build -d /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/WEB-INF/wsdl -verbose -wsdl -cp :::::::: -wrapperbean -createxsdimports ws.Test_CXF_WS
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide]
     [copy] Copying 2 files to /home/userone/CXFTimeoutClientDemo/build/CXF_BasicAuthDemo.war/WEB-INF/classes

deploy:
     [echo] *******************  Deploying   *********************
     [echo] ********** CXF_BasicAuthDemo.war to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
     [copy] Copying 7 files to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] The EMPTY 'CXF_BasicAuthDemo.war.dodeploy' tells JBoss AS7 to deploy the application
     [echo] This file is needed if we want to deploy an exploded application in JBossAS7
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

post-deploy:
     [echo] *******************  NOTE  *********************
     [echo] ***** You should be able to access your WSDL using Browser now *****
     [echo] http://userone:passwordone@localhost:8080/CXF_BasicAuthDemo/Test_CXF_WSService?wsdl
     [echo]
     [echo]
     [echo] RMEMBER *** Syntax:
     [echo] http://BasicUsername:BasicPassword@localhost:8080/CXF_BasicAuthDemo/Test_CXF_WSService?wsdl
     [echo] and then save it in your file system with following name:
     [echo] src/META-INF/wsdl/CXFBasicAuthService.wsdl
     [echo] And then run the ' ant client' To generate client artifacts
     [echo] ************************************************

BUILD SUCCESSFUL
Total time: 5 seconds

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

1:39:30,022 INFO  [org.jboss.as.webservices] (MSC service thread 1-4) JBAS015540: Stopping service jboss.ws.endpoint."CXF_BasicAuthDemo.war".Test_CXF_WS
01:39:30,028 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-6) remove: jboss.ws:context=CXF_BasicAuthDemo,endpoint=Test_CXF_WS
01:39:30,030 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-8) Stopped deployment CXF_BasicAuthDemo.war in 10ms
01:39:30,032 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) Starting deployment of "CXF_BasicAuthDemo.war"
01:39:30,120 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-2) Add Service
 id=Test_CXF_WS
 address=http://localhost:8080/CXF_BasicAuthDemo
 implementor=ws.Test_CXF_WS
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://test.org}Test_CXF_WSService
 portName={http://test.org}DemoCXFServicePort
 wsdlLocation=null
 mtomEnabled=false
01:39:30,120 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-2) register: jboss.ws:context=CXF_BasicAuthDemo,endpoint=Test_CXF_WS
01:39:30,128 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-2) Creating Service {http://test.org}Test_CXF_WSService from class ws.Test_CXF_WS
01:39:30,154 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-2) Setting the server's publish address to be http://localhost:8080/CXF_BasicAuthDemo
01:39:30,162 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-2) WSDL published to: file:/home/userone/jboss-as-7.1.0.Beta1/standalone/data/wsdl/CXF_BasicAuthDemo.war/Test_CXF_WSService.wsdl
01:39:30,169 INFO  [org.jboss.as.webservices] (MSC service thread 1-2) JBAS015539: Starting service jboss.ws.endpoint."CXF_BasicAuthDemo.war".Test_CXF_WS
01:39:30,178 INFO  [org.jboss.web] (MSC service thread 1-5) registering web context: /CXF_BasicAuthDemo
01:39:30,190 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Replaced deployment "CXF_BasicAuthDemo.war" with deployment "CXF_BasicAuthDemo.war"

Step12). Now run the command “ant run” in your shell prompt to run the WebService client to access the WebService operation using BASIC Authentication credentials. “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: build.xml

client:
   [delete] Deleting directory /home/userone/CXFTimeoutClientDemo/clientStuff
[wsconsume] Consuming wsdl: src/META-INF/wsdl/CXFBasicAuthService.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/CXFTimeoutClientDemo/clientStuff/DemoCXF_BasicAuth_Client.jar

run:
    [javac] Compiling 1 source file to /home/userone/CXFTimeoutClientDemo/clientStuff
     [java] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
     [java] log4j:WARN Please initialize the log4j system properly.
     [java] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
     [java]
     [java] 	 service.sayHello("MiddlewareMagic") invoked at : Sun Nov 27 01:41:26 IST 2011
     [java]
     [java] 	 service.sayHello("MiddlewareMagic") = Hello Mr, MiddlewareMagic

BUILD SUCCESSFUL
Total time: 8 seconds

NOTE: If you will pass a wrong credential to JBoss then you may see following kind of exceptions:

*************************On Server Side ***********************
1:42:05,021 ERROR [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http-localhost-127.0.0.1-8080-6) Login failure: javax.security.auth.login.LoginException: java.lang.NullPointerException
	at org.jboss.security.vault.SecurityVaultUtil.isVaultFormat(SecurityVaultUtil.java:59)
	at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:250)
	at org.jboss.security.auth.spi.UsersRolesLoginModule.login(UsersRolesLoginModule.java:155)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:616)
	at javax.security.auth.login.LoginContext.invoke(LoginContext.java:784)
	at javax.security.auth.login.LoginContext.access$000(LoginContext.java:203)
	at javax.security.auth.login.LoginContext$4.run(LoginContext.java:698)
	at javax.security.auth.login.LoginContext$4.run(LoginContext.java:696)
	at java.security.AccessController.doPrivileged(Native Method)
	at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:695)
	at javax.security.auth.login.LoginContext.login(LoginContext.java:594)
	at org.jboss.security.authentication.JBossCachedAuthenticationManager.defaultLogin(JBossCachedAuthenticationManager.java:412)
	at org.jboss.security.authentication.JBossCachedAuthenticationManager.authenticate(JBossCachedAuthenticationManager.java:346)
	at org.jboss.security.authentication.JBossCachedAuthenticationManager.isValid(JBossCachedAuthenticationManager.java:155)
	at org.jboss.as.web.security.JBossWebRealm.authenticate(JBossWebRealm.java:214)
************************* On Client Side ***********************
 javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:194)
 	at org.apache.tools.ant.taskdefs.Java.run(Java.java:764)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:218)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:132)
 	at org.apache.tools.ant.taskdefs.Java.execute(Java.java:105)
 	at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
     .
     .
     .
 Caused by: javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:145)
 	at $Proxy36.sayHello(Unknown Source)
 	at client.Test_CXF_Client.main(Unknown Source)
 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
     .
     .
     .
 Caused by: org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with http://localhost:8080/CXF_BasicAuthDemo
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1554)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1493)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1401)
 	at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
 	at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:648)
 	at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
 	at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
 	at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:533)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:463)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:366)
 	at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:319)
 	at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:88)
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)
 	... 28 more
 --- Nested Exception ---
 javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:145)
 	at $Proxy36.sayHello(Unknown Source)
 	at client.Test_CXF_Client.main(Unknown Source)
 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 	at java.lang.reflect.Method.invoke(Method.java:597)

.
.
Thanks
MiddlewareMagic Team


EJB based CXF WebService with Basic Authentication in JBoss AS7

Hi,

JBoss AS7 provides support for Apache CXF 2.4.4, so in this demonstration we will see how to develop a Simple EJB3 Based CXF webService with Basic Authentication enabled. In this Example we will also see how we can use some JBoss Specific Annotations like “org.jboss.ejb3.annotation.SecurityDomain” to map the Security domain defined inside our “standalone-full.xml” file. We will also see how can we enable the BASIC Authentication using another JBoss Specific annotation “org.jboss.ws.api.annotation.WebContext“, the most useful part of this annotation is using this annotation we can define whether the user will have access to the wsdl can be accessed outside of the Basic Authentication scope or not. This can be specified using the @WebContext annotation’s attribute “secureWSDLAccess“.

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

Configuring “security-domain” inside the “standalone-full.xml” file

Here we will first create a security-domain inside the security subsystem “/home/userone/jboss-as-7.1.0.Beta1/standalone/configuration/standard-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:security:1.1">
            <security-domains>
                <security-domain name="other" cache-type="default">
                    <authentication>
                        <login-module code="UsersRoles" flag="required"/>
                    </authentication>
                </security-domain>
                <security-domain name="jboss-web-policy" cache-type="default">
                    <authorization>
                        <policy-module code="Delegating" flag="required"/>
                    </authorization>
                </security-domain>
                <security-domain name="jboss-ejb-policy" cache-type="default">
                    <authorization>
                        <policy-module code="Delegating" flag="required"/>
                    </authorization>
                </security-domain>

                <!--****************************************************************-->
                <!-- Following Part is added Here for Our CXF Application security -->
                <security-domain name="cxfservice-security-domain" cache-type="default">
                    <authentication>
                        <login-module code="UsersRoles" flag="required">
                            <module-option name="usersProperties" value="cxfservice-users.properties"/>
                            <module-option name="rolesProperties" value="cxfservice-roles.properties"/>
                            <module-option name="unauthenticatedIdentity" value="nobody"/>
                        </login-module>
                    </authentication>
                </security-domain>
            </security-domains>
        </subsystem>

NOTE: the properties files “cxfservice-users.properties” and “cxfservice-roles.properties” we will later add inside our CXFBasedEJB3 Service Jar file.

Developing EJB3 based CXFWebService

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

Step2). Create a property file with name “cxfservice-roles.properties” inside “/home/userone/EJB_CXFService_BasicAuth/src” as following:

userone=TestRole

Step3). Create a property file with name “cxfservice-users.properties” inside “/home/userone/EJB_CXFService_BasicAuth/src” as following:

userone=passwordone

Step4).Now we will write the EJB3 webservice endpoint interface with name “SecureCXF_EJB_Intf.java” inside “/home/userone/EJB_CXFService_BasicAuth/src” as following:

package ws;
public interface SecureCXF_EJB_Intf
  {
     String sayHello(String name);
  }

Step5).Now we will write the EJB3 webservice implementation class with name “SecureCXF_EJB.java” inside “/home/userone/EJB_CXFService_BasicAuth/src” as following:

package ws;
//Standard Annotations
import javax.jws.WebService;
import javax.ejb.Stateless;
import javax.annotation.security.RolesAllowed;

//JBoss Specific Annotations
import org.jboss.ws.api.annotation.WebContext;
import org.jboss.ejb3.annotation.SecurityDomain;

@WebService(name = "SecureCXF_EJB", targetNamespace="http://ws/")
@Stateless
@SecurityDomain("cxfservice-security-domain")
@RolesAllowed("TestRole")
@WebContext(contextRoot="/EJB_CXF_BasicAuthDemo", urlPattern="/*", authMethod="BASIC", transportGuarantee="NONE", secureWSDLAccess=false)
public class SecureCXF_EJB implements SecureCXF_EJB_Intf
{
    public String sayHello(String name)
     {
        System.out.println("\n\t [SecureCXF_EJB] sayHello() invoked : Hello, Mr. "+name);
        return "Hello, Mr. "+name;
     }
}

Step6). Now we will write the WebService Client “Client.java” inside “/home/userone/EJB_CXFService_BasicAuth/src” as following which demonstrates two ways of clients code:

package client;
import java.net.URL;
import  javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class Client
  {
       public static void main(String ar[]) throws Exception
       {
          String BASIC_USER="userone";
          String BASIC_PWD="passwordone";
          //String SERVICE_ENDPOINT="http://localhost:8080/EJB_CXF_BasicAuthDemo/SecureCXF_EJB";
          String SERVICE_ENDPOINT=ar[0];
          URL wsdl_URL=new URL(SERVICE_ENDPOINT+"?wsdl");
          QName SERVICE = new QName("http://ws/", "SecureCXF_EJBService");

          JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
          factory.setServiceClass(SecureCXFEJB.class);
          factory.setAddress(SERVICE_ENDPOINT);
          SecureCXFEJB service = (SecureCXFEJB) factory.create();
          System.out.println("Got the Service: "+service);
          BindingProvider bp = (BindingProvider)service;
          bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, BASIC_USER);
          bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, BASIC_PWD);
          System.out.println(service.sayHello("MiddlewareMagic"));

        /* // Below is the alternative Client Code which can be used to invole the service //

          SecureCXFEJBService service=new SecureCXFEJBService(wsdl_URL,SERVICE);
          SecureCXFEJB port=service.getSecureCXFEJBPort();
          System.out.println("Got the Service port: "+port);
          BindingProvider bp = (BindingProvider)port;
          bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, BASIC_USER);
          bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, BASIC_PWD);
          System.out.println(port.sayHello("MiddlewareMagic"));
        */
       }
  }

Step7). AS we are going to deploy the WebService in Exploded format inside the JBoss AS7 container so we will need to create and deploy a File with name “${AppName}.dodeploy” means in our case the filename will be “EJB_CXF_BasicAuthDemo.jar.dodeploy”. Create this file and place it inside “/home/userone/EJB_CXFService_BasicAuth/src” directory.

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

<project name="JBoss_Service" default="post-deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="java.home.dir" value="/home/userone/MyJdks/jdk1.6.0_05" />
<property name="basedir" value="." />
<property name="jar.name" value="EJB_CXF_BasicAuthDemo.jar" />
<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="EJB_CXF_BasicAuth_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="${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}/${jar.name}"/>
           <mkdir dir="${output.dir}/${jar.name}/META-INF/wsdl"/>
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}"/>
        </target>

    <target name="build" depends="init">
       <javac srcdir="${src.dir}" destdir="${output.dir}/${jar.name}"  includes="*.java" excludes="Client.java" classpathref="jboss.classpath"/>
       <wsprovide
        	fork="false"
        	keep="true"
        	destdir="${output.dir}"
        	resourcedestdir="${output.dir}/${jar.name}/META-INF/wsdl"
        	sourcedestdir="${output.dir}"
        	genwsdl="true"
        	verbose="true"
        	sei="ws.SecureCXF_EJB">
            	<classpath>
                	  <pathelement path="${output.dir}/${jar.name}"/>
            	</classpath>
      </wsprovide>
        <copy todir="${output.dir}/${jar.name}">
	  <fileset dir="${basedir}/src">
	      <include name="*.properties"/>
	  </fileset>
	</copy>
    </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying   *********************" />
            <echo message="********** ${jar.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${jar.name}/**"/>
                </fileset>
            </copy>
            <echo message="The EMPTY '${jar.name}.dodeploy' tells JBoss AS7 to deploy the application"/>
            <echo message="This file is needed if we want to deploy an exploded application in JBossAS7"/>
            <copy todir="${jboss.home}/standalone/deployments/">
	        <fileset dir="${basedir}/src">
	          <include name="${jar.name}.dodeploy"/>
	        </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/EJB_CXF_BasicAuthDemo/SecureCXF_EJB?wsdl" />
            <echo message="            " />
            <echo message="            " />
        </target>

        <target name="client">
             <delete dir="${client.dir}" />
             <wsconsume
                      fork="true"
                      keep="true"
                      destdir="${client.dir}"
                      sourcedestdir="${client.dir}"
                      package="client"
                      wsdlLocation="service.wsdl"
                      wsdl="http://localhost:8080/EJB_CXF_BasicAuthDemo/SecureCXF_EJB?wsdl">
            </wsconsume>
            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" />
       </target>

        <target name="run" depends="client">
            <javac srcdir="${src.dir}" destdir="${client.dir}"  includes="Client.java" classpathref="client.classpath"/>
            <java classname="client.Client"  >
	        <classpath>
	            <pathelement location="${client.dir}"/>
	            <path refid="client.classpath"/>
	        </classpath>
                <arg value="http://localhost:8080/EJB_CXF_BasicAuthDemo/SecureCXF_EJB"/>
            </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.

Step9). 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%

Step10). 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 EJB_CXFService_BasicAuth]$ ant
Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/EJB_CXFService_BasicAuth/build
    [mkdir] Created dir: /home/userone/EJB_CXFService_BasicAuth/build
    [mkdir] Created dir: /home/userone/EJB_CXFService_BasicAuth/build/EJB_CXF_BasicAuthDemo.jar
    [mkdir] Created dir: /home/userone/EJB_CXFService_BasicAuth/build/EJB_CXF_BasicAuthDemo.jar/META-INF/wsdl
   [delete] Deleting directory /home/userone/EJB_CXFService_BasicAuth/clientStuff
    [mkdir] Created dir: /home/userone/EJB_CXFService_BasicAuth/clientStuff

build:
    [javac] Compiling 2 source files to /home/userone/EJB_CXFService_BasicAuth/build/EJB_CXF_BasicAuthDemo.jar
[wsprovide] Generating from endpoint: ws.SecureCXF_EJB
[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/EJB_CXFService_BasicAuth/build -classdir /home/userone/EJB_CXFService_BasicAuth/build -d /home/userone/EJB_CXFService_BasicAuth/build/EJB_CXF_BasicAuthDemo.jar/META-INF/wsdl -verbose -wsdl -cp :::::: -wrapperbean -createxsdimports ws.SecureCXF_EJB
[wsprovide] java2ws - Apache CXF 2.4.4
[wsprovide]
     [copy] Copying 2 files to /home/userone/EJB_CXFService_BasicAuth/build/EJB_CXF_BasicAuthDemo.jar

deploy:
     [echo] *******************  Deploying   *********************
     [echo] ********** EJB_CXF_BasicAuthDemo.jar to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
     [copy] Copying 6 files to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] The EMPTY 'EJB_CXF_BasicAuthDemo.jar.dodeploy' tells JBoss AS7 to deploy the application
     [echo] This file is needed if we want to deploy an exploded application in JBossAS7
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/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/EJB_CXF_BasicAuthDemo/SecureCXF_EJB?wsdl
     [echo]
     [echo]

BUILD SUCCESSFUL
Total time: 4 seconds

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

00:14:52,862 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) Starting deployment of "EJB_CXF_BasicAuthDemo.jar"
00:14:52,883 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-7) JNDI bindings for session bean named SecureCXF_EJB in deployment unit deployment "EJB_CXF_BasicAuthDemo.jar" are as follows:

00:14:52,911 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] (MSC service thread 1-7) Add Service
 id=SecureCXF_EJB
 address=http://localhost:8080/EJB_CXF_BasicAuthDemo
 implementor=ws.SecureCXF_EJB
 invoker=org.jboss.wsf.stack.cxf.JBossWSInvoker
 serviceName={http://ws/}SecureCXF_EJBService
 portName={http://ws/}SecureCXF_EJBPort
 wsdlLocation=null
 mtomEnabled=false
00:14:52,911 INFO  [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-7) register: jboss.ws:context=EJB_CXF_BasicAuthDemo,endpoint=SecureCXF_EJB
00:14:52,919 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (MSC service thread 1-7) Creating Service {http://ws/}SecureCXF_EJBService from class ws.SecureCXF_EJB
00:14:52,937 INFO  [org.apache.cxf.endpoint.ServerImpl] (MSC service thread 1-7) Setting the server's publish address to be http://localhost:8080/EJB_CXF_BasicAuthDemo
00:14:52,945 INFO  [org.jboss.wsf.stack.cxf.deployment.WSDLFilePublisher] (MSC service thread 1-7) WSDL published to: file:/home/userone/jboss-as-7.1.0.Beta1/standalone/data/wsdl/EJB_CXF_BasicAuthDemo.jar/SecureCXF_EJBService.wsdl
00:14:52,952 INFO  [org.jboss.as.webservices] (MSC service thread 1-6) JBAS015539: Starting service jboss.ws.endpoint."EJB_CXF_BasicAuthDemo.jar".SecureCXF_EJB
00:14:52,954 INFO  [org.jboss.web] (MSC service thread 1-2) registering web context: /EJB_CXF_BasicAuthDemo
00:14:52,971 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Replaced deployment "EJB_CXF_BasicAuthDemo.jar" with deployment "EJB_CXF_BasicAuthDemo.jar"

Step12). Now run the command “ant run” in your shell prompt to run the WebService client to access the WebService operation using BASIC Authentication credentials. “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 EJB_CXFService_BasicAuth]$ ant run
Buildfile: build.xml

client:
   [delete] Deleting directory /home/userone/EJB_CXFService_BasicAuth/clientStuff
[wsconsume] Consuming wsdl: http://localhost:8080/EJB_CXF_BasicAuthDemo/SecureCXF_EJB?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/EJB_CXFService_BasicAuth/clientStuff/EJB_CXF_BasicAuth_Client.jar

run:
    [javac] Compiling 1 source file to /home/userone/EJB_CXFService_BasicAuth/clientStuff
     [java] log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
     [java] log4j:WARN Please initialize the log4j system properly.
     [java] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
     [java] Got the Service: org.apache.cxf.jaxws.JaxWsClientProxy@7e4e194f
     [java] Hello, Mr. MiddlewareMagic

BUILD SUCCESSFUL
Total time: 8 seconds

NOTE: If you will pass a wrong credential to JBoss then you may see following kind of exceptions:

*************************On Server Side ***********************
01:07:34,864 ERROR [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http-localhost-127.0.0.1-8080-6) Login failure: javax.security.auth.login.LoginException: java.lang.NullPointerException
	at org.jboss.security.vault.SecurityVaultUtil.isVaultFormat(SecurityVaultUtil.java:59)
	at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:250)
	at org.jboss.security.auth.spi.UsersRolesLoginModule.login(UsersRolesLoginModule.java:155)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:616)
	at javax.security.auth.login.LoginContext.invoke(LoginContext.java:784)
************************* On Client Side ***********************
 Got the Service: org.apache.cxf.jaxws.JaxWsClientProxy@4977fa9a
 javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:194)
 	at org.apache.tools.ant.taskdefs.Java.run(Java.java:764)
 	at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:218)
      .
      .
      .
 Caused by: javax.xml.ws.WebServiceException: Could not send Message.
 	at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:145)
 	at $Proxy36.sayHello(Unknown Source)
 	at client.Client.main(Unknown Source)
      .
      .
      .
  Caused by: org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with http://localhost:8080/EJB_CXF_BasicAuthDemo/SecureCXF_EJB
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1554)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1493)
 	at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1401)
 	at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
 	at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:648)

.
.
Thanks
MiddlewareMagic Team


  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

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