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.symcpe.hendrix.storm.bolts.helpers.AlertViewerBolt.java

@Override
public void execute(Tuple tuple) {
    short ruleId = 0;
    try {/*from  w w w . j a va  2s .  c  o m*/
        ruleId = tuple.getShortByField(Constants.FIELD_RULE_ID);
        String endPoint = uiEndpoint + ruleId;
        HendrixEvent event = (HendrixEvent) 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);
}

From source file:org.kontalk.xmppserver.registration.checkmobi.CheckmobiValidationClient.java

private JsonObject parseResponse(CloseableHttpResponse res) throws IOException {
    try {/*  w  w  w .ja  va  2  s  .  c  o m*/
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            if (entity != null) {
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                if (charset == null)
                    charset = Charset.forName("UTF-8");
                Reader reader = new InputStreamReader(entity.getContent(), charset);
                return (JsonObject) new JsonParser().parse(reader);
            }

            // no response body
            return new JsonObject();
        } else
            throw new HttpResponseException(res.getStatusLine().getStatusCode(),
                    res.getStatusLine().getReasonPhrase());
    } finally {
        res.close();
    }
}

From source file:fi.vm.kapa.identification.shibboleth.extattribute.ShibbolethExtAttributeConnector.java

@Nullable
@Override//w  ww  . java2 s  . c o  m
protected Map<String, IdPAttribute> doDataConnectorResolve(
        @Nonnull AttributeResolutionContext attributeResolutionContext,
        @Nonnull AttributeResolverWorkContext attributeResolverWorkContext) throws ResolutionException {
    Map<String, IdPAttribute> attributes = new HashMap<>();

    logger.debug("Trying to resolve attributes from adapter REST URL: " + adapterUrl);

    String token = attributeResolutionContext.getPrincipal();

    logger.debug("Using token: '{}' to fetch session attributes", token);

    try {
        String attributeCallUrl = adapterUrl + "?token=" + token;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet getMethod = new HttpGet(attributeCallUrl);
        HttpContext context = HttpClientContext.create();

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

        int status = restResponse.getStatusLine().getStatusCode();

        logger.debug("Response code from adapter HTTP " + status);

        if (status == HTTP_OK) {
            Gson gson = new Gson();

            Map<String, String> attributeMap = gson.fromJson(EntityUtils.toString(restResponse.getEntity()),
                    new TypeToken<Map<String, String>>() {
                    }.getType());

            if (attributeMap != null) {
                logger.debug("Attribute map size: {}", attributeMap.size());

                attributeMap.keySet().forEach(key -> {
                    String value = attributeMap.get(key);

                    logger.debug("--attribute key: {}, attribute value: {}", key, value);

                    if (StringUtils.isNotBlank(value)) {
                        IdPAttribute idPAttribute = new IdPAttribute(key);
                        List<IdPAttributeValue<String>> values = new ArrayList<>();
                        values.add(new StringAttributeValue(value));
                        idPAttribute.setValues(values);
                        attributes.put(key, idPAttribute);
                    }
                });
            } else {
                logger.warn("Attribute fetch OK but no content was found");
            }
        } else {
            logger.warn("No attributes found for session");
        }
    } catch (Exception e) {
        logger.error("Error in connection to Adapter", e);
    }

    return attributes;
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerUserResourceAsteriskTest.java

private void getAndCompare(String address, String acceptType, int expectedStatus) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(address);
    get.addHeader("Accept", acceptType);
    try {// w  w  w . j  av a2 s. c om
        CloseableHttpResponse response = client.execute(get);
        assertEquals(expectedStatus, response.getStatusLine().getStatusCode());
        Book book = readBook(response.getEntity().getContent());
        assertEquals(123, book.getId());
        assertEquals("CXF in Action", book.getName());
    } finally {
        get.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerUserResourceAsteriskTest.java

private void getAndCompareChapter(String address, String acceptType, int expectedStatus) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(address);
    get.addHeader("Accept", acceptType);
    try {//  w  w  w.j  a  va  2  s  .  co  m
        CloseableHttpResponse response = client.execute(get);
        assertEquals(expectedStatus, response.getStatusLine().getStatusCode());
        Chapter c = readChapter(response.getEntity().getContent());
        assertEquals(1, c.getId());
        assertEquals("chapter 1", c.getTitle());
    } finally {
        get.releaseConnection();
    }
}

From source file:com.fanmei.pay4j.http.DefaultRequestExecutor.java

private FanmeiResponse genFanmeiResponse(Charset charset, CloseableHttpResponse response)
        throws RequestException {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        return new DefaultFanmeiResponse(response, charset);
    } else {/*  w  ww  .j a v  a 2s.com*/
        throw RequestException.of(status, JSON.toJSONString(response));
    }
}

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

public void unsubscribe() throws IOException {
    Scanner sc = new Scanner(new File(UNSUBSCRIPTIONFILE));
    String subscriptionstring = "";
    while (sc.hasNextLine()) {
        subscriptionstring += sc.nextLine();
    }//from ww  w .j av  a2s  .co m
    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);

    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();
        }
    }
}

From source file:com.dnastack.bob.service.fetcher.util.HttpUtils.java

/**
 * Executes GET/POST and obtain the response.
 *
 * @param request request/*from  w ww .  j  a  v a2 s  .  co m*/
 *
 * @return response
 */
public String executeRequest(HttpRequestBase request) {
    String response = null;

    CloseableHttpResponse res = null;
    try {
        res = httpClient.execute(request);
        StatusLine line = res.getStatusLine();
        int status = line.getStatusCode();
        HttpEntity entity = res.getEntity();
        response = (entity == null) ? null : EntityUtils.toString(entity);
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            if (res != null) {
                res.close();
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return response;
}

From source file:com.googlecode.webutilities.servlets.WebProxyServlet.java

private void copyResponse(CloseableHttpResponse fromResponse, HttpServletResponse toResponse)
        throws IOException {
    toResponse.setStatus(fromResponse.getStatusLine().getStatusCode());
    for (Header header : fromResponse.getAllHeaders()) {
        toResponse.setHeader(header.getName(), header.getValue());
    }//from  w  ww  .  j  a v a  2 s . c  om
    HttpEntity entity = fromResponse.getEntity();
    IOUtils.copy(entity.getContent(), toResponse.getOutputStream());
}