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.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform DELETE request against an RTC server.
 * @param serverURI The RTC server//  w  w w .  j a  va2s .  c o m
 * @param uri The relative URI for the DELETE. It is expected that it is already encoded if necessary.
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param httpContext The context from the login if cycle is being managed by the caller
 * Otherwise <code>null</code> and this call will handle the login.
 * @param listener The listener to report errors to.
 * May be <code>null</code> if there is no listener.
 * @return The HttpContext for the request. May be reused in subsequent requests
 * for the same user
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException
 * @throws GeneralSecurityException 
 */
public static HttpClientContext performDelete(String serverURI, String uri, String userId, String password,
        int timeout, HttpClientContext httpContext, TaskListener listener)
        throws IOException, InvalidCredentialsException, GeneralSecurityException {

    CloseableHttpClient httpClient = getClient();
    String fullURI = getFullURI(serverURI, uri);

    HttpDelete delete = getDELETE(fullURI, timeout);
    if (httpContext == null) {
        httpContext = createHttpContext();
    }

    LOGGER.finer("DELETE: " + delete.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(delete, httpContext);
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        Header locationHeader = response.getFirstHeader(LOCATION);
        boolean redirectsFollowed = false;
        int paranoia = 100;
        while (statusCode == 302 && locationHeader != null && paranoia > 0) {
            redirectsFollowed = true;
            // follow the redirects. Eventually we will get to a point where we can authenticate
            closeResponse(response);
            String redirectURI = locationHeader.getValue();
            HttpGet request = getGET(redirectURI, timeout);
            LOGGER.finer("DELETE following redirect before auth: " + request.getURI()); //$NON-NLS-1$
            response = httpClient.execute(request, httpContext);
            statusCode = response.getStatusLine().getStatusCode();
            locationHeader = response.getFirstHeader(LOCATION);
            paranoia--;
        }

        // based on the response do any authentication. If authentication requires
        // the request to be performed again (i.e. Basic auth) re-issue request
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, listener);

        if (response != null) {
            checkDeleteResponse(response, fullURI, serverURI, userId, listener);
        }

        // retry delete request if we have to do authentication or we followed a redirect to a Get
        if (redirectsFollowed || response == null) {
            // Do the actual delete
            paranoia = 100;
            do {
                // follow the redirects. Eventually we will get to a point where we can authenticate
                closeResponse(response);
                HttpDelete request = getDELETE(fullURI, timeout);
                LOGGER.finer("DELETE following redirect after auth: " + request.getURI()); //$NON-NLS-1$
                response = httpClient.execute(request, httpContext);
                statusCode = response.getStatusLine().getStatusCode();
                locationHeader = response.getFirstHeader(LOCATION);
                if (locationHeader != null) {
                    fullURI = locationHeader.getValue();
                }
                paranoia--;
            } while (statusCode == 302 && locationHeader != null && paranoia > 0);
            checkDeleteResponse(response, fullURI, serverURI, userId, listener);
        }

        return httpContext;
    } finally {
        closeResponse(response);
    }
}

From source file:org.wuspba.ctams.ws.ITJudgeController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (Judge j : doc.getJudges()) {
            ids.add(j.getId());//from w w w.  j  a  va2  s  .  c o m
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITPersonController.delete();
    ITJudgeQualificationController.delete();
}

From source file:guru.nidi.ramltester.loader.SimpleUrlFetcher.java

@Override
public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name) throws IOException {
    final HttpGet get = postProcessGet(new HttpGet(base + "/" + encodeUrl(name)));
    final CloseableHttpResponse getResult = client.execute(get);
    if (getResult.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Http response status not ok: " + getResult.getStatusLine().toString());
    }/*  w  w w.j  av  a2  s.  c o m*/
    return getResult.getEntity().getContent();
}

From source file:org.wuspba.ctams.ws.ITJudgeQualificationController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (JudgeQualification q : doc.getJudgeQualifications()) {
            ids.add(q.getId());//from w  w w  . jav a  2  s .  co  m
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }
}

From source file:utils.ImportExportUtils.java

/**
 * Registering the clientApplication/*from   w  w w .  j  a v a  2  s  .  c  o m*/
 * @param username user name of the client
 * @param password password of the client
 */
static String registerClient(String username, String password) throws APIExportException {

    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();

    String concatUsernamePassword = username + ":" + password;
    byte[] encodedBytes = Base64
            .encodeBase64(concatUsernamePassword.getBytes(Charset.forName(ImportExportConstants.CHARSET)));
    String encodedCredentials;
    try {
        encodedCredentials = new String(encodedBytes, ImportExportConstants.CHARSET);
    } catch (UnsupportedEncodingException e) {
        String error = "Error occurred while encoding the user credentials";
        log.error(error, e);
        throw new APIExportException(error, e);
    }
    //payload for registering
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(ImportExportConstants.CLIENT_NAME, config.getClientName());
    jsonObject.put(ImportExportConstants.OWNER, username);
    jsonObject.put(ImportExportConstants.GRANT_TYPE, ImportExportConstants.DEFAULT_GRANT_TYPE);
    jsonObject.put(ImportExportConstants.SAAS_APP, true);

    //REST API call for registering
    CloseableHttpResponse response;
    String encodedConsumerDetails;
    CloseableHttpClient client = null;
    try {
        String url = config.getDcrUrl();
        client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(jsonObject.toJSONString(), ImportExportConstants.CHARSET));
        request.setHeader(HttpHeaders.AUTHORIZATION,
                ImportExportConstants.AUTHORIZATION_KEY_SEGMENT + " " + encodedCredentials);
        request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 401) {
            String errormsg = "invalid username or password entered ";
            log.error(errormsg);
            throw new APIExportException(errormsg);
        }
        String jsonString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObj = (JSONObject) new JSONParser().parse(jsonString);

        //storing encoded Consumer credentials
        String consumerCredentials = jsonObj.get(ImportExportConstants.CLIENT_ID) + ":"
                + jsonObj.get(ImportExportConstants.CLIENT_SECRET);
        byte[] bytes = Base64.encodeBase64(consumerCredentials.getBytes(Charset.defaultCharset()));
        encodedConsumerDetails = new String(bytes, ImportExportConstants.CHARSET);
    } catch (ParseException e) {
        String msg = "error occurred while getting consumer key and consumer secret from the response";
        log.error(msg, e);
        throw new APIExportException(msg, e);
    } catch (IOException e) {
        String msg = "Error occurred while registering the client";
        log.error(msg, e);
        throw new APIExportException(msg, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
    return encodedConsumerDetails;
}

From source file:org.wildfly.swarm.topology.consul.AdvertisingTestBase.java

protected Map<?, ?> getDefinedServicesAsMap() throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();

    HttpUriRequest request = new HttpGet(servicesUrl);
    CloseableHttpResponse response = client.execute(request);

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    String content = EntityUtils.toString(response.getEntity());
    return mapper.readValue(content, Map.class);
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Check the response for a delete (or it could be a get if we were following
 * redirects & posted the form). Idea is to see if its an auth failure or
 * something really serious (not found isn't serious, just means already deleted).
 * @param response The response//from   www. jav  a  2  s  .c om
 * @param fullURI The full uri that was used for the request.
 * @param serverURI The RTC Server portion of the uri
 * @param userId The user id on behalf of whom the request was made
 * @param listener A listener to notify of issues.
 * @throws InvalidCredentialsException Thrown if the authentication failed.
 * @throws IOException Thrown if a serious error occurred.
 */
private static void checkDeleteResponse(CloseableHttpResponse response, String fullURI, String serverURI,
        String userId, TaskListener listener) throws InvalidCredentialsException, IOException {
    int statusCode;
    statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 401) {
        // the user is unauthenticated
        throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));

    } else if (statusCode == 404) {
        // this is ok, build result already deleted

    } else {
        int responseClass = statusCode / 100;
        if (responseClass != 2) {
            if (listener != null) {
                listener.fatalError(Messages.HttpUtils_DELETE_failed(fullURI, statusCode));
            }

            throw logError(fullURI, response, Messages.HttpUtils_DELETE_failed(fullURI, statusCode));
        }
    }
}

From source file:bit.changepurse.wdk.http.HTTPResponse.java

private HTTPStatusCode getStatusCode(CloseableHttpResponse apacheResponse) {
    StatusLine statusLine = apacheResponse.getStatusLine();
    return HTTPStatusCode.fromInt(statusLine.getStatusCode());
}

From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsAndInterOpsDUnitTest.java

public static void doGetsUsingRestApis(String restEndpoint) {

    //HttpHeaders headers = setAcceptAndContentTypeHeaders(); 
    String currentOperation = null;
    JSONObject jObject;/* w w w . j  av  a2 s  .c  om*/
    JSONArray jArray;
    try {
        //1. Get on key="1" and validate result.
        {
            currentOperation = "GET on key 1";

            HttpGet get = new HttpGet(restEndpoint + "/People/1");
            get.addHeader("Content-Type", "application/json");
            get.addHeader("Accept", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(get);

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            StringBuffer str = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }

            jObject = new JSONObject(str.toString());

            assertEquals(jObject.get("id"), 101);
            assertEquals(jObject.get("firstName"), "Mithali");
            assertEquals(jObject.get("middleName"), "Dorai");
            assertEquals(jObject.get("lastName"), "Raj");
            assertEquals(jObject.get("gender"), Gender.FEMALE.name());
        }

        //2. Get on key="16" and validate result.
        {
            currentOperation = "GET on key 16";

            HttpGet get = new HttpGet(restEndpoint + "/People/16");
            get.addHeader("Content-Type", "application/json");
            get.addHeader("Accept", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(get);

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            StringBuffer str = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }

            jObject = new JSONObject(str.toString());

            assertEquals(jObject.get("id"), 104);
            assertEquals(jObject.get("firstName"), "Shila");
            assertEquals(jObject.get("middleName"), "kumari");
            assertEquals(jObject.get("lastName"), "Dixit");
            assertEquals(jObject.get("gender"), Gender.FEMALE.name());
        }

        //3. Get all (getAll) entries in Region
        {

            HttpGet get = new HttpGet(restEndpoint + "/People");
            get.addHeader("Content-Type", "application/json");
            get.addHeader("Accept", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse result = httpclient.execute(get);
            assertEquals(result.getStatusLine().getStatusCode(), 200);
            assertNotNull(result.getEntity());

            HttpEntity entity = result.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            result.close();

            try {
                jObject = new JSONObject(sb.toString());
                jArray = jObject.getJSONArray("People");
                assertEquals(jArray.length(), 16);
            } catch (JSONException e) {
                fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
            }
        }

        //4. GetAll?limit=10 (10 entries) and verify results
        {
            HttpGet get = new HttpGet(restEndpoint + "/People?limit=10");
            get.addHeader("Content-Type", "application/json");
            get.addHeader("Accept", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(get);
            assertEquals(response.getStatusLine().getStatusCode(), 200);
            assertNotNull(response.getEntity());

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            StringBuffer str = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }

            try {
                jObject = new JSONObject(str.toString());
                jArray = jObject.getJSONArray("People");
                assertEquals(jArray.length(), 10);
            } catch (JSONException e) {
                fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
            }
        }

        //5. Get keys - List all keys in region
        {

            HttpGet get = new HttpGet(restEndpoint + "/People/keys");
            get.addHeader("Content-Type", "application/json");
            get.addHeader("Accept", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(get);
            assertEquals(response.getStatusLine().getStatusCode(), 200);
            assertNotNull(response.getEntity());

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            StringBuffer str = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }

            try {
                jObject = new JSONObject(str.toString());
                jArray = jObject.getJSONArray("keys");
                assertEquals(jArray.length(), 16);
            } catch (JSONException e) {
                fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
            }
        }

        //6. Get data for specific keys
        {

            HttpGet get = new HttpGet(restEndpoint + "/People/1,3,5,7,9,11");
            get.addHeader("Content-Type", "application/json");
            get.addHeader("Accept", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(get);
            assertEquals(response.getStatusLine().getStatusCode(), 200);
            assertNotNull(response.getEntity());

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            StringBuffer str = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }

            try {
                jObject = new JSONObject(str.toString());
                jArray = jObject.getJSONArray("People");
                assertEquals(jArray.length(), 6);

            } catch (JSONException e) {
                fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("unexpected exception", e);
    }
}

From source file:functional.PathTraversingTest.java

@Test
public void testTraversalDenied() throws Exception {
    HttpGet httpget = new HttpGet("http://localhost:8080/../../");

    CloseableHttpResponse execute = httpclient.execute(httpget);
    execute.close();/*  ww w.  ja  v a2  s . c  om*/
    assertEquals(403, execute.getStatusLine().getStatusCode());
}