Diapositiva 1 - Giovanni Morana

Transcript

Diapositiva 1 - Giovanni Morana
Facoltà di Ingegneria - Università degli studi di Catania
Dipartimento di Ingegneria Informatica e delle Telecomunicazioni
RESTful WS con JAVA
Breve introduzione
Giovanni Morana
RESTful
Roy Fielding's PhD thesis (99):
“Architectural Styles and the Design of Network-based Software Architectures.”
Si chiede:
1. Why is the Web so prevalent and ubiquitous?
2. What makes the Web scale?
3. How can I apply the architecture of the Web to my own applications?
Java Web Services
RESTful
Risorse indirizzabili
- Info e dati sono risorse accessibili attraverso URI (Uniform
Resource Identifier).
Interfaccia uniforme
- Gestione CRUD delle risorse
Risorse in differenti formati
- le risorse possono essere accedute usando diversi formati
(plain text, XML, JSON)
Comunicazioni STATELESS
- maggiore flessibilità, facilità di scaling up
Java Web Services
RESTful WS
REpresentational State Transfer (REST)
REST è uno architectural style: le informazioni sono considerate
risorse, identificate da URI, accessibili da remoto.
REST si basa su comunicazioni stateless di tipo Client-Server.
Tipicamente usa HTTP come protocollo di comunicazione.
Un RESTful web service è uno speciale tipo di WS gestito secondo i
principi REST.
Usa i metodi POST, GET, PUT e DELETE per mappare le operazioni
CRUD:
Creazione (Create)
Lettura (Read)
Scrittura/Aggiornamento (Update)
Eliminazione (Delete)
Java Web Services
Indirizzamento
Ciascuna richiesta HTTP fatta per gestire una risorsa “REST” deve fare
riferimento ad un URI specifico.
scheme://host:port/path?queryString#fragment
Scheme: http/https
Host: nome logico o indirizzo IP
Port: porta/opzionale
Path: stringa(con /) per identificare la risorsa in uno schema gerarchico
Query string: Lista di parametri (coppie nome=valore delimitate da &).
http://www.ing.unict.it:8087/studente?Nome=Marco&Cognome=Rossi
Fragment: indirizza porzioni specifiche del documento/risorsa a cui si accede
Java Web Services
Interfaccia Uniforme
Ogni servizio REST ha una interfaccia uniforme ben definita
Ciascun medoto esposto ha uno scopo specifico
Metodo GET:
Usato per recuperare le informazioni. Metodo idempotente, non modifica lo stato della
risorsa (safe accessing)
Metodo PUT:
Usato per aggiornare lo stato delle risorse remote. Metodo idempotente.
Metodo DELETE
Usato per eliminare la risorsa remot. Metodo idempotente
Metodo POST
Unico metodo non idempotente, usato per creare nuove risorse (rappresentazione nel
body)
Metodo OPTIONS
Usato per richiedere informazoni circa i parametri associati al tipo di comunicazione
relativaalle risorse richieste.Serve a definire meglio l'interfacciamento Client-Server
Java Web Services
Diversità dei formati
Ogni risorsa sul web può essere rappresentata in difersi formati (text, XML, JSON)
Per scambiare dati in diversi formati, client e server devono accordarsi sul tipo di
formato utilizzato.
Solitamente si usa un Content-Type header per informare l'altra parte in quale
formato si sta comunicand.
Il Content-Type header us il formato Multipurpose Internet Mail Extension (MIME).
type/subtype;name=value;
Type identifica la famiglia mentre subtype indica la categoria.
Opzionalmente è possibile inserire, attraverso name=value, specifici valori
text/plain
text/html
application/xml
charset=iso-8859-1
Java Web Services
RESTful WS e JAVA
La libreria JAX-RS (JSR 311) fornisce gli strumenti per creare web
services RESTful-oriented in Java.
Fa parte della piattaforma EE.
Dal sito http://jersey.java.net/:
Jersey is the open source JAX-RS (JSR 311) Reference
Implementation for building RESTful Web services. But, it is also
more than the Reference Implementation. Jersey provides additional
APIs and extension points (SPIs) so that developers may extend
Jersey to suite their needs.
Java Web Services
JAX-RS
@PATH(percorsoRisorsa) percorso relativo che identifica la risorsa
@POST
identifica richieste HTTP POST
@GET
identifica richieste HTTP GET
@PUT
identifica richieste HTTP PUT
@DELETE identifica risposta a richieste HTTP DELETE
@Produces( MediaType.TEXT_PLAIN, [altri tipi]) definisce il tipo MIME usato per GET
@Consumes( tipi ) definisce il tipo MIME usato per nel metodo considerato
Attraverso queste annotazioni è possible trasformare un POJO in un RESTful Web Service
Java Web Services
Esempio server
- HELLO WORLD Package HW;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/Saluto")
public class HelloWorld {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String ptHW() {
return "Hello World!";
}
@GET
@Produces(MediaType.TEXT_HTML)
public String htmlHW() {
return "<html> <title>" + "HW example" + "</title> <body> <h2>" +
"Hello ” + “ </h2> <h1> World! </h1> </body> </html> ";
}
}
Java Web Services
Esempio Client
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
public class Client {
private WebResource webResource;
private Client client;
private static final String BASE_URI = "http://localhost:8080/Saluto/resources";
public NewJerseyClient() {
com.sun.jersey.api.client.config.ClientConfig config = new
com.sun.jersey.api.client.config.DefaultClientConfig();
client = Client.create(config);
webResource = client.resource(BASE_URI).path("HW");
}
public String ptHW() throws UniformInterfaceException {
WebResource res = webResource;
return res.accept(javax.ws.rs.core.MediaType.TEXT_PLAIN).get(String.class);
}
public static void main(String args[]){
Client client = new Client();
System.out.print("Starting execution...");
System.out.print(client.ptHW());
}
Java Web Services
Riferimenti
[1] Java EE Tutorial, ORACLE
[2] RESTful Web Services Cookbook, Solutions for Improving Scalability and Simplicity
By Subbu Allamaraju
Publisher: O'Reilly Media / Yahoo Press
[3] RESTful Java with Jax-RS
By Bill Burke
Publisher: O'Reilly
Java Web Services
Facoltà di Ingegneria - Università degli studi di Catania
Dipartimento di Ingegneria Informatica e delle Telecomunicazioni
RESTful WS con JAVA
DOMANDE?
Giovanni Morana