• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Crie seu sistema REST com JAX-RS e o futuro
 

Crie seu sistema REST com JAX-RS e o futuro

on

  • 3,405 views

Palestra de Guilherme Silveira durante o Javaone Brazil no keynote hall.

Palestra de Guilherme Silveira durante o Javaone Brazil no keynote hall.

Statistics

Views

Total Views
3,405
Views on SlideShare
3,403
Embed Views
2

Actions

Likes
2
Downloads
37
Comments
0

1 Embed 2

http://twitter.com 2

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • 1 uri. 1 http verb\n
  • implementing a specific response\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Crie seu sistema REST com JAX-RS e o futuro Crie seu sistema REST com JAX-RS e o futuro Presentation Transcript

  • Put your systems to REST Guilherme Silveira @guilhermecaelum
  • Guilherme Silveira guilherme.silveira@caelum.com.br2002 guj.com.br2003 vraptor2004 caelum.com.br2009 restfulie2010 tectura.com.br
  • banco.com calendario.comviagem.com empresa.com
  • CORBAparaíso?
  • EJBparaíso?
  • SOAPparaíso?
  • o que é REST?
  • qual o futuro da integração na web?
  • representação de uma viagem<?xml version="1.0" encoding="UTF-8" standalum="yes"?><flight> <information> <from>sao paulo</from> <to>seoul</to> </information>  <value>900.00</value></flight>
  • service locator ao integrar: acoplamento++ unrest pay unresttrips.comguilherme
  • service locator ao integrar: acoplamento++ unrest pay unresttrips.comguilherme
  • representação em REST<?xml version="1.0" encoding="UTF-8" standalum="yes"?><flight> <information> <from>sao paulo</from> <to>seoul</to> </information>  <value>900.00</value> <link rel="payment" href="http://resttrips.com/payment/custom"/</flight>
  • Rest Client: hipermídiaflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value);
  • alterando o serviço<?xml version="1.0" encoding="UTF-8" standalum="yes"?><flight> <information> <from>sao paulo</from> <to>seoul</to> </information>  <value>900.00</value> <link rel="payment" href="http://paysite.com/custom"/></flight>
  • dependency injection em integração: acoplamento-- restrips pay resttrips.com guilherme paysite.com
  • dependency injection em integração: acoplamento-- restrips pay resttrips.com guilherme paysite.com
  • trip = recurso http://kayak.com/f/574XR4payment = recurso any_uri_unknown_at_compile_time
  • eu nunca viajo sozinho
  • meu amigo ricky
  • Rest Client: compartilhando uma viagemflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value/2);// send the payment link to another part of the webflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value/2);
  • Rest Client: compartilhando uma viagemflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value/2);// send the payment link to another part of the webflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value/2);
  • Rest Client: compartilhando uma viagemflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value/2);// send the payment link to another part of the webflight = Client.at(http://resttrips.com/f/574XR4).get();confirmation = flight.getLink("payment"). patch(cardInformation, value/2);
  • calendar: integrando sistemasmyself = Client.at(http://users.calendar.com) .with(auth).get();myself.link("calendar").patch(flight.link("self"));
  • calendar: integrando sistemasmyself = Client.at(http://users.calendar.com) .with(auth).get();myself.link("calendar").patch(flight.link("self"));
  • calendar: outros exemplosme.link("calendar").patch(representacao_aniversarios)me.link("calendar").patch(represetancao_hotel)
  • e daí?
  • e daí?Atualizações na viagem ==> refletem aquiAtualizações no hotel ==> refletem aquiAtualizações no encontro ==> refletem aqui
  • e daí? gre! nte e ,i us n ãoAtualizações na viagem ==> refletem aquiAtualizações no hotel ==> refletem aquiAtualizações no encontro ==> refletem aqui
  • o que mais?
  • o que mais?Remove ==> Cancela a viagemRemove ==> Cancela o hotelRemove ==> Email para colegas
  • o que mais? liz e! nt ra esce e, d s tr rq ue o n ãoRemove ==> Cancela a viagemRemove ==> Cancela o hotelRemove ==> Email para colegas
  • mas qual o formato dopagamento ou calendário?
  • #json, #xml,#soap #etc?
  • qual #json, #xml #etc?
  • exercise
  • quem é este?
  • quem é essa?
  • fácil? e ela?
  • fácil? e ela? lh a! fi in ha é m n ão
  • conteúdo sem semântica não tem valor!
  • qual “formato”?
  • qual “formato”?micro formats, media types, rdf etc
  • qual “formato”? nk s! er li hyp ts e a fo rm icro mmicro formats, media types, rdf etc
  • integração na web
  • Put your server to REST leonard richardsons model
  • Server Maturity 1 uri, 1 http verb/services.do?action=install&...
  • Server Maturity 1 uri, 1 http verb/services.do?action=install&...@Path("/services")public class Services {  @GET  public Response services(    @QueryParam("action") String action) {    ServiceFactory factory = new ServiceFactory();    Service service = factory.getServiceFor(action);    return service.execute();  }}
  • Server Maturity 1 uri, 1 http verbpublic class InstallService {  public Response execute() {    return Response.ok()             .type("application/xml")             .entity("<service>...</service>")             .build();  }}
  • But?
  • 1 uri, 1 http verb/services.do?action=install&... I know them all beforehand.
  • 1 uri, 1 http verb/services.do?action=install&...Any change will break all our clients!
  • a priori knowledge
  • a priori knowledge =
  • a priori knowledge = coupling++
  • Server Maturity Multiple uris, 1 http verb/install?...
  • Server Maturity Multiple uris, 1 http verb/install?... @Path("/services") public class Services {   @GET @Path("install")   public Response install() {     return new InstallService().execute();   }   @GET @Path("uninstall")   public Response uninstall() {     return new UninstallService().execute();   }
  • but...
  • GET hellGET should not imply in undesireable effects
  • POST hellGET could help us with cache!
  • Server Maturity Multiple uris, multiple verbs POST /cloud GET /cloud/1547437/softwarePOST /cloud/1547437/software
  • rails + restfulie rubyonrails.org
  • rails + restfulie rubyonrails.orgclass SoftwaresController < ApplicationController    acts_as_restfulie  respond_to :xml, :json    def create    @item = Item.create(params[:item])    respond_with @item, :status => :created  end    def show    @item = Item.find(params[:id])    respond_with @item  endend
  • JAX-RS@Path("/softwares")public class SoftwareResource {  @POST @Consumes("application/xml")  public Response install(Software software) {    software = SoftwareRepository.register(software);    long id = software.getId();    URI uri = UriBuilder.fromPath("/softwares/" + id)                                       .build();    software.install();    return Response.created(uri).build();  }
  • JAX-RS  @DELETE @Path("{id}")  public Response uninstall(@PathParam("id") Long id) {    Software software = SoftwareRepository.retrieve(id);    software.uninstall();    return Response.ok().build();  }
  • Uniform Interface++ Resources++
  • Http verbs examplePOST createsPUT replacesPATCH updatesDELETE removesGET retrievesOPTIONS tells me what i can do...
  • Is a Restful service a cute CRUD?
  • yes
  • but there is more!
  • @XmlRootElement@XmlType(propOrder= {"id", "host", "softwares", "links"})public class Machine {  private final all variables here;  @XmlElement(name="link", namespace="http://www.w3.org/2005/Atom")  public List<Link> getLinks() {    return Arrays.asList(      Link.to("/machines/" + getId(), "self"),      Link.to("/machines/" + getId() + "/softwares", "softwares")    );  }  @XmlElementWrapper(name="softwares")  @XmlElement(name="software")  public List<Software> getSoftwares() {    return softwares;  }  public void install(Software software) {    getSoftwares().add(software);  }  public void uninstall(Software software) {    getSoftwares().remove(software);  }} Machine.java
  • @XmlRootElement@XmlType(propOrder= {"id", "host", "softwares", "links"})public class Machine {  private final all variables here;  @XmlElement(name="link", namespace="http://www.w3.org/2005/Atom")  public List<Link> getLinks() {    return Arrays.asList(      Link.to("/machines/" + getId(), "self"),      Link.to("/machines/" + getId() + "/softwares", "softwares")    );  }  @XmlElementWrapper(name="softwares")  @XmlElement(name="software")  public List<Software> getSoftwares() {    return softwares;  }  public void install(Software software) {    getSoftwares().add(software);  }  public void uninstall(Software software) {    getSoftwares().remove(software);  }} Machine.java
  • @Path("/machines")public class MachineResource { MachineResource @Path("{id}/softwares") public SoftwareResource softwares(@PathParam("id") Long id) { Machine machine = new MachineRepository().retrieve(id); if (machine != null) { SoftwareResource softwareResource = new SoftwareResource(); softwareResource.setMachine(machine); return softwareResource; } throw new WebApplicationException(404); } @POST @Consumes("application/xml") public Response create(Machine machine) { Long id = new MachineRepository().save(machine); return Response.created(UriBuilder.fromPath("/" + id).build()).build(); } @GET @Path("{id}") @Produces("application/xml") public Machine show(@PathParam("id") Long id) { return new MachineRepository().retrieve(id); } @GET @Produces("application/xml") public Machines list() { Machines machines = new Machines(); machines.setMachine(new MachineRepository().list()); return machines;
  • @Path("/machines")public class MachineResource { MachineResource @Path("{id}/softwares") public SoftwareResource softwares(@PathParam("id") Long id) { Machine machine = new MachineRepository().retrieve(id); if (machine != null) { SoftwareResource softwareResource = new SoftwareResource(); softwareResource.setMachine(machine); return softwareResource; } throw new WebApplicationException(404); } @POST @Consumes("application/xml") public Response create(Machine machine) { Long id = new MachineRepository().save(machine); return Response.created(UriBuilder.fromPath("/" + id).build()).build(); } @GET @Path("{id}") @Produces("application/xml") public Machine show(@PathParam("id") Long id) { return new MachineRepository().retrieve(id); } @GET @Produces("application/xml") public Machines list() { Machines machines = new Machines(); machines.setMachine(new MachineRepository().list()); return machines;
  • Server Modelaccording toLeonard Richardson, 2008 one uri + one verb
  • Server Modelaccording toLeonard Richardson, 2008 Ugly one uri + one verb
  • Server Modelaccording toLeonard Richardson, 2008 multiple uris one uri + one verb
  • Server Modelaccording toLeonard Richardson, 2008 Less ugly multiple uris one uri + one verb
  • Server Modelaccording toLeonard Richardson, 2008 multiple verbs multiple uris one uri + one verb
  • Server Modelaccording toLeonard Richardson, 2008 cute CRUD multiple verbs multiple uris one uri + one verb
  • Server Model restaccording toLeonard Richardson, 2008 hypermedia multiple verbs multiple uris one uri + one verb
  • JAX-RS 2 wishlist
  • guj
  • vraptor 0, 2, 3
  • java keynotes
  • exemplosvraptor.org
  • 1. repetições?@Path("/services")public class Services {  @GET  public Response services(    @QueryParam("action") String action) {    ServiceFactory factory = new ServiceFactory();    Service service = factory.getServiceFor(action);    return service.execute();  }}
  • você quer fazer copy+paste?
  • repetir = inferno
  • Convention over Configuration@Resourcepublic class Services { private final ServiceFactory factory; public Services(ServiceFactory factory) { this.factory = factory; } public void services(String action) { factory.getServiceFor(action).execute(); }}
  • yes!
  • yes!
  • 2. TDD: hard to test@Path("/products")public class Products { coupled to the  @GET implementation  public Response create(    @QueryParam("what") String what) {    // persists    return Response.ok()             .type("application/xml")             .entity("<product>...</product>")             .build();  }}
  • 3. Content negotiation na unha@Path("/softwares")public class SoftwareResource {  @POST @Consumes("application/xml")  public Response install(Software software) {    software = SoftwareRepository.register(software);    long id = software.getId();    URI uri = UriBuilder.fromPath("/softwares/" + id)                                       .build(); software.install();    return Response.created(uri).build();  }
  • 4. URI coupling writing the URI once...  @GET @Path("/softwares/{id}")  public Response install(@QueryParam("id") Softwaresoftware) { // ...  }
  • 4. URI coupling writing the URI again several times@Path("/softwares")public class SoftwareResource {  @POST @Consumes("application/xml")  public Response install(Software software) {    software = SoftwareRepository.register(software);    long id = software.getId();    URI uri = UriBuilder.fromPath("/softwares/" + id)                                       .build(); software.install();    return Response.created(uri).build();  }
  • 4. URI coupling code@Path("/softwares")public class SoftwareResource {  @POST @Consumes("application/xml")  public Response install(Software software) {    software = SoftwareRepository.register(software);    long id = software.getId();    URI uri = UriBuilder.fromPath("/softwares/" + id)                                       .build(); software.install();    return Response.created(uri).build();  }
  • repetir = inferno
  • 5. Parameter list@Path("/machines")public class MachineResource { @Path("{id}/softwares") public SoftwareResource softwares(@PathParam("id") Long id) { Machine machine = new MachineRepository().retrieve(id); if (machine == null) { throw new WebApplicationException(404); } // ... }}
  • repetir = inferno
  • java =string oriented?
  • java =annotation oriented?
  • Cliente REST
  • Response response = client.at ("http://localhost:9998/user/574").get(); 6. Client internal DSLs
  • Response response = client.at ("http://localhost:9998/user/574").get();User user = response.getResource();System.out.println("user: " + user.getName()); 6. Client internal DSLs
  • User user = response.getResource();System.out.println("user: " + user.getName());Link link = resource(user).getLink("machine");response = link.follow().post(new Machine());
  • Link link = resource(user).getLink("machine");response = link.follow().post(new Machine());double amount = resource(user).refresh(). getAmountDue();
  • double amount = resource(user).refresh(). getAmountDue();link = resource(user).getLink("payment");Payment payment = new Payment(amount);response = link.follow().post(payment);
  • link = resource(user).getLink("payment");Payment payment = new Payment(amount);response = link.follow().post(payment);System.out.println("payment completed");
  • link = resource(user).getLink("payment");Payment payment = new Payment(amount);response = link.follow().post(payment);System.out.println("payment completed"); uma DSL alto nívelcom suporte a hipermídia
  • bottom up design by committe mime type microformato
  • hypermídiaviabilizando a integração através da web
  • vraptor mvc based REST
  • Arun Gupta jersey vraptor 3
  • vraptor somos nozes
  • @guilhermecaelumobrigado