lunes, 19 de mayo de 2014

Web Service + REST + JAX-RS

En WebServices existen dos modalidades: SOAP y REST
  1. JAX-WS represents SOAP
  2. JAX-RS represents REST
SOAP es intercambio de mensajes SOAP (que son mensajes envueltos en XML).
JAX WS es la implementación estándar de web services SOAP en Java. Viene desde la versión de JDK 6.

REST es una implementación posterior. Más rica, no sólo utiliza un tipo de mensaje HTTP para el intercambio de mensajes, si no que permite más mensajes. Esto es, con Rest puedes tener un cliente que envíe mensajes HTTP de tipo GET, PUT, POST y DELETE. Cada mensaje enviará los datos correspondientes asociados hacia el servidor, que, recibirá la petición, la entenderá, y delegará en el método correspondiente. GET sirve para recuperar un dato desde el cliente al servidor, PUT para insertar un dato, POST para enviar información para modificar y DELETE para eliminar información del servidor.

The important thing to know about the request body is that it is unique to each service. The service designer must define the format of the request body and convey that to service consumers. Information in the request body is typically encoded in XML or JSON format. Here is a typical HTTP request that contains XML information within the body:

Service CallDescription
GET http://{server}/MyRestService/library/booksGet a list of books
PUT http://{server}/MyRestService/library/books/12345Create a new book with ISBN 12345
GET http://{server}/MyRestService/library/books/12345Get a single book with ISBN 12345
DELETE http://{server}/MyRestService/library/books/12345Delete a single book with ISBN 12345

Link muy util:



Algunas implementaciones REST:
  • Apache CXF
  • Jersey
  • RESTeasy (is JBOSS provided implementation of JAX-RS specification for building RESTful Web Services and RESTful Java applications. Though this is not limited to be used in JBOSS only, and you can use with other servers also. In this post, I am building such a hello world application in tomcat server)
  • Restlet
  • Apache Wink

Ejemplo usando RESTeasy:

http://howtodoinjava.com/2013/05/09/resteasy-tomcat-hello-world-application/

Ejemplo usando CXF con Spring:

http://dhruba.name/2008/12/08/rest-service-example-using-cxf-22-jax-rs-10-jaxb-and-spring/
http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/

Luego para acceder a la URL, vamos a:

http://localhost:8081/WSRestWithSpringProject/services

Y haciendo clic en la URL, vemos lo siguiente:


Para acceder a alguno de los dos servicios expuestos hacemos:

  • http://localhost:8081/WSRestWithSpringProject/myservice/users
  • http://localhost:8081/WSRestWithSpringProject/myservice/customers

Si queremos acceder a un método pasando por parámetro un valor:


El método es del estilo:

    @GET
    @Path("/users")
    @Produces("application/xml") //The @Produces annotation is used to 
    specify the format of the response. W
    @Override
    public Response getUsers(@QueryParam("id")String id) {
  
    UserCollection usersList = new UserCollection(users.values());
    if (StringUtils.hasText(id)){
    Integer idAsInt = Integer.valueOf(id);
    User user = users.get(idAsInt);
    System.out.println("user: " + user);
        return Response.status(200).entity(user).build();
   
    return Response.status(200).entity(usersList).build();
    }

Leer:
http://stackoverflow.com/questions/11552248/when-to-use-queryparam-vs-pathparam

Otro Ejemplo usando CXF con Spring + JSON:

This is a simple link to demostrate how to create a simple JAX-RS Web Service in Java using Spring and Apache CXF. This service will be follow the request/response pattern, it will using HTTP POSTs which are formatted JSON requests and it will produce JSON responses:

http://www.dreamsyssoft.com/blog/blog.php?/archives/7-Simple-JAX-RS-Web-Service-in-Java-with-Spring-and-CXF.html

@Path("/myservice")
@Consumes("application/json")
@Produces("application/json")
public interface UserManagerJson {

@GET
@Path("/fetchUserById")
public UserResponseJson fetchUserById(@QueryParam("id")String request);

..
}

public class UserManagerimplJson implements UserManagerJson {

@Override
public UserResponseJson fetchUserById(String request) {
UserResponseJson userResponseJson = new UserResponseJson();
userResponseJson.setSuccess(true);
userResponseJson.setErrorMessage("OK");
userResponseJson.setUsers(new ArrayList<String>());
return userResponseJson;
}
..
}

ApplicationContext.xml

.....
.....        
   <!-- 2. CON JSON RESPONSE -->
  <jaxrs:server id="userManagerWithJson" address="/dos">
  <jaxrs:serviceBeans>
  <ref bean="userManagerService"/>
  </jaxrs:serviceBeans>
  <jaxrs:providers>
<ref bean='jsonProvider' />
</jaxrs:providers>
  </jaxrs:server>
 
  <bean id="jsonProvider" 
class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
    
<bean id="userManagerService" class="service.json.UserManagerimplJson"/>

.....
.....

POM.XML

....
....
 <!-- Provider para jax-rs para devolver una respuesta en formato json -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.1.1</version>
</dependency>
....
....


No hay comentarios:

Publicar un comentario