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.wso2.msf4j.delegates.client.MSF4JClientResponseContext.java

/**
 * Constructor of MSF4JClientResponseContext.
 *//*  w  ww  .  j  a  va  2s  .  c  o m*/
public MSF4JClientResponseContext(CloseableHttpResponse response) throws IOException {
    this.statusCode = response.getStatusLine().getStatusCode();
    for (Header header : response.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    this.entityStream = response.getEntity().getContent();
}

From source file:uk.org.openeyes.APIUtils.java

/**
 * Trigger a WS call through HTTP for patient search
 * /* w  w  w . j  av a  2 s  . c o m*/
 * @param resourceType The REST resource name (only "Patient" supported now)
 * @param requestParams The arguments for the HTTP call 
 * @return The status code from the HTTP answer
 * @throws ConnectException 
 */
public int read(String resourceType, String requestParams) throws ConnectException {

    DefaultHttpClient http = new DefaultHttpClient();

    int result = -1;
    String strURL = "http://" + host + ":" + port + "/api/" + resourceType
            + "?resource_type=Patient&_format=xml";
    if (requestParams != null) {
        strURL += "&" + requestParams;
    }
    HttpGet get = new HttpGet(strURL);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(authUserName, authUserPassword);

    get.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));

    try {
        get.addHeader("Content-type", "text/xml");
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient httpclient = builder.build();

        CloseableHttpResponse httpResponse = httpclient.execute(get);
        result = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity2 = httpResponse.getEntity();
        StringWriter writer = new StringWriter();
        //IOUtils.copy(entity2.getContent(), writer);
        this.response = entity2.getContent().toString();
        EntityUtils.consume(entity2);
    } catch (ConnectException e) {
        // this happens when there's no server to connect to
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();
    }
    return result;
}

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

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

        //get request data
        String id_usuario = form.getItem("id_usuario");
        String id_sala = form.getItem("id_sala");
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/usuarios-salas/" + id_usuario + "/" + id_sala);

        HttpDelete delete = new HttpDelete();
        delete.setURI(builder.build());/*ww  w.  j a v  a 2s  .c om*/
        delete.addHeader("Authorization", "BEARER " + authToken);
        delete.addHeader("accept", "application/json");

        CloseableHttpResponse deleteResponse = httpClient.execute(delete);

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

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

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        String id_usuario = form.getItem("id_usuario");
        request.setAttribute("message",
                "Error al intentar expulsar usuario: " + id_usuario + "; " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

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

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/usuarios-salas/sala/" + sala.getId());

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }//from   w w  w  .  ja  v  a2  s  . c  o  m
        //parse message data from response
        Gson gson = new Gson();
        UsuarioBean[] usrList = gson.fromJson(restResp, UsuarioBean[].class);
        request.setAttribute("usuarios", usrList);

        return mapping.getForwardByName("success");

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

}

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

/**
 * Test deleting a non-existing analysis.
 * /*  www . ja v  a 2s .  c o m*/
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Delete a non-existing analysis")
public void testDeleteNonExistingAnalysis() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpDelete("/api/analyses/" + 100);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wso2.carbon.ml.project.test.DeleteProjectsTestCase.java

/**
 * Test deleting a project./*from w  ww.  ja v a2  s .  com*/
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Delete an exsisting project")
public void testDeleteProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpDelete("/api/projects/" + projectName);
    assertEquals("Unexpected response recieved", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:it.tai.solr.http.HttpInvoker.java

private void checkResponse(CloseableHttpResponse response) throws IOException {
    if (response == null) {
        throw new IOException("No data response");
    }//from w  w w  .ja  v a2s  .  c om
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Response status code: " + response.getStatusLine().getStatusCode());
    }
}

From source file:com.rootcloud.ejb.RootCloudBean.java

public String updateAlarmStatus(String deviceId, String alarmId, String status) {
    StringBuilder urlBuilder = new StringBuilder();
    urlBuilder.append(baseurl);/*w ww . j  a v  a 2  s  . co  m*/
    urlBuilder.append("/service-hzjj-device/api/hzjj/update-alarm/crm?deviceId=").append(deviceId)
            .append("&alarmId=").append(alarmId).append("&status=").append(status);
    try {
        if (isTokenExpire()) {
            initAccessToken();
        }
        StringBuilder cookieBuilder = new StringBuilder();
        cookieBuilder.append(
                "_ga=GA1.2.1131583934.1534823162; _gid=GA1.2.1073767397.1534823162; Hm_lvt_63a8403da4c50b3dd2f667c37bcf65e1=1534757253,1534837562;");
        cookieBuilder.append("access_token=").append(access_token).append(";");
        cookieBuilder.append("session_token=").append(refresh_token);
        HttpPost httpPost;
        httpPost = new HttpPost(urlBuilder.toString());
        httpPost.setHeader("content-type", "application/json");
        httpPost.addHeader("cookie", cookieBuilder.toString());
        httpPost.addHeader("current_app", current_app);
        httpPost.addHeader("current_tenant", current_tenant);
        httpClient = createHttpClient();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //System.out.println("update-alarm?");
            log4j.info(String.format(
                    "RootCloudBeanupdateAlarm?,?1:%s,?2:%s,?3:%s,:%s",
                    deviceId, alarmId, status, "200"));
            return "200";
        } else {
            log4j.info(String.format(
                    "RootCloudBeanupdateAlarm,?1:%s,?2:%s,?3:%s,:%s",
                    deviceId, alarmId, status, String.valueOf(response.getStatusLine().getStatusCode())));
        }
    } catch (Exception ex) {
        log4j.error("RootCloudBeanupdateAlarm", ex);
    }
    return "";
}

From source file:com.olacabs.fabric.compute.builder.impl.HttpJarDownloader.java

public Path download(final String url) {
    HttpGet httpGet = new HttpGet(URI.create(url));
    CloseableHttpResponse response = null;
    try {// ww  w  .java2s.  c o m
        response = httpClient.execute(httpGet);
        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            throw new RuntimeException(String.format("Server returned [%d][%s] for url: %s",
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), url));
        }
        Header[] headers = response.getHeaders("Content-Disposition");
        String filename = null;
        if (null != headers) {
            for (Header header : headers) {
                for (HeaderElement headerElement : header.getElements()) {
                    if (!headerElement.getName().equalsIgnoreCase("attachment")) {
                        continue;
                    }
                    NameValuePair attachment = headerElement.getParameterByName("filename");
                    if (attachment != null) {
                        filename = attachment.getValue();
                    }
                }
            }
        }
        if (Strings.isNullOrEmpty(filename)) {
            String[] nameParts = url.split("/");
            filename = nameParts[nameParts.length - 1];
        }
        return Files.write(Paths.get(this.tmpDirectory, filename),
                EntityUtils.toByteArray(response.getEntity()));
    } catch (IOException e) {
        throw new RuntimeException("Error loading class from: " + url, e);
    } finally {
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                LOGGER.error("Could not close connection to server: ", e);
            }
        }
    }
}

From source file:com.srotya.tau.dengine.bolts.helpers.AlertViewerBolt.java

@Override
public void execute(Tuple tuple) {
    short ruleId = 0;
    try {//w  ww  . j a  v a2 s.co  m
        ruleId = tuple.getShortByField(Constants.FIELD_RULE_ID);
        String endPoint = uiEndpoint + ruleId;
        TauEvent event = (TauEvent) tuple.getValueByField(Constants.FIELD_EVENT);
        HttpPost req = new HttpPost(endPoint);
        req.setEntity(new StringEntity(new Gson().toJson(event.getHeaders()), ContentType.APPLICATION_JSON));
        CloseableHttpResponse resp = client.execute(req);
        counter++;
        if (counter % 1000 == 0) {
            System.out.println(endPoint + "\t" + resp.getStatusLine().getStatusCode() + "\t"
                    + EntityUtils.toString(resp.getEntity()));
            System.err.println("Alerts sent to UI:" + counter);
        }
    } catch (Exception e) {
        StormContextUtil.emitErrorTuple(collector, tuple, AlertViewerBolt.class, tuple.toString(),
                "Failed to send alert to UI", e);
    }
    collector.ack(tuple);
}