SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
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

Weitere Àhnliche Inhalte

Was ist angesagt?

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 ✔
 
Open Source Debugging v1.3.2
Open Source Debugging v1.3.2Open Source Debugging v1.3.2
Open Source Debugging v1.3.2Matthew McCullough
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thriftknight1128
 
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
 
gRPC - RPC rebirth?
gRPC - RPC rebirth?gRPC - RPC rebirth?
gRPC - RPC rebirth?LuĂ­s Barbosa
 
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
 
Fluentd introduction at ipros
Fluentd introduction at iprosFluentd introduction at ipros
Fluentd introduction at iprosTreasure Data, Inc.
 
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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 
cq_cxf_integration
cq_cxf_integrationcq_cxf_integration
cq_cxf_integrationAnkur Chauhan
 
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
 

Ähnlich wie 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
 

KĂŒrzlich hochgeladen

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 

KĂŒrzlich hochgeladen (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 

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