SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
Java REST in Practice
  Asynchronous JAX-RS


        Ted Pennings
      16 December 2010
REST Overview

REST is an architectural style

  Client - Server

  Most often over HTTP with JSON or XML

Describes the location of resources + actions
REST Principles
Resource-based

Stateless

Cacheable

Layered, with optional intermediaries

Safety / Idempotency
The Basic Operations


CRUD (Create, Read, Update, Delete)

Performed atomically on one uniquely identified
asset or a set of assets
REST with HTTP
REST verbs apply directly to HTTP methods

  GET - READ


                                     o nus!
                                   B
  POST - CREATE


                                           ONS
  PUT - UPDATE
                                      OPTI
                                            AD
  DELETE
                                        HE
Encoded in JSON or XML
                                          RA CE
                                        T
REST HTTP Example
     Widget Registry at http:/
                             /server/widgets

                           Create a Widget (Bolt, weighs 10g)


POST /widgets                                       HTTP/1.1 200 OK
Host: server                                        Date: Wed, 15 Dec 2010 23:59:59 GMT
User-agent: Ted’s Presentation                      Content-Type: text/plain
Content-type: Application/JSON                      Transfer-Encoding: chunked
Content-length: 115
                                                    {
{                                                       newAssetId: 15
    widget : {                                      }
        type : ‘bolt’,
        weight : {
          amount : 10,
          unit : ‘grams’
       }                                                Alternatively, could redirect to new
    }
}                                                           asset with Location header
Another HTTP Example
    Widget Registry at http:/
                            /server/widgets

                         Get Widget from last slide (ID 15 )



GET /widgets/15                                    HTTP/1.1 200 OK
Host: server                                       Date: Wed, 15 Dec 2010 23:59:59 GMT
User-agent: Ted’s Presentation                     Content-Type: text/plain
                                                   Transfer-Encoding: chunked
                                                   Content-length: 135

                                                   {
                                                       widget : {
                                                           id : 15,
                                                           type : ‘bolt’,
                                                           weight : {
 Also available in browser at                                amount : 10,
                                                             unit : ‘grams’

  http:/
       /server/widgets/15
                                                          }
                                                       }
                                                   }
Final HTTP Example
     Widget Registry at http:/
                             /server/widgets

                           Update Widget previously created


PUT /widgets/15                                    HTTP/1.1 200 OK
Host: server                                       Date: Wed, 15 Dec 2010 23:59:59 GMT
User-agent: Ted’s Presentation                     Content-Type: text/plain
Content-type: Application/JSON                     Transfer-Encoding: chunked
Content-length: 134

{
    widget : {
        id : 15,

                                                 (weight was actually 1 gram, typo)
        type : ‘bolt’,
        weight : {
          amount : 10,
          unit : ‘grams’
       }
    }
}
What We Just Saw


REST is resource-oriented

Assets are identified with URLs

The HTTP method specifies the operation
So What?

Putting the important information (what, how)
at the HTTP protocol-level allows
intermediaries to act and advise

Increased scalability and lower costs
Intermediaries


Two categories:

   - Proxies (client-chosen)

   - Gateways (provider-chosen)
Client Intermediaries

Mostly proxies

May or may not cache

May alter Javascript for client safety

Firewalls (eg block NSFW + illegal content)
Provider Intermediaries
Caching reverse-proxies and CDNs

Message remediation / translation

Security (eg XSRF nonces)

Also, protocol-level load balancing / failover

Should be invisible to client
Safety

Data retrieval methods are considered safe

Should not alter application data

GET / HEAD / OPTIONS / TRACE

Highly Cacheable by intermediaries!
Idempotency

Methods that may be executed more than once
with the same result are idempotent

PUT / DELETE

All safe methods are idempotent

POST is not always idempotent
Enter JAX-RS

Abstract specification for tagging resource
endpoints and operations in Java code

Annotation-driven

Exposes results of method calls in the same
way JAX-WS or Spring-WS does
Using JAX-RS

Providers implement it (like JPA)

  Provider agnostic ; can easily switch (unlike JPA)

  Jersey is the reference implementation

Can couple with message marshallers/unmarshallers

  Most rely on JAXB, even for JSON
JAX-RS Annotations
The litany found in the javax.ws.rs package...

@Path(“/path”)

@GET / @POST / @PUT / @DELETE /etc

@Produces + @Consumes(“text/plain”)

@PathParam + @HeaderParam + @QueryParam
Creating a Time Service
http:/
     /yourserver/context/time

@Path("/time")
public class TimeJaxRsResource {



    @GET
    @Produces("text/plain")
    public String getCurrentTime() {
         return new Date().toString();
    }

}
Using Paths
http:/
     /yourserver/context/time/eastern
@Path("/time")
public class TimeJaxRsResource {

    @GET
    @Path("/eastern")
    @Produces("text/plain")
    public String getCurrentEasternTime() {
         DateFormat format = new SimpleDateFormat();
         TimeZone eastern = TimeZone.getTimeZone(
                    "America/New_York");
         format.setTimeZone(eastern);
         return format.format(new Date());
    }

}
Using Path Variables
http:/
     /yourserver/context/time/tz/America_Chicago
@Path("/time")
public class TimeJaxRsResource {

    @GET
    @Path("/tz/{timezone}")
    @Produces("text/plain")
    public String getTime(@PathParam ("timezone") String tz) {
         DateFormat format = new SimpleDateFormat();
         TimeZone timezone = TimeZone.getTimeZone(tz);
         format.setTimeZone(timezone);
         return format.format(new Date());
    }

}
What We’ve Created

Stateless




Unfortunately, not useful if cached

Not necessarily asynchronous from a client
perspective (due to accuracy concerns)
Message Marshalling
JSON to marshall/unmarshall messages

Most commonly used: Jackson

Create a file containing in the following
org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider

   META-INF/services/javax.ws.rs.ext.MessageBodyReader


   META-INF/services/javax.ws.rs.ext.MessageBodyWriter
Example : Prime Numbers

 Prime number generation is computationally
 expensive but fairly simple

 Worker thread(s) generate prime numbers

 A web UI shows the latest additions
 http:/
      /primes.tedpennings.com/
The Prime Algorithm

	   long x, y;
	   for (x = start; x < Long.MAX_VALUE; x++) {
	   	 if (x % 2 != 0 || x == 2) {
	   	 	 for (y = 2; y <= x / 2; y++) {
	   	 	 	 if (x % y == 0) {
	   	 	 	 	 break;
	   	      	 }
	   	 	 }
	   	 	 if (y > x / 2) {
	   	 	 	 System.out.println("Discovered prime: " + x);
	   	 	 	 repo.add(x);
	   	 	 }
	   	 }
	   }
The Workers

Stateless loop of code trying to identify primes

Add to MongoDB once found

Simple JAR distributed to workers

Currently, only one; possibility for more
The App

Methods to find the most recent number and
batches of numbers greater than X

Exposed over RESTful HTTP with JSON

Runs in Jetty, fronted by an intermediary

  http:/
       /primes.tedpennings.com/primes/since/13183229
Example Code - Service
http:/
     /prime.tedpennings.com/primes/since/1500
@Path("/")
public class PrimeJaxRsResource {

    private final MongoPrimeRepository repo = new MongoPrimeRepository();


    @GET
    @Path("/since/{since}")
    @Produces("application/json")
    public Set<Long> getPrimesSince(@PathParam("since") long since) {
        LOG.info("Showing the default number of primes since " + since);
        return repo.getPrimes(since);
    }


}
The Intermediary


Nginx reverse-proxying Jetty (same node)




Caches all GET operations
The Web UI

Periodical Ajax requests for the numbers since the
most recent request (asynchronously)

Does not require full batches

  Size varies based on complexity + worker speed

All JavaScript, with jQuery
Demo and Code

Demo and Code Walkthrough




http:/
     /primes.tedpennings.com

http:/
     /s3.tedpennings.com/prime-jaxrs.zip
Possible Follow-up

Use some kind of MapReduce to distribute
workload across multiple workers (Hadoop?)




Use Chef or Puppet to dynamically provision
workers and initialize application
Resources (haha)

Roy Fielding’s Thesis             http:/
                                       /www.ics.uci.edu/~fielding/pubs/dissertation/top.htm




Jersey site         http:/
                         /jersey.java.net


Wikipedia (surprisingly good for this)



This awesome font : http:/
                         /www.dafont.com/hand-of-sean.font
Contact


http:/
     /ted.pennin.gs / ted@pennin.gs




twitter: @thesleepyvegan

Contenu connexe

Tendances

Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectLaurence Svekis ✔
 
Generating Unified APIs with Protocol Buffers and gRPC
Generating Unified APIs with Protocol Buffers and gRPCGenerating Unified APIs with Protocol Buffers and gRPC
Generating Unified APIs with Protocol Buffers and gRPCC4Media
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transferVictor Cherkassky
 
Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)N Masahiro
 
How happy they became with H2O/mruby and the future of HTTP
How happy they became with H2O/mruby and the future of HTTPHow happy they became with H2O/mruby and the future of HTTP
How happy they became with H2O/mruby and the future of HTTPIchito Nagata
 
gRPC and Microservices
gRPC and MicroservicesgRPC and Microservices
gRPC and MicroservicesJonathan Gomez
 
Fluentd unified logging layer
Fluentd   unified logging layerFluentd   unified logging layer
Fluentd unified logging layerKiyoto Tamura
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSocketsJosh Glover
 
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t... Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...AboutYouGmbH
 
Bryan lawrence
Bryan lawrenceBryan lawrence
Bryan lawrencevinunag99
 
Memento: TimeGates, TimeBundles, and TimeMaps
Memento: TimeGates, TimeBundles, and TimeMapsMemento: TimeGates, TimeBundles, and TimeMaps
Memento: TimeGates, TimeBundles, and TimeMapsMichael Nelson
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 

Tendances (20)

Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game project
 
Open Source Debugging v1.3.2
Open Source Debugging v1.3.2Open Source Debugging v1.3.2
Open Source Debugging v1.3.2
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Fluentd and WebHDFS
Fluentd and WebHDFSFluentd and WebHDFS
Fluentd and WebHDFS
 
Generating Unified APIs with Protocol Buffers and gRPC
Generating Unified APIs with Protocol Buffers and gRPCGenerating Unified APIs with Protocol Buffers and gRPC
Generating Unified APIs with Protocol Buffers and gRPC
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)
 
gRPC - RPC rebirth?
gRPC - RPC rebirth?gRPC - RPC rebirth?
gRPC - RPC rebirth?
 
How happy they became with H2O/mruby and the future of HTTP
How happy they became with H2O/mruby and the future of HTTPHow happy they became with H2O/mruby and the future of HTTP
How happy they became with H2O/mruby and the future of HTTP
 
gRPC and Microservices
gRPC and MicroservicesgRPC and Microservices
gRPC and Microservices
 
Caché acelerador de contenido
Caché acelerador de contenidoCaché acelerador de contenido
Caché acelerador de contenido
 
Fluentd unified logging layer
Fluentd   unified logging layerFluentd   unified logging layer
Fluentd unified logging layer
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
 
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t... Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 
upload test 1
upload test 1upload test 1
upload test 1
 
Bryan lawrence
Bryan lawrenceBryan lawrence
Bryan lawrence
 
Memento: TimeGates, TimeBundles, and TimeMaps
Memento: TimeGates, TimeBundles, and TimeMapsMemento: TimeGates, TimeBundles, and TimeMaps
Memento: TimeGates, TimeBundles, and TimeMaps
 
Building Netty Servers
Building Netty ServersBuilding Netty Servers
Building Netty Servers
 
Fluentd introduction at ipros
Fluentd introduction at iprosFluentd introduction at ipros
Fluentd introduction at ipros
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 

Similaire à Introduction to REST and JAX-RS

Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to ThriftDvir Volk
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesciklum_ods
 
Java web programming
Java web programmingJava web programming
Java web programmingChing Yi Chan
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPCDocker, Inc.
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Javaelliando dias
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwrdeimos
 
Protobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-KitProtobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-KitManfred Touron
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with DropwizardAndrei Savu
 
Hatkit Project - Datafiddler
Hatkit Project - DatafiddlerHatkit Project - Datafiddler
Hatkit Project - Datafiddlerholiman
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication developmentGanesh Gembali
 
Progressive web apps
Progressive web appsProgressive web apps
Progressive web appsFastly
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
Creating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdfCreating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdfShaiAlmog1
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 

Similaire à Introduction to REST and JAX-RS (20)

Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Java
 
Servlets
ServletsServlets
Servlets
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Protobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-KitProtobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-Kit
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with Dropwizard
 
Hatkit Project - Datafiddler
Hatkit Project - DatafiddlerHatkit Project - Datafiddler
Hatkit Project - Datafiddler
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
Progressive web apps
Progressive web appsProgressive web apps
Progressive web apps
 
cq_cxf_integration
cq_cxf_integrationcq_cxf_integration
cq_cxf_integration
 
08 ajax
08 ajax08 ajax
08 ajax
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
Creating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdfCreating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdf
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 

Dernier

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Introduction to REST and JAX-RS

  • 1. Java REST in Practice Asynchronous JAX-RS Ted Pennings 16 December 2010
  • 2. REST Overview REST is an architectural style Client - Server Most often over HTTP with JSON or XML Describes the location of resources + actions
  • 3. REST Principles Resource-based Stateless Cacheable Layered, with optional intermediaries Safety / Idempotency
  • 4. The Basic Operations CRUD (Create, Read, Update, Delete) Performed atomically on one uniquely identified asset or a set of assets
  • 5. REST with HTTP REST verbs apply directly to HTTP methods GET - READ o nus! B POST - CREATE ONS PUT - UPDATE OPTI AD DELETE HE Encoded in JSON or XML RA CE T
  • 6. REST HTTP Example Widget Registry at http:/ /server/widgets Create a Widget (Bolt, weighs 10g) POST /widgets HTTP/1.1 200 OK Host: server Date: Wed, 15 Dec 2010 23:59:59 GMT User-agent: Ted’s Presentation Content-Type: text/plain Content-type: Application/JSON Transfer-Encoding: chunked Content-length: 115 { { newAssetId: 15 widget : { } type : ‘bolt’, weight : { amount : 10, unit : ‘grams’ } Alternatively, could redirect to new } } asset with Location header
  • 7. Another HTTP Example Widget Registry at http:/ /server/widgets Get Widget from last slide (ID 15 ) GET /widgets/15 HTTP/1.1 200 OK Host: server Date: Wed, 15 Dec 2010 23:59:59 GMT User-agent: Ted’s Presentation Content-Type: text/plain Transfer-Encoding: chunked Content-length: 135 { widget : { id : 15, type : ‘bolt’, weight : { Also available in browser at amount : 10, unit : ‘grams’ http:/ /server/widgets/15 } } }
  • 8. Final HTTP Example Widget Registry at http:/ /server/widgets Update Widget previously created PUT /widgets/15 HTTP/1.1 200 OK Host: server Date: Wed, 15 Dec 2010 23:59:59 GMT User-agent: Ted’s Presentation Content-Type: text/plain Content-type: Application/JSON Transfer-Encoding: chunked Content-length: 134 { widget : { id : 15, (weight was actually 1 gram, typo) type : ‘bolt’, weight : { amount : 10, unit : ‘grams’ } } }
  • 9. What We Just Saw REST is resource-oriented Assets are identified with URLs The HTTP method specifies the operation
  • 10. So What? Putting the important information (what, how) at the HTTP protocol-level allows intermediaries to act and advise Increased scalability and lower costs
  • 11. Intermediaries Two categories: - Proxies (client-chosen) - Gateways (provider-chosen)
  • 12. Client Intermediaries Mostly proxies May or may not cache May alter Javascript for client safety Firewalls (eg block NSFW + illegal content)
  • 13. Provider Intermediaries Caching reverse-proxies and CDNs Message remediation / translation Security (eg XSRF nonces) Also, protocol-level load balancing / failover Should be invisible to client
  • 14. Safety Data retrieval methods are considered safe Should not alter application data GET / HEAD / OPTIONS / TRACE Highly Cacheable by intermediaries!
  • 15. Idempotency Methods that may be executed more than once with the same result are idempotent PUT / DELETE All safe methods are idempotent POST is not always idempotent
  • 16. Enter JAX-RS Abstract specification for tagging resource endpoints and operations in Java code Annotation-driven Exposes results of method calls in the same way JAX-WS or Spring-WS does
  • 17. Using JAX-RS Providers implement it (like JPA) Provider agnostic ; can easily switch (unlike JPA) Jersey is the reference implementation Can couple with message marshallers/unmarshallers Most rely on JAXB, even for JSON
  • 18. JAX-RS Annotations The litany found in the javax.ws.rs package... @Path(“/path”) @GET / @POST / @PUT / @DELETE /etc @Produces + @Consumes(“text/plain”) @PathParam + @HeaderParam + @QueryParam
  • 19. Creating a Time Service http:/ /yourserver/context/time @Path("/time") public class TimeJaxRsResource { @GET @Produces("text/plain") public String getCurrentTime() { return new Date().toString(); } }
  • 20. Using Paths http:/ /yourserver/context/time/eastern @Path("/time") public class TimeJaxRsResource { @GET @Path("/eastern") @Produces("text/plain") public String getCurrentEasternTime() { DateFormat format = new SimpleDateFormat(); TimeZone eastern = TimeZone.getTimeZone( "America/New_York"); format.setTimeZone(eastern); return format.format(new Date()); } }
  • 21. Using Path Variables http:/ /yourserver/context/time/tz/America_Chicago @Path("/time") public class TimeJaxRsResource { @GET @Path("/tz/{timezone}") @Produces("text/plain") public String getTime(@PathParam ("timezone") String tz) { DateFormat format = new SimpleDateFormat(); TimeZone timezone = TimeZone.getTimeZone(tz); format.setTimeZone(timezone); return format.format(new Date()); } }
  • 22. What We’ve Created Stateless Unfortunately, not useful if cached Not necessarily asynchronous from a client perspective (due to accuracy concerns)
  • 23. Message Marshalling JSON to marshall/unmarshall messages Most commonly used: Jackson Create a file containing in the following org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider META-INF/services/javax.ws.rs.ext.MessageBodyReader META-INF/services/javax.ws.rs.ext.MessageBodyWriter
  • 24. Example : Prime Numbers Prime number generation is computationally expensive but fairly simple Worker thread(s) generate prime numbers A web UI shows the latest additions http:/ /primes.tedpennings.com/
  • 25. The Prime Algorithm long x, y; for (x = start; x < Long.MAX_VALUE; x++) { if (x % 2 != 0 || x == 2) { for (y = 2; y <= x / 2; y++) { if (x % y == 0) { break; } } if (y > x / 2) { System.out.println("Discovered prime: " + x); repo.add(x); } } }
  • 26. The Workers Stateless loop of code trying to identify primes Add to MongoDB once found Simple JAR distributed to workers Currently, only one; possibility for more
  • 27. The App Methods to find the most recent number and batches of numbers greater than X Exposed over RESTful HTTP with JSON Runs in Jetty, fronted by an intermediary http:/ /primes.tedpennings.com/primes/since/13183229
  • 28. Example Code - Service http:/ /prime.tedpennings.com/primes/since/1500 @Path("/") public class PrimeJaxRsResource { private final MongoPrimeRepository repo = new MongoPrimeRepository(); @GET @Path("/since/{since}") @Produces("application/json") public Set<Long> getPrimesSince(@PathParam("since") long since) { LOG.info("Showing the default number of primes since " + since); return repo.getPrimes(since); } }
  • 29. The Intermediary Nginx reverse-proxying Jetty (same node) Caches all GET operations
  • 30. The Web UI Periodical Ajax requests for the numbers since the most recent request (asynchronously) Does not require full batches Size varies based on complexity + worker speed All JavaScript, with jQuery
  • 31. Demo and Code Demo and Code Walkthrough http:/ /primes.tedpennings.com http:/ /s3.tedpennings.com/prime-jaxrs.zip
  • 32. Possible Follow-up Use some kind of MapReduce to distribute workload across multiple workers (Hadoop?) Use Chef or Puppet to dynamically provision workers and initialize application
  • 33. Resources (haha) Roy Fielding’s Thesis http:/ /www.ics.uci.edu/~fielding/pubs/dissertation/top.htm Jersey site http:/ /jersey.java.net Wikipedia (surprisingly good for this) This awesome font : http:/ /www.dafont.com/hand-of-sean.font
  • 34. Contact http:/ /ted.pennin.gs / ted@pennin.gs twitter: @thesleepyvegan