MTOM with Axis2 version 1.3#

A step-by-step guide to writing a web service which supports MTOM and a web service client to call it. The example assumes a Windows environment and Eclipse as the development environment.

Setup the Development Environment

1. Download Tomcat version 5.5 from http://tomcat.apache.org/download-55.cgi

2. Set the JAVA_HOME environment variable to the Java JDK directory. Note that you have to set the variable to the JDK and not the JRE install folder.

3. Run startup.bat from the Tomcat distribution bin directory to make sure Tomcat will run. If all is good, run shutdown.bat from the bin directory to stop the Tomcat server.

4. Download Axis2 version 1.3 (http://ws.apache.org/axis2/download/1_3/download.cgi)

a. Download the Standard Distribution and the WAR distribution.

5. Copy the axis2.war file from the WAR distribution in step 4 to the webapps folder under Tomcat. Start Tomcat by running startup.bat. If Tomcat was able to consume the war file, then you should be able to browse to http://localhost:8080/axis2/ to see the Axis2 web application default page.

6. Upon startup, Tomcat unpacked the axis2.war file. Have a look at the axis2.xml configuration file within axis2\WEB-INF\conf\ folder.

7. The axis2.xml file contains the administrator username and password for axis2 administration. By default the username and password to admin and axis2, respectively. You can modify this by changing the values and restarting Tomcat.

8. Point your browser to the axis2 web application and choose the Administration link. http://localhost:8080/axis2/axis2-admin/login. Type in the username and password to access the admin console.

9. So far we have Tomcat and Axis2 up and running. To make this exercise less painful, we should also download TCPMon so we can view the SOAP message we create. Download TCPMon from: http://ws.apache.org/commons/tcpmon/download.cgi. This utility is very cool and easy to use. Before you start TCPMon (by running tcpmon.bat from the build), have a look at the user guide. http://wso2.org/project/wsas/java/2.1/docs/tools/tcpmonguide.html

Create MTOM Enabled Web Service

1. Create a new Java Project in Eclipse. Name the project TestMTOM.

2. Add the axis2 jar files to the classpath. The axis2 jar files are within the lib directory of the axis2 standard distribution.

3. Create a new class named TestService within a package named com.test. Paste the following for the class implementation.

package com.test;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import javax.activation.DataHandler;

import org.apache.axiom.om.OMElement;

import org.apache.axiom.om.OMText;

public class TestService

{

private static final String OUTPUT_FILE = "C:\\HOLD\\att.pdf";

public void receiveMTOM(OMElement element) throws Exception

{

System.out.println("received request...");

OMText binaryNode = (OMText) (element.getFirstElement()).getFirstOMChild();

binaryNode.setOptimize(true);

DataHandler dh = (DataHandler) binaryNode.getDataHandler();

InputStream is = dh.getInputStream();

byte[] buf = readFully(is);

writeOutput(buf);

System.out.println("done writing output file.");

}

private static void writeOutput(byte[] buf)throws IOException

{

File of = new File(OUTPUT_FILE);

if(of.exists())

{

of.delete();

}

of.createNewFile();

setContents(new File(OUTPUT_FILE),buf);

}

private static void setContents(File aFile, byte[] aContents) throws FileNotFoundException, IOException

{

if (aFile == null)

{

throw new IllegalArgumentException("File should not be null.");

}

if (!aFile.exists())

{

throw new FileNotFoundException("File does not exist: " + aFile);

}

if (!aFile.isFile())

{

throw new IllegalArgumentException("Should not be a directory: " + aFile);

}

if (!aFile.canWrite())

{

throw new IllegalArgumentException("File cannot be written: " + aFile);

}

/**

* declared here only to make visible to finally clause;

* generic reference

*/

OutputStream output = null;

try

{

output = new FileOutputStream(aFile);

output.write(aContents);

}

finally

{

/**

* flush and close both "output" and its underlying FileWriter

*/

if (output != null)

output.close();

}

}

private static byte[] readFully(InputStream is) throws IOException

{

int size = 10000;

/**

* Offset - how much we've read

*/

int off = 0;

int got;

byte[] ret = new byte[size];

try

{

while (true)

{

got = is.read(ret, off, size - off);

/**

* End of stream

*/

if (got == -1)

break;

off += got;

if (off == size)

{

/**

* If we've read to the end of our buffer,

* enlarge it.

*/

size *= 2;

byte[] tmp = new byte[size];

System.arraycopy(ret, 0, tmp, 0, off);

ret = tmp;

}

}

}

finally

{

if(is!=null)is.close();

}

/**

* If we've got a bigger buffer than we need, resize it

*/

if (off != size)

{

byte[] tmp = new byte[off];

System.arraycopy(ret, 0, tmp, 0, off);

ret = tmp;

}

return ret;

}

}

The receiveMTOM() method expects an OMElement, which then contains the binary file. The method simply pulls the binary file out of the SOAP message and saves it to the local file system. The file is identified by the OUTPUT_FILE static variable. Note that we have to

binaryNode.setOptimize(true);

prior to calling the getDataHandler() method.

4. The service implementation is done. Now we have to create a service.xml file. To do that, first create a folder under the root of the project and name it META-INF. Within this folder, create an xml file and name it services.xml. Paste the following into that file.

<service name="TestService">

<description>

This service is to get the running Axis version

</description>

<parameter name="ServiceClass">com.test.TestService</parameter>

<parameter name="enableMTOM">true</parameter>

<operation name="receiveMTOM">

<messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />

</operation>

</service>

To enable MTOM, we have to add a parameter for the service called enableMTOM and set its value to true. Note that MTOM is disabled by default.

5. The next thing we have to do is package the service as a jar file but with a "aar" extension. You can do this several ways, but the easiest approach is to just use Eclipse's Export functionality.

6. Once you have the aar file, copy it under the axis2 deployment within Tomcat. This would be at TOMCAT_INSTALL\webapps\axis2\WEB-INF\services\

7. Restart Tomcat.

Create MTOM enabled Web Service Client

1. Before we can call the service, we need a proxy to the web service. Assuming Tomcat is running, browse to the following URL. http://localhost:8080/axis2/services/TestService?wsdl

2. To create the proxy, save the WSDL file to the bin directory of the Axis2 installation. Name the file TestService.wsdl. Note that within this directory, you'll also have the WSDL2Java.bat file that we need to use to create the web service proxy.

3. After you save the WSDL file, open a command prompt and execute

WSDL2JAVA -uri TestService.wsdl

This should create the proxy files with a folder name src.

4. Now we need to create a java project within Eclipse for the web service client. Create a new Project and name it TestMTOMClient.

5. Add the Axis2 jar files to the classpath.

6. Copy the src folder from step 3 under the TestMTOMClient project and refresh the project in Eclipse.

7. Now create a class to execute the web service. Name the class TestClient and paste the following in its place.

package com.test;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import junit.framework.TestCase;

import org.apache.axiom.om.OMAbstractFactory;

import org.apache.axiom.om.OMElement;

import org.apache.axiom.om.OMFactory;

import org.apache.axiom.om.OMNamespace;

import org.apache.axiom.om.OMText;

import org.apache.axis2.Constants;

import org.apache.axis2.util.Base64;

import com.test.TestServiceStub.ReceiveMTOM;

 

public class TestClient extends TestCase

{

private static final String EPR = "http://localhost:9080/axis2/services/TestService";

private static final String INPUT_FILE = "C:\\HOLD\\small.pdf";

public static void main(String[] args) throws Exception

{

}

public void testMTOM()throws Exception

{

TestServiceStub stub = new TestServiceStub(EPR);

stub._getServiceClient().getOptions().setProperty(

Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);

/**

* set timeout

*/

stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(10000);

String base64String = Base64.encode(readFully(INPUT_FILE));

ReceiveMTOM rmtom = new ReceiveMTOM();

OMFactory fac = OMAbstractFactory.getOMFactory();

OMText binaryNode =fac.createOMText(base64String,"application/pdf",true);

OMNamespace omNs = fac.createOMNamespace("http://test.com", "ns0");

OMElement method = fac.createOMElement("receiveMTOM", omNs);

method.addChild(binaryNode);

rmtom.setElement(method);

stub.receiveMTOM(rmtom);

System.out.println("done calling service...");

}

}

The testMTOM() method creates a stub and sets the enableMTOM property. It then reads the a file and then does a base64 encoded on the file's contents. Finally, it calls the receiveMTOM() metod on the stub. Note that to call the web service, we need a sample file. The class above assumes there is a file named "small.pdf" at c:\hold\. So create a folder named hold in the root of the c:\ drive and copy a pdf file in that directory. Name the file small.pdf.

9. Before you call the service, start TCPMon so we can view the SOAP message that the client sends to the service so you can verify that the SOAP Message is really an MTOM enabled SOAP request. Configurre TCPMon so that the listen port is 9080 and the listener's Target port is 8080. Assuming that Tomcat is running on port 8080. Also realize that the client above is setup to call the service on 9080 so as long as we configure TCPMon correctly we should be okay. If you are not using TCPMon, change the EPR variable in the client class so that it points to port 8080 or whatever port your service is running on.

10. Assuming you did everything correctly, you should be able to send some MTOM SOAP messages to the service. When the service receives a request, it save the binary file to c:\hold\att.pdf.

 

References

1. Download Tomcat: http://tomcat.apache.org/download-55.cgi

2. Download Axis2 version 1.3: http://ws.apache.org/axis2/download/1_3/download.cgi

3. Download TCPMonitor: http://ws.apache.org/commons/tcpmon/download.cgi

4. Using TCPMonitor: http://wso2.org/project/wsas/java/2.1/docs/tools/tcpmonguide.html

5. A very good article on MTOM with Axis2: http://ws.apache.org/axis2/1_1_1/mtom-guide.html

6. Apache MTOM User Guide: http://ws.apache.org/axis2/1_0/mtom-guide.html

11/9/2007 3:22:14 PM (Eastern Standard Time, UTC-05:00) #    Comments [4]  |  Trackback

 

WS-Security, Axis2 and Rampart#

One of the things that I don’t like about Java is that the community is not using the same foundational libraries. For example, there is not a standard J2EE application server. Instead there is a specification and hundreds of vendors. As a result, everyone seems to be using a different implementation of a specification, and thus finding answers to questions is a lot harder because the user community is spread across many many implementations.

Recently, I had to call a web service which was protected by WS-Security UsernameToken. I was able to quickly call the service with Axis 1.1 and WSS4J but when I tried to use Axis2 and Rampart I ran into exception after exception. After several days of struggling, I was eventually able to create a web service client that created the proper soap message.

This blog contains a step by step procedure to create a web service client to a web service which is protected by ws-security UsernameToken.

I am assuming that you have already deployed the web service which is protected by ws-security and that you simply want to call the service using Axis2 version 1.3 and Rampart 1.3. Here are the steps:

1) Download Axis2 version 1.3 from http://ws.apache.org/axis2/

2) Download Rampart 1.3 from http://ws.apache.org/axis2/modules/index.html

3) Add Axis2 JARs to your client application classpath--all JARs from the Axis2 distribution lib directory.

3) Add the Rampart jars to your client application classpath--all jars from the Rampart distribution lib directory.

4) Create a proxy to the web service that is protected by ws-security--using the WSDL2Java tool or batch file.

5) Create an Axis2 client-configuration file which engages rampart and which has the ws-security parameter. Place this file within your client application project. For example, the standard is to create a folder called "conf" for this file.

Here is an example file:

 

<axisconfig name="AxisJava2.0">

<!-- engage rampart -->

<module ref="rampart" />

 

<!-- ws-security parameters: UsernameToken and PasswordText -->

<parameter name="OutflowSecurity">

<action>

<items>UsernameToken</items>

<user>myusername</user>

<passwordCallbackClass>com.mycomp.test.PWCBHandler</passwordCallbackClass>

<passwordType>PasswordText</passwordType>

</action>

</parameter>

<!-- ================================================= -->

<!-- Parameters -->

<!-- ================================================= -->

<parameter name="hotdeployment">true</parameter>

<parameter name="hotupdate">false</parameter>

<parameter name="enableMTOM">false</parameter>

<parameter name="enableSwA">false</parameter>

<!--Uncomment if you want to enable file caching for attachments -->

<!--parameter name="cacheAttachments">true</parameter>

<parameter name="attachmentDIR"></parameter>

<parameter name="sizeThreshold">4000</parameter-->

<!--This will give out the timout of the configuration contexts, in seconds-->

<parameter name="ConfigContextTimeoutInterval">30</parameter>

<!--During a fault, stacktrace can be sent with the fault message. The following flag will control -->

<!--that behaviour.-->

<parameter name="sendStacktraceDetailsWithFaults">false</parameter>

<parameter name="DrillDownToRootCauseForFaultReason">false</parameter>

<parameter name="userName">admin</parameter>

<parameter name="password">axis2</parameter>

<!--Set the flag to true if you want to enable transport level session mangment-->

<parameter name="manageTransportSession">false</parameter>

<!-- Following parameter will completely disable REST handling in Axis2-->

<parameter name="disableREST" locked="true">false</parameter>

<!-- ================================================= -->

<!-- Message Receivers -->

<!-- ================================================= -->

<!--This is the Deafult Message Receiver for the system , if you want to have MessageReceivers for -->

<!--all the other MEP implement it and add the correct entry to here , so that you can refer from-->

<!--any operation -->

<!--Note : You can ovride this for particular service by adding the same element with your requirement-->

<messageReceivers>

<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"

class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/>

<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"

class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>

</messageReceivers>

<!-- ================================================= -->

<!-- Message Formatter -->

<!-- ================================================= -->

<!--Following content type to message formatter mapping can be used to implement support for different message -->

<!--format serialization in Axis2. These message formats are expected to be resolved based on the content type. -->

<messageFormatters>

<messageFormatter contentType="application/x-www-form-urlencoded"

class="org.apache.axis2.transport.http.XFormURLEncodedFormatter"/>

<messageFormatter contentType="application/xml"

class="org.apache.axis2.transport.http.ApplicationXMLFormatter"/>

<messageFormatter contentType="text/xml"

class="org.apache.axis2.transport.http.ApplicationXMLFormatter"/>

<messageFormatter contentType="application/echo+xml"

class="org.apache.axis2.transport.http.ApplicationXMLFormatter"/>

</messageFormatters>

<!-- ================================================= -->

<!-- Transport Ins -->

<!-- ================================================= -->

<transportReceiver name="http"

class="org.apache.axis2.transport.http.SimpleHTTPServer">

<parameter name="port">6060</parameter>

</transportReceiver>

<!--Uncomment this and configure as appropriate for JMS transport support, after setting up your JMS environment (e.g. ActiveMQ)

<transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">

<parameter name="myTopicConnectionFactory">

<parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>

<parameter name="java.naming.provider.url">tcp://localhost:61616</parameter>

<parameter name="transport.jms.ConnectionFactoryJNDIName">TopicConnectionFactory</parameter>

</parameter>

<parameter name="myQueueConnectionFactory">

<parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>

<parameter name="java.naming.provider.url">tcp://localhost:61616</parameter>

<parameter name="transport.jms.ConnectionFactoryJNDIName">QueueConnectionFactory</parameter>

</parameter>

<parameter name="default">

<parameter name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>

<parameter name="java.naming.provider.url">tcp://localhost:61616</parameter>

<parameter name="transport.jms.ConnectionFactoryJNDIName">QueueConnectionFactory</parameter>

</parameter>

</transportReceiver>-->

<!-- ================================================= -->

<!-- Transport Outs -->

<!-- ================================================= -->

<transportSender name="tcp"

class="org.apache.axis2.transport.tcp.TCPTransportSender"/>

<transportSender name="local"

class="org.apache.axis2.transport.local.LocalTransportSender"/>

<transportSender name="http"

class="org.apache.axis2.transport.http.CommonsHTTPTransportSender">

<parameter name="PROTOCOL">HTTP/1.1</parameter>

<parameter name="Transfer-Encoding">chunked</parameter>

<!-- If following is set to 'true', optional action part of the Content-Type will not be added to the SOAP 1.2 messages -->

<!-- <parameter name="OmitSOAP12Action">true</parameter> -->

</transportSender>

<transportSender name="https"

class="org.apache.axis2.transport.http.CommonsHTTPTransportSender">

<parameter name="PROTOCOL">HTTP/1.1</parameter>

<parameter name="Transfer-Encoding">chunked</parameter>

</transportSender>

<!-- ================================================= -->

<!-- Global Modules -->

<!-- ================================================= -->

<!-- Comment this to disable Addressing -->

<module ref="addressing"/>

<!--Configuring module , providing parameters for modules whether they refer or not-->

<!--<moduleConfig name="addressing">-->

<!--<parameter name="addressingPara">N/A</parameter>-->

<!--</moduleConfig>-->

<!-- ================================================= -->

<!-- Clustering -->

<!-- ================================================= -->

<!-- Configure and uncomment following for preparing Axis2 to a clustered environment -->

<!--

<cluster class="org.apache.axis2.cluster.tribes.TribesClusterManager">

<parameter name="param1">value1</parameter>

</cluster>

-->

<!-- ================================================= -->

<!-- Phases -->

<!-- ================================================= -->

<phaseOrder type="InFlow">

<!-- System predefined phases -->

<phase name="Transport">

<handler name="RequestURIBasedDispatcher"

class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher">

<order phase="Transport"/>

</handler>

<handler name="SOAPActionBasedDispatcher"

class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher">

<order phase="Transport"/>

</handler>

</phase>

<phase name="Addressing">

<handler name="AddressingBasedDispatcher"

class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">

<order phase="Addressing"/>

</handler>

</phase>

<phase name="Security"/>

<phase name="PreDispatch"/>

<phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">

<handler name="RequestURIBasedDispatcher"

class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>

<handler name="SOAPActionBasedDispatcher"

class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>

<handler name="RequestURIOperationDispatcher"

class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>

<handler name="SOAPMessageBodyBasedDispatcher"

class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>

<handler name="HTTPLocationBasedDispatcher"

class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>

</phase>

<phase name="RMPhase"/>

<!-- System predefined phases -->

<!-- After Postdispatch phase module author or service author can add any phase he want -->

<phase name="OperationInPhase"/>

<phase name="soapmonitorPhase"/>

</phaseOrder>

<phaseOrder type="OutFlow">

<!-- user can add his own phases to this area -->

<phase name="soapmonitorPhase"/>

<phase name="OperationOutPhase"/>

<!--system predefined phase-->

<!--these phase will run irrespective of the service-->

<phase name="RMPhase"/>

<phase name="PolicyDetermination"/>

<phase name="MessageOut"/>

<phase name="Security"/>

</phaseOrder>

<phaseOrder type="InFaultFlow">

<phase name="Addressing">

<handler name="AddressingBasedDispatcher"

class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">

<order phase="Addressing"/>

</handler>

</phase>

<phase name="Security"/>

<phase name="PreDispatch"/>

<phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">

<handler name="RequestURIBasedDispatcher"

class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>

<handler name="SOAPActionBasedDispatcher"

class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>

<handler name="RequestURIOperationDispatcher"

class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>

<handler name="SOAPMessageBodyBasedDispatcher"

class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>

<handler name="HTTPLocationBasedDispatcher"

class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>

</phase>

<phase name="RMPhase"/>

<!-- user can add his own phases to this area -->

<phase name="OperationInFaultPhase"/>

<phase name="soapmonitorPhase"/>

</phaseOrder>

<phaseOrder type="OutFaultFlow">

<!-- user can add his own phases to this area -->

<phase name="soapmonitorPhase"/>

<phase name="OperationOutFaultPhase"/>

<phase name="RMPhase"/>

<phase name="PolicyDetermination"/>

<phase name="MessageOut"/>

</phaseOrder>

</axisconfig>

 

The configuration file above is a typical client config file with the rampart and ws-security configuration.

6) When calling the web service through the web service stub, you'll have to give Axis the path to the Axis configuration file above. Moreover, for Axis to engage Rampart, you'll have to give Axis the path to the Axis respository folder. The repository folder needs to have a subdirectory called "modules" and within that directory, the Rampart 1.3 "mar" file has to exist. Therefore, create a folder somewhere within your project called "repository". Then create a subdirectory called "modules". Finally, copy the "rampart-1.3.mar" file from the Rampart distributable.

7) Now you are ready to make a service call. First create an instance of a custom configuration passing in the repository path and the axis configuration file path.

ConfigurationContext cxt =

ConfigurationContextFactory.createConfigurationContextFromFileSystem("c:\\folderpath\\repository","c:\\path_to_axis_config_file.xml");

8) Create a stub with the custom axis configuration instance.

HelloServiceStub stub = new HelloServiceStub(ctx,"http://localhost:8080/services/HelloService");

HelloServiceStub.Echo echoReq = new HelloServiceStub.Echo();

System.out.println("calling service...");

HelloServiceStub.EchoResponse resp = stub.echo(echoReq);

System.out.println("done calling service...");

The key to the whole process was ConfigurationContextFactory.createConfigurationContextFromFileSystem. When calling this method, you need to make sure you pass the correct repository path and a proper Axis2 client configuration file. The path to the repository has to have a sub directory called "modules" and that has to contain the rampart "mar" file. If this is not correct, then Axis2 will not be able to engage Rampart.

10/9/2007 8:00:29 AM (Eastern Daylight Time, UTC-04:00) #    Comments [4]  |  Trackback

 

All content © 2008, Sayed Y. Hashimi
On this page
This site
Calendar
<December 2008>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 1.8.5223.2

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts