41
1 Web Service Implementation, Deploy and Test 课课课 课课课课课课课课课课课课课课课课

Web Service Implementation, Deploy and Test

  • Upload
    arion

  • View
    80

  • Download
    0

Embed Size (px)

DESCRIPTION

课程名:以服务为中心的软件开发设计与实现. Web Service Implementation, Deploy and Test. Outline. Web service implementation and deploy REST JAX-WS. Representational State Transfer (REST). Two Camps SOAP, WS-* / XML-RPC REST (Representational State Transfer) What is REST? - PowerPoint PPT Presentation

Citation preview

Page 1: Web Service Implementation,  Deploy and Test

1

Web Service Implementation, Deploy and Test

课程名:以服务为中心的软件开发设计与实现

Page 2: Web Service Implementation,  Deploy and Test

2

Outline• Web service implementation and deploy

– REST– JAX-WS

Page 3: Web Service Implementation,  Deploy and Test

3

Representational State Transfer (REST)

Page 4: Web Service Implementation,  Deploy and Test

4

Two Camps on Web Services• Two Camps

– SOAP, WS-* / XML-RPC– REST (Representational State Transfer)

• What is REST? – Discussed in a PhD thesis by Roy Fielding– When client traverses link, accesses new resource (i.e.,

transfers state)– Uses existing standards, e.g., HTTP

Page 5: Web Service Implementation,  Deploy and Test

5

REST Characteristics• Client-Server: Clients pull representations• Stateless: each request from client to server

must contain all needed information. • Uniform interface: all resources are accessed

with a generic interface (HTTP-based)• Interconnected resource representations• Layered components - intermediaries, such as

proxy servers, cache servers, to improve performance, security

Page 6: Web Service Implementation,  Deploy and Test

6

REST: HTTP-based!• Security? Use SSL and HTTP Authentication• HTTP methods/verbs: GET / POST / PUT /

DELETE / HEAD• Results should include URI for more info• HTTP Headers, encoding, compression,

caching, proxies• Error handling? Use HTTP status/response

codes & messages– Resource location change? Use HTTP Redirect

Page 7: Web Service Implementation,  Deploy and Test

7

REST Example• Web Sites

– GET http://en.wikipedia.org/wiki/REST– GET http://www.bing.com/search?q=codecamp

• Web Services– Flickr REST API

• http://www.flickr.com/services/rest?method=flickr.photos.search&api_key={api_key}&tags={tag}

• http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg

Page 8: Web Service Implementation,  Deploy and Test

8

Detailed REST methods• HTTP provides a simple set of operations. Amazingly,

all Web exchanges are done using this simple HTTP API:– GET = "give me some info" (Retrieve)– POST = "here's some update info" (Update)– PUT = "here's some new info" (Create)– DELETE = "delete some info" (Delete)

• The HTTP API is CRUD (Create, Retrieve, Update, and Delete)

Page 9: Web Service Implementation,  Deploy and Test

9

Difference between GET/POST• GET:

– For information retrieval– Data will be attached in URL

• Example: login.action?name=hyddd&password=idontknow• Length Limit: IE (2083bytes), depends on OS/Browser

• POST:– Anything– Data will be in the body of HTTP package

Page 10: Web Service Implementation,  Deploy and Test

10W

eb S

erve

r

HTTP POST URL 3PO(HTML/XML)

HTTP GET request URL 1

HTTP responseURL to submitted PO

PartsList

PartData

PO

HTTP responseResponse(HTML/XML doc)

HTTP responseResponse(HTML/XML doc)

HTTP GET request URL 2

Process of RESTful involing

Page 11: Web Service Implementation,  Deploy and Test

11

JSON Example

XML

JSON

{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] }}}

<menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup></menu>

Page 12: Web Service Implementation,  Deploy and Test

12

Describing REST web services• SOAP: WSDL (Web Services Description

Language)• REST: ?

– WADL (Web Application Description Language)• Not supported

– Resistance due to fear it would impose an RPC style

– Write-up Documentation– Popular Web Services provide client libraries for

popular languages/platforms

Page 13: Web Service Implementation,  Deploy and Test

13

Error Handling in REST

• Use HTTP codes (use the entity-body for more info)– 200 OK– 201 Created

– HTTP Location Header should have URI to new resource

– 400 Bad Request– 404 Not Found– 500 Internal Server Error– 301 Moved Permanently– 403 Forbidden– 401 Unauthorized– 409 Conflict

Page 14: Web Service Implementation,  Deploy and Test

14

Support in .NET

• WCF .NET 3.5 – added support for building REST Style services

• WCF .NET 3.5sp1 - UriTemplate flexibility, support ADO.NET Entity Framework entities in WCF contracts, improvements in the the dev tools

• ASP.NET MVC• .NET 4.0: URL Routing in web forms• WCF REST Starter Kit (beta) – make it easier

– Help page, Representation formats using Accepts HTTP Header, Declarative caching, X-HTTP-Method-Override

Page 15: Web Service Implementation,  Deploy and Test

15

Support in other technologies• Java: JAX-RS

– Jersey, RESTEasy, Enunciate, CXF, RESTlet• Python: Django• Flash/Flex: URLRequest class

– Browser plug-ins limited to GET and POST– AIR – supports all methods

• Ruby – ActiveResource– Mapping RESTful resources as models in a Rails

application• iPhone – ObjectiveResource, json-framework

Page 16: Web Service Implementation,  Deploy and Test

16

Create a REST Web Service• Jersey

– A RESTful web service framework based on JAX-RS standard

– Supported by MyEclipse since ver. 7.0• How to write a Simple HelloWorld RESTful Web

Service in MyEclipse

Page 17: Web Service Implementation,  Deploy and Test

17

HelloWorld RESTful Web Service• Create a Web Service Project

REST (JAX-RS)

Page 18: Web Service Implementation,  Deploy and Test

18

HelloWorld RESTful Web Service• Configure libraries

CoreJAXBClientJSONATOM

Page 19: Web Service Implementation,  Deploy and Test

19

HelloWorld RESTful Web Service• Create resource class

HelloWorldResource

Page 20: Web Service Implementation,  Deploy and Test

20

HelloWorld RESTful Web Service• Write your HelloWorldResouce

import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;

@Path("/helloworld")public class HelloWorldResource { @GET @Produces("text/plain") public String sayHello() { return "Hello World"; }}

javax.ws.rs.GETjavax.ws.rs.Produces

Page 21: Web Service Implementation,  Deploy and Test

21

HelloWorld RESTful Web Service• View web.xml generated by MyEclipse

<servlet> <display-name>JAX-RS REST Servlet</display-name> <servlet-name>JAX-RS REST Servlet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContaine</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JAX-RS REST Servlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>

Page 22: Web Service Implementation,  Deploy and Test

22

HelloWorld RESTful Web Service• Deploy to Tomcat

HelloWorld MyEclipse Tomcat

Page 23: Web Service Implementation,  Deploy and Test

23

HelloWorld RESTful Web Service• Deploy to Tomcat

Successful

Page 24: Web Service Implementation,  Deploy and Test

24

HelloWorld RESTful Web Service• Test

– type in http://localhost:8080/HelloWorld/services/helloworld

Successful

Page 25: Web Service Implementation,  Deploy and Test

25

Tools in MyEclipse

Page 26: Web Service Implementation,  Deploy and Test

26

Path Parameter Example

@GET@Path("/{name}")@Produces("text/plain")public String sayHiWithName(@PathParam("name") String name) {

return "Hi, " + name;}

Page 27: Web Service Implementation,  Deploy and Test

27

Annotations• @Path

– URL Path• @GET / @POST

– HTTP Method• @Consumes

– MIME type the resource can accept from client (for POST)

• @Produces– MIME type the resource can produce (send back to

client)

Page 28: Web Service Implementation,  Deploy and Test

28

Parameters• @QueryParam

– appended to the request URL with a leading "?" and then name/value pairs

– http://www.google.com/search?q=apache+wink• @PathParam• @MatrixParam• @HeaderParam• @CookieParam• https://cwiki.apache.org/WINK/jax-rs-parameters.html

Page 29: Web Service Implementation,  Deploy and Test

29

XML vs. JavaObject@XmlRootElementpublic class Person {

private String id;private Stringname;private List<String> addresses;

@XmlElement(name="id")public String getId() {

return id;}

@XmlElement(name="name")public String getName() {

return name;}

@XmlElement(name="address")public List<String> getAddresses() {

return addresses;}}

<person><address>Tsinghua University</address><address>FIT Building</address><address>1-308</address><id>2010210760</id><name>TANG Wenbin</name></person>

Page 30: Web Service Implementation,  Deploy and Test

30

Invoke REST Service in Java//set URLURL url = new URL("http://localhost:8080/HelloWorld/services/helloworld/xml");

//make connectionURLConnection urlc = url.openConnection();

//use GET modeurlc.setDoInput(true);urlc.setAllowUserInteraction(false);

//get resultBufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

String l = null;while ((l=br.readLine())!=null) {

System.out.println(l);} br.close();

Page 31: Web Service Implementation,  Deploy and Test

31

Test with REST WS Explorer

Page 32: Web Service Implementation,  Deploy and Test

32

Test with REST WS Explorer

Page 33: Web Service Implementation,  Deploy and Test

33

Java API for XML Web Services (JAX-WS)

Page 34: Web Service Implementation,  Deploy and Test

34

JAX-WS• JAX-WS is a Java programming language API for

creating web services.• Latest version JAX-WS 2.0 • Part of Java EE.• New in Java SE 6.• API stack for web services.• Replaces JAX-RPC.• New API’s: JAX-WS, SAAJ, Web Service metadata• New packages: javax.xml.ws, javax.xml.soap,javax.jws

Page 35: Web Service Implementation,  Deploy and Test

35

Writing A Web Service with JAX-WSpackage loanservice;

import javax.jws.WebService;import javax.jws.WebMethod;import javax.xml.ws.Endpoint;

@WebService

public class LoanApprover {

@WebMethod public boolean approve(String name) { return name.equals("Mike"); }

Page 36: Web Service Implementation,  Deploy and Test

36

Writing A Web Service with JAX-WS(cont.)

public static void main(String[] args){ LoanApprover la = new LoanApprover();

Endpoint endpoint = Endpoint.publish(“http://localhost:8080/loanservice”, la);

}}

Page 37: Web Service Implementation,  Deploy and Test

37

Compile the Web ServiceCreate a myservice directory.

From the directory just above loanservice, run Java’sAnnotation Processing Tool (APT):

C:\>apt -d myservice loanservice/LoanApprover.java

This populates a directory named myservice.The directory holds the compiled package as well as a new

directory (package) called jaxws.The new jaxws package holds classes associated with the

parameters to and from each web service method.Use the -s switch to generate the source code.

Page 38: Web Service Implementation,  Deploy and Test

38

Publish the ServiceFrom a directory just above myservice:

C:\>java -cp myservice loanservice/LoanApprover

To view the WSDL, visit the service with a browser at http://localhost:8080/loanapprover?wsdl

Page 39: Web Service Implementation,  Deploy and Test

39

Generate Stub CodeMake a client directory.

C:\>wsimport –p client –keep http://localhost:8080/loanapprover?wsdl

This populates the client subdirectory with .classand .java files.

Page 40: Web Service Implementation,  Deploy and Test

40

Write the Clientpackage client;

class ApproverClient {

public static void main(String args[]){ LoanApproverService service = new LoanApproverService(); LoanApprover approverProxy = service.getLoanApproverPort(); boolean result = approverProxy.approve("Mike"); if(result) System.out.println("Approved"); else System.out.println("Not approved");

}}

Page 41: Web Service Implementation,  Deploy and Test

41

Compile & Run the ClientC:\>javac –cp . client/ApproverClient.java

C:\>java -cp . client/ApproverClientApproved