protected BrowserCache.Entry getEntry(ClientRequest request) throws Exception { String uri = request.getUri(); BrowserCache.Entry entry = null; String acceptHeader = request.getHeaders().getFirst(HttpHeaders.ACCEPT); if (acceptHeader != null) { List<WeightedMediaType> waccepts = new ArrayList<WeightedMediaType>(); String[] split = acceptHeader.split(","); for (String accept : split) { waccepts.add(WeightedMediaType.valueOf(accept)); } Collections.sort(waccepts); List<MediaType> accepts = new ArrayList<MediaType>(); for (WeightedMediaType accept : waccepts) { accepts.add(new MediaType(accept.getType(), accept.getSubtype(), accept.getParameters())); } for (MediaType accept : accepts) { entry = cache.get(uri, accept); if (entry != null) return entry; } } else { return cache.getAny(uri); } return null; }
public <T> T execute(Command<T> command) { ClientRequest restRequest = new ClientRequest(url); try { restRequest.body(MediaType.APPLICATION_XML, new JaxbCommandsRequest(deploymentId, command)); ClientResponse<Object> response = restRequest.post(Object.class); if (response.getResponseStatus() == Status.OK) { JaxbCommandsResponse commandResponse = response.getEntity(JaxbCommandsResponse.class); List<JaxbCommandResponse<?>> responses = commandResponse.getResponses(); if (responses.size() == 0) { return null; } else if (responses.size() == 1) { JaxbCommandResponse<?> responseObject = responses.get(0); if (responseObject instanceof JaxbExceptionResponse) { JaxbExceptionResponse exceptionResponse = (JaxbExceptionResponse) responseObject; String causeMessage = exceptionResponse.getCauseMessage(); throw new RuntimeException( exceptionResponse.getMessage() + (causeMessage == null ? "" : " Caused by: " + causeMessage)); } else { return (T) responseObject.getResult(); } } else { throw new RuntimeException("Unexpected number of results: " + responses.size()); } } else { // TODO error handling throw new RuntimeException("REST request error code " + response.getResponseStatus()); } } catch (Exception e) { throw new RuntimeException("Unable to execute REST request: " + e.getMessage(), e); } }
@Test public void testFailure() throws Exception { try { String testName = "testFailure"; startup(); deployTopic(testName); ClientRequest request = new ClientRequest(generateURL("/topics/" + testName)); ClientResponse<?> response = request.head(); response.releaseConnection(); Assert.assertEquals(200, response.getStatus()); Link sender = MessageTestBase.getLinkByTitle( manager.getQueueManager().getLinkStrategy(), response, "create"); System.out.println("create: " + sender); Link pushSubscriptions = MessageTestBase.getLinkByTitle( manager.getQueueManager().getLinkStrategy(), response, "push-subscriptions"); System.out.println("push subscriptions: " + pushSubscriptions); PushTopicRegistration reg = new PushTopicRegistration(); reg.setDurable(true); XmlLink target = new XmlLink(); target.setHref("http://localhost:3333/error"); target.setRelationship("uri"); reg.setTarget(target); reg.setDisableOnFailure(true); reg.setMaxRetries(3); reg.setRetryWaitMillis(10); response = pushSubscriptions.request().body("application/xml", reg).post(); Assert.assertEquals(201, response.getStatus()); Link pushSubscription = response.getLocationLink(); response.releaseConnection(); ClientResponse<?> res = sender.request().body("text/plain", Integer.toString(1)).post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); Thread.sleep(5000); response = pushSubscription.request().get(); PushTopicRegistration reg2 = response.getEntity(PushTopicRegistration.class); response.releaseConnection(); Assert.assertEquals(reg.isDurable(), reg2.isDurable()); Assert.assertEquals(reg.getTarget().getHref(), reg2.getTarget().getHref()); Assert.assertFalse(reg2.isEnabled()); response.releaseConnection(); String destination = reg2.getDestination(); ClientSession session = manager.getQueueManager().getSessionFactory().createSession(false, false, false); ClientSession.QueueQuery query = session.queueQuery(new SimpleString(destination)); Assert.assertFalse(query.isExists()); manager.getQueueManager().getPushStore().removeAll(); } finally { shutdown(); } }
public static void main(String[] args) throws Exception { // get the push consumers factory resource ClientRequest request = new ClientRequest("http://localhost:9095/queues/jms.queue.orders"); ClientResponse res = request.head(); Link pushConsumers = res.getHeaderAsLink("msg-push-consumers"); // next create the XML document that represents the registration // Really, just create a link with the shipping URL and the type you want posted PushRegistration reg = new PushRegistration(); BasicAuth authType = new BasicAuth(); authType.setUsername("guest"); authType.setPassword("guest"); Authentication auth = new Authentication(); auth.setType(authType); reg.setAuthenticationMechanism(auth); XmlLink target = new XmlLink(); target.setHref("http://localhost:9095/queues/jms.queue.shipping"); target.setType("application/xml"); target.setRelationship("destination"); reg.setTarget(target); res = pushConsumers.request().body("application/xml", reg).post(); System.out.println( "Create push registration. Resource URL: " + res.getLocationLink().getHref()); }
@Test public void testAsync() throws Exception { ClientRequest request = new ClientRequest("http://localhost:8080/"); ClientResponse<String> response = request.get(String.class); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("hello", response.getEntity()); }
@Test public void testTimeout() throws Exception { ClientRequest request = new ClientRequest("http://localhost:8080/timeout"); ClientResponse<String> response = request.get(String.class); Assert.assertEquals( 408, response.getStatus()); // exception mapper from another test overrides 503 to 408 }
private JaxbCommandResponse<?> executeTaskCommand(String deploymentId, Command<?> command) throws Exception { List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(command); String urlString = new URL( deploymentUrl, deploymentUrl.getPath() + "rest/runtime/" + DEPLOYMENT_ID + "/execute") .toExternalForm(); logger.info("Client request to: " + urlString); ClientRequest restRequest = new ClientRequest(urlString); JaxbCommandsRequest commandMessage = new JaxbCommandsRequest(commands); assertNotNull("Commands are null!", commandMessage.getCommands()); assertTrue("Commands are empty!", commandMessage.getCommands().size() > 0); String body = JaxbSerializationProvider.convertJaxbObjectToString(commandMessage); restRequest.body(MediaType.APPLICATION_XML, body); ClientResponse<JaxbCommandsResponse> responseObj = restRequest.post(JaxbCommandsResponse.class); checkResponse(responseObj); JaxbCommandsResponse cmdsResp = responseObj.getEntity(); return cmdsResp.getResponses().get(0); }
@Test public void testSuccessFirst() throws Exception { try { String testName = "testSuccessFirst"; startup(); deployTopic(testName); ClientRequest request = new ClientRequest(generateURL("/topics/" + testName)); ClientResponse<?> response = request.head(); response.releaseConnection(); Assert.assertEquals(200, response.getStatus()); Link sender = MessageTestBase.getLinkByTitle( manager.getTopicManager().getLinkStrategy(), response, "create"); System.out.println("create: " + sender); Link pushSubscriptions = MessageTestBase.getLinkByTitle( manager.getTopicManager().getLinkStrategy(), response, "push-subscriptions"); System.out.println("push subscriptions: " + pushSubscriptions); String sub1 = generateURL("/subscribers/1"); String sub2 = generateURL("/subscribers/2"); PushTopicRegistration reg = new PushTopicRegistration(); reg.setDurable(true); XmlLink target = new XmlLink(); target.setHref(sub1); reg.setTarget(target); response = pushSubscriptions.request().body("application/xml", reg).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); reg = new PushTopicRegistration(); reg.setDurable(true); target = new XmlLink(); target.setHref(sub2); reg.setTarget(target); response = pushSubscriptions.request().body("application/xml", reg).post(); response.releaseConnection(); Assert.assertEquals(201, response.getStatus()); shutdown(); startup(); deployTopic(testName); ClientResponse<?> res = sender.request().body("text/plain", Integer.toString(1)).post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); Receiver.latch.await(1, TimeUnit.SECONDS); Assert.assertEquals("1", Receiver.subscriber1); Assert.assertEquals("1", Receiver.subscriber2); manager.getTopicManager().getPushStore().removeAll(); } finally { shutdown(); } }
private JsonNode sendRequest() throws Exception { final ClientRequest clientRequest = new ClientRequest(SEARCH_URI); // For capturing Response final ClientResponse<String> clientResponse = clientRequest.get(String.class); // Collecting response in JsonNode final JsonNode jsonReply = new ObjectMapper().readTree(clientResponse.getEntity()); return jsonReply; }
private ClientRequest buildClientRequest() throws Exception { final ClientRequest request = mock(ClientRequest.class); final MultivaluedMap<String, String> headerMap = new MultivaluedMapImpl<String, String>(); when(request.getHeaders()).thenReturn(headerMap); when(request.getUri()).thenReturn(URI); when(request.getHttpMethod()).thenReturn(HTTP_METHOD); return request; }
/** * Verify that EJBBookReader and EJBBookWriterImpl are correctly injected into EJBBookResource. * * @throws Exception */ @Test public void testVerifyInjectionJaxRs() throws Exception { log.info("starting testVerifyInjectionJaxRs()"); ClientRequest request = new ClientRequest("http://localhost:8080/resteasy-ejb-test/verifyInjection/"); ClientResponse<?> response = request.get(); log.info("result: " + response.getEntity(Integer.class)); assertEquals(200, response.getStatus()); assertEquals(200, response.getEntity(Integer.class).intValue()); }
public void run() { try { ClientRequest req = new ClientRequest(url); req.header("Accept-Wait", acceptWaitTime); ClientResponse<?> response = req.post(); response.releaseConnection(); isFinished = true; } catch (Exception e) { failed = true; } }
/** * Creates the request OutputStream, to be sent to the end Service invoked, as a <a * href="http://commons.apache.org/io/api-release/org/apache/commons/io/output/DeferredFileOutputStream.html" * >DeferredFileOutputStream</a>. * * @param request - * @return - DeferredFileOutputStream with the ClientRequest written out per HTTP specification. * @throws IOException - */ private DeferredFileOutputStream writeRequestBodyToOutputStream(final ClientRequest request) throws IOException { DeferredFileOutputStream memoryManagedOutStream = new DeferredFileOutputStream( this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(), getTempfilePrefix(), ".tmp", this.fileUploadTempFileDir); request.writeRequestBody(request.getHeadersAsObjects(), memoryManagedOutStream); memoryManagedOutStream.close(); return memoryManagedOutStream; }
@SuppressWarnings("unchecked") public ClientResponse execute(ClientRequest request) throws Exception { String uri = request.getUri(); final HttpRequestBase httpMethod = createHttpMethod(uri, request.getHttpMethod()); try { loadHttpMethod(request, httpMethod); final HttpResponse res = httpClient.execute(httpMethod, httpContext); BaseClientResponse response = new BaseClientResponse( new BaseClientResponseStreamFactory() { InputStream stream; public InputStream getInputStream() throws IOException { if (stream == null) { HttpEntity entity = res.getEntity(); if (entity == null) return null; stream = new SelfExpandingBufferredInputStream(entity.getContent()); } return stream; } public void performReleaseConnection() { // Apache Client 4 is stupid, You have to get the InputStream and close it if // there is an entity // otherwise the connection is never released. There is, of course, no close() // method on response // to make this easier. try { if (stream != null) { stream.close(); } else { InputStream is = getInputStream(); if (is != null) { is.close(); } } } catch (Exception ignore) { } } }, this); response.setAttributes(request.getAttributes()); response.setStatus(res.getStatusLine().getStatusCode()); response.setHeaders(extractHeaders(res)); response.setProviderFactory(request.getProviderFactory()); return response; } finally { cleanUpAfterExecute(httpMethod); } }
// @Test public void testInheritance() throws Exception { ResteasyDeployment dep = deployment; ClientRequest request = new ClientRequest(generateURL("/datacenters/1")); ClientResponse res = request.get(); Assert.assertEquals(200, res.getStatus()); DataCenter dc = (DataCenter) res.getEntity(DataCenter.class); Assert.assertEquals(dc.getName(), "Bill"); request = new ClientRequest(generateURL("/datacenters/1")); res = request.body("application/xml", dc).put(); Assert.assertEquals(200, res.getStatus()); dc = (DataCenter) res.getEntity(DataCenter.class); Assert.assertEquals(dc.getName(), "Bill"); }
public void run() { try { isFinished = false; ClientRequest request = new ClientRequest(url); ClientResponse<?> response = request.post(); response.releaseConnection(); System.out.println("NPS response: " + response.getStatus()); Assert.assertEquals(201, response.getStatus()); isFinished = true; } catch (Exception e) { System.out.println("Exception " + e); failed = true; } }
@Test public void testNewSubNotBlockedByTimeoutTask() throws Exception { // Default config is 1s interval, 300s timeout. // Create a topic String testName = "AutoAckTopicTest.testNewSubNotBlockedByTimeoutTask"; TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); deployment.setName(testName); manager.getTopicManager().deploy(deployment); // Create a consumer ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/" + testName)); ClientResponse<?> response = request.head(); response.releaseConnection(); Assert.assertEquals(200, response.getStatus()); Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); // Create the pull-subscription itself. ClientResponse<?> res = subscriptions.request().post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); Link sub1 = res.getLocationLink(); Assert.assertNotNull(sub1); Link consumeNext1 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); Assert.assertNotNull(consumeNext1); // Pull on the topic for 8s (long enoguh to guarantee the rest of the test // will pass/fail due to the timeouttask + test operations) AcceptWaitListener awlistener = new AcceptWaitListener(consumeNext1.getHref()); Thread t = new Thread(awlistener); t.start(); // Wait 2 seconds to ensure a new TimeoutTask is running concurrently. Thread.sleep(2000); // Attempt to create a new pull-subscription. Validate that it takes no longer than 2 seconds // (it should take like 20ms, but give it a relatively huge amount of leeway) NewPullSubscriber nps = new NewPullSubscriber(subscriptions.getHref()); Thread npsThread = new Thread(nps); npsThread.start(); Thread.sleep(2000); Assert.assertTrue("NewPullSubscriber did not finish in 2 seconds!", nps.isFinished()); Assert.assertFalse("AcceptWaitListener failed to open connection!", awlistener.isFailed()); Assert.assertFalse("NewPullSubscriber failed to open new subscription!", nps.isFailed()); npsThread.interrupt(); t.interrupt(); }
@Ignore public void testDeleteMember() throws Exception { final String Path = "/members/1"; ClientRequest webResource = new ClientRequest(BASE_URI + Path); ClientResponse response = null; ClientRequest resource = webResource; resource.queryParameter("auth_token", AUTH_TOKEN); response = resource.delete(ClientResponse.class); assertTrue(response.getStatus() == HTTP_STATUS_OK); }
private void _test(ClientRequest request, UriBuilder uriBuilder, String path) { request.clear(); uriBuilder.replacePath(generateURL(path)); try { ClientResponse<String> response = request.get(String.class); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); MultivaluedMap<String, String> headers = response.getHeaders(); for (Object key : headers.keySet()) { System.out.println(key + ": " + headers.get(key)); } response.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void incorrectMediaType_returns406() throws Exception { // given final ClientRequest clientRequest = client.getClientRequestFactory().createRelativeRequest("user"); clientRequest.accept(MediaType.APPLICATION_ATOM_XML_TYPE); // when final ClientResponse<?> resp = clientRequest.get(); final RestfulResponse<JsonRepresentation> restfulResponse = RestfulResponse.of(resp); // then assertThat(restfulResponse.getStatus(), is(RestfulResponse.HttpStatusCode.NOT_ACCEPTABLE)); }
@BeforeClass public static void deployServer() throws InterruptedException { System.out.println("server default charset: " + Charset.defaultCharset()); Map<String, Charset> charsets = Charset.availableCharsets(); Charset charset = null; for (Iterator<String> it = charsets.keySet().iterator(); it.hasNext(); ) { String cs = it.next(); if (!cs.equals(Charset.defaultCharset().name())) { charset = charsets.get(cs); break; } } System.out.println("server using charset: " + charset); System.out.println(TestServerExpand.class.getCanonicalName()); String separator = System.getProperty("file.separator"); String classpath = System.getProperty("java.class.path"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; System.out.println("classpath: " + classpath); System.out.println("path: " + path); ProcessBuilder processBuilder = new ProcessBuilder(path, "-cp", classpath, TestServerNoExpand.class.getCanonicalName()); try { System.out.println("Starting server JVM"); process = processBuilder.start(); System.out.println("Started server JVM"); } catch (IOException e1) { e1.printStackTrace(); } ClientRequest request = new ClientRequest(generateURL("/junk")); ClientResponse<?> response = null; while (true) { try { response = request.get(); if (response.getStatus() == 200) { System.out.println("Server started: " + response.getEntity(String.class)); break; } System.out.println("Waiting on server ..."); } catch (Exception e) { // keep trying } System.out.println("Waiting for server"); Thread.sleep(1000); } }
/** * The purpose of this method is to run the external REST request. * * @param url The url of the RESTful service * @param mediaType The mediatype of the RESTful service */ private String runRequest(String url, MediaType mediaType) { String result = null; System.out.println("==============================================="); System.out.println("URL: " + url); System.out.println("MediaType: " + mediaType.toString()); try { // Using the RESTEasy libraries, initiate a client request // using the url as a parameter ClientRequest request = new ClientRequest(url); // Be sure to set the mediatype of the request request.accept(mediaType); // Request has been made, now let's get the response ClientResponse<String> response = request.get(String.class); // 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 BufferedReader br = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(response.getEntity().getBytes()))); // Loop over the br in order to print out the contents System.out.println("\n*** Response from Server ***\n"); String output = null; while ((output = br.readLine()) != null) { System.out.println(output); result = output; } } catch (ClientProtocolException cpe) { System.err.println(cpe); } catch (IOException ioe) { System.err.println(ioe); } catch (Exception e) { System.err.println(e); } System.out.println("\n==============================================="); return result; }
@Test public void testResource2() throws Exception { ClientRequest request = new ClientRequest(generateURL("/nocache")); try { ClientResponse<?> response = request.get(); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String value = response.getResponseHeaders().getFirst("cache-control"); Assert.assertEquals("no-cache", value); System.out.println("Cache-Control: " + value); CacheControl cc = CacheControl.valueOf(value); Assert.assertTrue(cc.isNoCache()); response.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } }
private BaseClientResponse createClientResponse(ClientRequest request, BrowserCache.Entry entry) { BaseClientResponse response = new BaseClientResponse(new CachedStreamFactory(entry)); response.setStatus(200); response.setHeaders(entry.getHeaders()); response.setProviderFactory(request.getProviderFactory()); return response; }
@Test public void testGetCustomerByIdUsingClientRequest() throws Exception { // deploymentUrl = new URL("http://localhost:8180/test/"); // GET http://localhost:8080/test/rest/customer/1 ClientRequest request = new ClientRequest(deploymentUrl.toString() + RESOURCE_PREFIX + "/customer/1"); request.header("Accept", MediaType.APPLICATION_XML); // we're expecting a String back ClientResponse<String> responseObj = request.get(String.class); Assert.assertEquals(200, responseObj.getStatus()); System.out.println("GET /customer/1 HTTP/1.1\n\n" + responseObj.getEntity()); String response = responseObj.getEntity().replaceAll("<\\?xml.*\\?>", "").trim(); Assert.assertEquals("<customer><id>1</id><name>Acme Corporation</name></customer>", response); }
@Test public void testResource() throws Exception { ClientRequest request = new ClientRequest(generateURL("/maxage")); try { ClientResponse<?> response = request.get(); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus()); System.out.println( "Cache-Control: " + response.getResponseHeaders().getFirst("cache-control")); CacheControl cc = CacheControl.valueOf(response.getResponseHeaders().getFirst("cache-control")); Assert.assertFalse(cc.isPrivate()); Assert.assertEquals(3600, cc.getMaxAge()); response.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void testContentType() throws Exception { String message = "--boo\r\n" + "Content-Disposition: form-data; name=\"foo\"\r\n" + "Content-Transfer-Encoding: 8bit\r\n\r\n" + "bar\r\n" + "--boo--\r\n"; ClientRequest request = new ClientRequest(TEST_URI + "/mime"); request.body("multipart/form-data; boundary=boo", message.getBytes()); ClientResponse<String> response = request.post(String.class); Assert.assertEquals("Status code is wrong.", 20, response.getStatus() / 10); Assert.assertEquals( "Response text is wrong", MediaType.valueOf(TEXT_PLAIN_WITH_CHARSET_UTF_8), MediaType.valueOf(response.getEntity())); }
public Status doGet(String url, MediaType mediaType) throws Exception { ClientRequest request = createClientRequest(url); ClientResponse<String> result = null; try { if (mediaType != null) { request.accept(mediaType); } addParams(request); result = request.get(String.class); LOGGER.info("O servico '{}' respondeu com a seguinte mensagem: {}.", url, result.getEntity()); return result.getResponseStatus(); } catch (Exception e) { LOGGER.warn("Erro durante chamada ao metodo GET da URL: {}.", url, e); throw e; } finally { releaseConnection(result); } }
private void addParams(ClientRequest request) { if (map != null && !map.isEmpty()) { Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { String key; request.queryParameter(key = it.next().toString(), map.get(key)); } } }
@Test public void testRestUrlStartHumanTaskProcess() throws Exception { // create REST request String urlString = new URL( deploymentUrl, deploymentUrl.getPath() + "rest/runtime/test/process/org.jbpm.humantask/start") .toExternalForm(); ClientRequest restRequest = new ClientRequest(urlString); // Get and check response logger.debug(">> [org.jbpm.humantask/start]" + urlString); ClientResponse responseObj = restRequest.post(); assertEquals(200, responseObj.getStatus()); JaxbProcessInstanceResponse processInstance = (JaxbProcessInstanceResponse) responseObj.getEntity(JaxbProcessInstanceResponse.class); long procInstId = processInstance.getId(); urlString = new URL(deploymentUrl, deploymentUrl.getPath() + "rest/task/query?taskOwner=" + USER_ID) .toExternalForm(); restRequest = new ClientRequest(urlString); logger.debug(">> [task/query]" + urlString); responseObj = restRequest.get(); assertEquals(200, responseObj.getStatus()); JaxbTaskSummaryListResponse taskSumlistResponse = (JaxbTaskSummaryListResponse) responseObj.getEntity(JaxbTaskSummaryListResponse.class); long taskId = findTaskId(procInstId, taskSumlistResponse.getResult()); urlString = new URL( deploymentUrl, deploymentUrl.getPath() + "rest/task/" + taskId + "/start?userId=" + USER_ID) .toExternalForm(); restRequest = new ClientRequest(urlString); // Get response logger.debug(">> [task/?/start] " + urlString); responseObj = restRequest.post(); // Check response checkResponse(responseObj); }