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

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

Introduction

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

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:com.networknt.traceability.TraceabilityHandlerTest.java

@Test
public void testPostWithTid() throws Exception {
    String url = "http://localhost:8080/post";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader(Constants.TRACEABILITY_ID, "12345");
    httpPost.setHeader(Headers.CONTENT_TYPE.toString(), "application/json");
    try {/*w  w  w  .j a  va2 s.c  o  m*/
        StringEntity stringEntity = new StringEntity("post");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = client.execute(httpPost);
        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("post", s);
            Header tid = response.getFirstHeader(Constants.TRACEABILITY_ID);
            Assert.assertEquals("12345", tid.getValue());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ch.ralscha.extdirectspring_itest.InfoServiceTest.java

@Test
public void testApiDebug() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {//from   w w w . ja va2s.com
        HttpGet g = new HttpGet("http://localhost:9998/controller/api-debug.js?group=itest_info_service");
        response = client.execute(g);
        String responseString = EntityUtils.toString(response.getEntity());
        String contentType = response.getFirstHeader("Content-Type").getValue();
        ApiControllerTest.compare(responseString, contentType, api(), ApiRequestParams.builder().build());
        SimpleServiceTest.assertCacheHeaders(response, false);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:ch.ralscha.extdirectspring_itest.InfoServiceTest.java

@Test
public void testApiFingerprinted() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {//w  w w. j ava2 s  .com
        HttpGet g = new HttpGet("http://localhost:9998/controller/api-1.2.1.js?group=itest_info_service");
        response = client.execute(g);
        String responseString = EntityUtils.toString(response.getEntity());
        String contentType = response.getFirstHeader("Content-Type").getValue();
        ApiControllerTest.compare(responseString, contentType, api(), ApiRequestParams.builder().build());
        SimpleServiceTest.assertCacheHeaders(response, true);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:org.apache.activemq.artemis.tests.integration.rest.util.TopicRestMessageContext.java

@Override
public void initPullConsumers() throws IOException {
    String pullUri = getPullConsumerUri();
    CloseableHttpResponse response = null;
    if (this.durableSub || !this.autoAck) {
        String extraOpt = "durable=" + this.durableSub + "&autoAck=" + this.autoAck;
        response = connection.post(pullUri, "application/x-www-form-urlencoded", extraOpt);
    } else {/*from w  w w .  j a  va2 s .  co  m*/
        response = connection.post(pullUri);
    }

    int code = ResponseUtil.getHttpCode(response);

    try {
        if (code == 201) {
            Header header = response.getFirstHeader("Location");
            contextMap.put(KEY_PULL_CONSUMERS_LOC, header.getValue());
            header = response.getFirstHeader(KEY_MSG_CONSUME_NEXT);
            contextMap.put(KEY_MSG_CONSUME_NEXT, header.getValue());
            header = response.getFirstHeader(KEY_MSG_ACK_NEXT);
            if (header != null) {
                contextMap.put(KEY_MSG_ACK_NEXT, header.getValue());
            }
        } else {
            throw new IllegalStateException(
                    "Failed to init pull consumer " + ResponseUtil.getDetails(response));
        }
    } finally {
        response.close();
    }
}

From source file:org.apache.activemq.artemis.tests.integration.rest.util.RestMessageContext.java

private void prepareSelf() throws IOException {
    String destLink = getDestLink();
    CloseableHttpResponse response = connection.request(destLink);
    int code = ResponseUtil.getHttpCode(response);
    if (code != 200) {
        System.out.println("failed to init " + destLink);
        System.out.println("reason: " + ResponseUtil.getDetails(response));
    }/*  w  w w  . java2  s .c  om*/
    try {
        Header header = response.getFirstHeader(KEY_MSG_CREATE);
        contextMap.put(KEY_MSG_CREATE, header.getValue());
        header = response.getFirstHeader(KEY_MSG_CREATE_ID);
        contextMap.put(KEY_MSG_CREATE_ID, header.getValue());

        header = response.getFirstHeader(KEY_MSG_PULL);
        if (header != null) {
            contextMap.put(KEY_MSG_PULL, header.getValue());
        }
        header = response.getFirstHeader(KEY_MSG_PUSH);
        if (header != null) {
            contextMap.put(KEY_MSG_PUSH, header.getValue());
        }
        header = response.getFirstHeader(KEY_MSG_PULL_SUB);
        if (header != null) {
            contextMap.put(KEY_MSG_PULL_SUB, header.getValue());
        }
        header = response.getFirstHeader(KEY_MSG_PUSH_SUB);
        if (header != null) {
            contextMap.put(KEY_MSG_PUSH_SUB, header.getValue());
        }
    } finally {
        response.close();
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.ValidAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/login/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("nombre_usuario", form.getItem("user")));
        params.add(new BasicNameValuePair("password", form.getItem("pw")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            System.out.println(restResp);
            throw new RuntimeException("Los datos ingresados son incorrectos");
        }/*  ww  w  .j a  va2  s  .c  o  m*/

        Header authHeader = postResponse.getFirstHeader("Auth-Token");
        String headerValue = authHeader != null ? authHeader.getValue() : "";

        HttpPost adminPost = new HttpPost("http://25.136.78.82:8080/login/admin");
        adminPost.addHeader("Authorization", "BEARER " + headerValue);
        adminPost.addHeader("accept", "application/json");

        postResponse = httpClient.execute(adminPost);
        responseEntity = postResponse.getEntity();
        responseStatus = postResponse.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException("Accesso restringido a Administradores");
        }

        request.getSession().setAttribute("user", restResp);
        request.getSession().setAttribute("token", headerValue);
        request.getSession().setAttribute("login_tmst", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar login: " + e.getMessage());
        response.setStatus(401);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.apache.hadoop.gateway.GatewayMultiFuncTest.java

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testPostWithContentTypeKnox681() throws Exception {
    LOG_ENTER();/* w w w  .j a v a2  s  .c  om*/

    MockServer mock = new MockServer("REPEAT", true);

    params = new Properties();
    params.put("MOCK_SERVER_PORT", mock.getPort());
    params.put("LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort());

    String topoStr = TestUtils.merge(DAT, "topologies/test-knox678-utf8-chars-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "knox681.xml");
    FileUtils.writeStringToFile(topoFile, topoStr);

    topos.reloadTopologies();

    mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED)
            .content("{\"name\":\"value\"}".getBytes()).contentLength(-1)
            .contentType("application/json; charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat");

    String uname = "guest";
    String pword = uname + "-password";

    HttpHost targetHost = new HttpHost("localhost", gatewayPort, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(uname, pword));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPut request = new HttpPut(gatewayUrl + "/knox681/repeat");
    request.addHeader("X-XSRF-Header", "jksdhfkhdsf");
    request.addHeader("Content-Type", "application/json");
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED));
    assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat"));
    assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/json; charset=UTF-8"));
    String body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8"));
    assertThat(body, is("{\"name\":\"value\"}"));
    response.close();
    client.close();

    mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED)
            .content("<test-xml/>".getBytes()).contentType("application/xml; charset=UTF-8")
            .header("Location", gatewayUrl + "/knox681/repeat");

    client = HttpClients.createDefault();
    request = new HttpPut(gatewayUrl + "/knox681/repeat");
    request.addHeader("X-XSRF-Header", "jksdhfkhdsf");
    request.addHeader("Content-Type", "application/xml");
    response = client.execute(request, context);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED));
    assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat"));
    assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/xml; charset=UTF-8"));
    body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8"));
    assertThat(the(body), hasXPath("/test-xml"));
    response.close();
    client.close();

    mock.stop();

    LOG_EXIT();
}

From source file:org.artifactory.webapp.wicket.page.config.repos.remote.HttpRepoPanel.java

@Override
protected TitledAjaxSubmitLink createTestButton() {
    return new TitledAjaxSubmitLink("test", "Test", form) {
        @Override/*from   ww w  .j  a  va2  s  . co m*/
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            HttpRepoDescriptor repo = getRepoDescriptor();
            if (!validate(repo)) {
                AjaxUtils.refreshFeedback();
                return;
            }
            // always test with url trailing slash
            String url = PathUtils.addTrailingSlash(repo.getUrl());
            HttpRequestBase testMethod = getRemoteRepoTestMethod(url);
            CloseableHttpClient client = getRemoteRepoTestHttpClient(repo, url);
            CloseableHttpResponse response = null;
            try {
                response = client.execute(testMethod);
                boolean success = remoteRepoTestValidStatus(response.getStatusLine().getStatusCode());
                if (!success) {
                    IOUtils.closeQuietly(response);
                    final Header serverHeader = response.getFirstHeader("Server");
                    // S3 hosted repositories are not hierarchical and does not have a notion of "collection" (folder, directory)
                    // Therefore we should not add the trailing slash when testing them
                    if (serverHeader != null && "AmazonS3".equals(serverHeader.getValue())) {
                        log.debug("Remote repository is hosted on Amazon S3, trying without a trailing slash");

                        url = repo.getUrl();
                        testMethod = getRemoteRepoTestMethod(url);
                        response = client.execute(testMethod);
                        success = remoteRepoTestValidStatus(response.getStatusLine().getStatusCode());
                    }
                }
                if (!success) {
                    error("Connection failed: Error " + response.getStatusLine().getStatusCode() + ": "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    info("Successfully connected to server");
                }
            } catch (Exception e) {
                error("Connection failed with exception: " + HttpClientUtils.getErrorMessage(e));
                log.debug("Test connection to '" + url + "' failed with exception", e);
            } finally {
                IOUtils.closeQuietly(response);
                IOUtils.closeQuietly(client);
            }
            AjaxUtils.refreshFeedback(target);
        }
    };
}