Download Connect disparate applications using XML and JAX –RS with Rational

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Connect disparate applications using XML and JAX –RS with Rational
Application Developer 7.5.5
by Neeraj Agrawal, IBM
Java™ API for RESTful Web Services (JAX-RS) is a programming model that allows
you to create Representational State Transfer (REST) services quickly. JAX-RS
application development is now supported in IBM® Rational® Application Developer
for WebSphere v7.5.5. This article demonstrates how to build two applications (EAR
files) in Rational Application Developer. The first one is used to host a Web service and
is an example of how you can expose your service interface as a thin layer on top of your
existing n-tier application and return data to clients in XML format. The second
application is the consumer of your service.
The example will show you how to:
1. Host a JAX-RS Web Service
•
Configure a JAX – RS provider
•
Create a XML schema and use JAX-B technology to generate Java classes.
•
Create a Web project with JAX-RS capabilities.
•
Write Web service implementation code. The Web service returns data in
XML format.
2. Consume a Web service in another application
A Java Server Faces page invokes a Web service programmatically, the returned
XML is transformed back to a Java class and this class is hooked to the JSF page
to display data.
Page 1 of 22
1. Configure a JAX – RS provider
Although Rational Application Developer v7.5.5 supports JAX-RS
development, an implementation is not included with the product. In order to develop
JAX-RS applications, you must download a JAX-RS 1.0 implementation and include in
the development environment by doing the following :
a) Download the JAX-RS 1.0 implementation from
http://incubator.apache.org/wink/downloads.html
b) Set the JAX-RS preference. From the main menu, select Window >
Preferences.
c) In the left pane, select Web Services > JAX-RS Libraries.
d) Click New to add the appropriate library files.
Page 2 of 22
2. Create a XML schema and use JAX-B technology to generate Java classes.
In this step you will create a XML schema and use it to generate Java classes. You can
use a utility project for this purpose. This project will be packaged as a JAR file and serve
as an interface to your Web service. The clients of the Web service can use a Java class to
deserialize the XML. Non-Java clients would use a XML schema.
Page 3 of 22
A. Create a Java Project and name it as WebServiceUtility
B. Select File >New >XML Schema and name it as address.xsd
C. You can use the Design pane of the editor to create a XML schema. The final schema
looks like:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Address"
xmlns:tns="http://www.example.org/Address"
elementFormDefault="qualified">
Page 4 of 22
<element name="Address">
<complexType>
<sequence>
<element name="name" type="string"/>
<element name="streetNo" type="string"/>
<element name="streetname" type="string"/>
<element name="city" type="string"/>
<element name="state" type="string"/>
<element name="zipcode" type="string"/>
</sequence>
</complexType>
</element>
</schema>
D. Now right click on the schema and select Generate >Java.
and select JAXB Schema to Java Bean
Click Next., Choose the defaults and click Finish.
You will see the classes created under org.example.address
Page 5 of 22
3. Host the Web service in a Web application
A. Use File >New > Dynamic Web Project to create a Web project.
Page 6 of 22
B. Click the Modify button to display the Project Facets page and select the JAX-RS
check box.
Page 7 of 22
C. Click Next in the Web project wizard to view the JAX – RS capabilities page.
The Apache Wink library which you configured in Section 1 is configured along with the
servlet which dispatches the client request to the appropriate implementation of the Web
service. Click Finish.
Page 8 of 22
D. You will use the JAXB classes that you generated in Section 2. Right-click your Web
project and select Properties. In the left pane, select Java EE Module Dependencies .
Click the Web Libraries tab and select the WebServiceUtility check box.
Click OK.
Page 9 of 22
E.
Create a Java class using the New > Class wizard. Name the class
AddressWebService,and click OK. This class will become your Web
Service implementation class. We will fill in the details of the class later.
F. To invoke the Web service from the Apache Wink framework, you need to create a
class which extends from javax.ws.rs.core.Application . This class needs to set in the init params
of the Apache Wink framework servlet. Later, you will see implementation details of the
Application subclass.
Open the web.xml file which is located in the WebContent/WEB-INF folder of the Web
project. In the Web Application Structure section, click Add and select Initialization
Parameter.
Page 10 of 22
G. If you do not set the values using the editor, and leave the fields empty, Rational
Application Developer detects it as an error and assists you to quickly configure the
Application sub class. In the error right click and select Quick Fix. This brings up a
Quick Fix dialog:
Page 11 of 22
H. Once you choose Create a new JAX-RS Application sub-class, the superclass is
automatically set. Set the class name and click Finish. The init parameters in the web.xml
are now properly configured.
Page 12 of 22
I. Your web.xml now looks like the following:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>
JAXRSWebService</display-name>
<servlet>
<servlet-name>JAX-RS Servlet</servlet-name>
<servletclass>org.apache.wink.server.internal.servlet.RestServlet</servletclass>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>AddressApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>
/jaxrs/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
J. Now you can complete the implementation of the Application subclass that you
created in Step H by adding the Service implementation class in the data-structure and
returning it.
public class AddressApp extends Application {
public AddressApp() {
}
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(AddressWebService.class);
return classes;
}
}
Page 13 of 22
K. Implementation of the Web Service
Open the AddressWebService class and replace the contents with the code below:
import java.util.HashMap;
import
import
import
import
javax.ws.rs.GET;
javax.ws.rs.Path;
javax.ws.rs.PathParam;
javax.ws.rs.Produces;
import org.example.address.Address;
@Produces("application/xml")
@Path(value="/addresseService")
public class AddressWebService {
private static HashMap<Integer, Address> addresses = new
HashMap<Integer, Address>();
public AddressWebService() {
initAddreses();
}
private void initAddreses(){
Address address = new Address();
address.setName("Neeraj Agrawal");
address.setStreetNo("111");
address.setStreetname("Foo Lane");
address.setCity("Cary");
address.setState("NC");
address.setZipcode("27513");
addresses.put(0, address);
address = new Address();
address.setName("Jack Smith");
address.setStreetNo("123");
address.setStreetname("Foo Lane");
address.setCity("Cary");
address.setState("NC");
address.setZipcode("27513");
addresses.put(1, address);
}
@GET
@Path(value="{id}")
public Address getCustomer(@PathParam("id") int cId) {
return this.addresses.get(cId);
}
}
Page 14 of 22
A few things to note here are the annotations used
@Path: identifies
the URI path template to which the Web service responds. Its value is
a partial URI path relative to the context root of the WAR.
@Produces: defines the type of data returned, since you are using XML to be returned
choose "application/xml", other possible values are “text/plain”,
“text/html”
Your Web service is ready to be deployed on the server.
4.
Consume a Web service in another application(EAR)
This section demonstrates how you can consume a REST service in a JSF page using
JAX-B binding. Typically a Web service is hosted in a different application server than
the consumer of the application. For the example, it is assumed that a developer of a
Web service provides you with the url of the service and WebServiceUtility project. The
utility project has all the necessary Java classes which can be attached to a JAXB
deserializer.
Page 15 of 22
A. Start by creating a Web project and selecting the JavaServer Faces IBM Enhanced
Project configuration
Page 16 of 22
B. Select the WebServiceUtility project in the Web project’s Java EE Module
Dependency page so that it is available in the classpath during development as well as
during runtime.
Page 17 of 22
C. Create a Web page called ShowAddress.jsp by right-clicking the WebContent
folder of your project and selecting New > Web Page.
Page 18 of 22
D. Choose a JavaBean from the Data and Services drawer of the Palette and drop on the
page.
The Add JavaBean wizard opens. Specify address as the name and
org.example.address.Address as the class. Click Finish.
Page 19 of 22
Dropping the bean creates the necessary UI elements and fills in the plumbing code in the
pagecode file of the page.
E. Add a form, input box and a button to the page by dragging these items from the
palette. The final page looks like the following:
Page 20 of 22
F. Open the ShowAddress.java file which was created when you created a Web page in
Step C.
Now we will add code in the button callback to invoke the service
public String doButton1Action() {
int n = Integer.parseInt(getInputText());
String url
="http://localhost:9081/JAXRSWebService/jaxrs/addresseService/";
url +=n;
URL restWebService;
URLConnection yc;
try {
restWebService = new URL(url);
yc = restWebService.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
String data = null;
while ((inputLine = in.readLine()) != null) {
data = inputLine;
}
in.close();
populateData(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
G. Desererializing of code from XML to Java class is done in the following method:
private void populateData(String data){
try {
JAXBContext jc =
JAXBContext.newInstance("org.example.address");
Unmarshaller unmarshaller = jc.createUnmarshaller();
setAddress((Address)
unmarshaller.unmarshal( new StringReader(data) ));
} catch (JAXBException e) {
e.printStackTrace();
}
}
Page 21 of 22
H. Now run the page on a server by right-clicking the page and selecting Run > Run on
Server.
Enter 1 as the address id and click the Submit button. The information in the JSF page is
displayed.
About the author
Neeraj works on Java EE tooling at IBM Rational at IBM Research Triangle Park Lab in
Durham, North Carolina. He holds an undergraduate degree in Computer Sc. and Engg.
from H.B.T.I, India and MS in Computer Science from University of Bridgeport,
Connecticut.
© Copyright IBM Corporation 2010. All rights reserved.
Page 22 of 22