This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Official Documentation (ws Apache Org) - Axis2 - Part 2 as PDF for free.
AXIS 2 Índice de contenido AXIS 2..................................................................................................................................................1 Apache Axis2 Modules.........................................................................................................................4 Axis2 - WS-Addressing Implementation.........................................................................................4 Using the SOAP Monitor.................................................................................................................4 Welcome to Apache Sandesha2.......................................................................................................6 Resources:...................................................................................................................................6 Securing SOAP Messages with Rampart.........................................................................................7 Content........................................................................................................................................7 Introduction.................................................................................................................................7 Rampart-1.1 Configuration.........................................................................................................7 Rampart Specific Assertions..................................................................................................7 Service Configration...............................................................................................................8 Client Confiuration.................................................................................................................8 Rampart-1.0 Configuration.........................................................................................................8 OutflowSecurity Parameter....................................................................................................8 InflowSecurity Parameter.......................................................................................................9 References.................................................................................................................................10 Examples...................................................................................................................................10 Web Services Policy Support In Apache Axis2..................................................................................12 Content...........................................................................................................................................12 What is Web Services (WS) Policy?..............................................................................................12 Client Side WS-Policy Support.....................................................................................................12 How it works:.................................................................................................................................12 Phase 1: At PolicyEvaluator......................................................................................................12 Phase 2: At AxisServiceBasedMultiLanguageClientEmitter....................................................13 Phase 3: Runtime......................................................................................................................13 Server Side WS-Policy Support.....................................................................................................13 Resources.......................................................................................................................................14 RESTful Web Services Support..........................................................................................................14 Content...........................................................................................................................................14 Introduction....................................................................................................................................14 REST Web Services with HTTP POST.........................................................................................15 Sample REST - HTTP POST Client.........................................................................................15 Access a REST Web Service via HTTP GET................................................................................16 Resources.......................................................................................................................................17 JSON Support in Axis2......................................................................................................................17 What is JSON?...............................................................................................................................17 Why JSON Support for Axis2?......................................................................................................17 How to use JSON in Axis2............................................................................................................18 Step 1.........................................................................................................................................18 Step 2.........................................................................................................................................19 Step 3.........................................................................................................................................19 Tests and Samples..........................................................................................................................19 Integration Test..........................................................................................................................19 Yahoo-JSON Sample.................................................................................................................20 1
Guide to using EJB Provider for Axis2..............................................................................................20 1. Creating a Simple Stateless Session EJB...................................................................................20 2. Creating the Axis2 Service Archive...........................................................................................22 Using the SOAP Monitor...................................................................................................................24 Axis2 Reference Guide.......................................................................................................................27 WSDL2Java Reference..................................................................................................................27 Java2WSDL Reference..................................................................................................................27 Apache Axis2 Tools............................................................................................................................28 Code Generator Tool Guide for Command Line and Ant Task.....................................................29 Content......................................................................................................................................29 Introduction...............................................................................................................................29 Command Line Version.............................................................................................................29 Option Reference..................................................................................................................29 Ant Task....................................................................................................................................30 Ant Task Reference..............................................................................................................30 Example Build File Using the Custom Ant Task..................................................................32 Invoking the Code Generator From Ant...............................................................................33 Appendix...................................................................................................................................40 Service Archive Generator Wizard Guide for Eclipse Plug-in......................................................40 Content......................................................................................................................................40 Introduction...............................................................................................................................40 Installation.................................................................................................................................41 Operation...................................................................................................................................41 Appendix...................................................................................................................................48 Code Generator Wizard Guide for Eclipse Plug-in.......................................................................49 Content......................................................................................................................................49 Introduction...............................................................................................................................49 Installation.................................................................................................................................49 Operation - WSDL2Java...........................................................................................................49 Operation - Java2WSDL...........................................................................................................55 Appendix...................................................................................................................................58 Maven2 AAR Plug-in Guide..........................................................................................................59 Introduction...............................................................................................................................59 Goals.........................................................................................................................................59 Configuration............................................................................................................................59 The aar Goal..............................................................................................................................59 File Sets.....................................................................................................................................60 Maven2 Java2WSDL Plug-in Guide.............................................................................................60 Introduction...............................................................................................................................60 Goals.........................................................................................................................................61 The Java2WSDL Goal..............................................................................................................61 Configuration............................................................................................................................61 Maven2 WSDL2Code Plug-in Guide............................................................................................62 Introduction...............................................................................................................................62 Goals.........................................................................................................................................62 The WSDL2Code Goal.............................................................................................................63 Configuration............................................................................................................................63 Migrating from Apache Axis 1.x to Axis2..........................................................................................64 Content...........................................................................................................................................64 Compatibility.................................................................................................................................64 2
Getting Started...............................................................................................................................65 Custom Deployment of Services, Handlers, and Modules............................................................66 Transports for HTTP Connection..................................................................................................69 Data Binding Support....................................................................................................................69 Best Usage.....................................................................................................................................76 Design Notes......................................................................................................................................76 Axis2 RPC Support........................................................................................................................76 Introduction...............................................................................................................................76 Step 1 - Converting RPC Style WSDL's into Doc/Lit Style WSDL....................................76 Step 2 - Unwrapping the Schema.........................................................................................78 Step 3 - Populate Type Information......................................................................................78 Step 4 - Generate Code with Unwrapped Parameters..........................................................79 Bringing the Parameters Together and Exploding Them..........................................................80 Conclusion................................................................................................................................80
3
Apache Axis2 Modules Axis2 - WS-Addressing Implementation This is an implementation of WS-Addressing submission version (2004-08) and WSAddressing 2005-08 versions. Complete WS-Addressing Final version will be available, once the specification itself gets finalized. Axis2 engine contains addressing support by default. So you may need not put this module, unless you specifically want to use a particular release of this module.
Using the SOAP Monitor Web service developers often want to see the SOAP messages that are being used to invoke the Web services, along with the results of those messages. The goal of the SOAP Monitor utility is to provide a way for the developers to monitor these SOAP messages without requiring any special configuration or restarting the server. In this utility, a handler has been written and added to the global handler chain. As SOAP requests and responses are received, the SOAP message information is forwarded to a SOAP monitor service where it can be displayed using a Web browser interface. The SOAP message information is accessed by a Web browser by going to http://localhost:8080/axis2/SOAPMonitor (where 8080 is the port number where the application server is running). The SOAP message information is displayed through a Web browser by using an applet that opens a socket connection to the SOAP monitor service. This applet requires a Java plug-in 1.3 or higher to be installed in your browser. If you do not have a correct plug-in, the browser will prompt you to install one. The port used by the SOAP monitor service to communicate with applets is configurable. Edit the web.xml file to change the port used by the Axis2 Web application. The SOAP Monitor module (soapmonitor.mar) is available in the axis2.war but it is not engaged by default. The SOAP Monitor is NOT enabled by default for security reasons. The SOAP Monitor can be engaged by inserting the following in the axis2.xml file. ●
<module ref="soapmonitor"/>
In the axis2.xml file, define your phase orders for the 'soapmonitorPhase' referenced in the module.xml of soapmonitor.mars. Below is an example which should NOT be copied exactly, since the default phases change occasionally. The important point here is that 'soapmonitorPhase' should be placed under the 'user can add his own phases to this area' comment in the 'inflow', 'outflow', 'INfaultflow', and 'Outfaultflow' sections.
4
To configure the servlet to communicate with the applet, add the following code to the web.xml (The SOAPMonitorPort is configurable.):
Finally, compile the applet classes and place them at the root (eg: /webapps/axis2/) of the extracted WAR file. You can find the SOAPMonitorApplet.java in the source distribution. To compile, use the following command: ●
Alternatively, you can directly get the compiled applet classes from the WEBINF/lib/axis2-soapmonitor-*.jar which is inside the extracted axis2.war. To extract the axis2soapmonitor-*.jar file, simply execute the command, jar -xf axis2-soapmonitor-*.jar and place the compiled applet classes in the root directory of the extracted WAR, for example, in /webapps/axis2/. Using a Web browser, go to http[s]://host[:port][/webapp]/SOAPMonitor (e.g.http://localhost:8080/axis2/SOAPMonitor) substituting the correct values for your Web application. This will show the SOAP Monitor applet used to view the service requests and responses. Any requests to services that have been configured and deployed correctly should show up in the applet. The SOAPMonitor with attachments currently serializes themselves as base64 characters. It is therefore recommended to use the TCPMon tool to correctly capture MTOM and SWA messages as an multipart mime where the binary data is an attachment.
Welcome to Apache Sandesha2 Sandesha2 is an implementation of WS-ReliableMessaging specification published by IBM, Microsoft, BEA and TIBCO. Sandesha2 was built on top of Axis2. Therefore by using Sandesha2 you can add reliable messaging capability to the web services hosted using Axis2. Sandesha2 can also be used with Axis2 client to interact with already hosted web services in a reliable manner. Please see sandesha2 user guide for more information on using Sandesha2. Read Sandesha2 Architecture guide to see how Sandesha2 work internally.
Securing SOAP Messages with Rampart Axis2 comes with a module based on Apache WSS4J [1] to provide WS-Security features, called "Rampart". This document explains how to engage and configure Rampart module.
Content •
Introduction
•
Rampart-1.1 Configuration
•
•
Rampart Specific Assertions
•
Service Configration
•
Client Confiuration
Rampart-1.0 Configuration •
OutflowSecurity Parameter
•
InflowSecurity Parameter
•
References
•
Examples
Introduction Since rampart module inserts handlers in the system specific security phase, it must be engaged globally. These handlers can be configured using WS-SecurityPolicy[2] and Rampart specific policy assertions. Rampart-1.0 used two axis2 parameters for configuration and these are still supported in the 1.1 release as well. The rampart-1.1 release is available here: ●
First it should be engaged by inserting the following in the axis2.xml file. ●
<module ref="rampart"/>
The web admin interface can be used when Axis2 is deployed in a servlet container such as Apache Tomcat. At the server it is possible to provide security on a per service basis. The configuration parameters should be set in the service.xml file of the service. The client side config parameters should be set in the axis2.xml of the client's Axis2 repository.
Rampart-1.1 Configuration Rampart Specific Assertions Rampart uses the standard WS-SecurityPolicy[2] assertions and also defines its own assertions to be able capture the configuration information that is not provided in WSSecurityPolicy. The Rampart specific assertion's xsd can be found here: ●
Service Configration To configure the service one will simply have to add the policy element into the sevices.xml file. A sample service.xml file is available here: ●
Client Confiuration On the client side, a policy object should be created and loaded into options. Creating the policy object can be done using a "policy.xml" file as follows. //Creating the object StAXOMBuilder builder = new StAXOMBuilder(pathToPolicyfile); Policy clientPolicy = PolicyEngine.getPolicy(builder.getDocumentElement()); //setting the object Options options = new Options(); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, clientPolicy);
Rampart-1.0 Configuration Rampart module uses two parameters: •
OutflowSecurity
•
InflowSecurity
The configuration that can go in each of these parameters are described below:
OutflowSecurity Parameter This parameter is used to configure the outflow security handler. The outflow invoked more than once in the outflow one can provide configuration for invocations. The 'action' element describes one of these configurations. 'OutflowSecurity' parameter can contain more than one 'action' elements. The 'action' element is available here: ●
handler can be each of these Therefore the schema of this
An outflow configuration to add a timestamp, sign and encrypt the message once, is shown in Example 1 and Example 2 shows how to sign the message twice by chaining the outflow handler (using two 'action' elements) Following is a description of the elements that can go in an 'action' element of the OutflowSecurity parameter Parameter
Description
Example
items
Add a Timestamp, Sign the SOAP body and Encrypt the SOAP body Security actions for the inflow Timestamp Signature Encrypt
user
The user's name
Set alias of the key to be used to sign <user> bob
passwordCallback Callback class used to provide <passwordCallbackClass> Class the password required to org.apache.axis2.security.PWCallback
8
create the UsernameToken or wordCallbackClass> to sign the message property file used to get the signature parameters such as signaturePropFile crypto provider, keystore and its password
Set example.properties file as the signature property file <signaturePropFile> example.properties
Key identifier to be used in signatureKeyIdent referring the key in the ifier signature
Use the serial number of the certificate <signatureKeyIdentifier> IssuerSerial
Key identifier to be used in encryptionKeyIde referring the key in ntifier encryption
Use the serial number of the certificate <encryptionKeyIdentifier>IssuerSerial
encryptionUser
The user's name for encryption.
<encryptionUser>alice
encryptionSymAlg Symmetric algorithm to be orithm used for encryption
Use AES-128 <encryptionSymAlgorithm> http://www.w3.org/2001/04/xmlenc#aes12 8-cbc
Use RSA-OAEP <parameter name="encryptionSymAlgorithm"> http://www.w3.org/2001/04/xmlenc#rsaoaep-mgf1p Sign Foo and Bar elements qualified by "http://app.ns/ns" <signatureParts> {Element}{http://app.ns/ns}Foo;{Element} {http://app.ns/ns}Bar
signatureParts
Sign multiple parts in the SOAP message
optimizeParts
Optimize the CipherValue MTOM Optimize the elements specified by the XPath query //xenc:EncryptedData/xenc:CipherData/xen c:CipherValue
InflowSecurity Parameter This parameter is used to configure the inflow security handler. The 'action' element is used to encapsulate the configuration elements here as well. The schema of the 'action' element is available here. Example 3 shows the configuration to decrypt, verify signature and validate timestamp. Parameter
Description
Example
items
first the incoming message should be decrypted and then the signatures should be verified and should be checked for the Security actions for the inflow availability of the Timestamp Timestamp Signature Encrypt
Callback class used to obtain passwordCallback password for decryption and Class UsernameToken verification signaturePropFile
Please note that the '.properties' files used in properties such as OutSignaturePropFile are the same property files that are using in the WSS4J project. Following shows the properties defined in a sample property file org.apache.ws.security.crypto.provider=org.apache.ws.security.components .crypto.Merlin org.apache.ws.security.crypto.merlin.keystore.type=pkcs12 org.apache.ws.security.crypto.merlin.keystore.password=security org.apache.ws.security.crypto.merlin.keystore.alias=16c73ab6-b892-458fabf5-2f875f74882e org.apache.ws.security.crypto.merlin.alias.password=security org.apache.ws.security.crypto.merlin.file=keys/x509.PFX.MSFT org.apache.ws.security.crypto.provider defines the implementation of the org.apache.ws.security.components.crypto.Crypto interface to provide the crypto information required by WSS4J. The other properties defined are the configuration properties used by the implementation class (org.apache.ws.security.components.crypto.Merlin).
Examples Example 1: An outflow configuration to add a timestamp, sign and encrypt the message once
10
Example 2: An outflow configuration to sign the message twice and add a timestamp
Example 3: An inflow configuration to decrypt, verify signature and validate timestamp
11
Web Services Policy Support In Apache Axis2 This document gives you an introduction to the role of Web services policy in Apache Axis2. Send your feedback to: [email protected]. (Subscription details are available on the Axis2 site.) Kindly prefix every email subject with [Axis2].
Content •
What is Web Services (WS) Policy?
•
Client Side WS-Policy Support
•
Server Side WS-Policy Support
•
Resources
What is Web Services (WS) Policy? To consume non trivial web services you must fully understand its XML contract (WSDL) along with any other additional requirements, capabilities, or preferences that translate to the configuration of the service and essentially becomes the policies of the service. WS Policy framework provides a way to express the policies of a service in a machinereadable way. A Web services infrastructure can be enhanced to understand and enforce policies at runtime. For instance, a service author might write a policy requiring a digital signature and encryption, while service consumers can use the policy information to reason out whether they can adhere to this policy information to use the service. Furthermore, Web service infrastructure can be enhanced to enforce those requirements without requiring the service author to write even a single line of code.
Client Side WS-Policy Support This release fully supports WS Policy at client-side. It means that when you codegen a stub against a WSLD which contains policies, the stub will contain the capability to engage the required modules with the appropriate configurations, plus it will generate additional methods in the stub where the user can set certain properties. For instance, if there is a security policy attached to a binding, the generated stub will engage the security module for that service with the appropriate security configurations with some addtional methods that the user can use to set properties in the generated stub.
How it works: Phase 1: At PolicyEvaluator The Codegen engine runs a few of its registered extensions before it generates the stub. When the PolicyEvalutor (which is a registered Codegen extension) is initialized, it populates a registry of QNames of supported policy assertions to PolicyExtensions. For instance, module Foo might have a mapping of assertion {http://test.com/foo, foo} which means any assertion that has this name will be processed by this module. The Foo module might implement the ModulePolicyExtension interface through which the PolicyExtension object can be obtained. A PolicyExtension is the access point for a module to add any additional methods to the
12
stub. For instance a Reliable Messaging module can add startSequence() and endSequence() methods to the stub, that the user must call to start and end an RM sequence. Then at the engagement of the PolicyEvaluator, the effective policy of each message of every operation is calculated based on policy information declared in the WSDL document. Here we assume that the effective policy of an operation contains a single alternative (Multiple policy alternatives are not supported). Then we split that policy as follows into few other policies such that, each policy will contain assertions that can be processed by a single module. <wsp:Policy>
=>
<wsp:Policy>
<wsp:Policy>
Then each policy is given the appropriate PolicyExtension with an org.w3c.Element type object to which the module can append any other elements/attributes it wishes. Those attributes/elements should resolve to meaningful stub functions through the Custom PolicyExtensionTemplate.xsl at a latter point of time. For instance, depending on the policy, the Security module can append <username>, <passwd> elements to the given element as children, which are later resolved into setUsername(..), setPasswd(..), functions of the stub. This way a module can include additional methods to the stub that can be used to get specific propreties from the user. These methods store any user input in the ServiceClient properties (ServiceClient.getOptions().putProperty(...)) which can later be accessed by the module.
Phase 2: At AxisServiceBasedMultiLanguageClientEmitter Further, policies (based on the WSDL) at appropriate levels (service level, operation level) are stored as policy strings in the stub. If there are a few policies at a given level, they are merged together and represented as a single policy in the stub. Few more generic methods are also added to the stub which are used to evaluate and process the policies at runtime.
Phase 3: Runtime When a new stub object is created, the policy strings in the stub are converted into policy objects and are set in the AxisDescription hierarchy that is used in the stub. In other words, any policy information available in the WSDL will be preserved in the AxisService object that is used in the stub. Then based on its policy, each AxisDescription is engaged to a set of modules. Modules can do a prior calculation of configurations if needed at the engagement. When the stub method is invoked, those modules which are engaged to that AxisDescription, access the policy for that operation via the AxisDescription object. It can get the other required information from the MessageContext, which is stored by stub methods that the module has added to the stub earlier, through the ModulePolicyExtension implementation. The modules are required to load their configurations according to the effective policy, which is set at AxisDescription, and the properties they get via MessageContext.
Server Side WS-Policy Support In this current release, the Apache Axis2 framework uses the WS-Commons/Neethi framework to manipulate policy documents. All its description builders store the policy information included in description documents (services.xml, axis2.xml, .. etc) in the appropriate description classes. This information is available at both deployment and run time
13
via these description classes. When generating WSDL dynamically for each service, policy information in the description classes is included. For instance, if you declare a policy in axis2.xml, then that policy is reflected in the service elements of the WSDL of every service. If a policy is declared in a services.xml, it is shown in the service element of WSDL for that particular service. Further, when a service is deployed, an arbitary policy alternative is selected and set for each AxisOperation and AxisMessages of the AxisService. If the selected Policy alternative cannot be supported by any modules that are capable of processing the selective alternative, then the service is considered as a faulty service. Else, the set of modules is engaged at appropriate levels to support the requirments and capabilities that are defined in the Policies associated with the AxisDescription. It is evident that there is some work left to make Apache Axis2 a fully fledged ws-policy supported Web service infrastructure. However, it is encouraging to note that we've taken the first steps towards this goal. We appreciate any suggestions, patches, etc., you send us in this regard. Keep on contributing!
Resources Apache Neethi (WS Policy Implementation) official site: ●
http://ws.apache.org/commons/neethi/index.html
Sanka Samaranayake, March 2006. Web services Policy - Why, What & How: ●
RESTful Web Services Support This document presents an introduction on REST and REST with HTTP POST and GET.
Content •
Introduction
•
Doing REST Web Services with HTTP POST •
•
Sample REST - HTTP POST Client
Access a REST Web Service via HTTP GET
Introduction WSDL 2.0 HTTP Binding defines a way to implement REST (Representational State Transfer) with Web services. Axis2 implements the most defined HTTP binding specification. REST Web services are a reduced subset of the usual Web service stack. The Axis2 REST implementation assumes the following properties: 1. REST Web services are Synchronous and Request Response in nature. 2. When REST Web services are accessed via GET, the service and the operations are identified based on the URL. The parameters are assumed as parameters of the Web
14
service. In this case, the GET based REST Web services support only simple types as arguments and it should adhere to the IRI style. 3. POST based Web services do not need a SOAP Envelope or a SOAP Body. REST Web Services do not have Headers and the payload is sent directly. Axis2 can be configured as a REST Container and can be used to send and receive RESTful Web service requests and responses. REST Web services can be accessed using HTTP GET and POST.
REST Web Services with HTTP POST If REST is enabled, the Axis2 server will act as both a REST endpoint and a SOAP endpoint. When a message is received, if the content type is text/xml and if the SOAPAction Header is missing, then the message is treated as a RESTful Message, if not it is treated as a usual SOAP Message. On sending a message, whether the message is RESTful or not, can be decided from the client API. Set a property in the client API. ... Options options = new Options(); options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); ...
Sample REST - HTTP POST Client There is an example named, userguide.clients.RESTClient.java found in AXIS2_HOME/samples/userguide/src/userguide/clients which demonstrates the usage of the above. It uses the "echo" operation of the userguide.example1.MyServiceof the AXIS2_HOME/samples/userguide/src/userguide/example1. The class source will be as follows: public class RESTClient { private static String toEpr = "http://localhost:8080/axis2/services/MyService"; public static void main(String[] args) throws AxisFault { Options options = new Options(); options.setTo(new EndpointReference(toEpr)); options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); ServiceClient sender = new ServiceClient(); sender.engageModule(new QName(Constants.MODULE_ADDRESSING)); sender.setOptions(options); OMElement result = sender.sendReceive(getPayload()); try { XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(System.out); result.serialize(writer); writer.flush(); }
Access a REST Web Service via HTTP GET Axis2 allows users to access Web services that have simple type parameters via HTTP GET. For example, the following URL requests the Version Service via HTTP GET. However, the Web service arriving via GET assumes REST. Other parameters are converted into XML and put into the SOAP body. ●
JSON Support in Axis2 This document explains the JSON support implementation in Axis2. It includes an introduction to JSON, an outline as to why JSON support is useful to Axis2 and how to it should be used. Document also provides details on test cases and samples.
What is JSON? JSON (Java Script Object Notation) is another data exchangeable format like XML, but it is more lightweight and easily readable. It is based on a subset of JavaScript language. Therefore, JavaScript can understand JSON, and it can make JavaScript objects by using JSON strings. JSON is based on key-value pairs and it uses colons to separate keys and values. JSON doesn't use end tags, and it uses braces (curly brackets) to enclose JSON Objects. json object == {?root??:{?test??:??json object??}} When it comes to converting XML to JSON and vice versa, there are two major conventions, one named "Badgerfish" and the other, ?Mapped??. The main difference between these two conventions exists in the way they map XML namespaces into JSON. <xsl:root xmlns:xsl="http://foo.com">my json string This XML string can be converted into JSON as follows. Using ?Badgerfish?? {"xsl:root":{"@xmlns":{"xsl":"http://foo.com"},"data":{"$":"my json string"}}} Using ?Mapped?? If we use the namespace mapping as http://foo.com -> foo {"foo.root":{"data":"my json string"}} JSON support implementation is a new feature in Apache Axis2/Java. It will become a crucial improvement in the future with applications like JavaScript Web services.
Why JSON Support for Axis2? Apache Axis2 is a Web services stack that delivers incoming messages into target applications. In most cases, these messages are SOAP messages. In addition, it is also
17
possible to send REST messages through Axis2. Both types of messages use XML as their data exchangeable format. So if we can use XML as a format, why not use JSON as another format? There are many advantages of implementing JSON support in Axis2. Mainly, it helps the JavaScript users (services and clients written in JavaScript) to deal with Axis2. When the service or the client is in JavaScript, it can use the JSON string and directly build JavaScript objects to retrieve information, without having to build the object model (OMElement in Axis2). Also, JavaScript services can return the response through Axis2, just as a JSON string can be shipped in a JSONDataSource. Other than for that, there are some extra advantages of using JSON in comparison to XML. Although the conversation ?XML or JSON??? is still a hot topic, many people accept the fact that JSON can be passed and built easily by machines than in the case of XML. For more details of this implementation architecture, refer to the article "JSON Support for Apache Axis2"
How to use JSON in Axis2 At the moment JSON doesn't have a standard and unique content type. ?application/json?? (this is the content type which is approved in the JSON RFC ), ?text/javascript?? and ? text/json?? are some of the commonly used content types of JSON. Due to this problem, in Axis2, the user has been given the freedom of selecting the content type.
Step 1 Map the appropriate MessageFormatter and OMBuilder with the content type you are using in the axis2.xml file. e.g.1: If you are using the ?Mapped?? convention with the content type ?application/json?? <messageFormatters> <messageFormatter contentType="application/json" class="org.apache.axis2.json.JSONMessageFormatter"/> <messageBuilders> <messageBuilder contentType="application/json" class="org.apache.axis2.json.JSONOMBuilder"/> e.g.2: If you text/javascript??
Step 2 On the client side, make the ConfigurationContext by reading the axis2.xml in which the correct mappings are given. File configFile = new File("test-resources/axis2.xml"); configurationContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(nul l, configFile.getAbsolutePath()); .......... ServiceClient sender = new ServiceClient(configurationContext, null);
Step 3 Set the MESSAGE_TYPE option with exactly the same content type you used in the axis2.xml. e.g. If you use the content type ?application/json??, Options options = new Options(); options.setProperty(Constants.Configuration.MESSAGE_TYPE, ? application/json??); //more options //................... ServiceClient sender = new ServiceClient(configurationContext, null); sender.setOptions(options); If you are sending a request to a remote service, you have to know the exact JSON content type that is used by that service, and you have to use that content type in your client as well. HTTP POST method is used as the default to send JSON messages through Axis2, if the HTTP method is not set by the user. But if you want to send JSON in HTTP GET method as a parameter, you can do that by just setting an option on the client side. options.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); Here, the Axis2 receiving side (JSONOMBuilder) builds the OMElement by reading the JSON string which is sent as a parameter. The request can be made even through the browser. e.g. Sample JSON request through HTTP GET. The JSON message is encoded and sent.
GET /axis2/services/EchoXMLService/echoOM?query=%7B%22echoOM%22:%7B%22data%2 2:%5B%22my%20json%20string%22,%22my%20second%20json%20string%22%5D%7D%7D HTTP/1.1
Tests and Samples Integration Test The JSON integration test is available under ?test?? in the ?json?? module of Axis2. It uses the SimpleHTTPServer to deploy the service. A simple echo service is used to return the
19
incoming OMSourcedElementImpl object, which contains the JSONDataSource. There are two test cases for two different conventions and another one test case to send the request in GET.
Yahoo-JSON Sample This sample is available in the ?samples?? module of Axis2. It is a client which calls the Yahoo search API using the GET method, with the parameter ?output=json??. The Yahoo search service sends the response as a ?Mapped?? formatted JSON string with the content type ?text/javascript??. This content type is mapped with the JSONOMBuilder in the axis2.xml. All the results are shown in a GUI. To run the sample, execute the ant script. These two applications are good examples of using JSON support for Axis2. You can understand the architecture of JSON support implementation in Axis2 by looking at these samples.
Guide to using EJB Provider for Axis2 The EJB message receiver allows one to access stateless session EJBs (Enterprise JavaBeans) through Web services. The example used in this guide illustrates how to use EJB provider that ships with axis2 to access EJBs deployed on a J2EE server such as Geronimo or Jboss. This example explains how to use Geronimo 1.1 and Jboss 4.0.4.GA as application server. The following steps will take you through the example through which we will explain how to use an EJB provider in Axis2
1. Creating a Simple Stateless Session EJB First, we need to create a stateless session EJB. Use the following files to make an EJB for testing: Remote interface (Hello.java) package my.ejb; import javax.ejb.EJBObject; public interface Hello extends EJBObject, HelloBusiness { } The following interface defines the business methods available in 1.HelloBusiness.java package my.ejb; import java.rmi.RemoteException; public interface HelloBusiness { public String sayHello(String name) throws RemoteException; } 2, Remote home interface - HelloHome.java package my.ejb; import javax.ejb.EJBHome; import javax.ejb.CreateException; import java.rmi.RemoteException; public interface HelloHome extends EJBHome { public Hello create() throws CreateException, RemoteException; }
20
3. Bean class - HelloBean.java package my.ejb; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.ejb.EJBException; import javax.ejb.CreateException; public class HelloBean implements SessionBean { public void setSessionContext(SessionContext sessionContext) throws EJBException {}
}
public void ejbRemove() throws EJBException {} public void ejbActivate() throws EJBException {} public void ejbPassivate() throws EJBException {} public void ejbCreate() throws CreateException {} public String sayHello(String name) { return "Hello " + name + ", Have a nice day!"; }
4. Deployment descriptor - ejb-jar.xml <ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd" version="2.1"> <enterprise-beans> <session> <ejb-name>Hello my.ejb.HelloHomemy.ejb.Hello <ejb-class>my.ejb.HelloBean <session-type>Stateless Bean <method> <ejb-name>Hello <method-name>* Required Now we have to write application server specific deployment descriptor(s) for the Hello EJB. Following listing shows an example Geronimo/OpenEJB deployment descriptor (openejbjar.xml)
21
<enterprise-beans> <session> <ejb-name>Hello <jndi-name>my/ejb/HelloBean If you want to test on JBoss, use the following JBoss deployment descriptor (jboss.xml) <jboss> <enterprise-beans> <session> <ejb-name>Hello <jndi-name>my/ejb/HelloBean Compile the above java classes and bundle the compiled classes and the XML files into a jar file (HelloEJB.jar) as shown below. HelloEJB.jar | +--META-INF | +--ejb-jar.xml | +--jboss.xml [If you want to deploy on Jboss] | +--openejb-jar.xml [If you want to deploy on Geronimo/Openejb] | +--my +--ejb | +--Hello.class +--HelloBean.class +--HelloBusiness.class +--HelloHome.class Deploy HelloEJB.jar on appropriate J2EE application server.
2. Creating the Axis2 Service Archive Now we need to make the services.xml file.
22
<serviceGroup> <service name="HelloBeanService"> <description>Hello! web service <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.ejb.EJBInOnlyMessageReceiver"/> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.ejb.EJBMessageReceiver"/> <parameter name="ServiceClass" locked="false"> my.ejb.HelloBusiness <parameter name="remoteInterfaceName">my.ejb.Hello <parameter name="homeInterfaceName">my.ejb.HelloHome <parameter name="beanJndiName">my/ejb/HelloBean <parameter name="providerUrl">[URL] <parameter name="jndiContextClass"> [Context Factory Class Name] In the above services.xml file, replace the [URL] and [Context Factory Class Name] with valid values as follows: i.e. If the EJB is deployed on Geronimo: Replace [URL] by 127.0.0.1:4201 Replace [Context Factory Class Name] by org.openejb.client.JNDIContext For Jboss: Replace [URL] by jnp://localhost:1099 Replace [Context Factory Class Name] by org.jnp.interfaces.NamingContextFactory Bundle the HelloBeanService.wsdl, services.xml, remote interface class and home interface class as illustrated below: HelloBeanService.aar | +--META-INF | +--services.xml | +--lib | +--[jars used by the ejb client eg.initial context factory classes] | +--my +--ejb +--Hello.class +--HelloBusiness.class +--HelloHome.class The lib directory of HelloBeanService.aar must contain all the libraries needed to access the EJB. If the EJB is deployed on Geronimo, add the following jar files to the lib directory. •
cglib-nodep-2.1_3.jar
•
geronimo-ejb_2.1_spec-1.0.1.jar
•
geronimo-j2ee-jacc_1.0_spec-1.0.1.jar
23
•
geronimo-kernel-1.1.jar
•
geronimo-security-1.1.jar
•
openejb-core-2.1.jar
For JBoss add the following jar files. •
jnp-client.jar
•
jboss-client.jar
•
jboss-common-client.jar
•
jboss-remoting.jar
•
jboss-serialization.jar
•
jboss-transaction-client.jar
•
concurrent.jar
•
jbosssx-client.jar
•
jboss-j2ee.jar
Deploy HelloBeanService.aar on an Axis2 server. Now you can access the Hello EJB through Web services. Since our EJB message receivers extend RPC message receivers, org.apache.axis2.rpc.client.RPCServiceClient can be used to invoke the service as illustrated in the following code fragment.
... RPCServiceClient serviceClient = new RPCServiceClient(); Options options = serviceClient.getOptions(); EndpointReference targetEPR = new EndpointReference("http://localhost:8080/axis2/services/HelloBeanService "); options.setTo(targetEPR); QName hello = new QName("http://ejb.my/xsd", "sayHello"); Object[] helloArgs = new Object[] {"John"}; System.out.println(serviceClient.invokeBlocking(hello, helloArgs).getFirstElement().getText()); ...
Using the SOAP Monitor Web service developers often want to see the SOAP messages that are being used to invoke the Web services, along with the results of those messages. The goal of the SOAP Monitor utility is to provide a way for the developers to monitor these SOAP messages without requiring any special configuration or restarting the server. In this utility, a handler has been written and added to the global handler chain. As SOAP requests and responses are received, the SOAP message information is forwarded to a SOAP monitor service where it can be displayed using a Web browser interface. The SOAP message information is accessed by a Web browser by going to http://localhost:8080/axis2/SOAPMonitor (where 8080 is the port number where the application server is running). The SOAP message information is displayed through a Web browser by using an applet that opens a socket connection to the SOAP monitor service. This applet requires a Java plug-in 1.3 or higher to be installed in your browser. If you do not have a correct plug-in, the browser will prompt you to install one. The port used by the SOAP
24
monitor service to communicate with applets is configurable. Edit the web.xml file to change the port used by the Axis2 Web application. The SOAP Monitor module (soapmonitor.mar) is available in the axis2.war but it is not engaged by default. The SOAP Monitor is NOT enabled by default for security reasons. The SOAP Monitor can be engaged by inserting the following in the axis2.xml file. <module ref="soapmonitor"/> In the axis2.xml file, define your phase orders for the 'soapmonitorPhase' referenced in the module.xml of soapmonitor.mars. Below is an example which should NOT be copied exactly, since the default phases change occasionally. The important point here is that 'soapmonitorPhase' should be placed under the 'user can add his own phases to this area' comment in the 'inflow', 'outflow', 'INfaultflow', and 'Outfaultflow' sections.
25
To configure the servlet to communicate with the applet, add the following code to the web.xml (The SOAPMonitorPort is configurable.): <servlet> <servlet-name>SOAPMonitorService SOAPMonitorService <servlet-class> org.apache.axis2.soapmonitor.servlet.SOAPMonitorService <param-name>SOAPMonitorPort <param-value>5001 1 <servlet-mapping> <servlet-name>SOAPMonitorService /SOAPMonitor Finally, compile the applet classes and place them at the root (eg: /webapps/axis2/) of the extracted WAR file. You can find the SOAPMonitorApplet.java in the source distribution. To compile, use the following command: javac -classpath axis2-soapmonitor.jar SOAPMonitorApplet.java Alternatively, you can directly get the compiled applet classes from the WEBINF/lib/axis2-soapmonitor-*.jar which is inside the extracted axis2.war. To extract the axis2soapmonitor-*.jar file, simply execute the command, jar -xf axis2-soapmonitor-*.jar and place the compiled applet classes in the root directory of the extracted WAR, for example, in /webapps/axis2/. Using a Web browser, go to: ●
substituting the correct values for your Web application. This will show the SOAP Monitor applet used to view the service requests and responses. Any requests to services that have been configured and deployed correctly should show up in the applet. The SOAPMonitor with attachments currently serializes themselves as base64 characters. It is therefore recommended to use the TCPMon tool to correctly capture MTOM and SWA messages as an multipart mime where the binary data is an attachment.
26
Axis2 Reference Guide WSDL2Java Reference NAME wsdl2java.sh or wsdl2java.bat - Generates java code according to a given WSDL file to handle Web service invocation. These scripts can be found under the bin directory of the Axis2 distribution. SYNOPSIS wsdl2java.sh [OPTION]... -uri DESCRIPTION Given a WSDL file, this generates java code to handle Web service invocations. -o