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:io.crate.integrationtests.RestSQLActionIntegrationTest.java

@Test
public void testWithArgsAndBulkArgs() throws IOException {
    CloseableHttpResponse response = post(
            "{\"stmt\": \"INSERT INTO foo (bar) values (?)\", \"args\": [0], \"bulk_args\": [[0], [1]]}");
    assertEquals(400, response.getStatusLine().getStatusCode());
    String bodyAsString = EntityUtils.toString(response.getEntity());
    assertThat(bodyAsString,//w  w w. j a  v a2  s  .  c  o m
            startsWith("{\"error\":{\"message\":\"SQLActionException[request body contains args"
                    + " and bulk_args. It's forbidden to provide both]\",\"code\":4000},\"error_trace\":\"SQLActionException:"));
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpUpload(String url, String dataFieldName, byte[] data, List<NameValuePair> params) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  ww  w .  j  a  v a 2s. c  om*/
        HttpPost httppost = new HttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody(dataFieldName, data, ContentType.DEFAULT_BINARY, "tempfile");
        for (NameValuePair hp : params) {
            builder.addPart(hp.getName(),
                    new StringBody(hp.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
        }
        HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
        httppost.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(br);
            return je.getAsJsonObject();
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:fi.vm.kapa.identification.client.ProxyClient.java

public ProxyMessageDTO updateSession(Map<String, String> sessionData, String tid, String pid, String logTag)
        throws InternalErrorException, InvalidRequestException, IOException {

    String proxyCallUrl = proxyURLBase + tid + "&pid=" + pid;

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(proxyCallUrl);
    postMethod.setHeader(HEADER_TYPE, HEADER_VALUE);

    Gson gson = new Gson();
    postMethod.setEntity(new StringEntity(gson.toJson(sessionData)));
    HttpContext context = HttpClientContext.create();

    CloseableHttpResponse restResponse = httpClient.execute(postMethod, context);

    ProxyMessageDTO messageDTO = null;/*  www.  j  a  v  a 2 s  . c o  m*/

    int statusCode = restResponse.getStatusLine().getStatusCode();
    if (statusCode == HTTP_INTERNAL_ERROR) {
        logger.warn("<<{}>> Proxy encountered internal error", logTag);
        throw new InternalErrorException();
    } else {
        if (statusCode == HTTP_OK) {
            messageDTO = gson.fromJson(EntityUtils.toString(restResponse.getEntity()), ProxyMessageDTO.class);
        } else {
            logger.warn("<<{}>> Failed to build session, Proxy responded with HTTP {}", logTag, statusCode);
            throw new InvalidRequestException();

        }
    }
    restResponse.close();
    return messageDTO;
}

From source file:io.undertow.js.test.cdi.CDIInjectionProviderDependentTestCase.java

private void testRequest(TestHttpClient client) throws ClientProtocolException, IOException {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/cdi/foo");
    CloseableHttpResponse result = client.execute(get);
    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    assertEquals("Barpong", HttpClientUtils.readResponse(result));
}

From source file:org.elasticsearch.river.solr.support.SolrIndexer.java

public void indexDocuments(Map<String, Map<String, Object>> documents) throws IOException {
    StringBuilder jsonBuilder = new StringBuilder("[");
    int i = 0;//from w ww .  j  a  v  a  2s . com
    for (Map<String, Object> doc : documents.values()) {
        jsonBuilder.append(objectMapper.writeValueAsString(doc));

        if (i < documents.values().size() - 1) {
            jsonBuilder.append(",");
        }
        i++;
    }
    jsonBuilder.append("]");

    HttpPost httpPost = new HttpPost(solrUrl + "?commit=true");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(new StringEntity(jsonBuilder.toString()));

    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("documents were not properly indexed");
        }
    } finally {
        EntityUtils.consume(response.getEntity());
        response.close();
    }
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslServices() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();//from w  w w .j a  va  2 s  . c  o m

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // HTTPS client - with
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    jqmlogger.debug(rq.getURI());
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:org.apache.activemq.karaf.itest.ActiveMQBrokerFeatureTest.java

private void produceMessageWebConsole(String nameAndPayload) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new org.apache.http.auth.AuthScope("httpbin.org", 80),
            new org.apache.http.auth.UsernamePasswordCredentials(KarafShellHelper.USER,
                    KarafShellHelper.PASSWORD));
    CloseableHttpClient client = HttpClientBuilder.create() //
            .setDefaultCredentialsProvider(credsProvider).build();

    System.err.println(executeCommand("activemq:bstat").trim());
    System.err.println("attempting to access web console..");

    withinReason(new Callable<Boolean>() {
        public Boolean call() throws Exception {
            CloseableHttpResponse response = client.execute(new HttpGet(WEB_CONSOLE_URL + "index.jsp"));
            return response.getStatusLine().getStatusCode() != 200;
        }//from  w w  w  .  j  a v  a 2 s . c o m
    });

    System.err.println("attempting publish via web console..");

    // need to first get the secret
    CloseableHttpResponse response = client.execute(new HttpGet(WEB_CONSOLE_URL + "send.jsp"));
    int code = response.getStatusLine().getStatusCode();
    assertEquals("getting send succeeded", 200, code);

    String secret = getSecret(EntityUtils.toString(response.getEntity()));

    URI sendUri = new URIBuilder(WEB_CONSOLE_URL + "sendMessage.action") //
            .addParameter("secret", secret) //
            .addParameter("JMSText", nameAndPayload).addParameter("JMSDestination", nameAndPayload)
            .addParameter("JMSDestinationType", "queue").build();
    HttpPost post = new HttpPost(sendUri);
    CloseableHttpResponse sendResponse = client.execute(post);
    assertEquals("post succeeded, " + post, 302, sendResponse.getStatusLine().getStatusCode());
    System.err.println(executeCommand("activemq:bstat").trim());
}

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

@BeforeClass(alwaysRun = true)
public void initTest() throws MLIntegrationBaseTestException, MLHttpClientException {
    super.init();
    mlHttpclient = new MLHttpClient(instance, userInfo);
    // Check whether the analysis exists.
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/analyses/" + MLIntegrationTestConstants.ANALYSIS_NAME);
    if (Response.Status.OK.getStatusCode() != response.getStatusLine().getStatusCode()) {
        throw new SkipException("Skipping tests becasue an analysis is not available");
    }/*  w ww.  ja  va2 s .co m*/
}

From source file:no.api.meteo.client.DefaultMeteoClient.java

private void validateResponse(CloseableHttpResponse response) throws MeteoClientException {
    if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 203) {
        throw new MeteoClientException(
                "The request failed with error code " + response.getStatusLine().getStatusCode() + " : "
                        + response.getStatusLine().getReasonPhrase());
    }// w w w .  ja v a2 s.  c o m
}