Java Web Services - Web Services Overview. SOAP and REST in Java

14 downloads 125 Views 208KB Size Report
mvn archetype:create -DgroupId=com.igalia.java.webservices \ ..... http://www. amazon.com/Java-Web-Services-Up-Running/dp/059652112X. Leonard ...
Web Services Overview SOAP REST Conclusion

Java Web Services Web Services Overview. SOAP and REST in Java Manuel Rego Casasnovas

Master on Free Software / August 2012

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Outline

1

Web Services Overview

2

SOAP

3

REST

4

Conclusion

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Overview

Definition

Communication mechanism between two devices/machines/applications over a network Communication Client: Starts communication invoking an operation Server: Provides different operations to clients. Wait for requests and return responses

Network HTTP protocol

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Overview

Features Open standards HTTP as transport protocol Used by WWW Less problems in corporation firewalls

XML as message format Not binary Human readable

Language independent Servers and clients can be written in different languages Communication is done with standard protocols HTTP and XML

Widely tested technology HTTP and XML are well known Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Overview

Key benefits

Software systems are written in a variety of languages Systems usually have to interoperate with others

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Overview

History I

RPC (Remote Procedure Call) emerged in 1990s Invoke a procedure/subroutine/method in a remote machine Theoretically language neutral (C/C++ similarities) IDL (Interface Definition Language) Defines the service contract IDL compiler generates client-side or server-side artifacts

Systems relaying on RPC Microsoft’s DCOM (Distributed Common Object Model) CORBA (Common Object Request Broker Architecture) Java RMI (Remote Method Invocation) Samba

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Overview

History II

XML-RPC Lightweight RPC system Use XML to achieve language neutrality Rely on HTTP as transport protocol

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

Overview

Groups Web services can be divided in two subtypes/groups: SOAP-based and REST-style SOAP Messages are XML which follow SOAP standard SOAP services use WS-* standards (family of web service specifications)

REST Use standard verbs/methods of HTTP protocol (GET, POST, PUT and DELETE) Messages are usually XML or JSON (simpler than SOAP ones)

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP SOAP (Simple Object Access Protocol). Now SOAP is officially no longer an acronym Protocol for exchanging XML-based messages over computer networks, normally using HTTP/HTTPS SOAP specifies XML messages formats (verbose) How messages should be processed Encoding rules for standard and application-defined data types Convention for representing remote procedure calls and responses

SOAP is platform independent and language independent WSDL (Web Services Description Language) is the service contract Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Java Implementation I Create a new simple Maven project $ mvn archetype:create -DgroupId=com.igalia.java.webservices \ -DartifactId=example -DarchetypeArtifactId=maven-archetype-webapp

Configure build plugins in pom.xml maven-compiler-plugin 1.6 1.6 org.mortbay.jetty maven-jetty-plugin

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Java Implementation II

Add maven dependencies com.sun.xml.ws jaxws-rt 2.2.5

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Java Implementation III Web service interface (inside src/main/java/) package com.igalia.java.webservices.soap; import import import import

javax.jws.WebMethod; javax.jws.WebService; javax.jws.soap.SOAPBinding; javax.jws.soap.SOAPBinding.Style;

@WebService @SOAPBinding(style = Style.RPC) public interface HelloWorldService { @WebMethod String sayHello(); @WebMethod String sayGreetings(String name); }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Java Implementation IV Web service implementation package com.igalia.java.webservices.soap; import javax.jws.WebService; @WebService(endpointInterface = "com.igalia.java. webservices.soap.HelloWorldService") public class HelloWorldServiceImpl implements HelloWorldService { public String sayHello() { return "Hello World!"; } public String sayGreetings(String name) { return "Hi " + name + "!"; } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Java Implementation V Configure web.xml file com.sun.xml.ws.transport.http.servlet. WSServletContextListener JaxWsServlet com.sun.xml.ws.transport.http.servlet.WSServlet 1 JaxWsServlet /soap/*

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Java Implementation VI

Create a new file sun-jaxws.xml

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Testing I

Testing web service from browser: http://localhost:8080/example/soap/helloworld?wsdl

WSDL defining service contract

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Testing II

Test web service from Python from suds.client import Client url = "http://localhost:8080/example/soap/helloworld?wsdl" client = Client(url) print client.service.sayHello() print client.service.sayGreetings("John Doe")

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Service Testing III Test web service from Java package com.igalia.java.webservices.soap; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; public class SOAPClient { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/example/soap/helloworld?wsdl") ; QName qname = new QName("http://soap.webservices.java.igalia.com/", "HelloWorldServiceImplService"); Service service = Service.create(url, qname); HelloWorldService client = service.getPort(HelloWorldService.class); System.out.println(client.sayHello()); System.out.println(client.sayGreetings("John Doe")); } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Messages Format I

To show SOAP messages in Python example add following lines: import logging logging.basicConfig(level=logging.INFO) logging.getLogger(’suds.client’).setLevel(logging.DEBUG)

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Messages Format II

Request message

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

SOAP Messages Format III

Response message Hello World!

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP

Automatic Client Generation Generate client from WSDL $ wsimport -keep -p client -verbose \ http://localhost:8080/example/soap/helloworld?wsdl

Use generated client package client; public class HelloWorldClient { public static void main(String[] args) { HelloWorldServiceImplService service = new HelloWorldServiceImplService (); HelloWorldService client = service.getHelloWorldServiceImplPort(); System.out.println(client.sayHello()); System.out.println(client.sayGreetings("John Doe")); } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST REST (REpresentation State Transfer) Introduced and defined by Roy Fielding in his Ph.D. dissertation Principal author of HTTP specification Co-founder of Apache Software Foundation

Not a protocol. REST refers to a collection of network architecture principles which outline how resources are defined and addressed A resource is anything that has a URI (Uniform Resource Identifier) Representations use MIME types (XML, JSON, ...) to capture the resource state Clients invoke operations on these resources Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

RESTful Web Services I

RESTful is a web service implemented using HTTP and REST principles Use HTTP architecture: proxies, caches, . . . (higher scalability) Lots of web services claim to be REST Do not follow all REST specification (usually only GET and POST) They use XML or JSON for messages

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

RESTful Web Services II

HTTP well-known verbs/methods GET Read a resource POST Create a new resource PUT Update a resource DELETE Remove a resource

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

RESTful Web Services III

HTTP verbs and URI combination GET users: Read all users GET users?id=29: Read user with id 29 POST users: Create a new user PUT users: Update users list DELETE users: Remove users list DELETE users?id=29: Remove user with id 29

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

RESTful Web Services IV

HTTP standard status codes 200 Ok 400 Bad request (malformed) 403 Forbidden request (refused) 404 Not found 405 Method not allowed (unsupported) 415 Unsupported media type (unrecognized) 500 Internal server error (failed)

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Java Implementation I

Carry on with previous Maven project used in SOAP example Add new dependency com.sun.jersey jersey-server 1.8

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Java Implementation II

Add repository to find the new dependency maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Java Implementation III Create web service class package com.igalia.java.webservices.rest; import import import import import

javax.ws.rs.GET; javax.ws.rs.Path; javax.ws.rs.PathParam; javax.ws.rs.Produces; javax.ws.rs.core.MediaType;

@Path("/helloworld") public class HelloWorldService { @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello() { return "Hello World!"; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("/{name}") public String sayGreetings(@PathParam("name") String name) { return "Hi " + name + "!"; } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Java Implementation IV Configure web.xml file Jersey Web Application com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages com.igalia.java.webservices.rest 1 Jersey Web Application /rest/*

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Testing I

Testing web service from browser: http://localhost:8080/example/rest/helloworld/

or

http://localhost:8080/example/rest/helloworld/John%20Doe/

Test web service from terminal with curl $ curl -s -X GET http://localhost:8080/example/rest/helloworld/ $ curl -s -X GET http://localhost:8080/example/rest/helloworld/John%20Doe/

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Testing II Test web service from Python from httplib import HTTPConnection conn = HTTPConnection("localhost", 8080) conn.request("GET", "/example/rest/helloworld") res = conn.getresponse() print res.read() conn.request("GET", "/example/rest/helloworld/Jonh%20Doe") res = conn.getresponse() print res.read()

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

REST Service Testing III Test web service from Java package com.igalia.java.webservices.rest; import import import import

java.io.BufferedReader; java.io.InputStreamReader; java.net.HttpURLConnection; java.net.URL;

public class RESTClient { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/example/rest/helloworld/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); System.out.println(reader.readLine()); } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Other HTTP methods

In the examples only @GET annotations are used For the rest of HTTP verbs/methods use the corresponding annotation @POST @PUT @DELETE

Usually it is needed to use @Consumes (like @Produces)

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs I JAXB (Java Architecture for XML Binding) Create a DTO (Data Transfer Object) and use JAXB annotations package com.igalia.java.webservices.rest.dtos; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "message") public class MessageDTO { @XmlAttribute public String content; public MessageDTO() { } public MessageDTO(String content) { this.content = content; } } Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs II Define a new service that uses this DTO package com.igalia.java.webservices.rest; import import import import import import

java.util.*; javax.ws.rs.GET; javax.ws.rs.Path; javax.ws.rs.PathParam; javax.ws.rs.Produces; javax.ws.rs.core.MediaType;

import com.igalia.java.webservices.rest.dtos.MessageDTO; @Path("/messages") public class MessagesService { private static List messages = new ArrayList(Arrays.asList( "Message 1", "Message 2", "Message 3")); @GET @Produces(MediaType.APPLICATION_XML) @Path("/{index}") public MessageDTO getMessage(@PathParam("index") int index) { return new MessageDTO(messages.get(index)); } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs III

Test XML from browser: http://localhost:8080/example/rest/messages/1

Test web service from terminal with curl $ curl -s -X GET http://localhost:8080/example/rest/messages/1

Output improved with tidy $ curl -s -X GET http://localhost:8080/example/rest/messages/1 \ | tidy -xml -i -q

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs IV In order to return a list of messages a new DTO is needed package com.igalia.java.webservices.rest.dtos; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "messages-list") public class MessagesListDTO { @XmlElementWrapper(name = "messages") public List messages = new ArrayList(); public MessagesListDTO() { } public MessagesListDTO(List messages) { this.messages = messages; } }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs V

And the new method that return a list of messages @GET @Produces(MediaType.APPLICATION_XML) public MessagesListDTO getMessages() { List dtos = new ArrayList(); for (String message : messages) { dtos.add(new MessageDTO(message)); } return new MessagesListDTO(dtos); }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs VI

Receiving and XML via POST method @POST @Consumes(MediaType.APPLICATION_XML) public Response addMessage(MessageDTO dto) { messages.add(dto.content); return Response.ok().build(); }

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Managing XMLs VII

Create a file message.xml with following content

Testing POST method with curl $ curl -v -s -X POST \ --header "Content-type: application/xml" \ -d @message.xml http://localhost:8080/example/rest/messages/

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Response Codes Customization I

Current service that returns a message could cause a ArrayIndexOutOfBoundsException This exception should be managed in the web serviced and returned the proper HTTP status code (404 - Not Found) Use javax.ws.rs.core.Response class to manage it

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Response Codes Customization II Customizing response code if exception @GET @Produces(MediaType.APPLICATION_XML) @Path("/{index}") public Response getMessage(@PathParam("index") int index) { try { MessageDTO dto = new MessageDTO(messages.get(index)); return Response.ok().entity(dto).build(); } catch (IndexOutOfBoundsException e) { return Response.status(Status.NOT_FOUND).build(); } }

Test it with verbose option in curl $ curl -v -s -X GET http://localhost:8080/example/rest/messages/5

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Using JSON I

Add dependency com.sun.jersey jersey-json 1.8

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

REpresentation State Transfer

Using JSON II

Add a new method returning JSON @GET @Produces(MediaType.APPLICATION_JSON) @Path("/json/") public MessagesListDTO getMessagesJSON() { return getMessages(); }

Test JSON from browser: http://localhost:8080/example/rest/messages/json/

Manuel Rego Casasnovas

Java Web Services

Web Services Overview SOAP REST Conclusion

SOAP vs REST

SOAP vs REST

SOAP More verbose, but usually developer doesn’t have to deal with XML Automatic generation of clients code High attachment between client code and server methods

REST Readable message files (usually XMLs) Needed to parse XMLs, but may be easy with some libraries (e.g. JAXB) Simpler clients, it uses HTTP standards

Manuel Rego Casasnovas

Java Web Services

References

References I Martin Kalin Java Web Services: Up and Running http://www.amazon.com/Java-Web-Services-Up-Running/dp/059652112X

Leonard Richardson & Sam Ruby Restful Web Services http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260

Web service - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/Web_service

SOAP - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/SOAP

Manuel Rego Casasnovas

Java Web Services

References

References II

Representational State Transfer - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/Representational_State_Transfer

Web Services Tutorial http://www.w3schools.com/webservices/

Web Services Description Language (WSDL) 1.1 http://www.w3.org/TR/wsdl

Manuel Rego Casasnovas

Java Web Services