Você está na página 1de 13

Web Based Commerce 514H3

Dr Kingsley Sage
Room 2R308, Chichester II
khs20@sussex.ac.uk

Anirban Basu (for Labs)


a.basu@sussex.ac.uk

© University of Sussex 2006

Lecture 7

 Web services

1
Web services

 Web services have taken the enterprise computing


community by storm
 A real opportunity for interoperability across hardware,
operating systems, programming languages and
applications
 Lots of J2EE approaches to web services:
– Java API for XML Web Services (JAX-WS)
– Java API for XML-based RPC (JAX-RPC)
– SOAP with Attachments API for JAVA (SAAJ)
– Java API for XML Registries (JAXR)
 We shall be most interested in JAX-WS and JAX-RPC

Web services

 Although web services means lots of things to


different communities, J2EE takes a fairly narrow view
(thank goodness)
 A web service is a remote application described using
the Web Service Description Language (WSDL) and
accessed using the Simple Object Application
Protocol (SOAP) according to the rules defined by the
WS-I Basic Profile 1.1
 In order to understand SOAP and WDSL, you must
understand XML schema and XML namespaces

2
XML schema (1)

 A XML schema is similar in purpose to a


Document Type Definition (DTD) which
validates the structure of a XML document
 The schema is used (e.g. by a SAX or DOM
standard parser) by determine whether the
XML document is correct
 The end application determines whether the
XML data is valid

<?xml version=‘1.0’ encoding=‘UTF-8’ ?>


<schema xmlns=“http://www.w3.org/2001/XMLSchema”
xmlns:titan=“http://www.titan.com/Reservationn”
targetNamespace=“http://www.titan.com/Reservationn”

<element name=“address” type=“titan:AddressType” />

<complexType name=“AddressType”>
<sequence>
<element name=“street” type=“string” />
<element name=“city” type=“string” />
<element name=“state” type=“string” />
<element name=“zip” type=“string” />
</sequence>
</complexType>

</schema>

<?xml version=‘1.0’ encoding=‘UTF-8’ standalone=‘yes’?>


<address>
<street>3243 West 1st Ave.</street>
<city>Madison</city>
<state>WI</state>
<zip>53591</zip>
</address>

3
XML schema (3)
 XML schema support about two dozen data types and a
summary of the most useful ones and their mapping to Java
is shown below:
XML schema data type Java type
byte Byte, byte
boolean Boolean, boolean
short Short, short
int Integer, int
long Long, long
float Float, float
double Double, double
string java.lang.String
dateTime java.util.Calendar
integer java.math.BigInteger
decimal java.math.BigDecimal

SOAP 1.1 (1)

 SOAP 1.1 is simply a distributed object protocol


 The most significant difference between SOAP and
other distributed object protocols (e.g. DCOM,
CORBA’s IIOP) is that SOAP is based on XML
 Every SOAP message is a XML document consisting
of standard SOAP elements and application data
 SOAP messages are:
– wrapped in an <Envelope> element
– <Header> element: generally used for carrying data such as
security tokens, transaction IDs and so on
– <Body> element: carries the application information payload

4
SOAP 1.1 (2)

<?xml version=‘1.0’ encoding=‘UTF-8’ ?>


<env:Envelope xmlns:env=http://schemas.xmlsoap.org/soap/envelope/”>
<env:Header />
<env:Body>
<reservation xmlns=“http://www.titan.com/Reservation”>
<customer>
<! --- customer info goes here -- >
</customer>
<cruise-id>123</cruise-id>
<cabin-id>333</cruise-id>
<price-paid>6234.55</price-paid>
</reservation>
</env:Body>
</env:Envelope>

Web services styles (1)


 The SOAP message we just looked at was an example of a
Document/Literal message:
– The message body is a single XML schema instance and thus
the full message can be validated
– Document/Literal is becoming the preferred message style of
the web services community
 The other style allowed by the WS-I Basic Profile 1.1 (and
supported by EJB 3.0) is RPC/Literal:
– represents SOAP messages as RPC calls with parameters
and call values, each with its own schema type
 There is also a RPC/Encoded supported by EJB 3.0 (but not WS-I
Basic Profile 1.1) – industry moving away from this style, so best
keep clear. Life’s hard enough …

5
Web services styles (2)
 The other style allowed by the WS-I Basic Profile 1.1 (and supported by
EJB 3.0) is RPC/Literal:
– represents SOAP messages as RPC calls with parameters and call
values, each with its own schema type
public interface TravelAgent {
public String makeReservation(int cruiseID, int cabinID,
int customerID, double price);
}

<env:Envelope
xmlns:env=“http://schemas.xmlsoap.org/soap/envelope/”>
xmlns:titan=“http://www.titan.com/TravelAgent” />
<env:Body>
<titan:makeReservation>
<cruiseID>23</cruiseID>
<cabinID>144</cabinID>
<customerID>9393</customerID>
<price>5677.88</price>
</titan:makeReservation>
</env:Body>
</env:Envelope>

Exchanging SOAP messages with HTTP

 SOAP messages are network agnostic


 That said, SOAP is primarily exchanged using HTTP
 In fact, you can use SOAP messages to communicate
with arbitrary clients, as these message can often slip
through firewalls un-noticed. This gives rise to a style
of hack attack called SOAP tunneling
 In EJB 3.0, the most widely used protocol used for web
services is JAX-WS, which hides the details of SOAP
messaging so that the developer can focus on just
developing and invoking web services

6
WSDL

 Web Services Description Language (WSDL) is a XML


document used to describe a web service
 WSDL is programming language, platform and protocol
agnostic (this last point means that WSDL can describe
protocols other than SOAP/HTTP, although WS-I Basic
Profile 1.1 endorses only SOAP 1.1 or 1.2 over HTTP)
 Let’s say we want to implement a web service to
implement the following interface

public interface TravelAgent {


public String makeReservation(int cruiseID, int cabinID,
int customerID, double price);
}

<?xml version=‘1.0’?>
<definitions name=“TravelAgent”
xmlns=“http://schemas.xmlsoap.org/wsdl”
xmlns:soap=“http://schemas.xmlsoap.org/wsdl/soap/”
xmlns:xsd=“http://www.w3.org/2001/XMLSchema”
xmlns:titan=“http://www.titan.com/TravelAgent”
targetNamespace=“http://www.titan.com/TravelAgent”

<!-- message elements describe the parameters and return value -->
<message name=“RequestMessage”>
<part name=“cruiseId” type=“xsd:int” />
<part name=“cabinId” type=“xsd:int” />
<part name=“customerId” type=“xsd:int” />
<part name=“price” type=“xsd:double” />
</message>
<message name=“ResponseMessage”>
<part name=“reservationId” type=“xsd:string” />
</message>

<!-- portType element described the abstract interface of a web service -->
<portType name=“TravelAgent”
<operation name=“makeReservation”>
<input message=“titan:RequestMessage”/>
<output message=“titan:ResponseMessage”/>
</operation>
</portType>

7
<!-- binding element tells us which protocols and encoding styles are used -->
<binding name=“TravelAgentBinding” type=“titan:TravelAgent”>
<soap:binding style=“rpc” transport=“http://schemas.xmlsoap.org/soap/http” />
<operation name=“makeReservation”>
<soap:operation soapAction=“”>
<input>
<soap:body use=“literal” namespace=“http://www.titan.com/TravelAgent” />
</input>
<output>
<soap:body use=“literal” namespace=“http://www.titan.com/TravelAgent” />
</output>
</operation>
</binding>

<!-- service element tells us the Internet address of a web service -->
<service name=“TravelAgentService”
<port name=“TravelAgentPort” binding=“titan:TravelAgentBinding”>
<soap:address location=“http://www.titan.com/webservices/TravelAgent” />
</port>
</service>

</defniitions>

UDDI 2.0

 Universal Description, Discovery and Integration


(UDDI) is a specification that describes a standard for
publishing and discovering web services on the
Internet
 Essentially a repository describing companies and their
web services
 Often described as the electronic equivalent of:
– White pages: look up things by a name of identifier
– Yellow pages: look up by business or product category
– Green pages: look up by examining the technical entities of a
UDDI repository

8
Using JAX-WS

 Easy to use:
– sensible set of default values
– WSDL specs are generated for you from the code
 Two basic things you might want to do:
– Expose remote methods in a session bean as a web service
– Call a web service from a session bean
 Rather glossing over the details here – more interested
in the basic concepts. Fuller introduction in the web
services section in the on-line course notes

Exposing stateless session bean


methods as a web service
 You need to add two annotations: @WebService and
@WebMethod

import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.jws.WebMethod;

@Stateless
@WebService
public class TravelAgentBean
{
@WebMethod
public String makeReservation(int cruiseId, int cabinId,
int customerId, double price) {

...
}
}

9
The @WebService annotation
package javax.jws;

@Target({TYPE}) @Retention(value=RetentionPolicy.RUNTIME)
public @interface WebService {
String name() default “”;
String targetNamespace() default “”;
String serviceName() default “”;
String wsdlLocation() default “”;
String portName() default “”;
String endpointInterface default “”;
}

 name(): defaults to the short name of the Java class


or Java interface to which you are applying it to
 endpointInterface() attribute is used to
externalise the contract of the web service by
specifying that contract in the form of a Java interface

The @WebMethod annotation


package javax.jws;

@Target({ElementType.METHOD}) @Retention(value=RetentionPolicy.RUNTIME)
public @interface WebMethod
{
String operationName() default “”;
String action() default “”;
}

import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.jws.WebMethod;

@Stateless
@WebMethod(name=“TravelAgent”)
public class TravelAgentBean
{
@WebMethod(operationName=“Reserve”)
public String makeReservation(int cruiseId, int cabinId,
int customerId, double price) {
...
}
}

10
The endpointInterface
package com.titan.webservice; // on the TravelAgent bean
import javax.jws.WebService;

@WebService
public interface TravelAgentEndpoint {
public java.lang.String makeReservation(int cruiseId, int cabinId,
int customerId, double price);
}

package com.titan.webservice; // Implementation bean


import javax.jws.WebService;

@WebService(endpointInterface=“com.titan.webservice.TravelAgentEndpoint”)
public class TravelAgentBean implements TravelAgentEndpoint {
...
}

 So far, we have defined everything within the EJB


implementation class. An alternative is to use the
endpointInterface() attribute of the
@javax.jws.WebService annotation

Using a web service in a session


bean (1)
 JAX-WS contains a service class that the JAX-WS client uses to
communicate with a web service
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebEndpoint;

@WebServiceClient(name=“ProcessorService”,
targetNamespace=“http://charge-it.com/Processor”
wsdlLocation=“http://charge-it.com/Processor?wsdl” )
public class ProcessorService extends javax.xml.ws.Service {
public ProcessorService() {
super(new URL(“http://charge-it.com/Processor?wsdl”),
new Qname(“http://charge-it.com/Processor” ,”ProcessorService”));
}
public ProcessorService(String wsdlLocation, Qname serviceName) {
super(wsdlLocation, serviceName);
}
@WebEndpoint(name=“ProcessorPort”)
public Processor getProcessorPort() {
return (Processor)
super.getPort(
new Qname(“http://charge-it.com/Processor”,”ProcessorPort”),
Processor.class);
}
}

11
Using a web service in a session
bean (2)
 Rather than define a service endpoint, we use a tool to generate
a service endpoint for us (after all, the whole point is that we can
call a service for any language, platform etc.) …

package com.charge_it;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style=SOAPBinding.Style.RPC)
public interface Processor {
public int charge(String name, String number, java,util.Calendar expDate,
String cardType, float amount);
}

package com.titan.travelAgent;
import com.charge_it.ProcessorService;
import com.charge_it.Processor;

@Stateful
public class TravelAgentBean implements TravelAgentRemote {
@PersistenceContext(unitName=“titanDB”);
private EntityManager em;
@PersistenceContext EntityManager em;
Customer customer;
Cruise cruise;
private Cabin cabin;

@WebServiceRef(ProcessorService.class)
Processor processor;

public TicketDO bookPassage(CreditCardDO card double price)


throws IncompleteConversationalState {
...
}
try {
Reservation reservation = new Reservation(
customer, cruise, cabin, price, new Date());
em.persist(reservation);
String customerName = customer.getFirstName() + ” “ +
customer.getLastName();
java.util.Calendar expDate = new Calendar(card.date);
processor.charge(customerName, card.number, expDate, card.type.price);
TicketDO ticket = new TicketDO(customer, cruise, cabin, price);
return ticket;
} catch(Exception e) {
throw new EJBException(e);
}
}
...
}

12
Next time …

 Security

13