of 166 /166
JSR 339 Java API for RESTful Web Services

JSR 339 Java API for RESTful Web Services

Embed Size (px)

Citation preview

Page 1: JSR 339 Java API for RESTful Web Services

JSR 339 Java API for RESTful Web Services

Page 2: JSR 339 Java API for RESTful Web Services

GujavaSC / Adopt a JSR

Membros do GujavaSCParticipação Adopt a JSRGrupo de estudos

ArtigosPalestras

Page 3: JSR 339 Java API for RESTful Web Services

O que é REST?

Page 4: JSR 339 Java API for RESTful Web Services

É um estilo arquitetural…

Page 5: JSR 339 Java API for RESTful Web Services

Estilo arquitetural???

É um estilo arquitetural…

Page 6: JSR 339 Java API for RESTful Web Services

Enxaimel

Telhado

Madeiras

Tijolos

Page 7: JSR 339 Java API for RESTful Web Services

EstiloArquitetural

RESTHTTP

Page 8: JSR 339 Java API for RESTful Web Services

Características

Recursos são identificados por um ID;Sem estado;Vincule as coisas;Múltiplas representações;Interface uniforme.

Page 9: JSR 339 Java API for RESTful Web Services

Características

Recursos são identificados por um ID;Sem estado;Vincule as coisas;Múltiplas representações;Interface uniforme.

Page 10: JSR 339 Java API for RESTful Web Services

Interface Uniforme

Verbos HTTP Ação

POST Cria um novo recurso

PUT Atualiza um recurso

DELETE Remove um recurso

GET Retorna um recurso

Page 11: JSR 339 Java API for RESTful Web Services

JAX-RS 1.x

Final Release em 2008Objetivos

Baseado em POJOCentralizado em HTTPIndependência de formatoIndependência de containerInclusão no Java EE 6

Page 12: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 13: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

Page 14: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

Page 15: JSR 339 Java API for RESTful Web Services

@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

Exemplo JAX-RS 1.0

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 16: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 17: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 18: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 19: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 20: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);ResponseBuilder rb = Response.ok(books);return rb.build();

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 21: JSR 339 Java API for RESTful Web Services

Exemplo JAX-RS 1.0@Path("books")public class BookResource {

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public List<Book> listByYearAndName(@PathParam("year") Integer year,

@QueryParam("name") String name) {

List<Book> books = getListByYearAndName(year, name);// ResponseBuilder rb = Response.ok(books);// return rb.build();return books;

}}

http://localhost:8080/rest-example/resources/books/year/2011?name=Book1

Page 22: JSR 339 Java API for RESTful Web Services

JAX-RS 2.0

Final Release em Maio de 2013Solicitações (JSR 339)

Client APIAsynchronous processingFilters / InterceptorsBean ValidationHypermediaMVC

Page 23: JSR 339 Java API for RESTful Web Services

Client API

Page 24: JSR 339 Java API for RESTful Web Services

Client API

Baseada na API do Jersey (versão 1.x);Consumir serviços criados em qualquer linguagem.

Page 25: JSR 339 Java API for RESTful Web Services

Qual é o recurso?

Page 26: JSR 339 Java API for RESTful Web Services

Book!

Page 27: JSR 339 Java API for RESTful Web Services

Como foi exposto?

Page 28: JSR 339 Java API for RESTful Web Services

@Path("books")

public class BookResource {

@GET

@Path("{id}")

@Produces(MediaType.APPLICATION_JSON)

public Response read(@PathParam("id") Integer id) {

return Response.ok(readObject(id)).build();

}

}

http://localhost:8080/rest-example/resources/books/10

Page 29: JSR 339 Java API for RESTful Web Services

Como consultávamos?

Page 30: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 31: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 32: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 33: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 34: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 35: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 36: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

GSON, Jackson, Jettison, XStream

Page 37: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee6() throws Exception {

URL url = new URL("http://localhost:8080/rest-example/resources/books/10");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

String result = IOUtils.toString(con.getInputStream(), "UTF-8");

con.disconnect();

Book book = new Gson().fromJson(result, Book.class);

assertThat(book, notNullValue());

}

Page 38: JSR 339 Java API for RESTful Web Services

E agora com a Client API?

Page 39: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 40: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 41: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 42: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 43: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 44: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 45: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 46: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 47: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

WebTarget target =

client.target("http://localhost:8080/rest-example/resources");

WebTarget path = target.path("books/{id}");

WebTarget bookId = path.resolveTemplate("id", "10");

Builder invocation = bookId.request();

Book book = invocation.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 48: JSR 339 Java API for RESTful Web Services

...“um pouco” mais fluente...

Page 49: JSR 339 Java API for RESTful Web Services

@Test

public void deveConterOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Book book = client.target("http://localhost:8080/rest-example/resources")

.path("books/{id}")

.resolveTemplate("id", "10")

.request()

.get(Book.class);

client.close();

assertThat(book, notNullValue());

}

Page 50: JSR 339 Java API for RESTful Web Services

...@Delete...

Page 51: JSR 339 Java API for RESTful Web Services

@Test

public void deletarOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Response res = client.target("http://localhost:8080/rest-example/resources")

.path("books/{id}")

.resolveTemplate("id", "10")

.request()

.delete();

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), res.getStatus());

}

Page 52: JSR 339 Java API for RESTful Web Services

@Test

public void deletarOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Response res = client.target("http://localhost:8080/rest-example/resources")

.path("books/{id}")

.resolveTemplate("id", "10")

.request()

.delete();

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), res.getStatus());

}

Page 53: JSR 339 Java API for RESTful Web Services

@Test

public void deletarOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Response res = client.target("http://localhost:8080/rest-example/resources")

.path("books/{id}")

.resolveTemplate("id", "10")

.request()

.delete();

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), res.getStatus());

}

Page 54: JSR 339 Java API for RESTful Web Services

@Test

public void deletarOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Response res = client.target("http://localhost:8080/rest-example/resources")

.path("books/{id}")

.resolveTemplate("id", "10")

.request()

.delete();

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), res.getStatus());

}

Page 55: JSR 339 Java API for RESTful Web Services

...@Post...

Page 56: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 57: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 58: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 59: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivro_javaee7() {

Client client = ClientBuilder.newClient();

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 60: JSR 339 Java API for RESTful Web Services

Como configurar Filters e Interceptors?

Page 61: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivroComFiltroDeLog() {

Client client = ClientBuilder.newClient();

client.register(MyLoggingFilter.class);

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.register(MyEntityInterceptor.class)

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 62: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivroComFiltroDeLog() {

Client client = ClientBuilder.newClient();

client.register(MyLoggingFilter.class);

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.register(MyEntityInterceptor.class)

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 63: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivroComFiltroDeLog() {

Client client = ClientBuilder.newClient();

client.register(MyLoggingFilter.class);

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.register(MyEntityInterceptor.class)

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 64: JSR 339 Java API for RESTful Web Services

@Test

public void inserirOLivroComFiltroDeLog() {

Client client = ClientBuilder.newClient();

client.register(MyLoggingFilter.class);

Book book = new Book(1, "Android", "Direto das trincheiras");

Response response =

client.target("http://localhost:8080/rest-example/resources")

.path("books")

.register(MyEntityInterceptor.class)

.request(MediaType.APPLICATION_JSON)

.post(Entity.entity(book,

MediaType.APPLICATION_JSON));

response.close(); client.close();

assertEquals(Status.OK.getStatusCode(), response.getStatus());

}

Page 65: JSR 339 Java API for RESTful Web Services

AsynchronousProcessing

Page 66: JSR 339 Java API for RESTful Web Services

Que tal uma chamada assíncrona?

Page 67: JSR 339 Java API for RESTful Web Services

@Path("books")

public class BookResource {

@GET

@Path("{id}")

@Produces(MediaType.APPLICATION_JSON)

public Response read(@PathParam("id") Integer id) throws

InterruptedException {

Thread.sleep(5000L);

return Response.ok(readObject(id)).build();

}

}

Page 68: JSR 339 Java API for RESTful Web Services

@Path("books")

public class BookResource {

@GET

@Path("{id}")

@Produces(MediaType.APPLICATION_JSON)

public Response read(@PathParam("id") Integer id) throws

InterruptedException {

Thread.sleep(5000L);

return Response.ok(readObject(id)).build();

}

} Simulando um processamento pesado.

Page 69: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled());

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 70: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled());

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 71: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled());

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 72: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled());

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 73: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 74: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 75: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 76: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // false

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 77: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // false

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 78: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // false

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone());

assertThat(asyncResponse.get(), notNullValue());

}

Page 79: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // false

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // true

assertThat(asyncResponse.get(), notNullValue());

}

Page 80: JSR 339 Java API for RESTful Web Services

@Test

public void buscaOLivroDeFormaAssincrona() {

WebTarget target = ClientBuilder.newClient()

.target("http://localhost:8080/rest-example/resources")

.path("books/10");

Future<Book> asyncResponse = target.request().async().get(Book.class);

System.out.println("Cancelado: " + asyncResponse.isCancelled()); // false

Thread.sleep(2000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // false

Thread.sleep(5000L);

System.out.println("Finalizado: " + asyncResponse.isDone()); // true

assertThat(asyncResponse.get(), notNullValue());

}

Page 81: JSR 339 Java API for RESTful Web Services

Timeout no método get()JSR 236 - Concurrency Utilities for JavaTM EE

Page 82: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); Future<Book> asyncResponse = target.request().async().get(Book.class);

assertThat(asyncResponse.get(20L, TimeUnit.SECONDS), notNullValue());}

Page 83: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); Future<Book> asyncResponse = target.request().async().get(Book.class);

assertThat(asyncResponse.get(20L, TimeUnit.SECONDS), notNullValue());}

Page 84: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); Future<Book> asyncResponse = target.request().async().get(Book.class);

assertThat(asyncResponse.get(2L, TimeUnit.SECONDS), notNullValue());}

Page 85: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); Future<Book> asyncResponse = target.request().async().get(Book.class);

assertThat(asyncResponse.get(2L, TimeUnit.SECONDS), notNullValue());}

Page 86: JSR 339 Java API for RESTful Web Services

Posso enviar um InvocationCallback?

Page 87: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); target.request().async().get(new InvocationCallback<Book>() { public void completed(Book book) { assertThat(book, notNullValue()); }

public void failed(Throwable throwable) { fail(); } }); }

Page 88: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); target.request().async().get(new InvocationCallback<Book>() { public void completed(Book book) { assertThat(book, notNullValue()); }

public void failed(Throwable throwable) { fail(); } }); }

Page 89: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); target.request().async().get(new InvocationCallback<Book>() { public void completed(Book book) { assertThat(book, notNullValue()); }

public void failed(Throwable throwable) { fail(); } }); }

Page 90: JSR 339 Java API for RESTful Web Services

@Testpublic void buscaOLivroDeFormaAssincrona() { WebTarget target = ClientBuilder.newClient() .target("http://localhost:8080/rest-example/resources") .path("books/10"); target.request().async().get(new InvocationCallback<Book>() { public void completed(Book book) { assertThat(book, notNullValue()); }

public void failed(Throwable throwable) { fail(); } }); }

Page 91: JSR 339 Java API for RESTful Web Services

Assíncrono no servidor......se você quiser!

Page 92: JSR 339 Java API for RESTful Web Services

Primeiro, sem EJB...

Page 93: JSR 339 Java API for RESTful Web Services

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Runnable command = new Runnable() {

public void run() {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

};

Executors.newSingleThreadExecutor().execute(command);

}

}

Page 94: JSR 339 Java API for RESTful Web Services

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Runnable command = new Runnable() {

public void run() {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

};

Executors.newSingleThreadExecutor().execute(command);

}

}

Page 95: JSR 339 Java API for RESTful Web Services

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Runnable command = new Runnable() {

public void run() {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

};

Executors.newSingleThreadExecutor().execute(command);

}

}

Page 96: JSR 339 Java API for RESTful Web Services

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Runnable command = new Runnable() {

public void run() {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

};

Executors.newSingleThreadExecutor().execute(command); // JSR 236

}

}

Page 97: JSR 339 Java API for RESTful Web Services

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Runnable command = new Runnable() {

public void run() {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

};

Executors.newSingleThreadExecutor().execute(command); // JSR 236

}

}

Page 98: JSR 339 Java API for RESTful Web Services

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Runnable command = new Runnable() {

public void run() {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

};

Executors.newSingleThreadExecutor().execute(command); // JSR 236

}

}

Page 99: JSR 339 Java API for RESTful Web Services

E se for com EJB?

Page 100: JSR 339 Java API for RESTful Web Services

@Stateless

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Asynchronous

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

}

EJB 3.1 (Java EE 6)

Page 101: JSR 339 Java API for RESTful Web Services

@Stateless

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Asynchronous

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

}

Page 102: JSR 339 Java API for RESTful Web Services

@Stateless

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Asynchronous

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

}

Page 103: JSR 339 Java API for RESTful Web Services

@Stateless

@Path("async/books")

public class AsyncBookResource {

@GET

@Path("/")

@Asynchronous

@Produces(MediaType.APPLICATION_JSON)

public void longRunningOperation(@Suspended final AsyncResponse

asyncResponse) {

Thread.sleep(10000L);

asyncResponse.resume(new Book());

}

}

Page 104: JSR 339 Java API for RESTful Web Services

Filters and Interceptors

Page 105: JSR 339 Java API for RESTful Web Services

O que são os filters?

Page 106: JSR 339 Java API for RESTful Web Services

ClientRequestFilter

ClientResponseFilter

Page 107: JSR 339 Java API for RESTful Web Services

@Provider

public class LoggingFilter implements ClientRequestFilter,

ClientResponseFilter {

public void filter(ClientRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ClientRequestContext requestContext,

ClientResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 108: JSR 339 Java API for RESTful Web Services

@Provider

public class LoggingFilter implements ClientRequestFilter,

ClientResponseFilter {

public void filter(ClientRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ClientRequestContext requestContext,

ClientResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 109: JSR 339 Java API for RESTful Web Services

@Provider

public class LoggingFilter implements ClientRequestFilter,

ClientResponseFilter {

public void filter(ClientRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ClientRequestContext requestContext,

ClientResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 110: JSR 339 Java API for RESTful Web Services

@Provider

public class LoggingFilter implements ClientRequestFilter,

ClientResponseFilter {

public void filter(ClientRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ClientRequestContext requestContext,

ClientResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 111: JSR 339 Java API for RESTful Web Services

@Provider

public class LoggingFilter implements ClientRequestFilter,

ClientResponseFilter {

public void filter(ClientRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ClientRequestContext requestContext,

ClientResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 112: JSR 339 Java API for RESTful Web Services

ContainerRequestFilter

ContainerResponserFilter

Page 113: JSR 339 Java API for RESTful Web Services

@Provider

class LoggingFilter implements ContainerRequestFilter,

ContainerResponseFilter {

public void filter(ContainerRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ContainerRequestContext requestContext,

ContainerResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 114: JSR 339 Java API for RESTful Web Services

@Provider

class LoggingFilter implements ContainerRequestFilter,

ContainerResponseFilter {

public void filter(ContainerRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ContainerRequestContext requestContext,

ContainerResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 115: JSR 339 Java API for RESTful Web Services

@Provider

class LoggingFilter implements ContainerRequestFilter,

ContainerResponseFilter {

public void filter(ContainerRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ContainerRequestContext requestContext,

ContainerResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 116: JSR 339 Java API for RESTful Web Services

@Provider

class LoggingFilter implements ContainerRequestFilter,

ContainerResponseFilter {

public void filter(ContainerRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ContainerRequestContext requestContext,

ContainerResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 117: JSR 339 Java API for RESTful Web Services

@Provider

class LoggingFilter implements ContainerRequestFilter,

ContainerResponseFilter {

public void filter(ContainerRequestContext requestContext) throws

IOException {

log(requestContext);

}

public void filter(ContainerRequestContext requestContext,

ContainerResponseContext responseContext) throws IOException {

log(responseContext);

}

}

Page 118: JSR 339 Java API for RESTful Web Services

O que são os interceptors?

Page 119: JSR 339 Java API for RESTful Web Services

ReaderInterceptor

WriterInterceptor

Page 120: JSR 339 Java API for RESTful Web Services

Descompactando a requisição

Page 121: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipReaderInterceptor implements ReaderInterceptor {

Object aroundReadFrom(ReaderInterceptorContext ctx) ... {

if (isGzipped(ctx)) {

InputStream old = ctx.getInputStream();

ctx.setInputStream(new GZIPInputStream(old));

try {

return ctx.proceed();

} finally {

ctx.setInputStream(old);

}

} else {

return ctx.proceed();

}

}

}

Page 122: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipReaderInterceptor implements ReaderInterceptor {

Object aroundReadFrom(ReaderInterceptorContext ctx) ... {

if (isGzipped(ctx)) {

InputStream old = ctx.getInputStream();

ctx.setInputStream(new GZIPInputStream(old));

try {

return ctx.proceed();

} finally {

ctx.setInputStream(old);

}

} else {

return ctx.proceed();

}

}

}

Page 123: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipReaderInterceptor implements ReaderInterceptor {

Object aroundReadFrom(ReaderInterceptorContext ctx) ... {

if (isGzipped(ctx)) {

InputStream old = ctx.getInputStream();

ctx.setInputStream(new GZIPInputStream(old));

try {

return ctx.proceed();

} finally {

ctx.setInputStream(old);

}

} else {

return ctx.proceed();

}

}

}

Page 124: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipReaderInterceptor implements ReaderInterceptor {

Object aroundReadFrom(ReaderInterceptorContext ctx) ... {

if (isGzipped(ctx)) {

InputStream old = ctx.getInputStream();

ctx.setInputStream(new GZIPInputStream(old));

try {

return ctx.proceed();

} finally {

ctx.setInputStream(old);

}

} else {

return ctx.proceed();

}

}

}

Page 125: JSR 339 Java API for RESTful Web Services

Compactando a resposta

Page 126: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipWriteInterceptor implements WriteInterceptor {

void aroundWriteTo(WriterInterceptorContext ctx) ... {

OutputStream old = ctx.getOutputStream();

GZIPOutputStream gzipOutputStream = new GZIPOutputStream(old);

ctx.setOutputStream(gzipOutputStream);

updateHeaders(ctx);

try {

ctx.proceed();

} finally {

gzipOutputStream.finish();

ctx.setOutputStream(old);

}

}

}

Page 127: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipWriteInterceptor implements WriteInterceptor {

void aroundWriteTo(WriterInterceptorContext ctx) ... {

OutputStream old = ctx.getOutputStream();

GZIPOutputStream gzipOutputStream = new GZIPOutputStream(old);

ctx.setOutputStream(gzipOutputStream);

updateHeaders(ctx);

try {

ctx.proceed();

} finally {

gzipOutputStream.finish();

ctx.setOutputStream(old);

}

}

}

Page 128: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipWriteInterceptor implements WriteInterceptor {

void aroundWriteTo(WriterInterceptorContext ctx) ... {

OutputStream old = ctx.getOutputStream();

GZIPOutputStream gzipOutputStream = new GZIPOutputStream(old);

ctx.setOutputStream(gzipOutputStream);

updateHeaders(ctx);

try {

ctx.proceed();

} finally {

gzipOutputStream.finish();

ctx.setOutputStream(old);

}

}

}

Page 129: JSR 339 Java API for RESTful Web Services

@Provider

public class GzipWriteInterceptor implements WriteInterceptor {

void aroundWriteTo(WriterInterceptorContext ctx) ... {

OutputStream old = ctx.getOutputStream();

GZIPOutputStream gzipOutputStream = new GZIPOutputStream(old);

ctx.setOutputStream(gzipOutputStream);

updateHeaders(ctx);

try {

ctx.proceed();

} finally {

gzipOutputStream.finish();

ctx.setOutputStream(old);

}

}

}

Page 130: JSR 339 Java API for RESTful Web Services

Mas, qual é a diferença mesmo?

Page 131: JSR 339 Java API for RESTful Web Services

Filters: Acesso ao contexto do request/response.

Page 132: JSR 339 Java API for RESTful Web Services

Exemplo de Filters

Logar origem do request.Verificar qual o método http utilizado. Qual a URI.

Page 133: JSR 339 Java API for RESTful Web Services

Interceptors: Acesso ao contexto da mensagem.

Page 134: JSR 339 Java API for RESTful Web Services

Exemplo de Interceptors

Compactar o conteúdo da mensagem a ser enviada.Descompactar o conteúdo da mensagem a ser lida.

Page 135: JSR 339 Java API for RESTful Web Services

Posso logar minhas requisições antes de chegar ao método?

Page 136: JSR 339 Java API for RESTful Web Services

@PreMatching

Page 137: JSR 339 Java API for RESTful Web Services

@Provider@PreMatchingpublic class HttpPreMatchingFilter implements ContainerRequestFilter {

public void filter(ContainerRequestContext requestContext) throws IOException {

... }

}

Page 138: JSR 339 Java API for RESTful Web Services

@Provider@PreMatchingpublic class HttpPreMatchingFilter implements ContainerRequestFilter {

public void filter(ContainerRequestContext requestContext) throws IOException {

... }

}

Page 139: JSR 339 Java API for RESTful Web Services

@Provider@PreMatchingpublic class HttpPreMatchingFilter implements ContainerRequestFilter {

public void filter(ContainerRequestContext requestContext) throws IOException {

... }

}

Page 140: JSR 339 Java API for RESTful Web Services

Mas se eu quiser logar um método específico, é possível?

Page 141: JSR 339 Java API for RESTful Web Services

@NameBinding

Page 142: JSR 339 Java API for RESTful Web Services

@NameBinding@Target({ ElementType.TYPE, ElementType.METHOD })@Retention(value = RetentionPolicy.RUNTIME)public @interface Logged {}

Similar aos qualificadores do CDI

Page 143: JSR 339 Java API for RESTful Web Services

@Provider @Loggedpublic class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {

...}

Page 144: JSR 339 Java API for RESTful Web Services

@Path("/")public class MyResourceClass { @GET @Logged @Path("{name}") @Produces("text/plain") public String hello(@PathParam("name") String name) { return "Hello " + name; }

}

Page 145: JSR 339 Java API for RESTful Web Services

E a ordem? Posso definir?

Page 146: JSR 339 Java API for RESTful Web Services

@Priority

Page 147: JSR 339 Java API for RESTful Web Services

@Provider@Authenticated@Priority(Priorities.AUTHENTICATION)public class AuthenticationFilter implements ContainerRequestFilter{ ...}

Page 148: JSR 339 Java API for RESTful Web Services

Modifier and Type Constant Field Value

public static final int AUTHENTICATION 1000

public static final int AUTHORIZATION 2000

public static final int ENTITY_CODER 3000

public static final int HEADER_DECORATOR 4000

public static final int USER 5000

javax.ws.rs.Priorities

Page 149: JSR 339 Java API for RESTful Web Services

Bean ValidationJSR-349

Page 150: JSR 339 Java API for RESTful Web Services

Como eu aplico?

Page 151: JSR 339 Java API for RESTful Web Services

public class Book {

private Integer id;

@NotNull private String name;

private String description; private Integer year; private String genero;

}

Page 152: JSR 339 Java API for RESTful Web Services

@POST@Consumes(MediaType.APPLICATION_JSON)public Response create(@Valid Book book) {

ResponseBuilder rb = Response.ok(createObject(book)); return rb.build();

}

Page 153: JSR 339 Java API for RESTful Web Services

@GET@Path("/year/{year}")@Produces(MediaType.APPLICATION_JSON)public Response listByYearAndName(@Max(2015) @PathParam("year") Integer year, @QueryParam("name") String name) { List<Book> books = getListByYearAndName(year, name); ResponseBuilder rb = Response.ok(books); return rb.build();

}

Page 154: JSR 339 Java API for RESTful Web Services

HATEOAS

Hipermídia como motor do estado do aplicativo

“If the engine of application is not being driven by hypertext, then it cannot be RESTful and

cannot be a REST API” (Roy T. Fielding)

Page 155: JSR 339 Java API for RESTful Web Services

BookPurchas

e

Related Books

Author

Receipt

/books/1/author

/books/genre/programming

/books/1/purchase

/books/1/purchase/12/receipt

/books/1

Exemplo

Page 156: JSR 339 Java API for RESTful Web Services

Link: <http://gujavasc.org/resources/books/1/purchase>; rel=purchase, …

<book> <id>1</id> <year>2013</year> <name>REST in practice</name> <genre>programming</genre> <author>http://gujavasc.org/resources/books/1/author</author> <related>http://gujavasc.org/resources/books/genre/programming</related></book>

Links Transicionais

Links Estruturais

Page 157: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 158: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 159: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 160: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 161: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 162: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 163: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 164: JSR 339 Java API for RESTful Web Services

Links Transicionais@GET@Path("{id}")@Produces(MediaType.APPLICATION_JSON)public Response read(@PathParam("id") Integer id, @Context UriInfo uriInfo){

Link purchaseLink = Link.fromPath(uriInfo.getRequestUri().toString() + "/purchase")

.rel("purchase")

.build();

return Response.ok(readObject(id)) .links(purchaseLink) .link(uriInfo.getRequestUri().toString() + "/genre/programming", "genre") .build();

}

Page 165: JSR 339 Java API for RESTful Web Services

Integração com Java EE

Managed BeansCDIEJBBean ValidationJSON API

Page 166: JSR 339 Java API for RESTful Web Services

OBRIGADO!

Daniel Cunha (Soro) - @dvlc_Ivan Junckes Filho - @ivanjunckes

Ricardo Longa - @ricardolonga

https://github.com/gujavasc/jaxrs2