computación orientada a servicios (práctica)

Anuncio
COMPUTACIÓN
ORIENTADA A SERVICIOS
(PRÁCTICA)
Dr. Mauricio Arroqui
EXA-UNICEN
Actividad
•  Crear un servicio REST y un cliente para el mismo
ejercicio realizado durante la práctica para SOAP. Se
requiere la modelación del problema y correcta utilización
de los verbos.
•  A continuación se ejemplifica paso a paso la creación de un
servicio Rest y un cliente en Eclipse.
Server
Convertir a Maven Project (simplifica el agregado de
librerías)
Click derecho en el Proyecto -> Configure – Convert to Maven Project
Convertir a Maven Project
Abrir pom.xml y agregar abajo del tag <build>
<dependencies>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
Mi pom.xml completo
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>RestWebService</groupId>
<artifactId>RestWebService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
LAS QUE PEGAMOS
</dependencies>
</project>
Editar /WebContent/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/
javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/webapp_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RestWebService</display-name>
<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>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
Clase Java 1
@Path("/dtopservice")
public class DolarToPesoService {
@GET
@Produces("application/xml")
public String convertCtoF() {
Double peso;
Double dolar = 10.0;
peso = dolar * 9.4 * 1.2;
String result = "@Produces(\"application/xml\") Output: \n\nu$D to Peso Arg Tarjeta Converter Output: \n\n" + peso;
return "<dtopservice>" + "<dolar>" + dolar + "</dolar>" + "<dtopoutput>" + result + "</dtopoutput>" + "</
dtopservice>";
}
@Path("{c}")
@GET
@Produces("application/xml")
public String convertCtoFfromInput(@PathParam("c") Double c) {
Double peso;
Double dolar = c;
peso = ((dolar * 9) / 5) + 32;
String result = "@Produces(\"application/xml\") Output: \n\nu$D to Peso Arg Tarjeta Converter Output: \n\n" + peso;
return "<dtopservice>" + "<dolar>" + dolar + "</dolar>" + "<dtopoutput>" + result + "</dtopoutput>" + "</
dtopservice>";
}
}
Clase Java 2
@Path("/dtopservice")
public class DolarToPesoService {
@GET
@Produces("application/xml")
public String convertCtoF() {
Double peso;
Double dolar = 10.0;
peso = dolar * 9.4 * 1.2;
String result = "@Produces(\"application/xml\") Output: \n\nu$D to Peso Arg Tarjeta Converter Output: \n\n" + peso;
return "<dtopservice>" + "<dolar>" + dolar + "</dolar>" + "<dtopoutput>" + result + "</dtopoutput>" + "</
dtopservice>";
}
@Path("{c}")
@GET
@Produces("application/xml")
public String convertCtoFfromInput(@PathParam("c") Double c) {
Double peso;
Double dolar = c;
peso = ((dolar * 9) / 5) + 32;
String result = "@Produces(\"application/xml\") Output: \n\nu$D to Peso Arg Tarjeta Converter Output: \n\n" + peso;
return "<dtopservice>" + "<dolar>" + dolar + "</dolar>" + "<dtopoutput>" + result + "</dtopoutput>" + "</
dtopservice>";
}
}
Maven
•  Click derecho en el projecto -> Maven -> Update
Project
•  Click derecho en el projecto –> Run as … -> Maven
Build (opción 5) ->Add “clean install” -> Run
Arrancar el Tomcat
Test
•  http://localhost:8080/RestWebService/services/
dtopservice/
•  http://localhost:8080/RestWebService/services/
dtopservice/50/
•  http://localhost:8080/RestWebService/services/
ptodservice/
•  http://localhost:8080/RestWebService/services/
ptodservice/50/
Cliente
Estructura del proyecto
1.  Creamos un
paquete para el
cliente.
2.  Va a ser una
simple clase con
un método main()
Paquete donde
crearon el servidor
Clase Java
package ar.edu.unicen.exa.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class RestWebServiceClient {
public static void main(String[] args) {
System.out.println("STARTING");
RestWebServiceClient client = new RestWebServiceClient();
client.getPtoDResponse();
client.getDtoPResponse();
}
private void getDtoPResponse() {
try {
Client client = Client.create();
WebResource webResource2 = client.resource("http://localhost:8080/RestWebService/services/dtopservice/10");
ClientResponse response2 = webResource2.accept("application/xml").get(ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus());
}
String output2 = response2.getEntity(String.class);
System.out.println("\n============Get Dollars To Pesos Arg ============");
System.out.println(output2);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getPtoDResponse() {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RestWebService/services/ptodservice/10");
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("============Get Pesos Arg to Dollar Tarjeta============");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
FIN
Descargar