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.comcast.cdn.traffic_control.traffic_router.core.external.CoverageZoneTest.java

@Test
public void itGetsCaches() throws Exception {
    HttpGet httpGet = new HttpGet(
            "http://localhost:3333/crs/coveragezone/caches?deliveryServiceId=steering-target-4&cacheLocationId=location-3");

    CloseableHttpResponse response = null;
    try {//from   w  ww  .ja v a2s. c  o  m
        response = closeableHttpClient.execute(httpGet);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        assertThat(jsonNode.isArray(), equalTo(true));
        JsonNode cacheNode = jsonNode.get(0);
        assertThat(cacheNode.get("id").asText(), not(nullValue()));
        assertThat(cacheNode.get("fqdn").asText(), not(nullValue()));
        assertThat(cacheNode.get("ip4").asText(), not(nullValue()));
        assertThat(cacheNode.get("ip6").asText(), not(nullValue()));
        // If the value is null or otherwise not an int we'll get back -123456, so any other value returned means success
        assertThat(cacheNode.get("port").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("deliveryServices").isArray(), equalTo(true));
        assertThat(cacheNode.get("hashValues").get(0).asDouble(-1024.1024), not(equalTo(-1024.1024)));
        assertThat(cacheNode.get("available").asText(), anyOf(equalTo("true"), equalTo("false")));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.norconex.committer.gsa.GsaCommitter.java

@Override
protected void commitBatch(List<ICommitOperation> batch) {

    File xmlFile = null;//ww w.j  ava2 s  .com
    try {
        xmlFile = File.createTempFile("batch", ".xml");
        FileOutputStream fout = new FileOutputStream(xmlFile);
        XmlOutput xmlOutput = new XmlOutput(fout);
        Map<String, Integer> stats = xmlOutput.write(batch);
        fout.close();

        HttpPost post = new HttpPost(feedUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("data", xmlFile, ContentType.APPLICATION_XML, xmlFile.getName());
        builder.addTextBody("datasource", "GSA_Commiter");
        builder.addTextBody("feedtype", "full");

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(post);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new CommitterException("Invalid response to Committer HTTP request. " + "Response code: "
                    + status.getStatusCode() + ". Response Message: " + status.getReasonPhrase());
        }
        LOG.info("Sent " + stats.get("docAdded") + " additions and " + stats.get("docRemoved")
                + " removals to GSA");

    } catch (Exception e) {
        throw new CommitterException("Cannot index document batch to GSA.", e);
    } finally {
        FileUtils.deleteQuietly(xmlFile);
    }
}

From source file:org.sasabus.export2Freegis.network.SubscriptionManager.java

public boolean subscribe() throws IOException {
    for (int i = 0; i < SUBFILEARRAY.length; ++i) {
        Scanner sc = new Scanner(new File(SUBFILEARRAY[i]));
        String subscriptionstring = "";
        while (sc.hasNextLine()) {
            subscriptionstring += sc.nextLine();
        }/*from   w  ww  . j a  v a 2s  .  c  om*/
        sc.close();
        SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

        Date d = new Date();
        String timestamp = date_date.format(d) + "T" + date_time.format(d);
        timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
                + timestamp.substring(timestamp.length() - 2);
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DATE, 1);
        d = c.getTime();
        String valid_until = date_date.format(d) + "T" + date_time.format(d);
        valid_until = valid_until.substring(0, valid_until.length() - 2) + ":"
                + valid_until.substring(valid_until.length() - 2);
        subscriptionstring = subscriptionstring.replaceAll(":timestamp_valid", valid_until);
        subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp);

        String requestString = "http://" + this.address + ":" + this.portnumber_sender
                + "/TmEvNotificationService/gms/subscription.xml";

        HttpPost subrequest = new HttpPost(requestString);

        StringEntity requestEntity = new StringEntity(subscriptionstring,
                ContentType.create("text/xml", "ISO-8859-1"));

        CloseableHttpClient httpClient = HttpClients.createDefault();

        subrequest.setEntity(requestEntity);

        CloseableHttpResponse response = httpClient.execute(subrequest);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            try {
                System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode());
                System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase());
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responsebody = EntityUtils.toString(responseEntity);
                    System.out.println(responsebody);
                }
            } finally {
                response.close();
                httpClient.close();
            }
            return false;
        }
        System.out.println("Subscription of " + SUBFILEARRAY[i]);
    }
    return true;

}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void notAuthorized() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    // first authenticate with the login servlet
    final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login");
    final List<NameValuePair> data = new ArrayList<NameValuePair>() {
        {//from  w  ww . java 2s.c  om
            add(new BasicNameValuePair("username", "userB"));
            add(new BasicNameValuePair("password", "secret"));
        }
    };
    httpPost.setEntity(new UrlEncodedFormEntity(data));
    final CloseableHttpResponse respLogin = client.execute(httpPost);
    try {
        assertEquals(200, respLogin.getStatusLine().getStatusCode());

    } finally {
        respLogin.close();
    }

    // then we can just call the hello servlet
    final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello");
    final CloseableHttpResponse resp = client.execute(httpGet);
    try {
        assertEquals(403, resp.getStatusLine().getStatusCode());

    } finally {
        resp.close();
    }
}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void success() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    // first authenticate with the login servlet
    final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login");
    final List<NameValuePair> data = new ArrayList<NameValuePair>() {
        {/*from  ww w .  jav a  2 s.c o m*/
            add(new BasicNameValuePair("username", "userA"));
            add(new BasicNameValuePair("password", "secret"));
        }
    };
    httpPost.setEntity(new UrlEncodedFormEntity(data));
    final CloseableHttpResponse respLogin = client.execute(httpPost);
    try {
        assertEquals(200, respLogin.getStatusLine().getStatusCode());

    } finally {
        respLogin.close();
    }

    // then we can just call the hello servlet
    final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello");
    final CloseableHttpResponse resp = client.execute(httpGet);
    try {
        assertEquals(200, resp.getStatusLine().getStatusCode());
        System.out.println(EntityUtils.toString(resp.getEntity()));

    } finally {
        resp.close();
    }
}

From source file:com.bluehermit.apps.module.soap.client.HttpClientHelperImpl.java

public String post(String target, String message) throws Exception {
    String responeMessage = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   ww w  .  jav  a 2  s  .c  om
        HttpPost httppost = new HttpPost(target);
        httppost.setHeader("Content-Type", "text/xml");
        httppost.setEntity(new StringEntity(message));

        System.out.println("Executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    responeMessage = IOUtils.toString(instream, "UTF-8");
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    return responeMessage;
}

From source file:com.dgpx.web.BaiduTTSBean.java

public CloseableHttpResponse doHttpGet(String url, Map<String, String> params, RequestConfig config) {

    initHttpClient();/* w ww  .ja  va 2  s.  c o m*/
    try {
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (String k : params.keySet()) {
                builder.addParameter(k, params.get(k));
            }
        }
        URI uri = builder.build();
        HttpGet httpGet = new HttpGet(uri);
        if (config != null) {
            httpGet.setConfig(config);
        }
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response;
        }
    } catch (IOException ex) {
        Logger.getLogger(BaiduTTSBean.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (URISyntaxException ex) {
        Logger.getLogger(BaiduTTSBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;

}

From source file:javaeetutorial.web.websocketbot.BotBean.java

public String get(String msg, String uri) {
    msg = msg.toLowerCase().replaceAll("\\?", "");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from  w  ww . jav  a  2s .co  m
        HttpGet httpget = new HttpGet(uri + msg);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                String jsonresult = EntityUtils.toString(entity);
                System.out.println("Response content:" + jsonresult);
                return jsonresult;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        try {
            httpclient.close();
        } catch (Exception e2) {
            // TODO: handle exception
        }
    }
    return null;
}

From source file:com.thoughtworks.go.util.HttpService.java

public CloseableHttpResponse execute(HttpRequestBase httpMethod) throws IOException {
    GoAgentServerHttpClient client = httpClientFactory.httpClient();

    if (httpMethod.getURI().getScheme().equals("http") || !useMutualTLS) {
        httpMethod.setHeader("X-Agent-GUID", agentRegistry.uuid());
        httpMethod.setHeader("Authorization", agentRegistry.token());
    }/*from  w w w .  ja  va 2  s.c om*/

    CloseableHttpResponse response = client.execute(httpMethod);
    LOGGER.info("Got back {} from server", response.getStatusLine().getStatusCode());
    return response;
}

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

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        //get user data from session storage
        Gson gson = new Gson();
        Type usuarioType = new TypeToken<LoginTempBean>() {
        }.getType();/* w  ww  .  j ava 2 s.c o  m*/
        String sessUser = String.valueOf(request.getSession().getAttribute("user"));
        LoginTempBean user = gson.fromJson(sessUser, usuarioType);

        //prepare http post
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/usuarios-salas/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id_usuario", user.getId()));
        params.add(new BasicNameValuePair("id_sala", form.getItem("id_sala")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpPost.addHeader("Authorization", "BEARER " + request.getSession().getAttribute("token"));
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

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

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //get user data from session storage
        String salas = String.valueOf(request.getSession().getAttribute("salas"));
        List<SalaBean> salaList = gson.fromJson(salas, new TypeToken<List<SalaBean>>() {
        }.getType());
        SalaBean actual = salaList.stream().filter(s -> s.getId() == Integer.parseInt(form.getItem("id_sala")))
                .collect(Collectors.toList()).get(0);

        request.getSession().setAttribute("sala", actual);
        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar ingresar a Sala: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}