You are on page 1of 25

Java Web Services Interview Questions and Answers: Overview

Q. What are the different application


integration styles?

A. There are a number of different


integration styles like

1. Shared database
2. batch file transfer
3. Invoking remote procedures (RPC)
4. Exchanging asynchronous messages over
a message oriented middle-ware (MOM).
Q. What are the different styles of Web Services used for application integration?
A. SOAP WS and RESTful Web Service

Q. What are the differences between both SOAP WS and RESTful WS?
A.
 The SOAP WS supports both remote procedure call (i.e. RPC) and message
oriented middle-ware (MOM) integration styles. The Restful Web Service
supports only RPC integration style.

 The SOAP WS is transport protocol neutral. Supports multiple protocols like


HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol
specific. Supports only HTTP or HTTPS protocols.

 The SOAP WS permits only XML data format.You define operations, which
tunnels through the POST. The focus is on accessing the named operations and
exposing the application logic as a service. The REST permits multiple data
formats like XML, JSON data, text, HTML, etc. Any browser can be used
because the REST approach uses the standard GET, PUT, POST, and DELETE
Web operations. The focus is on accessing the named resources and exposing the
data as a service. REST has AJAX support. It can use the XMLHttpRequest
object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.

GET - read()
POST - create()
PUT - update()
DELETE - delete()

 SOAP based reads cannot be cached. REST based reads can be cached. Performs
and scales better.

 SOAP WS supports both SSL security and WS-security, which adds some
enterprise security features like maintaining security right up to the point where it
is needed, maintaining identities through intermediaries and not just point to point
SSL only, securing different parts of the message with different security
algorithms, etc. The REST supports only point-to-point SSL security. The SSL
encrypts the whole message, whether all of it is sensitive or not.

 The SOAP has comprehensive support for both ACID based transaction
management for short-lived transactions and compensation based transaction
management for long-running transactions. It also supports two-phase commit
across distributed resources. The REST supports transactions, but it is neither
ACID compliant nor can provide two phase commit across distributed
transactional resources as it is limited by its HTTP protocol.

 The SOAP has success or retry logic built in and provides end-to-end reliability
even through SOAP intermediaries. REST does not have a standard messaging
system, and expects clients invoking the service to deal with communication
failures by retrying.
Q. How would you decide what style of Web Service to use? SOAP WS or REST?
A. In general, a REST based Web service is preferred due to its simplicity, performance,
scalability, and support for multiple data formats. SOAP is favored where service requires
comprehensive support for security and transactional reliability.

The answer really depends on the functional and non-functional requirements. Asking the
questions listed below will help you choose.

 Does the service expose data or business logic? (REST is a better choice for
exposing data, SOAP WS might be a better choice for logic).Do the consumers
and the service providers require a formal contract? (SOAP has a formal contract
via WSDL)
 Do we need to support multiple data formats?
 Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
 Is the call synchronous or asynchronous?
 Is the call stateful or stateless? (REST is suited for statless CRUD operations)
 What level of security is required? (SOAP WS has better support for security)
 What level of transaction support is required? (SOAP WS has better support
for transaction management)
 Do we have limited band width? (SOAP is more verbose)
 What’s best for the developers who will build clients for the service? (REST is
easier to implement, test, and maintain)

Q. What tools do you use to test your Web Services?


A. SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.

Q. What is the difference between SOA and a Web service?


A.

SOA is a software design principle and an architectural pattern for implementing loosely
coupled, reusable and coarse grained services. You can implement SOA using any
protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc.
Messages can be in XML or Data Transfer Objects (DTOs).

Web service is an implementation technology and one of the ways to implement SOA.
You can build SOA based applications without using Web services – for example by
using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But
what Web services offer is the standards based and platform-independent service via
HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between
heterogeneous technologies such as J2EE and .NET.

Q. Web services when you can use traditional style middle-ware such as RPC, CORBA,
RMI and DCOM?
A.

The traditional middle-wares tightly couple connections to the applications and it can
break if you make any modification to your application. Tightly coupled applications are
hard to maintain and less reusable. Generally do not support heterogeneity. Do not work
across Internet. Can be more expensive and hard to use.

Web Services support loosely coupled connections. The interface of the Web service
provides a layer of abstraction between the client and the server. The loosely coupled
applications reduce the cost of maintenance and increases re-usability. Web Services
present a new form of middle-ware based on XML and Web. Web services are language
and platform independent. You can develop a Web service using any language and deploy
it on to any platform, from small device to the largest supercomputer. Web service uses
language neutral protocols such as HTTP and communicates between disparate
applications by passing XML messages to each other via a Web API. Do work across
internet, less expensive and easier to use.

Q. What are the different approaches to developing a SOAP based Web service? A. 2
approaches.

 The contract-first approach, where you define the contract first with XSD and
WSDL and the generate the Java classes from the contract.
 The contract-last approach where you define the Java classes first and then
generate the contract, which is the WSDL file from the Java classes.

Note: The WSDL describes all operations that the service provides, locations of the
endpoints (i.e.e where the services can be invoked), and simple and complex elements
that can be passed in requests and responses.

Q. What are the pros and cons of each approach, and which approach would you prefer?

A.

Contract-first Web service

PROS:

 Clients are decoupled from the server, hence the implementation logic can be
revised on the server without affecting the clients.
 Developers can work simultaneously on client and server side based on the
contract both agreed on.
 You have full control over how the request and response messages are constructed
-- for example, should "status" go as an element or as an attribute? The contract
clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries
without having to worry if the "status" would be generated as "attribute" instead
of an element. Potentially, even Web service frameworks and tool kits can be
changed as well from say Apache Axis to Apache CXF, etc

CONS:

 More upfront work is involved in setting up the XSDs and WSDLs. There are
tools like XML Spy, Oxygen XML, etc to make things easier. The object models
need to be written as well.

 Developers need to learn XSDs and WSDLs in addition to just knowing Java.

Contract-last Web service

PROS:
 Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The
services are created quickly by exposing the existing service logic with
frameworks/tool sets. For example, via IDE based wizards, etc.

 The learning curve and development time can be smaller compared to the
Contract-first Web service.

CONS:
 The development time can be shorter to initially develop it, but what about the on
going maintenance and extension time if the contract changes or new elements
need to be added? In this approach, since the clients and servers are more tightly
coupled, the future changes may break the client contract and affect all clients or
require the services to be properly versioned and managed.
 In this approach, The XML payloads cannot be controlled. This means changing
your OXM libraries could cause something that used to be an element to become
an attribute with the change of the OXM.

So, which approach will you choose?

The best practice is to use "contract-first", and here is the link that explains this much
better with examples --> contract-first versus contract-last web services In a nutshell, the
contract-last is more fragile than the "contract-first". You will have to decide what is
most appropriate based on your requirements, tool sets you use, etc.
Note: More Java Web Services interview questions and answers including WSDL, SOAP,
UDDI, JAXR, SAAJ, etc are covered in Java/J2EE Job Interview Companion with
diagrams.

More Web services Interview Questions and Answers


Java Web Services Interview Questions and Answers: RESTful Web services
Java Web Services Interview Questions and Answers: SOAP clients
SOAP versus RESTful Web service -- comparison

Web Services Interview Questions and Answers - RESTful Web Service


Overview

Q. Why would you use a RESTful Web service?


A. RESTful Web service is easy, straightforward, supports multiple data formats like
XML, JSON, etc and easily testable. For example,

It can be tested by

1. Directly invoking the service from the browser by typing a URL if the RESTFul
service supports GET request with query parameters. For example,

?
1 http://localhost:8080/executionservices/execution/1.0/order/create?accountId=123&qty=2

2. You could use a Firefox plugin like "poster" to post an XML request to your service.

3. You could write a Web Service client to consume the Web service from a test class or a
separate application client. You could use libraries like HttpClient, CXF Client,
URLConnection, etc to connect to the RESTful service.

Q. What are the various implementations of JAX-RS available to choose from in Java?
A. When you're developing with REST in Java, you have a lot of options to choose from
in terms of the frameworks. There's Jersey, the reference implementation from Oracle,
then you have RestEasy, the JBoss choice, and there is CXF, the Apache choice.

Q. How would you go about implemnting the RESTful Web service using the framework
of your choice?
A. Let's look at CXF as it is easy to configure. The steps involved include

 Bringing in the relevant framework jar files for Spring and CXF. For example, via
Maven using a pom.xml file.
 If the request and responses are XML based POST, then define an XSD file and
generate JAXB annotated classes for marshalling and unmarshalling the request
and response.
 Define the WebService interface and implementation classes.
 Define any interceptor and filter classes if required to intercept the request and
responses for implementing the cross-cutting concerns like security validation,
logging, auditing, setting up or initializing the locale, etc
 Wire up the classes via Spring and CXF config files. For example, webservices-
config.xml and cxf.xml.
 Finally define the CXF servlet and bootstrap the relevant config files via the
web.xml file.

Firstly, configure the maven pom.xml file to include the relevant jar files.

?
1
2 <dependency>
3 <groupId>org.springframework</groupId>
4 <artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
5 </dependency>
6 <dependency>
7 <groupId>org.springframework</groupId>
8 <artifactId>spring-web</artifactId>
9 <version>3.0.5.RELEASE</version>
</dependency>
10 <dependency>
11 <groupId>org.apache.cxf</groupId>
12 <artifactId>cxf-rt-frontend-jaxrs</artifactId>
13 <version>2.2.3</version>
</dependency>
14
15

Define the request and response objects with JAXB annotations as our Web service
payload is XML, hence it needs to be marshalled (i.e. convert from object to XML) and
unmarshalled (XML to object). OrderRequest & OrderResponse classes can be
generated from XSD file OrderRequestResponde.xsd shown below.

?
1 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
3 <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
4
5 <xs:complexType name="OrderResponse">
6 <xs:sequence>
7 <xs:element name="orderId" type="xs:string" minOccurs="0" />
8 <xs:element name="responseCode" type="responseCode"
minOccurs="0" />
9 <xs:element name="accountId" type="xs:string" minOccurs="0" />
10 </xs:sequence>
11 </xs:complexType>
12
13 <xs:complexType name="OrderRequest">
14 <xs:sequence>
<xs:element name="accountId" type="xs:string" minOccurs="0" />
15 <xs:element name="quantity" type="xs:int" minOccurs="0" />
16 </xs:sequence>
17 </xs:complexType>
18
19 <xs:simpleType name="responseCode">
<xs:restriction base="xs:string">
20 <xs:enumeration value="SUCCESS" />
21 <xs:enumeration value="FAILED" />
22 <xs:enumeration value="REJECTED" />
23 <xs:enumeration value="UNKNOWN" />
24 </xs:restriction>
</xs:simpleType>
25
26 </xs:schema>
27
28

The .java files can be generated via the xjc command to generate JAXB annotated
classes. The OrderRequest.java, OrderResponse.java, ResponseCode.java and
ObjectFactory.java files are generated under the package "com.myapp.data.order".

?
xjc -d "c:\temp" -p "com.myapp.data.order"
1 "C:\temp\xsd\OrderRequestResponde.xsd" -extension

Here are the generated files:

OrderRequest.java

?
1 //
// This file was generated by the JavaTM Architecture for XML
2
Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6
3 // See <a
4 href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
5 // Any modifications to this file will be lost upon recompilation of
6 the source schema.
7 // Generated on: 2012.02.07 at 05:07:31 PM EST
8 //
9
10
package com.myapp.data.order;
11
12 import javax.xml.bind.annotation.XmlAccessType;
13 import javax.xml.bind.annotation.XmlAccessorType;
14 import javax.xml.bind.annotation.XmlType;
15
16
17 /**
* Java class for OrderRequest complex type.
18 *
19 *
20 The following schema fragment specifies the expected content contained
21 within this class.
22 *
*
23 <pre>* <complexType name="OrderRequest">
24 * <complexContent>
25 * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
26 * <sequence>
* <element name="accountId"
27 type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
28 * <element name="quantity"
29 type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
30 * </sequence>
31 * </restriction>
* </complexContent>
32 * </complexType>
33 * </pre>
34 *
35 *
36 */
@XmlAccessorType(XmlAccessType.FIELD)
37 @XmlType(name = "OrderRequest", propOrder = {
38 "accountId",
39 "quantity"
40 })
41 public class OrderRequest {
42 protected String accountId;
43 protected Integer quantity;
44
45 /**
46 * Gets the value of the accountId property.
47 *
* @return
48 * possible object is
49 * {@link String }
50 *
51 */
public String getAccountId() {
52
return accountId;
53
54
55
56
57
58 }
59
60 /**
* Sets the value of the accountId property.
61 *
62 * @param value
63 * allowed object is
64 * {@link String }
65 *
*/
66 public void setAccountId(String value) {
67 this.accountId = value;
68 }
69
70 /**
* Gets the value of the quantity property.
71 *
72 * @return
73 * possible object is
74 * {@link Integer }
75 *
*/
76 public Integer getQuantity() {
77 return quantity;
78 }
79
80 /**
* Sets the value of the quantity property.
81
*
82 * @param value
83 * allowed object is
84 * {@link Integer }
85 *
*/
86 public void setQuantity(Integer value) {
87 this.quantity = value;
88 }
89
90 }
91
92
93
94
95
OrderResponse.java

?
1 //
// This file was generated by the JavaTM Architecture for XML
2
Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6
3 // See <a
4 href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
5 // Any modifications to this file will be lost upon recompilation of
6 the source schema.
// Generated on: 2012.02.07 at 05:07:31 PM EST
7 //
8
9
10 package com.myapp.data.order;
11
12 import javax.xml.bind.annotation.XmlAccessType;
13 import javax.xml.bind.annotation.XmlAccessorType;
14 import javax.xml.bind.annotation.XmlType;
15
16
/**
17 * Java class for OrderResponse complex type.
18 *
19 *
20 The following schema fragment specifies the expected content
contained within this class.
21 *
22 *
23 <pre>* <complexType name="OrderResponse">
24 * <complexContent>
25 * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
26 * <element name="orderId"
27 type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
28 * <element name="responseCode" type="{}responseCode"
29 minOccurs="0"/>
30 * <element name="accountId"
type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
31 * </sequence>
32 * </restriction>
33 * </complexContent>
34 * </complexType>
* </pre>
35 *
36 *
37 */
38 @XmlAccessorType(XmlAccessType.FIELD)
39 @XmlType(name = "OrderResponse", propOrder = {
"orderId",
40 "responseCode",
41 "accountId"
42 })
43 public class OrderResponse {
44
45 protected String orderId;
protected ResponseCode responseCode;
46
protected String accountId;
47
48 /**
49 * Gets the value of the orderId property.
50 *
51 * @return
* possible object is
52 * {@link String }
53 *
54 */
55 public String getOrderId() {
56 return orderId;
}
57
58 /**
59 * Sets the value of the orderId property.
60 *
61 * @param value
* allowed object is
62 * {@link String }
63 *
64 */
65 public void setOrderId(String value) {
66 this.orderId = value;
}
67
68 /**
69 * Gets the value of the responseCode property.
70 *
71 * @return
72 * possible object is
* {@link ResponseCode }
73 *
74 */
75 public ResponseCode getResponseCode() {
76 return responseCode;
}
77
78 /**
79 * Sets the value of the responseCode property.
80 *
81 * @param value
82 * allowed object is
* {@link ResponseCode }
83 *
84 */
85 public void setResponseCode(ResponseCode value) {
86 this.responseCode = value;
}
87
88
/**
89 * Gets the value of the accountId property.
90
91
92
93
94
95
96
97 *
* @return
98 * possible object is
99 * {@link String }
100 *
101 */
public String getAccountId() {
102 return accountId;
103 }
104
105 /**
106 * Sets the value of the accountId property.
107 *
* @param value
108 * allowed object is
109 * {@link String }
110 *
111 */
public void setAccountId(String value) {
112
this.accountId = value;
113 }
114
115 }
116
117
118
119
120
121
122

ResponseCode.java

?
1 //
// This file was generated by the JavaTM Architecture for XML
2
Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6
3 // See <a
4 href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
5 // Any modifications to this file will be lost upon recompilation of
6 the source schema.
7
8
9 // Generated on: 2012.02.07 at 05:07:31 PM EST
//
10
11
12 package com.myapp.data.order;
13
14 import javax.xml.bind.annotation.XmlEnum;
15 import javax.xml.bind.annotation.XmlType;
16
17
18 /**
19 ** Java class for responseCode.
20 *
21 The following schema fragment specifies the expected content contained
22 within this class.
23 *
*
24 <pre>* <simpleType name="responseCode">
25 * <restriction base="{http://www.w3.org/2001/XMLSchema}string">
26 * <enumeration value="SUCCESS"/>
27 * <enumeration value="FAILED"/>
28 * <enumeration value="REJECTED"/>
* <enumeration value="UNKNOWN"/>
29 * </restriction>
30 * </simpleType>
31 * </pre>
32 *
*/
33 @XmlType(name = "responseCode")
34 @XmlEnum
35 public enum ResponseCode {
36
37 SUCCESS,
38 FAILED,
REJECTED,
39 UNKNOWN;
40
41 public String value() {
42 return name();
43 }
44
public static ResponseCode fromValue(String v) {
45
return valueOf(v);
46 }
47
48 }
49
50
The ObjectFactory.java

?
1 //
2 // This file was generated by the JavaTM Architecture for XML
Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6
3 // See <a
4 href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
5 // Any modifications to this file will be lost upon recompilation of
6 the source schema.
// Generated on: 2012.02.07 at 05:07:31 PM EST
7 //
8
9
10 package com.myapp.data.order;
11
12 import javax.xml.bind.annotation.XmlRegistry;
13
14
15 /**
16 * This object contains factory methods for each
* Java content interface and Java element interface
17 * generated in the com.myapp.data.order package.
18 * An ObjectFactory allows you to programatically
19 * construct new instances of the Java representation
20 * for XML content. The Java representation of XML
21 ** content can consist of schema derived interfaces
and classes representing the binding of schema
22 * type definitions, element declarations and model
23 * groups. Factory methods for each of these are
24 * provided in this class.
25 *
*/
26 @XmlRegistry
27 public class ObjectFactory {
28
29
30 /**
31 * Create a new ObjectFactory that can be used to create new
32 instances of schema derived classes for package: com.myapp.data.order
*
33 */
34 public ObjectFactory() {
35 }
36
37 /**
* Create an instance of {@link OrderResponse }
38 *
39 */
40 public OrderResponse createOrderResponse() {
41 return new OrderResponse();
42 }
43
44
45
46 /**
47 * Create an instance of {@link OrderRequest }
48 *
*/
49 public OrderRequest createOrderRequest() {
50 return new OrderRequest();
51 }
52
53 }
54
55

Define the Web service interface ExecutionWebService.java.

?
1 package com.myapp.webservice.orderexecutionservices;
2
3
4 import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
5 import javax.ws.rs.Path;
6 import javax.ws.rs.PathParam;
7 import javax.ws.rs.Produces;
8 import javax.ws.rs.QueryParam;
9
import com.myapp.data.order.*;
10
11 @Path("execution/1.0")
12 public interface ExecutionWebService {
13
14
15 // -------------------------
16 // Create Order
17 // -------------------------
18
@POST
19 @Path("/order/create")
20 @Consumes("application/xml")
21 @Produces("text/xml")
22 OrderResponse createOrder(OrderRequest orderRequest);
23
24 // -------------------------
// Amend Order
25 // -------------------------
26
27 @POST
28 @Path("/order/amend")
29 @Consumes("application/xml")
30
31
32
33 @Produces("text/xml")
OrderResponse amendOrder(OrderRequest orderRequest);
34
35 //--------------------------
36 // Cancel Order
37 //--------------------------
38
39 @POST
40 @Path("/order/cancel")
@Consumes("application/xml")
41 @Produces("text/xml")
42 OrderResponse cancelOrder(OrderRequest orderRequest);
43
44 }
45
46
47

Define the Web service implementation class ExecutionWebServiceImpl.java. This


class makes use of the back-end service class OrderService.java to talk to to the DAO
layer, which is not shown here.

?
1 package com.myapp.webservice.orderexecutionservices.impl;
2
3 import java.util.ArrayList;
import java.util.Date;
4 import java.util.List;
5
6 import javax.annotation.Resource;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.ws.rs.WebApplicationException;
import javax.xml.datatype.DatatypeConfigurationException;
9 import javax.xml.ws.WebServiceContext;
10 import javax.xml.ws.handler.MessageContext;
11
12
13 import com.myapp.data.order.OrderRequest;
14 import com.myapp.data.order.OrderResponse;
15
16 public class ExecutionWebServiceImpl implements ExecutionWebService {
17
private OrderService orderService;
18
19 public ExecutionWebServiceImpl() {
20 }
21
22
23 public ExecutionWebServiceImpl(OrderService orderService) {
this.setOrderService(orderService);
24
}
25
26 public void setOrderService(OrderService orderService) {
27 this.orderService = orderService;
28 }
29
30 public OrderService getOrderService() {
return orderService;
31 }
32
33 @Override
34 public OrderResponse createOrder(OrderRequest orderRequest) {
35 OrderResponse response = null;
36 try {
//call to back end service
37 response = getOrderService().createOrder(orderRequest);
38 } catch (Exceprion e) {
39 throw new WebApplicationException(e);
40 }
41
return response;
42
}
43
44 @Override
45 public OrderResponse amendOrder(OrderRequest orderRequest) {
46 OrderResponse response = null;
47 try {
response = getOrderService().amendOrder(orderRequest);
48 } catch (Exception e) {
49 throw new WebApplicationException(e);
50 }
51
52 return response;
53 }
54
@Override
55 public OrderResponse cancelOrder(OrderRequest orderRequest) {
56
57 OrderResponse response = null;
58
59 try {
60 response = getOrderService().cancelOrder(orderRequest,
null);
61 } catch (Exception e) {
62 throw new WebApplicationException(e);
63 }
64
65 return response;
66 }
}
67
68
69
70
71
72
73
74
75

Now, wire up the above classes using Spring and CXF configuration files.

The webservices-config.xml file.

?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns:cxf="http://cxf.apache.org/core"
4 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
5 xmlns:jaxws="http://cxf.apache.org/jaxws"
6 xsi:schemaLocation="
http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://cxf.apache.org/jaxws
9 http://cxf.apache.org/schemas/jaxws.xsd
10 http://cxf.apache.org/jaxrs
11 http://cxf.apache.org/schemas/jaxrs.xsd">
12
<import resource="classpath:META-INF/cxf/cxf.xml" />
13 <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
14 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
15 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
16 <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
17
18
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
19
<!-- Configure Execution Web Services Beans -->
20 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
21 <bean id="executionWebService"
22 class="com.myapp.webservice.orderexecutionservices.impl.ExecutionWebServiceImpl">
23 <constructor-arg ref="orderService" />
24 </bean>
25 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
26 <!-- CONFIGURE ENDPOINTS -->
27 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
28 <jaxrs:server id="executionservices" address="/executionservices/">
29 <jaxrs:inInterceptors>
<ref bean="myAppInInterceptor" />
30 </jaxrs:inInterceptors>
31 <jaxrs:outInterceptors>
32 <ref bean="myAppOutInterceptor" />
33
34
35
36 </jaxrs:outInterceptors>
37 <jaxrs:providers>
38 <ref bean="exceptionMapperInterceptor" />
39 </jaxrs:providers>
<jaxrs:serviceBeans>
40 <ref bean="executionWebService" />
41 </jaxrs:serviceBeans>
42 </jaxrs:server>
43
44
45 <!-- define orderService, interceptors etc. left out for brevity -->
46 <!-- This can be defined in other Spring context files as well-->
47
</beans>
48
49
50
51

The cxf.xml file.

?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://cxf.apache.org/configuration/security"
4 xmlns:http="http://cxf.apache.org/transports/http/configuration"
5 xsi:schemaLocation="
6 http://cxf.apache.org/configuration/security
7 http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration
8 http://cxf.apache.org/schemas/configuration/http-conf.xsd
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-
11 beans.xsd">
12
13 <http:conduit name="*.http-conduit">
<http:tlsClientParameters secureSocketProtocol="SSL"
14 disableCNCheck="true"/>
15 <http:client AllowChunking="false" ReceiveTimeout="60000"/>
16 </http:conduit>
17 </beans>

Finally, register the CXF servlet and bootstrap the above config files via web.xml file.
The web.xml file snippet is shown below.

?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
6 id="services" version="2.5">
<display-name>webservices</display-name>
7
8 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
9 <!-- CONFIGURE SPRING CONTAINER -->
10 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
11
12 <context-param>
13 <param-name>contextConfigLocation</param-name>
<param-value>
14 classpath*:transactionContext.xml
15 classpath*:daoContext.xml
16
17 /WEB-INF/webservice-config.xml
18 classpath*:/cxf.xml
19
20 </param-value>
</context-param>
21 <listener>
22 <listener-
23 class>org.springframework.web.context.ContextLoaderListener</listener-
24 class>
25 </listener>
26 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
27 <!-- CONFIGURE CXF SERVLET -->
28 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
29 <servlet>
30 <servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-
31 class>
32 <load-on-startup>1</load-on-startup>
33 </servlet>
34 <servlet-mapping>
35 <servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
36 </servlet-mapping>
37
38 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
39 <!-- CONFIGURE JNDI RESOURCES -->
40 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<resource-ref>
41 <description>My App Data Source</description>
42 <res-ref-name>jdbc/dataSource/MyDB</res-ref-name>
43 <res-type>javax.sql.DataSource</res-type>
44 <res-auth>Container</res-auth>
45 </resource-ref>
46
</web-app>
47
48
49
50

Now, the sample client that consumes the Web service.

Note that the interface classes like ExecutionWebService, OrederRequest,


OrderResponse, etc will be required by both the client (i.e. the Web service consumer)
and the service implementation classes like ExecutionWebServiceImpl (i.e. service
provider). Hence, the interface classes need to be packaged as separate jar file to be used
by both the client and the service implementation.

?
1 package com.myapp.webservice.client;
2
import org.apache.cxf.jaxrs.client.Client;
3 import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
4
5 //...other imports
6
7 public class ExecutionWebServiceClient {
8
9 private static final String EXECUTION_SERVICES_CONTEXT_ROOT =
"executionservices";
10
11
12
public void consumeRestWebService( ) Throws Exception {
13 ExecutionWebService serviceClient =
14 JAXRSClientFactory.create("http://localhost:8080" +
15 EXECUTION_SERVICES_CONTEXT_ROOT, ExecutionWebService.class);
16 OrderRequest request = constructOrderReqObj(); // not shown
OrderResponse response = serviceClient.createOrder(request);
17
//... do something with the response.
18 }
19 }

The URLs that we be used will be like

?
1 http://localhost:8080/executionservices/execution/1.0/order/create
2 http://localhost:8080/executionservices/execution/1.0/order/amend
3 http://localhost:8080/executionservices/execution/1.0/order/cancel

That's all to it. You can also test your Web service using the "poster" plugin for Firefox.
The request payload will be something like:

?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <OrderRequest>
3 <orderId>orderId</orderId>
4 <responseCode>responseCode</responseCode>
5 <accountId>accountId</accountId>
</OrderRequest>
6

The response payload will be something like

?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <OrderResponse>
3 <orderId>orderId</orderId>
4 <responseCode>responseCode</responseCode>
5 <accountId>accountId</accountId>
</OrderResponse>
6

Note: You could generate the payload from the XSD file within eclipse IDE by selecting
the schema file and then right clicking to click on Generate --> XML. Make sure you
check optional elements to be included. It will also require a root element, henc you need
to wrap you r schema with something like

?
1 <xs:element name="OrderRequest" >
2
3 .......
4
5 </xs:element>

to generate the request payload and

?
1 <xs:element name="OrderResponse" >
2
3 .......
4
5 </xs:element>

to generate the response payload within eclipse IDE.

You might also like