Apache CXF is an open source services framework which is a result of the merge between the XFire and Celtix projects. CXF helps us build and develop services using JAX-WS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.
Showing posts with label web-service. Show all posts
Showing posts with label web-service. Show all posts
Thursday, 30 June 2011
Books for CXF web service
Apache CXF web service Development
Do you use Apache CXF? If so, you might take an interest in "Apache CXF Web Service Development".
The book does a good job of covering CXF use cases, going beyond the usual trivial Jax-WS examples. It also covers Jax-RS (RESTful) web services, and covers each in enough detail that you're likely to find what you need when working with CXF.
Jax-WS has largely demystified basic web service development, so there's a great amount of content on the web that will show you how to quickly annotate a POJO to get a web service up and running. But what if you need to do contract-first (top down) development? Lightweight resources often conveniently bypass this more difficult trail, but this book does a good job of handling it. (This is no great accomplishment for a book on web service development, but it does set the tone for the types of things this book will show.)
It also covers restful web services. I'd say a Java developer either currently using or wanting to use Apache CXF. The book isn't a complete reference for CXF, but it does introduce all the important topics. Once introduced, there's enough content to either solve your problem or at least educate you enough to effectively research what remains.
This book can be found here
.
Do you use Apache CXF? If so, you might take an interest in "Apache CXF Web Service Development".
The book does a good job of covering CXF use cases, going beyond the usual trivial Jax-WS examples. It also covers Jax-RS (RESTful) web services, and covers each in enough detail that you're likely to find what you need when working with CXF.
Jax-WS has largely demystified basic web service development, so there's a great amount of content on the web that will show you how to quickly annotate a POJO to get a web service up and running. But what if you need to do contract-first (top down) development? Lightweight resources often conveniently bypass this more difficult trail, but this book does a good job of handling it. (This is no great accomplishment for a book on web service development, but it does set the tone for the types of things this book will show.)
It also covers restful web services. I'd say a Java developer either currently using or wanting to use Apache CXF. The book isn't a complete reference for CXF, but it does introduce all the important topics. Once introduced, there's enough content to either solve your problem or at least educate you enough to effectively research what remains.
This book can be found here
Types of developmental styles for Web services
There are two development styles: Contract Last OR Code first and Contract First.
Code First approach or Bottum up approach
When using a contract-last approach, you start with the Java code, and let the Web service contract (WSDL, see sidebar) be generated from that.
Contract First approach OR Top Down approach
When using contract-first, you start with the WSDL contract, and use Java to implement said contract. Start with a WSDL contract and generate Java class to implement the service.
The Contract-First wsdl approach requires a good undertanding of WSDL and XSD (XML Schema Definition) for defining message formats. It’s a good idea to start with Code-First if you are fairly new to web services. Later you will look at how to start web service development using the Contract-First approach.
Code First approach or Bottum up approach
When using a contract-last approach, you start with the Java code, and let the Web service contract (WSDL, see sidebar) be generated from that.
Contract First approach OR Top Down approach
When using contract-first, you start with the WSDL contract, and use Java to implement said contract. Start with a WSDL contract and generate Java class to implement the service.
The Contract-First wsdl approach requires a good undertanding of WSDL and XSD (XML Schema Definition) for defining message formats. It’s a good idea to start with Code-First if you are fairly new to web services. Later you will look at how to start web service development using the Contract-First approach.
Wednesday, 22 June 2011
Wink – A framework for RESTful web services from Apache
Apache Wink 1.0 is a complete Java based solution for implementing and consuming REST based Web Services. The goal of the Wink framework is to provide a reusable and extendable set of classes and interfaces that will serve as a foundation on which a developer can efficiently construct applications.
Taken from Apache Wink official site: Click Here
Wink consists of a Server module for developing REST services, and of a Client module for consuming REST services. It cleanly separates the low-level protocol aspects from the application aspects. Therefore, in order to implement and consume REST Web Services the developer only needs to focus on the application business logic and not on the low-level technical details.
REST Web Service design structure
The Wink Server module is a complete implementation of the JAX-RS v1.0 specification. On top of this implementation, the Wink Server module provides a set of additional features that were designed to facilitate the development of RESTful Web services.
The Wink Client module is a Java based framework that provides functionality for communicating with RESTful Web services. The framework is built on top of the JDK HttpURLConnection and adds essential features that facilitate the development of such client applications.
Taken from Apache Wink official site: Click Here Wink consists of a Server module for developing REST services, and of a Client module for consuming REST services. It cleanly separates the low-level protocol aspects from the application aspects. Therefore, in order to implement and consume REST Web Services the developer only needs to focus on the application business logic and not on the low-level technical details.
REST Web Service design structure
The Wink Server module is a complete implementation of the JAX-RS v1.0 specification. On top of this implementation, the Wink Server module provides a set of additional features that were designed to facilitate the development of RESTful Web services.
The Wink Client module is a Java based framework that provides functionality for communicating with RESTful Web services. The framework is built on top of the JDK HttpURLConnection and adds essential features that facilitate the development of such client applications.
Saturday, 18 June 2011
Interview Question: Compare two web services type SOAP and RESTful (SOAP Vs RESTful)
Here are the differences between SOAP and Restful web services :
Now we come to most important stage of deciding which type to select. There is no one answer for selecting either SOAP based or RESTful Web Services. Neither is the right choice for every situation. The choice is dependant upon specific needs and which solution addresses them best. An architect should ask the following questions and the responses should assist him/her in making an informed decision:
| Criteria | SOAP | RESTful | Comments |
|---|---|---|---|
| Orientation | Wraps business logic | Accesses resources/data | |
| Developer View | Object oriented | Resource Oriented | |
| Language Independence | Yes | Yes | |
| Platform Independence | Yes | Yes | |
| Simplicity | No | Yes | |
| Standards Based | Yes | No | SOAP web services are based on SOAP and WS-* specifications |
| Security | SSL, WS-Security | SSL | WS-Security provides end-to-end security covering message integrity and authentication |
| Transactions | WS-AtomicTransaction | No | |
| Reliability | WS-ReliableMessaging | Application specific | |
| Performance | Good | Better | Caching and lower message payload makes RESTful web services performance efficient and scalable |
| Caching | No | GET operations can be cached | |
| Transport protocol support | HTTP, SMTP, JMS | HTTP | Multiple transport protocol support makes SOAP Web Services flexible |
| Message Size | Heavy, has SOAP and WS-* specific markup | Lightweight, no extra xml markup | |
| Message Communication protocol | XML | XML, JSON, other valid MIME type | This flexibility of REST makes its extremely useful in providing consumer need specific message payloads |
| Message Encoding | Yes | No | SOAP Web Services support text and binary encoding, RESTful encoding is limited to text |
| Service Description | WSDL | No formal contract definition | In REST, no formal way to describe a service interface means more dependence on written documentation |
| Human intelligible Payload | No | Yes | |
| Developer Tooling | Yes | Minimal or none | Complexity of SOAP Web Services dictates the need for using frameworks to facilitate rapid application development. REST on the other hand due to its simplicity can be developed without any framework |
Now we come to most important stage of deciding which type to select. There is no one answer for selecting either SOAP based or RESTful Web Services. Neither is the right choice for every situation. The choice is dependant upon specific needs and which solution addresses them best. An architect should ask the following questions and the responses should assist him/her in making an informed decision:
- Does the service expose data or business logic? (REST can be a good choice for exposing data, SOAP/WS-* might be a better choice for logic)
- Does the service need the capabilities of WS-*, or is a simpler RESTful approach sufficient?
- What’s best for the developers who will build clients for the service?
- Limited bandwidth and resources: Remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
- Totally stateless operations: If an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is suitable.
- Caching situations: If the information can be cached because of the totally stateless operation of the REST approach, this is perfect.
- Asynchronous processing and invocation: If application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging etc.
- Formal contracts: If both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
- Stateful operations: If the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.
- REST and SOAP: When to use each (or both)?
- SOAP vs REST: Complements or Competitors
- Introduction to Web APIs: REST vs SOAP
Sunday, 17 April 2011
WSDL Definition Element
The <definition> element must be the root element of all WSDL documents. It defines the name of the web service.
Refer here for more:
http://www.tutorialspoint.com/wsdl/index.htm
http://www.herongyang.com/WSDL/
Refer here for more:
http://www.tutorialspoint.com/wsdl/index.htm
http://www.herongyang.com/WSDL/
Monday, 11 April 2011
REST in Java
You may want to call the REST web service from Java. Following is the code for a simple Web Service client for the flickr web services interface.
pacage com.vaani.rest;import java.net.HttpURLConnection;import java.net.InetSocketAddress;import java.net.Proxy;import java.net.SocketAddress;import java.net.URL;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;public class FlickrClient { public static void main(String[] args) { String flickrURL = "http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]"; try { SocketAddress addr = new InetSocketAddress("[proxy]", 9090); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL u = new URL("http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]"); HttpURLConnection uc = (HttpURLConnection) u.openConnection(proxy); uc.setRequestProperty("Accept", "*/*"); uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); uc.setRequestProperty("Accept-Language", "en-us,en;q=0.5"); uc.setRequestProperty("Keep-Alive", "300"); uc.setRequestProperty("ucection", "keep-alive"); String proxyUser = "[netUserId]"; String proxyPassword = "[netPassword]"; uc.setRequestProperty("Proxy-Authorization", "NTLM " + new sun.misc.BASE64Encoder().encode((proxyUser + ":" + proxyPassword).getBytes())); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(uc.getInputStream()); System.out.println(doc.getDocumentElement().getTagName()); System.out.println(); } catch (Exception e) { e.printStackTrace(); } }} |
RESTful Web Service tutorial: An Introduction for beginners
REST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. Representational State Transfer(REST), a software architecture style used in developing stateless web services. While this style may be used to describe any distributed framework that uses a simple protocol for data transmission and no other additional data transfer rules, the most common use of REST is on on the Web with HTTP being the only protocol used here. In REST each service (called “resource” in REST) is viewed as resource identified by a URL, and the only operations allowed are the HTTP – GET (Read), PUT (Update), POST(Create) and DELETE (Delete). You can find this style similar in SQL, thinking of a resource as equivalent to a Table. The main features and constraints of REST architectural style are:
A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.
- Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.
- Stateless: All REST resources are required to be stateless. The idea is that the application would be resilient enough to work between server restarts. However, it is not uncommon to see some RESTful web services save states between requests.
- Caching: Caching is allowed, however it is required that “response to a request be implicitly or explicitly labeled as cacheable or non-cacheable”
- As there is no interface definition (like in SOAP), it becomes mandatory for a Client and Server to have a mutual understanding of the messages being transmitted between them.
A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.
Wednesday, 23 March 2011
JAX-WS quick tutorial
Prerequirements
You can download this code here.
- JDK 1.6 +
- Eclipse
Developing the Webservice End Point
- Open eclipse and create a java project "WS-Server"
- Create WS-Service Endpoint interface:
Now create the corresponding implementation:package com.vaani.jaxws.greet.enpoint;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface Greeting {
@WebMethod String sayHello(String name);
}package com.vaani.jaxws.greet.enpoint;
import javax.jws.WebService;
@WebService(endpointInterface = "com.vaani.jaxws.greet.enpoint")
public class GreetingImpl implements Greeting {
@Override
public String sayHello(String name) {
return "Hello, Welcom to jax-ws " + name;
}
} - Create end point publisher class( having main)
package com.vaani.jaxws.greet.publisher;
import javax.xml.ws.Endpoint;
import com.vaani.jaxws.greet.enpoint.GreetingImpl;
public class WSPublisher {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/WS/Greeting",
new GreetingImpl());
}
}
Developing the WebService Client
- Open eclipse and create a java project "WS-Client"
- Generate the client-stubs
a) Browse to the client folder by command prompt
b) Use command wsimport :CD %CLIENT_PROJECT_HOME%\src
It will look something like this:wsimport -s . http://localhost:8080/WS/Greeting?wsdl
Now this will generate 6 java source files and corresponding compiled class files, if you want you can remove these file. - Create client class which uses this service (using generated stubs)
package com.vaani.jaxws.greet.client;
import com.vaani.jaxws.greet.enpoint.Greeting;
import com.vaani.jaxws.greet.enpoint.GreetingImplService;
public class Client {
public static void main(String[] args){
GreetingImplService service = new GreetingImplService();
Greeting greeting = service.getGreetingImplPort();
System.out.println("------->> Call Started");
System.out.println(greeting.sayHello("Kinshuk"));
System.out.println("------->> Call Ended");
}
} - Run the class and you may get output like this:
------->> Call Started
Hello, Welcom to jax-ws Kinshuk
------->> Call Ended
You can download this code here.
Thursday, 17 March 2011
WSDL Document Example
Following is the WSDL file that is provided to demonstrate a simple WSDL program.
Assuming the service provides a single publicly available function, called sayHello. This function expects a single string parameter and returns a single string greeting. For example if you pass the parameter world then service function sayHello returns the greeting, "Hello, world!".
Assuming the service provides a single publicly available function, called sayHello. This function expects a single string parameter and returns a single string greeting. For example if you pass the parameter world then service function sayHello returns the greeting, "Hello, world!".
Content of HelloService.wsdl file
<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="SayHelloRequest">
<part name="firstName" type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting" type="xsd:string"/>
</message>
<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>
<service name="Hello_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="Hello_Port">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
</definitions>
Analysis of the Example
- Definition : HelloService
- Type : Using built-in data types and they are defined in XMLSchema.
- Message :
- sayHelloRequest : firstName parameter
- sayHelloresponse: greeting return value
- Port Type: sayHello operation that consists of a request and response service.
- Binding: Direction to use the SOAP HTTP transport protocol.
- Service: Service available at http://www.examples.com/SayHello/.
- Port: Associates the binding with the URI http://www.examples.com/SayHello/ where the running service can be accessed.
Tuesday, 15 March 2011
WSDL Elements
A WSDL document describes a web service using these major elements:
Following are the elements of WSDL document. Within these elements are further subelements, or parts:
A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document.
Proceed further to analyze an example of WSDL Document.
| Element | Defines |
|---|---|
| <types> | The data types used by the web service |
| <message> | The messages used by the web service |
| <portType> | The operations performed by the web service |
| <binding> | The communication protocols used by the web service |
Following are the elements of WSDL document. Within these elements are further subelements, or parts:
- Definition: element must be the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.
- Data types: the data types - in the form of XML schemas or possibly some other mechanism - to be used in the messages
- Message: an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.
- Operation: the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message
- Port type : an abstract set of operations mapped to one or more end points, defining the collection of operations for a binding; the collection of operations, because it is abstract, can be mapped to multiple transports through various bindings.
- Binding: the concrete protocol and data formats for the operations and messages defined for a particular port type.
- Port: a combination of a binding and a network address, providing the target address of the service communication.
- Service: a collection of related end points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.
- Documentation: element is used to provide human-readable documentation and can be included inside any other WSDL element.
- Import: element is used to import other WSDL documents or XML Schemas.
The WSDL Document Structure
The main structure of a WSDL document looks like this: <definitions> <types> |
Proceed further to analyze an example of WSDL Document.
WSDL introduction
WSDL Abstract:
- WSDL stands for Web Services Description Language
- WSDL is an XML based protocol for information exchange in decentralized and distributed environments.
- WSDL is the standard format for describing a web service.
- WSDL definition describes how to access a web service and what operations it will perform.
- WSDL is a language for describing how to interface with XML-based services.
- WSDL is an integral part of UDDI, an XML-based worldwide business registry.
- WSDL is the language that UDDI uses.
- WSDL was developed jointly by Microsoft and IBM.
- WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'
WSDL Usage:
WSDL is often used in combination with SOAP and XML Schema to provide web services over the Internet. A client program connecting to a web service can read the WSDL to determine what functions are available on the server. Any special datatypes used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL.History of WSDL
WSDL 1.1 was submitted as a W3C Note by Ariba, IBM and Microsoft for describing services for the W3C XML Activity on XML Protocols in March 2001.WSDL 1.1 has not been endorsed by the World Wide Web Consortium (W3C), however it has just (May 11th, 2005) released a draft for version 2.0, that will be a recommendation (an official standard), and thus endorsed by the W3C.
Saturday, 26 February 2011
CXF hello world tutorial
This example shows how to make cxf web service.
Get the bean ready:
First off, you need to download Apache CXF and drop the necessary .jars in your WEB-INF/lib directory:
The first thing which needed to be done was to create the service interface. The service interface defines which methods the web service client will be able to call. It’s pretty standard Java with just two JWS (Java Web Service) annotations thrown in:
The @WebParam annotation is in fact optional, but highly recommended since it will make like easier for the end consumers of your service. Without it, your parameter would be named arg0 making it less clear what parameters your service actually takes.
Implementing the actual service comes next:
I then had to tell Spring (which is used by CXF) where to find my Java classes. I created the following cxf.xml file inside my package directory (com/company/auth/service):
Finally, I updated my WEB-INF/web.xml file to let CXF know where my cxf.xml file was and define the CXF servlet:
The final step is to build the client. This was very easy when compared to getting the server up and running because I was able to simply swipe the code from the Apache CXF documentation. So, without further ado:
Get the bean ready:
package com.company.auth.bean;
import java.io.Serializable;
import java.util.Set;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String gid;
private String lastName;
private String firstName;
private Set<String> privileges;
public Employee() {}
public Set<String> getPrivileges() {
return privileges;
}
public void setPrivileges(Set<String> privileges) {
this.privileges = privileges;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGid() {
return gid;
}
public void setGid(String gid) {
this.gid = gid;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isUserInRole(String role) {
if(privileges == null) { return false; }
else { return privileges.contains(role); }
}
}
First off, you need to download Apache CXF and drop the necessary .jars in your WEB-INF/lib directory:
aopalliance-1.0.jar
commons-logging-1.1.jar
cxf-2.0-incubator.jar
geronimo-activation_1.1_spec-1.0-M1.jar (or Sun’s Activation jar)
geronimo-annotation_1.0_spec-1.1.jar (JSR 250)
geronimo-javamail_1.4_spec-1.0-M1.jar (or Sun’s JavaMail jar)
geronimo-servlet_2.5_spec-1.1-M1.jar (or Sun’s Servlet jar)
geronimo-ws-metadata_2.0_spec-1.1.1.jar (JSR 181)
jaxb-api-2.0.jar
jaxb-impl-2.0.5.jar
jaxws-api-2.0.jar
jetty-6.1.5.jar
jetty-util-6.1.5.jar
neethi-2.0.jar
saaj-api-1.3.jar
saaj-impl-1.3.jar
spring-core-2.0.4.jar
spring-beans-2.0.4.jar
spring-context-2.0.4.jar
spring-web-2.0.4.jar
stax-api-1.0.1.jar
wsdl4j-1.6.1.jar
wstx-asl-3.2.1.jar
XmlSchema-1.2.jar
xml-resolver-1.2.jar
The first thing which needed to be done was to create the service interface. The service interface defines which methods the web service client will be able to call. It’s pretty standard Java with just two JWS (Java Web Service) annotations thrown in:
package com.company.auth.service;
import javax.jws.WebService;
import javax.jws.WebParam;
import com.company.auth.bean.Employee;
@WebService
public interface AuthService {
Employee getEmployee(@WebParam(name="gid") String gid);
}
The @WebParam annotation is in fact optional, but highly recommended since it will make like easier for the end consumers of your service. Without it, your parameter would be named arg0 making it less clear what parameters your service actually takes.
Implementing the actual service comes next:
package com.company.auth.service;
import javax.jws.WebService;
import com.company.auth.bean.Employee;
import com.company.auth.dao.EmployeeDAO;
@WebService(endpointInterface = "com.company.auth.service.AuthService", serviceName = "corporateAuthService")
public class AuthServiceImpl implements AuthService {
public Employee getEmployee(String gid) {
EmployeeDAO dao = new EmployeeDAO();
return dao.getEmployee(gid);
}
}
I then had to tell Spring (which is used by CXF) where to find my Java classes. I created the following cxf.xml file inside my package directory (com/company/auth/service):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint id="auth"
implementor="com.company.auth.service.AuthServiceImpl"
address="/cxfAuth"/>
</beans>
Finally, I updated my WEB-INF/web.xml file to let CXF know where my cxf.xml file was and define the CXF servlet:
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Auth Manager</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/company/auth/service/cxf.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
The final step is to build the client. This was very easy when compared to getting the server up and running because I was able to simply swipe the code from the Apache CXF documentation. So, without further ado:
package com.company.auth.client;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.company.auth.bean.Employee;
import com.company.auth.service.AuthService;
public final class Client {
private Client() {
}
public static void main(String args[]) throws Exception {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(AuthService.class);
factory.setAddress("http://localhost:7001/authManager/services/cxfAuth");
AuthService client = (AuthService) factory.create();
Employee employee = client.getEmployee("0223938");
System.out.println("Server said: " + employee.getLastName() + ", " + employee.getFirstName());
System.exit(0);
}
}
Subscribe to:
Comments (Atom)

