List of usage examples for org.apache.http.message BasicStatusLine BasicStatusLine
public BasicStatusLine(ProtocolVersion protocolVersion, int i, String str)
From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportPingTest.java
@Test public void testResponseStatusCodeOf100ThrowsExpectedException() throws Exception { expectedException.expect(CommunicationErrorException.class); expectedException.expectMessage("Expected Message"); when(response.getStatusLine())/*from w w w .j a va 2s . c o m*/ .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 100, "Expected Message")); transport.ping(new PingRequest()); }
From source file:org.finra.dm.tools.common.databridge.DataBridgeWebClientTest.java
@Test public void testGetBusinessObjectData400BadContentThrows() throws Exception { int expectedStatusCode = 400; String expectedReasonPhrase = "testReasonPhrase"; String expectedErrorMessage = "invalid xml"; CloseableHttpResponse httpResponse = new MockCloseableHttpResponse( new BasicStatusLine(HttpVersion.HTTP_1_1, expectedStatusCode, expectedReasonPhrase)); httpResponse.setEntity(new StringEntity(expectedErrorMessage)); String actionDescription = "testActionDescription"; try {//from www. ja va 2 s.c o m dataBridgeWebClient.getBusinessObjectData(httpResponse, actionDescription); Assert.fail("expected HttpErrorResponseException, but no exception was thrown"); } catch (Exception e) { Assert.assertEquals("thrown exception type", HttpErrorResponseException.class, e.getClass()); HttpErrorResponseException httpErrorResponseException = (HttpErrorResponseException) e; Assert.assertEquals("httpErrorResponseException responseMessage", expectedErrorMessage, httpErrorResponseException.getResponseMessage()); Assert.assertEquals("httpErrorResponseException statusCode", expectedStatusCode, httpErrorResponseException.getStatusCode()); Assert.assertEquals("httpErrorResponseException statusDescription", expectedReasonPhrase, httpErrorResponseException.getStatusDescription()); Assert.assertEquals("httpErrorResponseException message", "Failed to " + actionDescription, httpErrorResponseException.getMessage()); } }
From source file:de.stklcode.jvault.connector.HTTPVaultConnectorOfflineTest.java
/** * Test exceptions thrown during request. *///from w w w. jav a 2s. com @Test public void requestExceptionTest() throws IOException { HTTPVaultConnector connector = new HTTPVaultConnector("http://127.0.0.1", null, 0, 250); // Test invalid response code. final int responseCode = 400; mockResponse(responseCode, "", ContentType.APPLICATION_JSON); try { connector.getHealth(); fail("Querying health status succeeded on invalid instance"); } catch (Exception e) { assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code")); assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode)); assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue())); } // Simulate permission denied response. mockResponse(responseCode, "{\"errors\":[\"permission denied\"]}", ContentType.APPLICATION_JSON); try { connector.getHealth(); fail("Querying health status succeeded on invalid instance"); } catch (Exception e) { assertThat("Unexpected type of exception", e, instanceOf(PermissionDeniedException.class)); } // Test exception thrown during request. when(httpMock.execute(any())).thenThrow(new IOException("Test Exception")); try { connector.getHealth(); fail("Querying health status succeeded on invalid instance"); } catch (Exception e) { assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); assertThat("Unexpected exception message", e.getMessage(), is("Unable to read response")); assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class)); } // Now simulate a failing request that succeeds on second try. connector = new HTTPVaultConnector("https://127.0.0.1", null, 1, 250); doReturn(responseMock).doReturn(responseMock).when(httpMock).execute(any()); doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "")) .doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "")) .doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "")) .doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "")).when(responseMock) .getStatusLine(); when(responseMock.getEntity()).thenReturn(new StringEntity("{}", ContentType.APPLICATION_JSON)); try { connector.getHealth(); } catch (Exception e) { fail("Request failed unexpectedly: " + e.getMessage()); } }
From source file:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java
public void canUploadPartValidatesResponseCode() throws IOException { final UUID uploadId = UUID.randomUUID(); final String partsDirectory = "/test/uploads/a/abcdef"; final String path = "/test/stor/object"; final ServerSideMultipartUpload upload = new ServerSideMultipartUpload(uploadId, path, partsDirectory); final ServerSideMultipartManager mngr = buildMockManager( new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"), String.format("{\"code\":\"%s\", \"message\":\"%s\"}", MantaErrorCode.SERVICE_UNAVAILABLE_ERROR.getCode(), "manta is unable to serve this request")); Assert.assertThrows(MantaMultipartException.class, () -> { mngr.uploadPart(upload, 1, new byte[0]); });//w w w .java 2s.com }
From source file:com.seleritycorp.common.base.http.client.FileHttpClient.java
private StatusLine createStatusLine(int statusCode, String reason) { return new BasicStatusLine(protocolVersion, statusCode, reason); }
From source file:name.persistent.behaviours.RemoteDomainSupport.java
private HttpResponse resolveRemotePURL(InetSocketAddress addr, String source, String qs, String accept, String language, Set<String> via) throws IOException, InterruptedException { HTTPObjectClient client = HTTPObjectClient.getInstance(); String url = qs == null ? source : source + "?" + qs; BasicHttpRequest req = new BasicHttpRequest("GET", url); if (accept != null) { req.setHeader("Accept", accept); }//from w w w. j a va2 s . c o m if (language != null) { req.setHeader("Accept-Language", language); } StringBuilder sb = new StringBuilder(); for (String v : via) { if (v.contains(VIA) && (v.endsWith(VIA) || v.contains(VIA + ","))) throw new InternalServerError("Request Loop Detected\n" + via + "\n" + VIA); if (sb.length() > 0) { sb.append(","); } sb.append(v); } sb.append(VIA); req.setHeader("Via", sb.toString()); try { HttpResponse resp = client.service(addr, req); if (!resp.containsHeader("Via")) { String original = "1.1 " + addr.getHostName(); if (addr.getPort() != 80 && addr.getPort() != 443) { original += ":" + addr.getPort(); } resp.addHeader("Via", original); } StatusLine status = resp.getStatusLine(); if (status.getStatusCode() >= 500) { ProtocolVersion ver = status.getProtocolVersion(); String phrase = status.getReasonPhrase(); resp.setStatusLine(new BasicStatusLine(ver, 502, phrase)); blackList.put(addr, Boolean.TRUE); return resp; } else { return resp; } } catch (GatewayTimeout e) { blackList.put(addr, Boolean.TRUE); return null; } }
From source file:org.elasticsearch.client.RestClientSingleHostTests.java
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))) .thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock .getArguments()[0]; HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock .getArguments()[3]; HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest(); //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException()); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException()); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); HttpResponse httpResponse = new BasicHttpResponse(statusLine); //return the same body that was sent if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { assertTrue( "the entity is not repeatable, cannot set it to the response directly", entity.isRepeatable()); httpResponse.setEntity(entity); }//from www . j av a 2s. c o m } //return the same headers that were sent httpResponse.setHeaders(request.getAllHeaders()); futureCallback.completed(httpResponse); } return null; } }); defaultHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header-default"); httpHost = new HttpHost("localhost", 9200); failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, defaultHeaders, new HttpHost[] { httpHost }, null, failureListener); }
From source file:org.callimachusproject.auth.AuthorizationManager.java
public HttpResponse authorize(ResourceOperation request, Set<Group> groups, CalliContext ctx) throws OpenRDFException, IOException { InetAddress clientAddr = ctx.getClientAddr(); long now = ctx.getReceivedOn(); String m = request.getMethod(); RDFObject target = request.getRequestedResource(); String or = request.getVaryHeader("Origin"); Map<String, String[]> map = getAuthorizationMap(request, now, clientAddr, groups); List<String> from = getAgentFrom(map.get("via")); if (isAnonymousAllowed(from, groups)) return null; // loop through first to see if further authorisation is needed DetachedRealm realm = getRealm(request); HttpResponse unauth = null;//from w ww . j ava 2s .co m boolean validOrigin = false; boolean noRealm = true; if (realm != null) { String cred = null; Collection<String> allowed = realm.allowOrigin(); try { if (or == null || isOriginAllowed(allowed, or)) { ObjectConnection con = ctx.getObjectConnection(); cred = realm.authenticateRequest(m, target, map, con); if (cred != null && isMember(cred, from, groups)) { ctx.setCredential(cred); return null; // this request is good } } } catch (TooManyRequests e) { StringEntity body = new StringEntity(e.getDetailMessage(), Charset.forName("UTF-8")); body.setContentType("text/plain"); BasicStatusLine line = new BasicStatusLine(HttpVersion.HTTP_1_1, e.getStatusCode(), e.getShortMessage()); HttpResponse resp = new BasicHttpResponse(line); resp.setHeader("Content-Type", "text/plain;charset=UTF-8"); for (Header hd : e.getResponseHeaders()) { resp.addHeader(hd); } resp.setEntity(body); return resp; } noRealm = false; validOrigin = or == null || isOriginAllowed(allowed, or); try { if (cred == null) { unauth = choose(unauth, realm.unauthorized(m, target, map, request.getEntity())); } else { unauth = choose(unauth, realm.forbidden(m, target, map)); } } catch (ResponseException exc) { if (unauth != null) { EntityUtils.consumeQuietly(unauth.getEntity()); } throw exc; } catch (Exception exc) { logger.error(exc.toString(), exc); } } if (unauth != null) return unauth; if (noRealm) { logger.info("No active realm for {}", request); } else if (!validOrigin) { logger.info("Origin {} not allowed for {}", or, request); } StringEntity body = new StringEntity("Forbidden", Charset.forName("UTF-8")); body.setContentType("text/plain"); HttpResponse resp = new BasicHttpResponse(_403); resp.setHeader("Content-Type", "text/plain;charset=UTF-8"); resp.setEntity(body); return resp; }
From source file:org.finra.herd.tools.common.databridge.DataBridgeWebClientTest.java
@Test public void testGetBusinessObjectDataStorageFilesCreateResponse200ValidResponseHttpResponseThrowsExceptionOnClose() throws Exception { CloseableHttpResponse httpResponse = new MockCloseableHttpResponse( new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), true); httpResponse.setEntity(/* www .j ava2 s . co m*/ new StringEntity(xmlHelper.objectToXml(new BusinessObjectDataStorageFilesCreateResponse()))); executeWithoutLogging(DataBridgeWebClient.class, () -> { BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse = dataBridgeWebClient .getBusinessObjectDataStorageFilesCreateResponse(httpResponse); assertNotNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse); }); }
From source file:com.telefonica.iot.cygnus.backends.http.HttpBackendTest.java
/** * [HttpBackend.createJsonResponse] -------- A JsonResponse object is not * created if the content-type header does not contains 'application/json'. */// w ww . j av a 2 s .c om @Test public void testCreateJsonResponseNoJsonPayload() { System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]") + "-------- A JsonResponse object is not created if the content-type header does not contains " + "'application/json'"); HttpResponseFactory factory = new DefaultHttpResponseFactory(); HttpResponse response = factory .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null); String responseStr = "{\"somefield1\":\"somevalue1\",\"somefield2\":\"somevalue2\"," + "\"somefield3\":\"somevalue3\"}"; try { response.setEntity(new StringEntity(responseStr)); } catch (UnsupportedEncodingException e) { System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]") + "- FAIL - There was some problem when creating the HttpResponse object"); throw new AssertionError(e.getMessage()); } // try catch response.addHeader("Content-Type", "text/html"); response.addHeader("Location", "http://someurl.org"); HttpBackend httpBackend = new HttpBackendImpl(host, port, false, false, null, null, null, null, maxConns, maxConnsPerRoute); try { JsonResponse jsonRes = httpBackend.createJsonResponse(response); try { assertEquals(null, jsonRes.getJsonObject()); System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]") + "- OK - The JsonResponse object could not be created with a 'text/html' content type " + "header"); } catch (AssertionError e) { System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]") + "- FAIL - The JsonResponse object was created with a 'text/html' content type header"); throw e; } // try catch } catch (Exception e) { System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]") + "- FAIL - There was some problem when creating the JsonResponse object"); throw new AssertionError(e.getMessage()); } // try catch }