Example usage for org.apache.http.client.methods CloseableHttpResponse getStatusLine

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getStatusLine.

Prototype

StatusLine getStatusLine();

Source Link

Usage

From source file:com.adobe.ags.curly.model.ActionResult.java

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;/*w  w w. j  a  va  2 s.c o m*/
    } 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);
}

From source file:org.jboss.additional.testsuite.jdkall.present.ejb.sfsb.SfsbTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)// w  w w  .ja  v  a  2s  .c  o m
public void sfsbTest(@ArquillianResource URL url) throws Exception {
    URL testURL = new URL(url.toString() + "sfsbCache?product=makaronia&quantity=10");

    final HttpGet request = new HttpGet(testURL.toString());
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(request);
        Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK,
                response.getStatusLine().getStatusCode());
        Thread.sleep(1000);
        response = httpClient.execute(request);
        Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK,
                response.getStatusLine().getStatusCode());
    } finally {
        IOUtils.closeQuietly(response);
        httpClient.close();
    }
}

From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java

/**
 * {@inheritDoc}/*from   www  .j  a v  a  2  s  . c o m*/
 */
@Override
public boolean sendNotification(String apiKey, String applicationId, String description, String revision,
        String changelog, String user) throws IOException {
    URI url = null;
    try {
        url = new URI(API_URL + DEPLOYMENT_ENDPOINT);
    } catch (URISyntaxException e) {
        // no need to handle this
    }
    HttpPost request = new HttpPost(url);
    setHeaders(request, apiKey);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("deployment[application_id]", applicationId));
    params.add(new BasicNameValuePair("deployment[description]", description));
    params.add(new BasicNameValuePair("deployment[revision]", revision));
    params.add(new BasicNameValuePair("deployment[changelog]", changelog));
    params.add(new BasicNameValuePair("deployment[user]", user));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
    request.setEntity(entity);
    CloseableHttpClient client = getHttpClient(url);
    try {
        CloseableHttpResponse response = client.execute(request);
        return HttpStatus.SC_CREATED == response.getStatusLine().getStatusCode();
    } finally {
        client.close();
    }
}

From source file:org.wso2.carbon.ml.analysis.test.GetAnalysesTestCase.java

/**
 * Test retrieving all analyzes.//from  w w  w.ja va 2s. c  o  m
 * 
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Get all analyses")
public void testGetAllAnalyzes() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/analyses/");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:com.hazelcast.config.XmlConfigSchemaLocationTest.java

private int getResponseCode(String url) throws Exception {
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {/*w  ww  .  ja  va 2s.co m*/
        response = httpClient.execute(httpGet);
        return response.getStatusLine().getStatusCode();
    } finally {
        IOUtil.closeResource(response);
    }
}

From source file:org.keycloak.testsuite.oauth.LoginStatusIframeEndpointTest.java

@Test
public void checkIframeCache() throws IOException {
    String version = testingClient.server().fetch(new ServerVersion());

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot()
                + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html");
        CloseableHttpResponse response = client.execute(get);

        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("no-cache, must-revalidate, no-transform, no-store",
                response.getHeaders("Cache-Control")[0].getValue());

        get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot()
                + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html?version=" + version);
        response = client.execute(get);//from  ww  w  .j a va 2s .  c  o  m

        assertEquals(200, response.getStatusLine().getStatusCode());
        assertTrue(response.getHeaders("Cache-Control")[0].getValue().contains("max-age"));
    }
}

From source file:com.hp.octane.integrations.services.rest.SSCRestClientImpl.java

@Override
public CloseableHttpResponse sendGetRequest(SSCProjectConfiguration sscProjectConfiguration, String url) {
    HttpGet request = new HttpGet(url);
    request.addHeader("Authorization", "FortifyToken " + getToken(sscProjectConfiguration, false));
    request.addHeader("Accept", "application/json");
    request.addHeader("Host", getNetHost(sscProjectConfiguration.getSSCUrl()));

    CloseableHttpResponse response;
    try {/*  ww  w .j  a  va 2  s.c  o  m*/
        response = httpClient.execute(request);
        //401. Access..
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            request.removeHeaders("Authorization");
            request.addHeader("Authorization", "FortifyToken " + getToken(sscProjectConfiguration, true));
            response = httpClient.execute(request);
        }
        return response;
    } catch (IOException e) {
        throw new TemporaryException(e);
    } catch (Exception e) {
        throw new PermanentException(e);
    }
}

From source file:org.wso2.carbon.ml.project.test.GetProjectsTestCase.java

/**
 * Test retrieving a project./*w  w w  .j  ava  2 s  . co  m*/
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Retrieve a project")
public void testGetProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/projects/" + MLIntegrationTestConstants.PROJECT_NAME);
    assertEquals("Unexpected response recieved", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:gobblin.compaction.audit.PinotAuditCountHttpClient.java

/**
 * A thread-safe method which fetches a tier-to-count mapping.
 * The returned json object from Pinot contains below information
 * {//ww  w  .  ja  va  2s .c o  m
 *    "aggregationResults":[
 *      {
 *          "groupByResult":[
 *            {
 *              "value":"172765137.00000",
 *              "group":[
 *                "kafka-08-tracking-local"
 *              ]
 *            }
 *          ]
 *      }
 *    ],
 *    "exceptions":[
 *    ]
 *    .....
 * }
 * @param datasetName name of dataset
 * @param start time start point in milliseconds
 * @param end time end point in milliseconds
 * @return A tier to record count mapping when succeeded. Otherwise a null value is returned
 */
public Map<String, Long> fetch(String datasetName, long start, long end) throws IOException {
    Map<String, Long> map = new HashMap<>();
    String query = "select tier, sum(count) from kafkaAudit where " + "eventType=\"" + datasetName + "\" and "
            + "beginTimestamp >= \"" + start + "\" and " + "beginTimestamp < \"" + end + "\" group by tier";

    String fullURL = targetUrl + URLEncoder.encode(query, Charsets.UTF_8.toString());
    HttpGet req = new HttpGet(fullURL);
    String rst = null;
    HttpEntity entity = null;
    log.info("Full url for {} is {}", datasetName, fullURL);

    try {
        CloseableHttpResponse response = httpClient.execute(req, HttpClientContext.create());
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode < 200 || statusCode >= 300) {
            throw new IOException(String.format("status code: %d, reason: %s", statusCode,
                    response.getStatusLine().getReasonPhrase()));
        }

        entity = response.getEntity();
        rst = EntityUtils.toString(entity);
    } finally {
        if (entity != null) {
            EntityUtils.consume(entity);
        }
    }

    JsonObject all = PARSER.parse(rst).getAsJsonObject();
    JsonArray aggregationResults = all.getAsJsonArray("aggregationResults");
    if (aggregationResults == null || aggregationResults.size() == 0) {
        log.error(all.toString());
        throw new IOException("No aggregation results " + all.toString());
    }

    JsonObject aggregation = (JsonObject) aggregationResults.get(0);
    JsonArray groupByResult = aggregation.getAsJsonArray("groupByResult");
    if (groupByResult == null || groupByResult.size() == 0) {
        log.error(aggregation.toString());
        throw new IOException("No aggregation results " + aggregation.toString());
    }

    log.info("Audit count for {} is {}", datasetName, groupByResult);
    for (JsonElement ele : groupByResult) {
        JsonObject record = (JsonObject) ele;
        map.put(record.getAsJsonArray("group").get(0).getAsString(),
                (long) Double.parseDouble(record.get("value").getAsString()));
    }

    return map;
}