org.apache.http.StatusLine Java Examples

The following examples show how to use org.apache.http.StatusLine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpClient.java    From jkes with Apache License 2.0 8 votes vote down vote up
public Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity) throws IOException {
    HttpRequestBase httpRequestBase = buildRequest(method, host, endpoint, params, entity);

    try (CloseableHttpResponse response = httpclient.execute(httpRequestBase)) {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();

        Response resp = Response.builder()
                .statusCode(statusLine.getStatusCode())
                .content(responseEntity == null ? null : EntityUtils.toString(responseEntity))
                .build();

        EntityUtils.consume(responseEntity);

        return resp;
    }
}
 
Example #2
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
private R handleResponse(ResponseParser<R> parser, HttpResponse response) throws IOException
{
    StatusLine statusLine= response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK)
    {
        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
            Charset charset = ContentType.getOrDefault(entity).getCharset();
            Reader reader = new InputStreamReader(entity.getContent(), charset);
            return parser.parseResponse(reader);
        }
        throw new NextcloudApiException("Empty response received");
    }
    throw new NextcloudApiException(String.format("Request failed with %d %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}
 
Example #3
Source File: HttpClientTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testDoHttpHead() throws Exception
{
    CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
    HttpContext context = null;
    when(closeableHttpResponse.getEntity()).thenReturn(null);
    StatusLine statusLine = mock(StatusLine.class);
    int statusCode = HttpStatus.SC_MOVED_PERMANENTLY;
    Header[] headers = { header };
    when(closeableHttpResponse.getAllHeaders()).thenReturn(headers);
    when(statusLine.getStatusCode()).thenReturn(statusCode);
    when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
    when(closeableHttpClient.execute(isA(HttpHead.class), eq(context)))
            .thenAnswer(getAnswerWithSleep(closeableHttpResponse));
    HttpResponse httpResponse = httpClient.doHttpHead(URI_TO_GO);
    assertEquals(HEAD, httpResponse.getMethod());
    assertEquals(URI_TO_GO, httpResponse.getFrom());
    assertEquals(statusCode, httpResponse.getStatusCode());
    assertThat(httpResponse.getResponseTimeInMs(), greaterThan(0L));
    assertThat(httpResponse.getResponseHeaders(), is(equalTo(headers)));
}
 
Example #4
Source File: AsyncHttpResponseHandler.java    From sealtalk-android with MIT License 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example #5
Source File: AsyncHttpResponseHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example #6
Source File: TestCustomRestClient.java    From helix with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetInstanceStoppableCheck() throws IOException {
  MockCustomRestClient customRestClient = new MockCustomRestClient(_httpClient);
  String jsonResponse = "{\n" + "   \"check1\": \"false\",\n" + "   \"check2\": \"true\"\n" + "}";

  HttpResponse httpResponse = mock(HttpResponse.class);
  StatusLine statusLine = mock(StatusLine.class);

  when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
  when(httpResponse.getStatusLine()).thenReturn(statusLine);
  customRestClient.setJsonResponse(jsonResponse);
  when(_httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);

  Map<String, Boolean> healthCheck =
      customRestClient.getInstanceStoppableCheck(HTTP_LOCALHOST, Collections.emptyMap());
  Assert.assertFalse(healthCheck.get("check1"));
  Assert.assertTrue(healthCheck.get("check2"));
}
 
Example #7
Source File: Utils.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
/**
 * This method prepares the mock http response with either the content of the <code>filename</code>
 * or the provided <code>content</code> String.<br>
 * <br>
 * <b>Important</b>: because of the way the content of an HTTP response is consumed, this method MUST be called each time
 * the client is called.
 *
 * @param filename The file to use for the json response.
 * @param httpClient The HTTP client for which we want to mock responses.
 * @param httpCode The http code that the mocked response will return.
 * @param startsWith When set, the body of the GraphQL POST request must start with that String.
 *
 * @return The JSON content of that file.
 *
 * @throws IOException
 */
public static String setupHttpResponse(String filename, HttpClient httpClient, int httpCode, String startsWith) throws IOException {
    String json = IOUtils.toString(Utils.class.getClassLoader().getResourceAsStream(filename), StandardCharsets.UTF_8);

    HttpEntity mockedHttpEntity = Mockito.mock(HttpEntity.class);
    HttpResponse mockedHttpResponse = Mockito.mock(HttpResponse.class);
    StatusLine mockedStatusLine = Mockito.mock(StatusLine.class);

    byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
    Mockito.when(mockedHttpEntity.getContent()).thenReturn(new ByteArrayInputStream(bytes));
    Mockito.when(mockedHttpEntity.getContentLength()).thenReturn(new Long(bytes.length));

    Mockito.when(mockedHttpResponse.getEntity()).thenReturn(mockedHttpEntity);

    if (startsWith != null) {
        GraphqlQueryMatcher matcher = new GraphqlQueryMatcher(startsWith);
        Mockito.when(httpClient.execute(Mockito.argThat(matcher))).thenReturn(mockedHttpResponse);
    } else {
        Mockito.when(httpClient.execute((HttpUriRequest) Mockito.any())).thenReturn(mockedHttpResponse);
    }

    Mockito.when(mockedStatusLine.getStatusCode()).thenReturn(httpCode);
    Mockito.when(mockedHttpResponse.getStatusLine()).thenReturn(mockedStatusLine);

    return json;
}
 
Example #8
Source File: ApacheHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public HttpResponse build() {
	ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
	StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
	HttpResponse response = new BasicHttpResponse(statusLine);

	InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(is);
	response.setEntity(entity);

	for (Map.Entry<String, List<String>> header : headers.entrySet()) {
		for (String value : header.getValue()) {
			response.addHeader(header.getKey(), value);
		}
	}

	return response;
}
 
Example #9
Source File: StateV1HealthUpdaterTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private ServiceStatusInfo getServiceStatusInfoFromJsonResponse(String content)
        throws IOException {
    CloseableHttpClient client = mock(CloseableHttpClient.class);

    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(client.execute(any())).thenReturn(response);

    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);

    when(statusLine.getStatusCode()).thenReturn(200);

    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    try (StateV1HealthUpdater updater = makeUpdater(client, entry -> content)) {
        when(httpEntity.getContentLength()).thenReturn((long) content.length());
        updater.run();
        return updater.getServiceStatusInfo();
    }
}
 
Example #10
Source File: AsyncHttpResponseHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example #11
Source File: RESTQueryPublisherTest.java    From bullet-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendResultUrlPutInMetadataAckPreserved() throws Exception {
    CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
    StatusLine mockStatusLine = mock(StatusLine.class);
    doReturn(200).when(mockStatusLine).getStatusCode();
    doReturn(mockStatusLine).when(mockResponse).getStatusLine();
    doReturn(mockResponse).when(mockClient).execute(any());
    RESTQueryPublisher publisher = new RESTQueryPublisher(mockClient, "my/custom/query/url", "my/custom/url", 5000);
    PubSubMessage actual = publisher.send(new PubSubMessage("foo", CONTENT, Metadata.Signal.ACKNOWLEDGE));

    Assert.assertTrue(actual.getMetadata() instanceof RESTMetadata);
    RESTMetadata actualMeta = (RESTMetadata) actual.getMetadata();
    Assert.assertEquals(actualMeta.getUrl(), "my/custom/url");

    ArgumentCaptor<HttpPost> argumentCaptor = ArgumentCaptor.forClass(HttpPost.class);
    verify(mockClient).execute(argumentCaptor.capture());
    HttpPost post = argumentCaptor.getValue();
    String actualMessage = EntityUtils.toString(post.getEntity(), RESTPubSub.UTF_8);
    String expectedMessage = "{'id':'foo','content':[98,97,114],'metadata':{'url':'my/custom/url','signal':ACKNOWLEDGE,'content':null,'created':" + actual.getMetadata().getCreated() + "}}";
    String actualHeader = post.getHeaders(RESTPublisher.CONTENT_TYPE)[0].getValue();
    String expectedHeader = RESTPublisher.APPLICATION_JSON;
    assertJSONEquals(actualMessage, expectedMessage);
    Assert.assertEquals(expectedHeader, actualHeader);
    Assert.assertEquals("my/custom/query/url", post.getURI().toString());
}
 
Example #12
Source File: FutureCallbackWrapper.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
private void finishSpan(@Nullable Exception e) {
    // start by reading the volatile field
    final Span localSpan = span;
    try {
        if (context != null) {
            Object responseObject = context.getAttribute(HttpCoreContext.HTTP_RESPONSE);
            if (responseObject instanceof HttpResponse) {
                StatusLine statusLine = ((HttpResponse) responseObject).getStatusLine();
                if (statusLine != null) {
                    span.getContext().getHttp().withStatusCode(statusLine.getStatusCode());
                }
            }
        }
        localSpan.captureException(e);
    } finally {
        localSpan.end();
    }
}
 
Example #13
Source File: CardcastService.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
@Nullable
private String getUrlContent(String urlStr) throws IOException {
    HttpResponse resp = client.execute(new HttpGet(urlStr));

    StatusLine sl = resp.getStatusLine();
    if (sl.getStatusCode() != HttpStatus.SC_OK) {
        LOG.error(String.format("Got HTTP response code %s from Cardcast for %s", sl, urlStr));
        return null;
    }

    HttpEntity entity = resp.getEntity();
    String contentType = entity.getContentType().getValue();
    if (!Objects.equals(contentType, "application/json")) {
        LOG.error(String.format("Got content-type %s from Cardcast for %s", contentType, urlStr));
        return null;
    }

    return EntityUtils.toString(entity);
}
 
Example #14
Source File: HttpUtil.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static String Delete(String endpoint, Map<String, String> data) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        HttpDelete httpDelete = new HttpDelete(endpoint + "?" + urlencode(data));
        httpDelete.setHeader("user-agent", "Pushfish-android");
        HttpResponse response = (new DefaultHttpClient()).execute(httpDelete);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw new IOException("Get failed with error code " + statusLine.getStatusCode());
        }
        response.getEntity().writeTo(out);
        return out.toString();
    } finally {
        out.close();
    }
}
 
Example #15
Source File: HttpRequestException.java    From caravan with Apache License 2.0 6 votes vote down vote up
public HttpRequestException(CloseableHttpResponse response) {
    super(toErrorMessage(response));

    StatusLine statusLine = response.getStatusLine();
    if (statusLine == null)
        return;

    _statusCode = statusLine.getStatusCode();
    _reasonPhrase = statusLine.getReasonPhrase();
    _protocolVersion = statusLine.getProtocolVersion();
    _responseHeaders = response.getAllHeaders();

    HttpEntity entity = response.getEntity();
    if (entity == null)
        return;

    try (InputStream is = entity.getContent();) {
        _responseBody = EntityUtils.toString(entity);
    } catch (Throwable ex) {

    }
}
 
Example #16
Source File: BitlyUrlService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Makes a GET request to the given address. Any query string should be appended already.
 * @param address	the fully qualified URL to make the request to
 * @return
 */
private String doGet(String address){
	try {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(address);
		HttpResponse response = httpclient.execute(httpget);
		
		//check reponse code
		StatusLine status = response.getStatusLine();
		if(status.getStatusCode() != 200) {
			log.error("Error shortening URL. Status: " + status.getStatusCode() + ", reason: " + status.getReasonPhrase());
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
		    return EntityUtils.toString(entity);
		}
		
	} catch (Exception e) {
		log.error(e.getClass() + ":" + e.getMessage());
	} 
	return null;
}
 
Example #17
Source File: ServiceResponseHandler.java    From snowflake-ingest-java with Apache License 2.0 6 votes vote down vote up
/**
 * handleExceptionStatusCode - throws the correct error for a status
 *
 * @param statusLine the status line we want to check
 * @throws BackOffException -- if we have a 503 exception
 * @throws IOException      - if we don't know what it is
 */
private static void handleExceptionalStatus(StatusLine statusLine,
                                            HttpResponse response)
                    throws IOException, IngestResponseException
{
  //if we have a 503 exception throw a backoff
  switch (statusLine.getStatusCode())
  {
    //If we have a 503, BACKOFF
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
      LOGGER.warn("503 Status hit, backoff");
      throw new BackOffException();

      //We don't know how to respond now...
    default:
      LOGGER.error("Status code {} found in response from service",
                   statusLine.getStatusCode());
      String blob = EntityUtils.toString(response.getEntity());
      throw new IngestResponseException(statusLine.getStatusCode(),
                                        IngestResponseException
                                        .IngestExceptionBody.parseBody(blob));
  }

}
 
Example #18
Source File: HttpServiceTest.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testQueryDruidDatasourcesBadResponse() throws DruidException, IOException {
    mockGets();
    when(http.queryDruidDatasources(any(DruidCluster.class))).thenCallRealMethod();
    DruidCluster cluster = mock(DruidCluster.class);
    String url = "http://battlelog.battlefield.com/bf3/";
    when(cluster.getBrokerUrl()).thenReturn(url);
    StatusLine sl = mock(StatusLine.class);
    when(sl.getStatusCode()).thenReturn(500);
    when(res.getStatusLine()).thenReturn(sl);
    when(client.execute(any(HttpGet.class))).thenReturn(res);
    try {
        http.queryDruidDatasources(cluster);
    } catch (DruidException e) {
        assertEquals(e.getMessage(), "Get request to cluster datasources endpoint failed: 500");
        verify(get, times(1)).releaseConnection();
        return;
    }
    fail();
}
 
Example #19
Source File: JSON.java    From validatar with Apache License 2.0 6 votes vote down vote up
/**
 * Makes the request and returns the String response using the given client, request and query.
 *
 * @param client The HttpClient to use.
 * @param request The HttpUriRequest to make.
 * @param query The Query object being run.
 * @return The String response of the call, null if exception (query is failed).
 */
String makeRequest(HttpClient client, HttpUriRequest request, Query query) {
    try {
        log.info("{}ing to {} with headers {}", request.getMethod(), request.getURI(), request.getAllHeaders());
        HttpResponse response = client.execute(request);
        StatusLine line = response.getStatusLine();
        log.info("Received {}: {} with headers {}", line.getStatusCode(), line.getReasonPhrase(), response.getAllHeaders());
        String data = EntityUtils.toString(response.getEntity());
        log.info("Received response as string {}", data);
        return data;
    } catch (IOException ioe) {
        log.error("Could not execute request", ioe);
        query.setFailure("Could not execute request");
        query.addMessage(ioe.toString());
    } catch (NullPointerException npe) {
        log.error("Received no response", npe);
        query.setFailure("Received no response");
        query.addMessage(npe.toString());
    }
    return null;
}
 
Example #20
Source File: HttpUrlConnStack.java    From simple_net_framework with MIT License 6 votes vote down vote up
private Response fetchResponse(HttpURLConnection connection) throws IOException {

        // Initialize HttpResponse with data from the HttpURLConnection.
        ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
        int responseCode = connection.getResponseCode();
        if (responseCode == -1) {
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }
        // 状态行数据
        StatusLine responseStatus = new BasicStatusLine(protocolVersion,
                connection.getResponseCode(), connection.getResponseMessage());
        // 构建response
        Response response = new Response(responseStatus);
        // 设置response数据
        response.setEntity(entityFromURLConnwction(connection));
        addHeadersToResponse(response, connection);
        return response;
    }
 
Example #21
Source File: HttpClientBasic.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
private void processResponse(CloseableHttpResponse response) 
            throws UnsupportedOperationException, IOException {
        try {
            // 获取响应头
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                _logger.info(header.getName() + ":" + header.getValue());
            }
            
            // 获取状态信息
            StatusLine sl =response.getStatusLine();
            _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", 
                    sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
            
            // 获取响应内容
            HttpEntity entity = response.getEntity();
            _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", 
                    null == entity.getContentType() ? "" : entity.getContentType().getValue(), 
                    entity.getContentLength(),
                    null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
            _logger.info(EntityUtils.toString(entity, _charset));
//            _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
        } finally {
            response.close();
        }
    }
 
Example #22
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private <X extends Throwable> void logContentOrThrow(@Nullable final Content content,
                                                     final Context context,
                                                     @Nullable final StatusLine statusLine,
                                                     final X exception) throws X
{
  String logMessage = buildLogContentMessage(content, statusLine);
  String repositoryName = context.getRepository().getName();
  String contextUrl = getUrl(context);

  if (content != null) {
    log.debug(logMessage, exception, repositoryName, contextUrl, statusLine);
  }
  else {
    if (exception instanceof RemoteBlockedIOException) {
      // trace because the blocked status of a repo is typically discoverable in the UI and other log messages
      log.trace(logMessage, exception, repositoryName, contextUrl, statusLine, exception);
    }
    else if (log.isDebugEnabled()) {
      log.warn(logMessage, exception, repositoryName, contextUrl, statusLine, exception);
    }
    else {
      log.warn(logMessage, exception, repositoryName, contextUrl, statusLine);
    }
    throw exception;
  }
}
 
Example #23
Source File: HttpRequest.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
public synchronized static String postData(String url) throws Exception {
       CloseableHttpClient httpclient = HttpClients.createDefault();
       HttpPost httpPost = new HttpPost(url);
       CloseableHttpResponse response = httpclient.execute(httpPost);
       String result = "";
       try {
           StatusLine statusLine = response.getStatusLine();
           HttpEntity entity = response.getEntity();
           // do something useful with the response body
           if (entity != null) {
               result = EntityUtils.toString(entity, "UTF-8");
           }else{
               LogKit.error("httpRequest postData2 error entity = null code = "+statusLine.getStatusCode());
           }
           // and ensure it is fully consumed
           //消耗掉response
           EntityUtils.consume(entity);
       } finally {
           response.close();
       }

       return result;
}
 
Example #24
Source File: ConfluenceRestClientTest.java    From confluence-publisher with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient recordHttpClientForMultipleResponsesWithContentAndStatusCode(List<String> contentPayloads, List<Integer> statusCodes) throws IOException {
    CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class);

    List<HttpEntity> httpEntities = contentPayloads.stream().map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList());
    when(httpResponseMock.getEntity())
            .thenReturn(httpEntities.get(0), httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1]));

    List<StatusLine> statusLines = statusCodes.stream().map((statusCode) -> recordStatusLine(statusCode, null)).collect(toList());
    when(httpResponseMock.getStatusLine())
            .thenReturn(statusLines.get(0), statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1]));

    CloseableHttpClient httpClientMock = anyCloseableHttpClient();
    when(httpClientMock.execute(any(HttpRequestBase.class))).thenReturn(httpResponseMock);

    return httpClientMock;
}
 
Example #25
Source File: ElasticSearchFilter.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Tuple<Boolean, String> isHealthy() {
  try {
    final Response response = restClient.performRequest(METHOD_GET, "_cluster/health");
    final StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() != 200) {
      return Tuple.tuple(false, "Request failed: " + statusLine.getReasonPhrase());
    }

    final JsonNode jsonNode = OBJECT_MAPPER.readTree(response.getEntity().getContent());
    final String status = jsonNode.get("status").asText();
    if (status.equals("red")) {
      return Tuple.tuple(false, "Elasticsearch cluster status is 'red'.");
    }

    return Tuple.tuple(true, "Elasticsearch filter is healthy.");
  } catch (IOException e) {
    LOG.error("Elasticsearch request failed", e);
    return Tuple.tuple(false, "Request threw an exception: " + e.getMessage());
  }
}
 
Example #26
Source File: ActionResult.java    From curly with Apache License 2.0 6 votes vote down vote up
public void processHttpResponse(CloseableHttpResponse httpResponse, ResultType resultType) throws IOException {
    StatusLine status = httpResponse.getStatusLine();
    String statusKey = COMPLETED_SUCCESSFUL;
    boolean successfulResponseCode = false;
    if (status.getStatusCode() >= 200 && status.getStatusCode() < 400) {
        successfulResponseCode = true;
    } else {
        statusKey = COMPLETED_UNSUCCESSFUL;
    }
    String resultMessage = "";
    if (resultType == ResultType.HTML) {
        ParsedResponseMessage message = extractHtmlMessage(httpResponse).orElse(UNKNOWN_RESPONSE);
        if (message.type == RESULT_TYPE.FAIL) {
            successfulResponseCode = false;
            statusKey = COMPLETED_UNSUCCESSFUL;
        }
        resultMessage = status.getReasonPhrase() + " / " + message.message;
    } else {
        resultMessage = status.getReasonPhrase();
    }
    percentSuccess().unbind();
    percentSuccess().set(successfulResponseCode ? 1 : 0);
    invalidateBindings();
    setStatus(statusKey, status.getStatusCode(), resultMessage);
}
 
Example #27
Source File: ServiceResponseHandler.java    From snowflake-ingest-java with Apache License 2.0 5 votes vote down vote up
/**
 * unmarshallIngestResponse
 * Given an HttpResponse object - attempts to deserialize it into
 * an IngestResponse object
 *
 * @param response the HTTPResponse we want to distill into an IngestResponse
 * @return An IngestResponse with all of the parsed out information
 * @throws IOException      - if our entity is somehow corrupt or we can't get it
 * @throws BackOffException if we have a 503 response
 */
public static IngestResponse unmarshallIngestResponse(HttpResponse response)
    throws IOException, IngestResponseException
{
  //we can't unmarshall a null response
  if (response == null)
  {
    LOGGER.warn("Null argument passed to unmarshallIngestResponse");
    throw new IllegalArgumentException();
  }

  //Grab the status line from the response
  StatusLine statusLine = response.getStatusLine();

  //If we didn't get a good status code, handle it
  if (!isStatusOK(statusLine))
  {

    //Exception status
    LOGGER.warn("Exceptional Status Code found in unmarshallInsert Response  - {}",
        statusLine.getStatusCode());

    handleExceptionalStatus(statusLine, response);
    return null;
  }

  //grab the response entity
  String blob = EntityUtils.toString(response.getEntity());

  //Read out the blob entity into a class
  return mapper.readValue(blob, IngestResponse.class);
}
 
Example #28
Source File: TestCustomRestClient.java    From helix with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IOException.class)
public void testGetPartitionStoppableCheck_when_response_empty() throws IOException {
  MockCustomRestClient customRestClient = new MockCustomRestClient(_httpClient);
  HttpResponse httpResponse = mock(HttpResponse.class);
  StatusLine statusLine = mock(StatusLine.class);

  when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NOT_FOUND);
  when(httpResponse.getStatusLine()).thenReturn(statusLine);
  when(_httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);
  customRestClient.setJsonResponse("");

  customRestClient.getPartitionStoppableCheck(HTTP_LOCALHOST,
      ImmutableList.of("db0", "db1"), Collections.emptyMap());
}
 
Example #29
Source File: SuccessWhaleExceptionTest.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
private static HttpResponse mockHttpResponse (final int code, final String statusMsg, final String body) throws IOException {
	final StatusLine statusLine = mock(StatusLine.class);
	when(statusLine.getStatusCode()).thenReturn(code);
	when(statusLine.getReasonPhrase()).thenReturn(statusMsg);

	final HttpEntity entity = mock(HttpEntity.class);
	when(entity.getContent()).thenReturn(new ByteArrayInputStream(body.getBytes()));

	final HttpResponse resp = mock(HttpResponse.class);
	when(resp.getStatusLine()).thenReturn(statusLine);
	when(resp.getEntity()).thenReturn(entity);
	return resp;
}
 
Example #30
Source File: LUISGrammarEvaluator.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object getSemanticInterpretation(final DataModel model,
        String utterance) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    if (PROXY_HOST != null) {
        HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
        builder.setProxy(proxy);
    }
    try (CloseableHttpClient client = builder.build()){
        final URIBuilder uribuilder = new URIBuilder(grammarUri);
        uribuilder.addParameter("subscription-key", subscriptionKey);
        uribuilder.addParameter("q", utterance);
        final URI uri = uribuilder.build();
        final HttpGet request = new HttpGet(uri);
        final HttpResponse response = client.execute(request);
        final StatusLine statusLine = response.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status != HttpStatus.SC_OK) {
            final String reasonPhrase = statusLine.getReasonPhrase();
            LOGGER.error("error accessing '" + uri +"': " +
                    reasonPhrase + " (HTTP error code "
                    + status + ")");
            return null;
        }
        final HttpEntity entity = response.getEntity();
        final InputStream input = entity.getContent();
        final Object interpretation = parseLUISResponse(model, input);
        return interpretation;
    } catch (IOException | URISyntaxException | ParseException | SemanticError e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
}