SlideShare a Scribd company logo
Put your systems to REST
       Guilherme Silveira
       @guilhermecaelum
Guilherme Silveira
                  guilherme.silveira@caelum.com.br




2002   guj.com.br
2003   vraptor
2004   caelum.com.br
2009   restfulie
2010   tectura.com.br
banco.com    calendario.com




viagem.com   empresa.com
CORBA
paraíso?
EJB
paraíso?
SOAP
paraí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.com

guilherme
service locator ao integrar:
                     acoplamento++

                           unrest
                            pay


                   unresttrips.com

guilherme
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ídia




flight = 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/574XR4




payment = recurso
        any_uri_unknown_at_compile_time
eu nunca viajo sozinho
meu amigo
  ricky
Rest Client: compartilhando uma viagem



flight = 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 web

flight = Client.at('http://resttrips.com/f/574XR4').get();

confirmation = flight.getLink("payment").
                  patch(cardInformation, value/2);
Rest Client: compartilhando uma viagem



flight = 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 web

flight = Client.at('http://resttrips.com/f/574XR4').get();

confirmation = flight.getLink("payment").
                  patch(cardInformation, value/2);
Rest Client: compartilhando uma viagem



flight = 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 web

flight = Client.at('http://resttrips.com/f/574XR4').get();

confirmation = flight.getLink("payment").
                  patch(cardInformation, value/2);
calendar: integrando sistemas


myself = Client.at('http://users.calendar.com')
                                .with(auth).get();

myself.link("calendar").patch(flight.link("self"));
calendar: integrando sistemas


myself = Client.at('http://users.calendar.com')
                                .with(auth).get();

myself.link("calendar").patch(flight.link("self"));
calendar: outros exemplos



me.link("calendar").patch(representacao_aniversarios)
me.link("calendar").patch(represetancao_hotel)
e daí?
e daí?




Atualizações na viagem ==> refletem aqui
Atualizações no hotel ==> refletem aqui
Atualizações no encontro ==> refletem aqui
e daí?




                          gre!
                      nte
                 e ,i
              us
         n ão

Atualizações na viagem ==> refletem aqui
Atualizações no hotel ==> refletem aqui
Atualizações no encontro ==> refletem aqui
o que mais?
o que mais?




Remove ==> Cancela a viagem
Remove ==> Cancela o hotel
Remove ==> Email para colegas
o que mais?



                                   liz e!
                              nt ra
                          esce
                   e,   d
               s tr
          rq ue
      o
 n ão
Remove ==> Cancela a viagem
Remove ==> Cancela o hotel
Remove ==> Email para colegas
mas qual o formato do
pagamento 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
 m

micro 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 verb


public 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 hell


GET should not imply in
  undesireable effects
POST hell


GET could help us with
        cache!
Server Maturity
  Multiple uris, multiple verbs




         POST /cloud
 GET /cloud/1547437/software
POST /cloud/1547437/software
rails + restfulie
  rubyonrails.org
rails + restfulie
                   rubyonrails.org
class 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
  end
end
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 example
POST creates

PUT replaces

PATCH updates

DELETE removes

GET retrieves

OPTIONS 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 Model
according to
Leonard Richardson, 2008




                           one uri + one verb
Server Model
according to
Leonard Richardson, 2008




                               Ugly
                           one uri + one verb
Server Model
according to
Leonard Richardson, 2008




                           multiple
                            uris



                            one uri + one verb
Server Model
according to
Leonard Richardson, 2008



                                      Less ugly
                           multiple
                            uris



                            one uri + one verb
Server Model
according to
Leonard Richardson, 2008


                                       multiple
                                        verbs
                           multiple
                            uris



                            one uri + one verb
Server Model
according to
Leonard Richardson, 2008
                           cute CRUD
                                       multiple
                                        verbs
                           multiple
                            uris



                            one uri + one verb
Server Model                      rest
according to
Leonard Richardson, 2008        hypermedia


                                       multiple
                                        verbs
                           multiple
                            uris



                            one uri + one verb
JAX-RS 2 wishlist
guj
vraptor 0, 2, 3
java keynotes
exemplos
vraptor.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


@Resource
public 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") Software
software) {
    // ...
  }
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ível
com suporte a hipermídia
bottom up
  design by committe
      mime type
    microformato
hypermídia
viabilizando a integração através da web
vraptor
 mvc based REST
Arun Gupta
   jersey
 vraptor 3
vraptor somos nozes
@guilhermecaelum




obrigado

More Related Content

Similar to Crie seu sistema REST com JAX-RS e o futuro

Arquitetura: chega de mesmice
Arquitetura: chega de mesmiceArquitetura: chega de mesmice
Arquitetura: chega de mesmice
Guilherme Silveira
 
Arquitetura chega de mesmice
Arquitetura  chega de mesmiceArquitetura  chega de mesmice
Arquitetura chega de mesmice
Guilherme Silveira
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Brian Sam-Bodden
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
Amazon Web Services
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
rajkamaltibacademy
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
Anatoly Sharifulin
 
Server side data sync for mobile apps with silex
Server side data sync for mobile apps with silexServer side data sync for mobile apps with silex
Server side data sync for mobile apps with silex
Michele Orselli
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
Antonio Peric-Mazar
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
Bastian Hofmann
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
Fernando Daciuk
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server
Masahiro Nagano
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
Andréia Bohner
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
Andréia Bohner
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and FluxTPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and Flux
Jirat Kijlerdpornpailoj
 
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
Atlassian
 
Summit2011 satellites-robinf-20110605
Summit2011 satellites-robinf-20110605Summit2011 satellites-robinf-20110605
Summit2011 satellites-robinf-20110605
Robin Fernandes
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 

Similar to Crie seu sistema REST com JAX-RS e o futuro (20)

Arquitetura: chega de mesmice
Arquitetura: chega de mesmiceArquitetura: chega de mesmice
Arquitetura: chega de mesmice
 
Arquitetura chega de mesmice
Arquitetura  chega de mesmiceArquitetura  chega de mesmice
Arquitetura chega de mesmice
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
 
Server side data sync for mobile apps with silex
Server side data sync for mobile apps with silexServer side data sync for mobile apps with silex
Server side data sync for mobile apps with silex
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and FluxTPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and Flux
 
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
 
Summit2011 satellites-robinf-20110605
Summit2011 satellites-robinf-20110605Summit2011 satellites-robinf-20110605
Summit2011 satellites-robinf-20110605
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 

More from Guilherme Silveira

Equipes ágeis em 2012 - Lições aprendidas
Equipes ágeis em 2012 - Lições aprendidasEquipes ágeis em 2012 - Lições aprendidas
Equipes ágeis em 2012 - Lições aprendidas
Guilherme Silveira
 
Introducao a machine learning na educacao
Introducao a machine learning na educacaoIntroducao a machine learning na educacao
Introducao a machine learning na educacao
Guilherme Silveira
 
Depois de Scrum e XP: não pare de aprender, não pare de inovar
Depois de Scrum e XP: não pare de aprender, não pare de inovarDepois de Scrum e XP: não pare de aprender, não pare de inovar
Depois de Scrum e XP: não pare de aprender, não pare de inovar
Guilherme Silveira
 
O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...
O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...
O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...
Guilherme Silveira
 
Software de qualidade e qualidade de código
Software de qualidade e qualidade de códigoSoftware de qualidade e qualidade de código
Software de qualidade e qualidade de código
Guilherme Silveira
 
Using the web for real
Using the web for realUsing the web for real
Using the web for real
Guilherme Silveira
 
Arquitetura: chega de mesmice
Arquitetura: chega de mesmiceArquitetura: chega de mesmice
Arquitetura: chega de mesmice
Guilherme Silveira
 
Rest @ Qcon 2010
Rest @ Qcon 2010Rest @ Qcon 2010
Rest @ Qcon 2010
Guilherme Silveira
 
Rest clients
Rest clientsRest clients
Rest clients
Guilherme Silveira
 
Rest clients
Rest clientsRest clients
Rest clients
Guilherme Silveira
 
Rest clients
Rest clientsRest clients
Rest clients
Guilherme Silveira
 
Um produto por semana
Um produto por semanaUm produto por semana
Um produto por semana
Guilherme Silveira
 
Deploy continuo, integraçao continua não basta
Deploy continuo, integraçao continua não bastaDeploy continuo, integraçao continua não basta
Deploy continuo, integraçao continua não basta
Guilherme Silveira
 
noSql + rest: Arquitetura Contemporanea
noSql + rest: Arquitetura ContemporaneanoSql + rest: Arquitetura Contemporanea
noSql + rest: Arquitetura Contemporanea
Guilherme Silveira
 
Rest workflows
Rest workflowsRest workflows
Rest workflows
Guilherme Silveira
 
Caelum 2010 - Rest Arquitetura Irreponsavel?
Caelum 2010 - Rest Arquitetura Irreponsavel?Caelum 2010 - Rest Arquitetura Irreponsavel?
Caelum 2010 - Rest Arquitetura Irreponsavel?
Guilherme Silveira
 
REST in Practice
REST in PracticeREST in Practice
REST in Practice
Guilherme Silveira
 
Caelum 2009 Rest Ao Restful - CEJUG 2009
Caelum 2009   Rest Ao Restful - CEJUG 2009Caelum 2009   Rest Ao Restful - CEJUG 2009
Caelum 2009 Rest Ao Restful - CEJUG 2009
Guilherme Silveira
 

More from Guilherme Silveira (18)

Equipes ágeis em 2012 - Lições aprendidas
Equipes ágeis em 2012 - Lições aprendidasEquipes ágeis em 2012 - Lições aprendidas
Equipes ágeis em 2012 - Lições aprendidas
 
Introducao a machine learning na educacao
Introducao a machine learning na educacaoIntroducao a machine learning na educacao
Introducao a machine learning na educacao
 
Depois de Scrum e XP: não pare de aprender, não pare de inovar
Depois de Scrum e XP: não pare de aprender, não pare de inovarDepois de Scrum e XP: não pare de aprender, não pare de inovar
Depois de Scrum e XP: não pare de aprender, não pare de inovar
 
O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...
O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...
O grandiosismo dos loucos - Agile Brazil 2011, Cecilia Fernandes e Guilherme ...
 
Software de qualidade e qualidade de código
Software de qualidade e qualidade de códigoSoftware de qualidade e qualidade de código
Software de qualidade e qualidade de código
 
Using the web for real
Using the web for realUsing the web for real
Using the web for real
 
Arquitetura: chega de mesmice
Arquitetura: chega de mesmiceArquitetura: chega de mesmice
Arquitetura: chega de mesmice
 
Rest @ Qcon 2010
Rest @ Qcon 2010Rest @ Qcon 2010
Rest @ Qcon 2010
 
Rest clients
Rest clientsRest clients
Rest clients
 
Rest clients
Rest clientsRest clients
Rest clients
 
Rest clients
Rest clientsRest clients
Rest clients
 
Um produto por semana
Um produto por semanaUm produto por semana
Um produto por semana
 
Deploy continuo, integraçao continua não basta
Deploy continuo, integraçao continua não bastaDeploy continuo, integraçao continua não basta
Deploy continuo, integraçao continua não basta
 
noSql + rest: Arquitetura Contemporanea
noSql + rest: Arquitetura ContemporaneanoSql + rest: Arquitetura Contemporanea
noSql + rest: Arquitetura Contemporanea
 
Rest workflows
Rest workflowsRest workflows
Rest workflows
 
Caelum 2010 - Rest Arquitetura Irreponsavel?
Caelum 2010 - Rest Arquitetura Irreponsavel?Caelum 2010 - Rest Arquitetura Irreponsavel?
Caelum 2010 - Rest Arquitetura Irreponsavel?
 
REST in Practice
REST in PracticeREST in Practice
REST in Practice
 
Caelum 2009 Rest Ao Restful - CEJUG 2009
Caelum 2009   Rest Ao Restful - CEJUG 2009Caelum 2009   Rest Ao Restful - CEJUG 2009
Caelum 2009 Rest Ao Restful - CEJUG 2009
 

Recently uploaded

Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
GDSC PJATK
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 

Recently uploaded (20)

Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 

Crie seu sistema REST com JAX-RS e o futuro

  • 1. Put your systems to REST Guilherme Silveira @guilhermecaelum
  • 2. Guilherme Silveira guilherme.silveira@caelum.com.br 2002 guj.com.br 2003 vraptor 2004 caelum.com.br 2009 restfulie 2010 tectura.com.br
  • 3. banco.com calendario.com viagem.com empresa.com
  • 7. o que é REST?
  • 8. qual o futuro da integração na web?
  • 9. 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>
  • 10. service locator ao integrar: acoplamento++ unrest pay unresttrips.com guilherme
  • 11. service locator ao integrar: acoplamento++ unrest pay unresttrips.com guilherme
  • 12. 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>
  • 13. Rest Client: hipermídia flight = Client.at('http://resttrips.com/f/574XR4').get(); confirmation = flight.getLink("payment"). patch(cardInformation, value);
  • 14. 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>
  • 15. dependency injection em integração: acoplamento-- restrips pay resttrips.com guilherme paysite.com
  • 16. dependency injection em integração: acoplamento-- restrips pay resttrips.com guilherme paysite.com
  • 17. trip = recurso http://kayak.com/f/574XR4 payment = recurso any_uri_unknown_at_compile_time
  • 18.
  • 19.
  • 20.
  • 21.
  • 22. eu nunca viajo sozinho
  • 23. meu amigo ricky
  • 24. Rest Client: compartilhando uma viagem flight = 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 web flight = Client.at('http://resttrips.com/f/574XR4').get(); confirmation = flight.getLink("payment"). patch(cardInformation, value/2);
  • 25. Rest Client: compartilhando uma viagem flight = 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 web flight = Client.at('http://resttrips.com/f/574XR4').get(); confirmation = flight.getLink("payment"). patch(cardInformation, value/2);
  • 26. Rest Client: compartilhando uma viagem flight = 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 web flight = Client.at('http://resttrips.com/f/574XR4').get(); confirmation = flight.getLink("payment"). patch(cardInformation, value/2);
  • 27. calendar: integrando sistemas myself = Client.at('http://users.calendar.com') .with(auth).get(); myself.link("calendar").patch(flight.link("self"));
  • 28. calendar: integrando sistemas myself = Client.at('http://users.calendar.com') .with(auth).get(); myself.link("calendar").patch(flight.link("self"));
  • 31. e daí? Atualizações na viagem ==> refletem aqui Atualizações no hotel ==> refletem aqui Atualizações no encontro ==> refletem aqui
  • 32. e daí? gre! nte e ,i us n ão Atualizações na viagem ==> refletem aqui Atualizações no hotel ==> refletem aqui Atualizações no encontro ==> refletem aqui
  • 34. o que mais? Remove ==> Cancela a viagem Remove ==> Cancela o hotel Remove ==> Email para colegas
  • 35. o que mais? liz e! nt ra esce e, d s tr rq ue o n ão Remove ==> Cancela a viagem Remove ==> Cancela o hotel Remove ==> Email para colegas
  • 36. mas qual o formato do pagamento ou calendário?
  • 43. fácil? e ela? lh a! fi in ha é m n ão
  • 44. conteúdo sem semântica não tem valor!
  • 46. qual “formato”? micro formats, media types, rdf etc
  • 47. qual “formato”? nk s! er li hyp ts e a fo rm icro m micro formats, media types, rdf etc
  • 49. Put your server to REST leonard richardsons model
  • 50. Server Maturity 1 uri, 1 http verb /services.do?action=install&...
  • 51. 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();   } }
  • 52. Server Maturity 1 uri, 1 http verb public class InstallService {   public Response execute() {     return Response.ok()              .type("application/xml")              .entity("<service>...</service>")              .build();   } }
  • 53. But?
  • 54. 1 uri, 1 http verb /services.do?action=install&... I know them all beforehand.
  • 55. 1 uri, 1 http verb /services.do?action=install&... Any change will break all our clients!
  • 58. a priori knowledge = coupling++
  • 59. Server Maturity Multiple uris, 1 http verb /install?...
  • 60. 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();   }
  • 62. GET hell GET should not imply in undesireable effects
  • 63. POST hell GET could help us with cache!
  • 64. Server Maturity Multiple uris, multiple verbs POST /cloud GET /cloud/1547437/software POST /cloud/1547437/software
  • 65. rails + restfulie rubyonrails.org
  • 66. rails + restfulie rubyonrails.org class 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   end end
  • 67. 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();   }
  • 68. JAX-RS   @DELETE @Path("{id}")   public Response uninstall(@PathParam("id") Long id) {     Software software = SoftwareRepository.retrieve(id);     software.uninstall();     return Response.ok().build();   }
  • 69. Uniform Interface++ Resources++
  • 70. Http verbs example POST creates PUT replaces PATCH updates DELETE removes GET retrieves OPTIONS tells me what i can do ...
  • 71. Is a Restful service a cute CRUD?
  • 72. yes
  • 73. but there is more!
  • 74. @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
  • 75. @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
  • 76. @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;
  • 77. @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;
  • 78. Server Model according to Leonard Richardson, 2008 one uri + one verb
  • 79. Server Model according to Leonard Richardson, 2008 Ugly one uri + one verb
  • 80. Server Model according to Leonard Richardson, 2008 multiple uris one uri + one verb
  • 81. Server Model according to Leonard Richardson, 2008 Less ugly multiple uris one uri + one verb
  • 82. Server Model according to Leonard Richardson, 2008 multiple verbs multiple uris one uri + one verb
  • 83. Server Model according to Leonard Richardson, 2008 cute CRUD multiple verbs multiple uris one uri + one verb
  • 84. Server Model rest according to Leonard Richardson, 2008 hypermedia multiple verbs multiple uris one uri + one verb
  • 86. guj
  • 90. 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();   } }
  • 91. você quer fazer copy+paste?
  • 93. Convention over Configuration @Resource public class Services { private final ServiceFactory factory; public Services(ServiceFactory factory) { this.factory = factory; } public void services(String action) { factory.getServiceFor(action).execute(); } }
  • 94. yes!
  • 95. yes!
  • 96. 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();   } }
  • 97. 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();   }
  • 98. 4. URI coupling writing the URI once ...   @GET @Path("/softwares/{id}")   public Response install(@QueryParam("id") Software software) { // ...   }
  • 99. 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();   }
  • 100. 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();   }
  • 102. 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); } // ... } }
  • 104. java = string oriented?
  • 105. java = annotation oriented?
  • 107. Response response = client.at ("http://localhost:9998/user/574").get(); 6. Client internal DSLs
  • 108. Response response = client.at ("http://localhost:9998/user/574").get(); User user = response.getResource(); System.out.println("user: " + user.getName()); 6. Client internal DSLs
  • 109. User user = response.getResource(); System.out.println("user: " + user.getName()); Link link = resource(user).getLink("machine"); response = link.follow().post(new Machine());
  • 110. Link link = resource(user).getLink("machine"); response = link.follow().post(new Machine()); double amount = resource(user).refresh(). getAmountDue();
  • 111. double amount = resource(user).refresh(). getAmountDue(); link = resource(user).getLink("payment"); Payment payment = new Payment(amount); response = link.follow().post(payment);
  • 112. link = resource(user).getLink("payment"); Payment payment = new Payment(amount); response = link.follow().post(payment); System.out.println("payment completed");
  • 113. link = resource(user).getLink("payment"); Payment payment = new Payment(amount); response = link.follow().post(payment); System.out.println("payment completed"); uma DSL alto nível com suporte a hipermídia
  • 114. bottom up design by committe mime type microformato
  • 117. Arun Gupta jersey vraptor 3

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. 1 uri. 1 http verb\n
  42. implementing a specific response\n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n