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:org.keycloak.testsuite.util.DeleteMeOAuthClient.java

public AccessTokenResponse getToken(String realm, String clientId, String clientSecret, String username,
        String password) {/*from w ww  .j a  v a  2 s . c  o m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost post = new HttpPost(
                OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl)).build(realm));

        List<NameValuePair> parameters = new LinkedList<NameValuePair>();
        parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
        parameters.add(new BasicNameValuePair("username", username));
        parameters.add(new BasicNameValuePair("password", password));
        if (clientSecret != null) {
            String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
            post.setHeader("Authorization", authorization);
        } else {
            parameters.add(new BasicNameValuePair("client_id", clientId));
        }

        UrlEncodedFormEntity formEntity;
        try {
            formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        post.setEntity(formEntity);

        CloseableHttpResponse response = httpclient.execute(post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to retrieve token: " + response.getStatusLine().toString()
                    + " / " + IOUtils.toString(response.getEntity().getContent()));
        }

        return JsonSerialization.readValue(response.getEntity().getContent(), AccessTokenResponse.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:io.kamax.mxisd.backend.wordpress.WordpressRestBackend.java

public CloseableHttpResponse withAuthentication(HttpRequestBase request) throws IOException {
    CloseableHttpResponse response = runRequest(request);
    if (response.getStatusLine().getStatusCode() == 403) { //FIXME we should check the JWT expiration time
        authenticate();/*from w w w  .  ja va  2  s  .  com*/
        response = runRequest(request);
    }

    return response;
}

From source file:io.crate.protocols.http.CrateHttpsTransportIntegrationTest.java

@Test
public void testBlobLayer() throws IOException {
    try {/*from www .  j  a va2  s  .  c  o  m*/
        execute("create blob table test");
        final String blob = StringUtils.repeat("abcdefghijklmnopqrstuvwxyz", 1024 * 600);
        String blobUrl = upload("test", blob);
        assertThat(blobUrl, not(isEmptyOrNullString()));
        HttpGet httpGet = new HttpGet(blobUrl);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertThat(response.getEntity().getContentLength(), is((long) blob.length()));
    } finally {
        execute("drop table if exists test");
    }
}

From source file:org.talend.dataprep.dataset.store.content.http.HttpContentStore.java

/**
 * @see DataSetContentStore#getAsRaw(DataSetMetadata)
 *///from   ww w .  ja  va2  s . com
@Override
public InputStream getAsRaw(DataSetMetadata dataSetMetadata, long limit) {
    HttpLocation location = (HttpLocation) dataSetMetadata.getLocation();
    HttpGet get = new HttpGet(location.getUrl());
    get.setHeader("Accept", "*/*");
    CloseableHttpResponse response;
    try {
        response = httpClient.execute(get);
        if (response.getStatusLine().getStatusCode() >= 400) {
            throw new IOException("error fetching " + location.getUrl() + " -> " + response.getStatusLine());
        }
        LOGGER.debug("HTTP remote dataset {} fetched from {}", dataSetMetadata, location.getUrl());
        return response.getEntity().getContent();
    } catch (IOException e) {
        throw new TDPException(DataSetErrorCodes.UNABLE_TO_READ_REMOTE_DATASET_CONTENT, e);
    }
}

From source file:com.networknt.correlation.CorrelationHandlerTest.java

@Test
public void testGetWithoutTid() throws Exception {
    String url = "http://localhost:8080/without";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    try {/*  w ww .  ja v  a 2 s .  co m*/
        CloseableHttpResponse response = client.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200, statusCode);
        if (statusCode == 200) {
            String s = IOUtils.toString(response.getEntity().getContent(), "utf8");
            Assert.assertNotNull(s);
            System.out.println("correlationId = " + s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.networknt.correlation.CorrelationHandlerTest.java

@Test
public void testWithCid() throws Exception {
    String url = "http://localhost:8080/with";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(Constants.CORRELATION_ID, "cid");
    try {//from  w w w.j  a v  a2  s . c  o m
        CloseableHttpResponse response = client.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200, statusCode);
        if (statusCode == 200) {
            String s = IOUtils.toString(response.getEntity().getContent(), "utf8");
            Assert.assertNotNull(s);
            Assert.assertEquals("cid", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fi.vm.kapa.identification.proxy.metadata.MetadataClient.java

List<MetadataDTO> getMetadataDTOs(CloseableHttpClient httpClient, HttpGet getMethod) throws IOException {
    List<MetadataDTO> serviceProviders = new ArrayList<>();
    CloseableHttpResponse response = httpClient.execute(getMethod);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        Gson gson = new Gson();
        serviceProviders = gson.fromJson(EntityUtils.toString(response.getEntity()),
                new TypeToken<List<MetadataDTO>>() {
                }.getType());/*from   w w w.  j  a v  a  2  s.c om*/
        response.close();
    } else {
        logger.warn("Metadata server responded with HTTP {}", statusCode);
        response.close();
    }
    return serviceProviders;
}

From source file:io.undertow.js.test.session.SessionTestCase.java

@Test
public void testSession() throws IOException, ScriptException {
    final TestHttpClient client = new TestHttpClient();
    try {// w w w.j  a v  a  2  s.  com

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/count");
        CloseableHttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        assertEquals("1", HttpClientUtils.readResponse(result));

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/count");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        assertEquals("2", HttpClientUtils.readResponse(result));

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.elasticsearch.test.rest.client.http.HttpResponse.java

HttpResponse(HttpUriRequest httpRequest, CloseableHttpResponse httpResponse) {
    this.httpRequest = httpRequest;
    this.statusCode = httpResponse.getStatusLine().getStatusCode();
    this.reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    if (httpResponse.getEntity() != null) {
        try {/*  www.  j a  v a2 s  .c  o m*/
            this.body = EntityUtils.toString(httpResponse.getEntity(), HttpRequestBuilder.DEFAULT_CHARSET);
        } catch (IOException e) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    } else {
        this.body = null;
    }
}

From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.search.OpenAMSearchConnector.java

/**
 * @param uid// w ww.  j ava  2s. c  o  m
 * @return {@link OpenAMSearchUsersResult}
 * @throws Exception
 */
@Override
public OpenAMSearchUsersResult searchOpenAMUserByUid(String uid) throws Exception {
    Preconditions.checkArgument((uid != null) && !(uid.isEmpty()),
            "The UID Parameter must not be " + "null or an empty String.");
    logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TRYING TO Search USER by UID : {}  WITH "
            + "OPENAM_CONNECTOR_SETTINGS : {} \n", uid, this.openAMConnectorSettings);

    OpenAMSearchUsersRequest openAMSearchUsersRequest = this.openAMRequestMediator.getRequest(SEARCH_USERS);
    URIBuilder uriBuilder = super.buildURI(this.openAMConnectorSettings, openAMSearchUsersRequest);
    SearchUserByUidParameter parameter = new SearchUserByUidParameter(uid);
    uriBuilder.setParameter(parameter.getkey(), URLDecoder.decode(parameter.getValue(), "UTF-8"));

    URI searchURI = uriBuilder.build();
    logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@OPENAM_SEARCH_USER_CONNECTOR_URI : {}\n",
            URLDecoder.decode(searchURI.toString(), "UTF-8"));

    IOpenAMAuthenticate openAMAuthenticate = this.authenticate();
    logger.debug("::::::::::::::::::::::::::::::AUTHENTICATE_FOR_SEARCH_USER : {}\n", openAMAuthenticate);

    HttpGet httpGet = new HttpGet(searchURI);
    httpGet.addHeader("Content-Type", "application/json");
    httpGet.addHeader(this.openAMCookieInfo.getOpenAMCookie(), openAMAuthenticate.getTokenId());

    CloseableHttpResponse response = this.httpClient.execute(httpGet);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IllegalStateException(
                "OpenAMSearchUser Error Code : " + response.getStatusLine().getStatusCode());
    }
    this.logout(openAMAuthenticate.getTokenId());
    OpenAMSearchUsersResult result = this.openAMReader.readValue(response.getEntity().getContent(),
            OpenAMSearchUsersResult.class);
    logger.trace(":::::::::::::::::::::::::::OPENAM_SEARCH_USERS_RESULT_AS_STRING : \n{}\n",
            this.openAMReader.writeValueAsString(result));
    return result;
}