From 190a538a00925029543c7c022852d5fdad183524 Mon Sep 17 00:00:00 2001 From: Ron Sigal Date: Sat, 19 Feb 2022 18:36:11 -0500 Subject: [PATCH 1/3] Turn quickstart jaxrs-client into a JAX-RS version of helloworld --- jaxrs-client/README.adoc | 163 +++++++----- jaxrs-client/pom.xml | 8 +- .../helloworld/server/HelloService.java} | 26 +- .../server/HelloWorldJaxRsServer.java | 62 +++++ .../server}/JaxRsActivator.java | 2 +- .../jaxrsclient/model/Contact.java | 61 ----- .../rest/ContactResourceRESTService.java | 97 ------- .../client/HelloWorldJaxRsClient.java | 163 ++++++++++++ .../client/HelloWorldJaxRsClientIT.java | 186 ++++++++++++++ .../jaxrsclient/test/ContactsRestClient.java | 212 ---------------- .../test/ContactsRestClientIT.java | 238 ------------------ .../test/SavedByClientRequestFilter.java | 42 ---- 12 files changed, 522 insertions(+), 738 deletions(-) rename jaxrs-client/src/{test/java/org/jboss/as/quickstarts/jaxrsclient/test/LogResponseFilter.java => main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java} (54%) create mode 100644 jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java rename jaxrs-client/src/main/java/org/jboss/as/quickstarts/{jaxrsclient/rest => helloworld/server}/JaxRsActivator.java (96%) delete mode 100644 jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/model/Contact.java delete mode 100644 jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/ContactResourceRESTService.java create mode 100644 jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java create mode 100644 jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java delete mode 100644 jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClient.java delete mode 100644 jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClientIT.java delete mode 100644 jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/SavedByClientRequestFilter.java diff --git a/jaxrs-client/README.adoc b/jaxrs-client/README.adoc index 46f85fb741..5511b720bb 100644 --- a/jaxrs-client/README.adoc +++ b/jaxrs-client/README.adoc @@ -1,23 +1,24 @@ include::../shared-doc/attributes.adoc[] -= jaxrs-client: JAX-RS Client API example += helloworld-jaxrs: JAX-RS Client API example :author: Rafael Benevides :level: Beginner :technologies: JAX-RS :openshift: true [abstract] -The `jaxrs-client` quickstart demonstrates JAX-RS Client API, which interacts with a JAX-RS Web service that runs on {productName}. +The `helloworld-jaxrs` quickstart demonstrates a JAX-RS resource class running on {productName}, accessed +by way of various clients, including the JAX-RS Client API. :standalone-server-type: default :archiveType: war == What is it? -The `jaxrs-client` quickstart demonstrates the JAX-RS Client API which interacts with a JAX-RS Web service. - -This client "calls" many `POST`, `GET`, and `DELETE` operations using different ways: synchronized, asynchronous, delayed and filtered invocations. +The `helloworld-jaxrs` quickstart demonstrates a JAX-RS resource class implementing `GET` and `POST` resource +methods. +The resource is accessed by web servers, curl, and the JAX-RS Client API. //************************************************* // Product Release content only //************************************************* @@ -32,77 +33,103 @@ include::../shared-doc/use-of-jboss-home-name.adoc[leveloffset=+1] include::../shared-doc/start-the-standalone-server.adoc[leveloffset=+1] // Build and Deploy the Quickstart include::../shared-doc/build-and-deploy-the-quickstart.adoc[leveloffset=+1] -// Run the Arquillian Tests -include::../shared-doc/run-arquillian-tests.adoc[leveloffset=+1] +== Invoking resource methods from a web browser + +The address of a JAX-RS resource method is the concatenation of + +1. the context path ("helloworld-jaxrs" in this case) +2. the value of `@ApplicationPath` in the `Application` subclass ("/rest") +3. the value of the `@Path` annotation on the resource class ("/"), +4. the value of the `@Path` annotation on the resource method (e.g., "/get/xml"). + +So the address of the resource method `HelloWorldJaxRsServer.getHelloWorldJSON()` looks something like + +http://localhost:8080/helloworld-jaxrs/rest/get/xml +== Invoking resource methods with curl + +Curl being more flexible than web browsers, it is straightforward to access `POST` methods: + +curl -d "hola" -X POST http://localhost:8080/helloworld-jaxrs/rest/post/xml + +== JAX-RS client API + +The JAX-RS specification provides a client API for accessing JAX-RS resources, which is demonstrated +by the `org.jboss.as.quickstarts.helloworld.client.HelloWorldJaxRsClientIT` class, which can be run with Arquillian. + +// Run the Arquillian Tests +include::../shared-doc/run-arquillian-tests.adoc[leveloffset=+1] + == Investigate the Console Output When you run the Arquillian tests, Maven prints summary of the performed tests to the console. You should see the following results. [source,options="nowrap"] ---- -------------------------------------------------------- -T E S T S -------------------------------------------------------- -Running org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest requestResponseFiltersTest -INFO: ### Testing Request and Response Filters ### -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest requestResponseFiltersTest -INFO: dropping all contacts -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest requestResponseFiltersTest -INFO: Invoking create new contact using a ClientRequestFilter -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest requestResponseFiltersTest -INFO: Invoking list all contacts using a ClientResponseFilter -org.jboss.as.quickstarts.jaxrsclient.test.LogResponseFilter filter -INFO: Date: Mon Dec 29 15:34:45 BRST 2014- Status: 200 -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest delayedInvocationTest -INFO: ### Testing Delayed invocaton ### -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest delayedInvocationTest -INFO: dropping all contacts -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest delayedInvocationTest -INFO: Creating a new contact invocation -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest delayedInvocationTest -INFO: Creating list all contacts invocation -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest delayedInvocationTest -INFO: invoking the new contact -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest delayedInvocationTest -INFO: invoking list all contacts ASYNC -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest asyncCrudTest -INFO: ### CRUD tests ASYNC ### -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest asyncCrudTest -INFO: dropping all contacts ASYNC -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest asyncCrudTest -INFO: creating a new contact ASYNC -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest asyncCrudTest -INFO: delete a contact by id ASYNC -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest asyncCrudTest -INFO: fetching all contacts ASYNC -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest invocationCallBackTest -INFO: ### Testing invocation callback ### -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest invocationCallBackTest -INFO: dropping all contacts -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest invocationCallBackTest -INFO: Creating a InvocationCallback -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest invocationCallBackTest -INFO: Invoking a service using the InvocationCallback -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest cruedTest -INFO: ### CRUD tests ### -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest cruedTest -INFO: dropping all contacts -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest cruedTest -INFO: creating a new contact -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest cruedTest -INFO: fetching a contact by id -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest cruedTest -INFO: fetching all contacts -org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest cruedTest -INFO: delete a contact by id -Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.51 sec - in org.jboss.as.quickstarts.jaxrsclient.test.ContactsRestClientTest - -Results : - -Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running org.jboss.as.quickstarts.helloworld.client.HelloWorldJaxRsClientIT +Feb 19, 2022 5:05:24 PM org.jboss.threads.Version +INFO: JBoss Threads version 2.4.0.Final +Feb 19, 2022 5:05:24 PM org.jboss.logmanager.JBossLoggerFinder getLogger +ERROR: The LogManager accessed before the "java.util.logging.manager" system property was set to "org.jboss.logmanager.LogManager". Results may be unexpected. +Feb 19, 2022 5:05:24 PM org.jboss.remoting3.EndpointImpl +INFO: JBoss Remoting version 5.0.19.Final +Feb 19, 2022 5:05:25 PM org.xnio.Xnio +INFO: XNIO version 3.8.2.Final +Feb 19, 2022 5:05:25 PM org.xnio.nio.NioXnio +INFO: XNIO NIO Implementation Version 3.8.2.Final +Feb 19, 2022 5:05:25 PM org.wildfly.security.Version +INFO: ELY00001: WildFly Elytron version 1.18.3.Final +=============================================== +URL: http://127.0.0.1:8080/helloworld-jaxrs/rest/get/xml +MediaType: application/xml + +*** Response from Server *** + +Hello World! + +=============================================== +=============================================== +URL: http://127.0.0.1:8080/helloworld-jaxrs/rest/get/json +MediaType: application/json + +*** Response from Server *** + +{"result":"Hello World!"} + +=============================================== +=============================================== +URL: http://127.0.0.1:8080/helloworld-jaxrs/rest/post/xml +MediaType: application/xml + +*** Response from Server *** + +Hola World! + +=============================================== +=============================================== +URL: http://127.0.0.1:8080/helloworld-jaxrs/rest/post/json +MediaType: application/json + +*** Response from Server *** + +{"result":"Hola World!"} + +=============================================== +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.082 s - in org.jboss.as.quickstarts.helloworld.client.HelloWorldJaxRsClientIT +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- maven-failsafe-plugin:2.22.2:verify (default) @ helloworld-jaxrs --- +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ ---- // Undeploy the Quickstart diff --git a/jaxrs-client/pom.xml b/jaxrs-client/pom.xml index 09f2cb0b0b..f54c48d624 100644 --- a/jaxrs-client/pom.xml +++ b/jaxrs-client/pom.xml @@ -30,7 +30,7 @@ jaxrs-client - 27.0.0.Beta1-SNAPSHOT + 26.0.1.Final war Quickstart: jaxrs-client A JAX-RS Client API project @@ -45,7 +45,7 @@ - 26.0.0.Final + 26.0.1.Final @@ -151,8 +151,8 @@ - org.jboss.resteasy - resteasy-jackson2-provider + com.sun.activation + jakarta.activation test diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/LogResponseFilter.java b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java similarity index 54% rename from jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/LogResponseFilter.java rename to jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java index a84e9de723..7805a62495 100644 --- a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/LogResponseFilter.java +++ b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java @@ -14,22 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.jaxrsclient.test; +package org.jboss.as.quickstarts.helloworld.server; -import java.io.IOException; -import java.util.logging.Logger; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; - -//This filter will log response date and status -public class LogResponseFilter implements ClientResponseFilter { - - private Logger log = Logger.getLogger(LogResponseFilter.class.getName()); +/** + * A simple CDI service which is able to say hello to someone + * + * @author Pete Muir + * + */ +public class HelloService { - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - log.info("Date: " + responseContext.getDate() + "- Status: " + responseContext.getStatus()); + String createHelloMessage(String name) { + return "Hello " + name + "!"; } + } diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java new file mode 100644 index 0000000000..ae59636094 --- /dev/null +++ b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java @@ -0,0 +1,62 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.quickstarts.helloworld.server; + +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; + +/** + * A simple JAX-RS resource class + * + */ +@Path("") +public class HelloWorldJaxRsServer { + + @Inject + HelloService helloService; + + @GET + @Path("/get/json") + @Produces({ "application/json" }) + public String getHelloWorldJSON() { + return "{\"result\":\"" + helloService.createHelloMessage("World") + "\"}"; + } + + @GET + @Path("/get/xml") + @Produces({ "application/xml" }) + public String getHelloWorldXML() { + return "" + helloService.createHelloMessage("World") + ""; + } + + @POST + @Path("/post/json") + @Produces({ "application/json" }) + public String postHelloWorldJSON(String greeting) { + return "{\"result\":\"" + greeting + " World!" + "\"}"; + } + + @POST + @Path("/post/xml") + @Produces({ "application/xml" }) + public String postHelloWorldXML(String greeting) { + return "" + greeting + " World!"; + } +} diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/JaxRsActivator.java b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java similarity index 96% rename from jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/JaxRsActivator.java rename to jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java index 00fcb62a3d..3e6bada671 100644 --- a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/JaxRsActivator.java +++ b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.jaxrsclient.rest; +package org.jboss.as.quickstarts.helloworld.server; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/model/Contact.java b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/model/Contact.java deleted file mode 100644 index f900476486..0000000000 --- a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/model/Contact.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.as.quickstarts.jaxrsclient.model; - -public class Contact { - - private Long id; - - private String name; - - private String phoneNumber; - - private String savedBy; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - - public String getSavedBy() { - return savedBy; - } - - public void setSavedBy(String savedBy) { - this.savedBy = savedBy; - } - -} diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/ContactResourceRESTService.java b/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/ContactResourceRESTService.java deleted file mode 100644 index fccd0fe4c3..0000000000 --- a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/jaxrsclient/rest/ContactResourceRESTService.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.as.quickstarts.jaxrsclient.rest; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.jboss.as.quickstarts.jaxrsclient.model.Contact; - -@Path("/contacts") -public class ContactResourceRESTService { - - private static Map contactsRepository = new HashMap<>(); - - /** - * Creates a new contact from the values provided and will return a JAX-RS response with either 200 ok, or 400 (BAD REQUEST) - * in case of errors. - */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response createContact(Contact contact) { - - Response.ResponseBuilder builder = null; - Long nextId = contactsRepository.keySet().size() + 1L; - try { - // Store the contact - contact.setId(nextId); - contactsRepository.put(nextId, contact); - - // Create an "ok" response with the persisted contact - builder = Response.ok(contact); - } catch (Exception e) { - // Handle generic exceptions - builder = Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()); - } - - return builder.build(); - } - - // delete all contacts - @DELETE - public Response removeAllContacts() { - contactsRepository.clear(); - return Response.ok().build(); - } - - // delete a specific contact - @DELETE - @Path("/{id}") - public Response removeContact(final @PathParam("id") Long id) { - contactsRepository.remove(id); - return Response.ok().build(); - } - - // Fetch all contacts - @GET - @Produces(MediaType.APPLICATION_JSON) - public Response getAll() { - Collection allcontacts = contactsRepository.values(); - return Response.ok(allcontacts).build(); - } - - // Fetch a specific contact - @GET - @Path("/{id}") - @Produces(MediaType.APPLICATION_JSON) - public Response getById(final @PathParam("id") Long id) { - Contact contact = contactsRepository.get(id); - return Response.ok(contact).build(); - } -} diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java new file mode 100644 index 0000000000..e1a7beff86 --- /dev/null +++ b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java @@ -0,0 +1,163 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.quickstarts.helloworld.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +public class HelloWorldJaxRsClient { + + private static final String REST_TARGET_URL = "http://localhost:8080/jaxrs-client/rest/"; + + /** + * Responses of the RESTful web service + */ + private static final String XML_RESPONSE = "Hello World!"; + private static final String JSON_RESPONSE = "{\"result\":\"Hello World!\"}"; + private static final String XML_RESPONSE_GREETING = "%s World!"; + private static final String JSON_RESPONSE_GREETING = "{\"result\":\"%s World!\"}"; + + public static void main(String[] args) throws Exception { + HelloWorldJaxRsClient client = new HelloWorldJaxRsClient(); + client.testGet(); + client.testPost(); + } + + String getRequestUrl(String verb, String format) { + return REST_TARGET_URL + verb + "/" + format; + } + + /** + * Test method that invokes GET resource methods on HelloWorldJaxRsServer. + */ + public void testGet() { + String response = runRequestGet(getRequestUrl("get", "xml"), MediaType.APPLICATION_XML_TYPE); + if (!XML_RESPONSE.equals(response)) { + throw new RuntimeException("Response is wrong:\nXML Response:" + response + "\nshould be: " + XML_RESPONSE); + } + + response = runRequestGet(getRequestUrl("get", "json"), MediaType.APPLICATION_JSON_TYPE); + if (!JSON_RESPONSE.equals(response)) { + throw new RuntimeException("Response is wrong:\nJSON Response:" + response + "\nshould be: " + JSON_RESPONSE); + } + } + + /** + * Test method that invokes POST resource methods on HelloWorldJaxRsServer. + */ + public void testPost() { + String response = runRequestPost(getRequestUrl("post", "xml"), MediaType.APPLICATION_XML_TYPE, "Hola"); + if (!String.format(XML_RESPONSE_GREETING, "Hola").equals(response)) { + throw new RuntimeException("Response is wrong:\nXML Response:" + response + "\nshould be: " + String.format(XML_RESPONSE_GREETING, "Hola")); + } + + response = runRequestPost(getRequestUrl("post", "json"), MediaType.APPLICATION_JSON_TYPE, "Hola"); + if (!String.format(JSON_RESPONSE_GREETING, "Hola").equals(response)) { + throw new RuntimeException("Response is wrong:\nJSON Response:" + response + "\nshould be: " + String.format(JSON_RESPONSE_GREETING, "Hola")); + } + } + + /** + * The purpose of this method is to run the external REST request on GET resource methods. + * + * @param url The url of the RESTful service + * @param mediaType The mediatype of the RESTful service + */ + private String runRequestGet(String url, MediaType mediaType) { + String result = null; + + System.out.println("==============================================="); + System.out.println("URL: " + url); + System.out.println("MediaType: " + mediaType.toString()); + + + // Using the RESTEasy libraries, initiate a client request + Client client = ClientBuilder.newClient(); + + // Set url as target + WebTarget target = client.target(url); + + // Be sure to set the mediatype of the request + target.request(mediaType); + + // Request has been made, now let's get the response + Response response = target.request().get(); + result = response.readEntity(String.class); + response.close(); + + // Check the HTTP status of the request + // HTTP 200 indicates the request is OK + if (response.getStatus() != 200) { + throw new RuntimeException("Failed request with HTTP status: " + response.getStatus()); + } + + // We have a good response, let's now read it + System.out.println("\n*** Response from Server ***\n"); + System.out.println(result); + System.out.println("\n==============================================="); + + return result; + } + + /** + * The purpose of this method is to run the external REST request on POST resource methods. + * + * @param url The url of the RESTful service + * @param mediaType The mediatype of the RESTful service + */ + private String runRequestPost(String url, MediaType mediaType, String greeting) { + String result = null; + + System.out.println("==============================================="); + System.out.println("URL: " + url); + System.out.println("MediaType: " + mediaType.toString()); + + + // Using the RESTEasy libraries, initiate a client request + Client client = ClientBuilder.newClient(); + + // Set url as target + WebTarget target = client.target(url); + + // Be sure to set the mediatype of the request + target.request(mediaType); + + // Create the entity parameter for the POST resource method and make the invocation + Response response = target.request().post(Entity.entity(greeting, MediaType.TEXT_PLAIN_TYPE)); + + // Request has been made, now let's get the response + result = response.readEntity(String.class); + response.close(); + + // Check the HTTP status of the request + // HTTP 200 indicates the request is OK + if (response.getStatus() != 200) { + throw new RuntimeException("Failed request with HTTP status: " + response.getStatus()); + } + + // We have a good response, let's now read it + System.out.println("\n*** Response from Server ***\n"); + System.out.println(result); + System.out.println("\n==============================================="); + + return result; + } +} diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java new file mode 100644 index 0000000000..e4672bfc0b --- /dev/null +++ b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java @@ -0,0 +1,186 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.quickstarts.helloworld.client; + +import java.net.URL; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.quickstarts.helloworld.server.JaxRsActivator; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(Arquillian.class) +@RunAsClient +public class HelloWorldJaxRsClientIT { + + /** + * Responses of the RESTful web service + */ + private static final String XML_RESPONSE = "Hello World!"; + private static final String JSON_RESPONSE = "{\"result\":\"Hello World!\"}"; + private static final String XML_RESPONSE_GREETING = "%s World!"; + private static final String JSON_RESPONSE_GREETING = "{\"result\":\"%s World!\"}"; + + @ArquillianResource + private URL deploymentUrl; + + @Deployment(testable = false) + public static WebArchive createDeployment() { + WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrs-client.war") + .addPackage(JaxRsActivator.class.getPackage()) + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); + return war; + } + + private String getRequestUrl(String verb, String format) { + return new StringBuilder(deploymentUrl.toString()) + .append("rest/" + verb + "/" + format) + .toString(); + } + + /** + * Test method that invokes GET resource methods on HelloWorldJaxRsServer. + */ + @Test + public void testGet() { + String response = runRequestGet(getRequestUrl("get", "xml"), MediaType.APPLICATION_XML_TYPE); + if (!XML_RESPONSE.equals(response)) { + throw new RuntimeException("Response is wrong:\nXML Response:" + response + "\nshould be: " + XML_RESPONSE); + } + + response = runRequestGet(getRequestUrl("get", "json"), MediaType.APPLICATION_JSON_TYPE); + if (!JSON_RESPONSE.equals(response)) { + throw new RuntimeException("Response is wrong:\nJSON Response:" + response + "\nshould be: " + JSON_RESPONSE); + } + } + + /** + * Test method that invokes POST resource methods on HelloWorldJaxRsServer. + */ + @Test + public void testPost() { + String response = runRequestPost(getRequestUrl("post", "xml"), MediaType.APPLICATION_XML_TYPE, "Hola"); + if (!String.format(XML_RESPONSE_GREETING, "Hola").equals(response)) { + throw new RuntimeException("Response is wrong:\nXML Response:" + response + "\nshould be: " + String.format(XML_RESPONSE_GREETING, "Hola")); + } + + response = runRequestPost(getRequestUrl("post", "json"), MediaType.APPLICATION_JSON_TYPE, "Hola"); + if (!String.format(JSON_RESPONSE_GREETING, "Hola").equals(response)) { + throw new RuntimeException("Response is wrong:\nJSON Response:" + response + "\nshould be: " + String.format(JSON_RESPONSE_GREETING, "Hola")); + } + + } + + /** + * The purpose of this method is to run the external REST request on GET resource methods. + * + * @param url The url of the RESTful service + * @param mediaType The mediatype of the RESTful service + */ + private String runRequestGet(String url, MediaType mediaType) { + String result = null; + + System.out.println("==============================================="); + System.out.println("URL: " + url); + System.out.println("MediaType: " + mediaType.toString()); + + + // Using the RESTEasy libraries, initiate a client request + Client client = ClientBuilder.newClient(); + + // Set url as target + WebTarget target = client.target(url); + + // Be sure to set the mediatype of the request + target.request(mediaType); + + // Request has been made, now let's get the response + Response response = target.request().get(); + result = response.readEntity(String.class); + response.close(); + + // Check the HTTP status of the request + // HTTP 200 indicates the request is OK + if (response.getStatus() != 200) { + throw new RuntimeException("Failed request with HTTP status: " + response.getStatus()); + } + + // We have a good response, let's now read it + System.out.println("\n*** Response from Server ***\n"); + System.out.println(result); + System.out.println("\n==============================================="); + + return result; + } + + /** + * The purpose of this method is to run the external REST request on POST resource methods. + * + * @param url The url of the RESTful service + * @param mediaType The mediatype of the RESTful service + */ + private String runRequestPost(String url, MediaType mediaType, String greeting) { + String result = null; + + System.out.println("==============================================="); + System.out.println("URL: " + url); + System.out.println("MediaType: " + mediaType.toString()); + + + // Using the RESTEasy libraries, initiate a client request + Client client = ClientBuilder.newClient(); + + // Set url as target + WebTarget target = client.target(url); + + // Be sure to set the mediatype of the request + target.request(mediaType); + + // Create the entity parameter for the POST resource method and make the invocation + Response response = target.request().post(Entity.entity(greeting, MediaType.TEXT_PLAIN_TYPE)); + + // Request has been made, now let's get the response + result = response.readEntity(String.class); + response.close(); + + // Check the HTTP status of the request + // HTTP 200 indicates the request is OK + if (response.getStatus() != 200) { + throw new RuntimeException("Failed request with HTTP status: " + response.getStatus()); + } + + // We have a good response, let's now read it + System.out.println("\n*** Response from Server ***\n"); + System.out.println(result); + System.out.println("\n==============================================="); + + return result; + } +} diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClient.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClient.java deleted file mode 100644 index 2decdf6164..0000000000 --- a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClient.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.as.quickstarts.jaxrsclient.test; - -import java.util.List; -import java.util.concurrent.Future; -import java.util.logging.Logger; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.InvocationCallback; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.jboss.as.quickstarts.jaxrsclient.model.Contact; -import org.junit.Assert; - -public class ContactsRestClient { - - private static final String REST_TARGET_URL = "http://localhost:8080/jaxrs-client/rest/contacts"; - private static final String CONTACT_NAME = "New Contact"; - private static final String CONTACT_PHONE = "+55-61-5555-1234"; - - private Logger log = Logger.getLogger(ContactsRestClient.class.getName()); - - public static void main(String[] args) throws Exception { - ContactsRestClient client = new ContactsRestClient(); - client.cruedTest(); - client.asyncCrudTest(); - client.delayedInvocationTest(); - client.invocationCallBackTest(); - client.requestResponseFiltersTest(); - - } - - // This test shows basic operations - - public void cruedTest() { - log.info("### CRUD tests ###"); - // 1 - drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(REST_TARGET_URL).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new contact - log.info("creating a new contact"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - Contact persistedContact = ClientBuilder.newClient().target(REST_TARGET_URL).request().post(Entity.entity(c, MediaType.APPLICATION_JSON), Contact.class); - Assert.assertEquals("A book should be persisted with Id=1!", (Long) 1L, (Long) persistedContact.getId()); - - // 3 - Fetch Contact by Id - log.info("fetching a contact by id"); - Contact fetchContctById = - ClientBuilder.newClient().target(REST_TARGET_URL).path("/{contactId}").resolveTemplate("contactId", persistedContact.getId()).request().get(Contact.class); - Assert.assertEquals("Fetched book with Id=1!", (Long) 1L, (Long) fetchContctById.getId()); - Assert.assertEquals("Fetched book with equal name", CONTACT_NAME, fetchContctById.getName()); - Assert.assertEquals("Fetched book with equal phone", CONTACT_PHONE, fetchContctById.getPhoneNumber()); - - // 4 - Fetch all Contacts - log.info("fetching all contacts"); - GenericType> contactsListType = new GenericType>() { - }; - List allContacts = ClientBuilder.newClient().target(REST_TARGET_URL).request().get(contactsListType); - Assert.assertEquals("Should have a single contact", 1, allContacts.size()); - - // 5 - Delete a Contact - log.info("delete a contact by id"); - response = ClientBuilder.newClient().target(REST_TARGET_URL).path("/{contactId}").resolveTemplate("contactId", persistedContact.getId()).request().delete(); - Assert.assertEquals("Contact 1 should be dropped", Response.ok().build().getStatus(), response.getStatus()); - } - - // This test shows some basic operations using ASYNC invocations and java.util.concurrent.Future - public void asyncCrudTest() throws Exception { - log.info("### CRUD tests ASYNC ###"); - - // 1 - drop all contacts ASYNC - log.info("dropping all contacts ASYNC"); - Response response = ClientBuilder.newClient().target(REST_TARGET_URL).request().async().delete().get(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new Contact ASYNC - log.info("creating a new contact ASYNC"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - - Future futureContact = ClientBuilder.newClient().target(REST_TARGET_URL).request().async().post(Entity.entity(c, MediaType.APPLICATION_JSON), Contact.class); - - Contact persistedContact = futureContact.get(); - Assert.assertEquals("A contact should be persisted with Id=1!", (Long) 1L, (Long) persistedContact.getId()); - - // 3 - Delete a contact ASYNC - log.info("delete a contact by id ASYNC"); - ClientBuilder.newClient().target(REST_TARGET_URL).path("{contactId}").resolveTemplate("contactId", persistedContact.getId()).request().async().delete().get(); - - // 4 - Fetch All Contacts ASYNC - log.info("fetching all contacts ASYNC"); - Future> futureContacts = ClientBuilder.newClient().target(REST_TARGET_URL).request().async().get(new GenericType>() { - }); - List allContacts = futureContacts.get(); - Assert.assertEquals("Should have no contacts", 0, allContacts.size()); - } - - // This test shows how to use javax.ws.rs.client.InvocationCallback - public void invocationCallBackTest() throws Exception { - log.info("### Testing invocation callback ###"); - - // 1 - drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(REST_TARGET_URL).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a InvocationCallback - log.info("Creating a InvocationCallback"); - InvocationCallback> invocationCallback = new InvocationCallback>() { - - @Override - public void completed(List allContacts) { - // Completed the invocation with no contact - Assert.assertEquals("Should have no contacts", 0, allContacts.size()); - } - - @Override - public void failed(Throwable throwable) { - // It should fail - Assert.fail(throwable.getMessage()); - - } - }; - // 3 - Invoke the service - log.info("Invoking a service using the InvocationCallback"); - ClientBuilder.newClient().target(REST_TARGET_URL).request().async().get(invocationCallback).get(); - } - - // Shows how to use a delayed REST invocation - public void delayedInvocationTest() throws Exception { - log.info("### Testing Delayed invocaton ###"); - - // 1 - Drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(REST_TARGET_URL).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new Contact Invocation - log.info("Creating a new contact invocation"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - Invocation saveContactInvocation = ClientBuilder.newClient().target(REST_TARGET_URL).request().buildPost(Entity.entity(c, MediaType.APPLICATION_JSON)); - - // 3 - Create a new list Contacts Invocation - log.info("Creating list all contacts invocation"); - Invocation listContactsInvocation = ClientBuilder.newClient().target(REST_TARGET_URL).request().buildGet(); - - // 4 - Synch Save contact - log.info("invoking the new contact"); - Contact persistedContact = saveContactInvocation.invoke(Contact.class); - Assert.assertEquals("A contacts should be persisted with Id=1!", (Long) 1L, (Long) persistedContact.getId()); - - // 5 - Async List contacts - log.info("invoking list all contacts ASYNC"); - GenericType> contactsListType = new GenericType>() { - }; - Future> futureAllContacts = listContactsInvocation.submit(contactsListType); - List allContacts = futureAllContacts.get(); - Assert.assertEquals("Should have a single contact", 1, allContacts.size()); - } - - // Shows how to use Request and Response filters - public void requestResponseFiltersTest() { - log.info("### Testing Request and Response Filters ###"); - - // 1 - Drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(REST_TARGET_URL).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new Contact Invocation - log.info("Invoking create new contact using a ClientRequestFilter"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - Contact persistedContact = - ClientBuilder.newClient().register(SavedByClientRequestFilter.class).target(REST_TARGET_URL).request() - .post(Entity.entity(c, MediaType.APPLICATION_JSON), Contact.class); - Assert.assertEquals("A contact should be persisted with savedBy", SavedByClientRequestFilter.USERNAME, persistedContact.getSavedBy()); - - // 3 - Fetch all Contacts - log.info("Invoking list all contacts using a ClientResponseFilter"); - GenericType> contactsListType = new GenericType>() { - }; - List allContacts = ClientBuilder.newClient().register(LogResponseFilter.class).target(REST_TARGET_URL).request().get(contactsListType); - Assert.assertEquals("Should have a single contact", 1, allContacts.size()); - } -} diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClientIT.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClientIT.java deleted file mode 100644 index de1989d697..0000000000 --- a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/ContactsRestClientIT.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.as.quickstarts.jaxrsclient.test; - -import java.net.URL; -import java.util.List; -import java.util.concurrent.Future; -import java.util.logging.Logger; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.InvocationCallback; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.RunAsClient; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.arquillian.test.api.ArquillianResource; -import org.jboss.as.quickstarts.jaxrsclient.model.Contact; -import org.jboss.as.quickstarts.jaxrsclient.rest.JaxRsActivator; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; - -@RunWith(Arquillian.class) -@RunAsClient -public class ContactsRestClientIT { - - //private static final String getRequestUrl() = "http://localhost:8080/jaxrs-client/rest/contacts"; - private static final String CONTACT_NAME = "New Contact"; - private static final String CONTACT_PHONE = "+55-61-5555-1234"; - - private Logger log = Logger.getLogger(ContactsRestClientIT.class.getName()); - - @ArquillianResource - private URL deploymentUrl; - - @Deployment(testable = false) - public static WebArchive createDeployment() { - WebArchive war = ShrinkWrap.create(WebArchive.class, "managed-executor-service.war") - .addPackage(JaxRsActivator.class.getPackage()) - .addPackage(Contact.class.getPackage()) - .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); - return war; - } - - private String getRequestUrl() { - return new StringBuilder(deploymentUrl.toString()) - .append("rest/contacts") - .toString(); - } - - - // This test shows basic operations - @Test - public void cruedTest() { - log.info("### CRUD tests ###"); - // 1 - drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(getRequestUrl()).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new contact - log.info("creating a new contact"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - Contact persistedContact = ClientBuilder.newClient().target(getRequestUrl()).request().post(Entity.entity(c, MediaType.APPLICATION_JSON), Contact.class); - Assert.assertEquals("A book should be persisted with Id=1!", (Long) 1L, (Long) persistedContact.getId()); - - // 3 - Fetch Contact by Id - log.info("fetching a contact by id"); - Contact fetchContctById = - ClientBuilder.newClient().target(getRequestUrl()).path("/{contactId}").resolveTemplate("contactId", persistedContact.getId()).request().get(Contact.class); - Assert.assertEquals("Fetched book with Id=1!", (Long) 1L, (Long) fetchContctById.getId()); - Assert.assertEquals("Fetched book with equal name", CONTACT_NAME, fetchContctById.getName()); - Assert.assertEquals("Fetched book with equal phone", CONTACT_PHONE, fetchContctById.getPhoneNumber()); - - // 4 - Fetch all Contacts - log.info("fetching all contacts"); - GenericType> contactsListType = new GenericType>() { - }; - List allContacts = ClientBuilder.newClient().target(getRequestUrl()).request().get(contactsListType); - Assert.assertEquals("Should have a single contact", 1, allContacts.size()); - - // 5 - Delete a Contact - log.info("delete a contact by id"); - response = ClientBuilder.newClient().target(getRequestUrl()).path("/{contactId}").resolveTemplate("contactId", persistedContact.getId()).request().delete(); - Assert.assertEquals("Contact 1 should be dropped", Response.ok().build().getStatus(), response.getStatus()); - } - - // This test shows some basic operations using ASYNC invocations and java.util.concurrent.Future - @Test - public void asyncCrudTest() throws Exception { - log.info("### CRUD tests ASYNC ###"); - - // 1 - drop all contacts ASYNC - log.info("dropping all contacts ASYNC"); - Response response = ClientBuilder.newClient().target(getRequestUrl()).request().async().delete().get(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new Contact ASYNC - log.info("creating a new contact ASYNC"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - - Future futureContact = ClientBuilder.newClient().target(getRequestUrl()).request().async().post(Entity.entity(c, MediaType.APPLICATION_JSON), Contact.class); - - Contact persistedContact = futureContact.get(); - Assert.assertEquals("A contact should be persisted with Id=1!", (Long) 1L, (Long) persistedContact.getId()); - - // 3 - Delete a contact ASYNC - log.info("delete a contact by id ASYNC"); - ClientBuilder.newClient().target(getRequestUrl()).path("{contactId}").resolveTemplate("contactId", persistedContact.getId()).request().async().delete().get(); - - // 4 - Fetch All Contacts ASYNC - log.info("fetching all contacts ASYNC"); - Future> futureContacts = ClientBuilder.newClient().target(getRequestUrl()).request().async().get(new GenericType>() { - }); - List allContacts = futureContacts.get(); - Assert.assertEquals("Should have no contacts", 0, allContacts.size()); - } - - // This test shows how to use javax.ws.rs.client.InvocationCallback - @Test - public void invocationCallBackTest() throws Exception { - log.info("### Testing invocation callback ###"); - - // 1 - drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(getRequestUrl()).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a InvocationCallback - log.info("Creating a InvocationCallback"); - InvocationCallback> invocationCallback = new InvocationCallback>() { - - @Override - public void completed(List allContacts) { - // Completed the invocation with no contact - Assert.assertEquals("Should have no contacts", 0, allContacts.size()); - } - - @Override - public void failed(Throwable throwable) { - // It should fail - Assert.fail(throwable.getMessage()); - - } - }; - // 3 - Invoke the service - log.info("Invoking a service using the InvocationCallback"); - ClientBuilder.newClient().target(getRequestUrl()).request().async().get(invocationCallback).get(); - } - - // Shows how to use a delayed REST invocation - @Test - public void delayedInvocationTest() throws Exception { - log.info("### Testing Delayed invocaton ###"); - - // 1 - Drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(getRequestUrl()).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new Contact Invocation - log.info("Creating a new contact invocation"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - Invocation saveContactInvocation = ClientBuilder.newClient().target(getRequestUrl()).request().buildPost(Entity.entity(c, MediaType.APPLICATION_JSON)); - - // 3 - Create a new list Contacts Invocation - log.info("Creating list all contacts invocation"); - Invocation listContactsInvocation = ClientBuilder.newClient().target(getRequestUrl()).request().buildGet(); - - // 4 - Synch Save contact - log.info("invoking the new contact"); - Contact persistedContact = saveContactInvocation.invoke(Contact.class); - Assert.assertEquals("A contacts should be persisted with Id=1!", (Long) 1L, (Long) persistedContact.getId()); - - // 5 - Async List contacts - log.info("invoking list all contacts ASYNC"); - GenericType> contactsListType = new GenericType>() { - }; - Future> futureAllContacts = listContactsInvocation.submit(contactsListType); - List allContacts = futureAllContacts.get(); - Assert.assertEquals("Should have a single contact", 1, allContacts.size()); - } - - // Shows how to use Request and Response filters - @Test - public void requestResponseFiltersTest() { - log.info("### Testing Request and Response Filters ###"); - - // 1 - Drop all contacts - log.info("dropping all contacts"); - Response response = ClientBuilder.newClient().target(getRequestUrl()).request().delete(); - Assert.assertEquals("All contacts should be dropped", Response.ok().build().getStatus(), response.getStatus()); - - // 2 - Create a new Contact Invocation - log.info("Invoking create new contact using a ClientRequestFilter"); - Contact c = new Contact(); - c.setName(CONTACT_NAME); - c.setPhoneNumber(CONTACT_PHONE); - Contact persistedContact = - ClientBuilder.newClient().register(SavedByClientRequestFilter.class).target(getRequestUrl()).request() - .post(Entity.entity(c, MediaType.APPLICATION_JSON), Contact.class); - Assert.assertEquals("A contact should be persisted with savedBy", SavedByClientRequestFilter.USERNAME, persistedContact.getSavedBy()); - - // 3 - Fetch all Contacts - log.info("Invoking list all contacts using a ClientResponseFilter"); - GenericType> contactsListType = new GenericType>() { - }; - List allContacts = ClientBuilder.newClient().register(LogResponseFilter.class).target(getRequestUrl()).request().get(contactsListType); - Assert.assertEquals("Should have a single contact", 1, allContacts.size()); - } -} diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/SavedByClientRequestFilter.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/SavedByClientRequestFilter.java deleted file mode 100644 index e5a765281b..0000000000 --- a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/jaxrsclient/test/SavedByClientRequestFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.as.quickstarts.jaxrsclient.test; - -import java.io.IOException; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; - -import org.jboss.as.quickstarts.jaxrsclient.model.Contact; - -//This filter adds a username to SavedBy field -public class SavedByClientRequestFilter implements ClientRequestFilter { - - public static final String USERNAME = "quickstartUser"; - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - String method = requestContext.getMethod(); - if ("POST".equals(method) && requestContext.hasEntity()) { - Contact contact = (Contact) requestContext.getEntity(); - contact.setSavedBy(USERNAME); - requestContext.setEntity(contact); - } - - } - -} From 479fd25e5e5894d090c5688054849ba020e92c84 Mon Sep 17 00:00:00 2001 From: Ron Sigal Date: Sat, 19 Feb 2022 18:50:11 -0500 Subject: [PATCH 2/3] Rename quickstart jaxrs-client to helloworld-jaxrs --- jaxrs-client/pom.xml | 6 +++--- .../helloworld/client/HelloWorldJaxRsClient.java | 2 +- .../helloworld/client/HelloWorldJaxRsClientIT.java | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jaxrs-client/pom.xml b/jaxrs-client/pom.xml index f54c48d624..b42c273a72 100644 --- a/jaxrs-client/pom.xml +++ b/jaxrs-client/pom.xml @@ -29,10 +29,10 @@ 2 - jaxrs-client + helloworld-jaxrs 26.0.1.Final war - Quickstart: jaxrs-client + Quickstart: helloworldhelloworld-jaxrs A JAX-RS Client API project @@ -136,7 +136,7 @@ test - + org.apache.httpcomponents httpclient diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java index e1a7beff86..766d53600d 100644 --- a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java +++ b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java @@ -25,7 +25,7 @@ public class HelloWorldJaxRsClient { - private static final String REST_TARGET_URL = "http://localhost:8080/jaxrs-client/rest/"; + private static final String REST_TARGET_URL = "http://localhost:8080/helloworld-jaxrs/rest/"; /** * Responses of the RESTful web service diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java index e4672bfc0b..dcac88ae49 100644 --- a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java +++ b/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java @@ -53,7 +53,7 @@ public class HelloWorldJaxRsClientIT { @Deployment(testable = false) public static WebArchive createDeployment() { - WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrs-client.war") + WebArchive war = ShrinkWrap.create(WebArchive.class, "helloworld-jaxrs.war") .addPackage(JaxRsActivator.class.getPackage()) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; From 812c3e27dcb815489a7796ec14a1809c55d073e2 Mon Sep 17 00:00:00 2001 From: Ron Sigal Date: Sat, 19 Feb 2022 18:57:14 -0500 Subject: [PATCH 3/3] Renamed quickstart jaxrs-client to helloworld-jaxrs --- {jaxrs-client => helloworld-jaxrs}/README.adoc | 0 {jaxrs-client => helloworld-jaxrs}/pom.xml | 0 .../org/jboss/as/quickstarts/helloworld/server/HelloService.java | 0 .../as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java | 0 .../jboss/as/quickstarts/helloworld/server/JaxRsActivator.java | 0 .../src/main/webapp/WEB-INF/beans.xml | 0 .../as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java | 0 .../as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename {jaxrs-client => helloworld-jaxrs}/README.adoc (100%) rename {jaxrs-client => helloworld-jaxrs}/pom.xml (100%) rename {jaxrs-client => helloworld-jaxrs}/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java (100%) rename {jaxrs-client => helloworld-jaxrs}/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java (100%) rename {jaxrs-client => helloworld-jaxrs}/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java (100%) rename {jaxrs-client => helloworld-jaxrs}/src/main/webapp/WEB-INF/beans.xml (100%) rename {jaxrs-client => helloworld-jaxrs}/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java (100%) rename {jaxrs-client => helloworld-jaxrs}/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java (100%) diff --git a/jaxrs-client/README.adoc b/helloworld-jaxrs/README.adoc similarity index 100% rename from jaxrs-client/README.adoc rename to helloworld-jaxrs/README.adoc diff --git a/jaxrs-client/pom.xml b/helloworld-jaxrs/pom.xml similarity index 100% rename from jaxrs-client/pom.xml rename to helloworld-jaxrs/pom.xml diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java b/helloworld-jaxrs/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java similarity index 100% rename from jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java rename to helloworld-jaxrs/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloService.java diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java b/helloworld-jaxrs/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java similarity index 100% rename from jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java rename to helloworld-jaxrs/src/main/java/org/jboss/as/quickstarts/helloworld/server/HelloWorldJaxRsServer.java diff --git a/jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java b/helloworld-jaxrs/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java similarity index 100% rename from jaxrs-client/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java rename to helloworld-jaxrs/src/main/java/org/jboss/as/quickstarts/helloworld/server/JaxRsActivator.java diff --git a/jaxrs-client/src/main/webapp/WEB-INF/beans.xml b/helloworld-jaxrs/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jaxrs-client/src/main/webapp/WEB-INF/beans.xml rename to helloworld-jaxrs/src/main/webapp/WEB-INF/beans.xml diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java b/helloworld-jaxrs/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java similarity index 100% rename from jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java rename to helloworld-jaxrs/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClient.java diff --git a/jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java b/helloworld-jaxrs/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java similarity index 100% rename from jaxrs-client/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java rename to helloworld-jaxrs/src/test/java/org/jboss/as/quickstarts/helloworld/client/HelloWorldJaxRsClientIT.java