Example usage for org.apache.http.client ResponseHandler ResponseHandler

List of usage examples for org.apache.http.client ResponseHandler ResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.client ResponseHandler ResponseHandler.

Prototype

ResponseHandler

Source Link

Usage

From source file:org.commonjava.couch.test.fixture.RemoteRESTFixture.java

public <T> Listing<T> getListing(final String url, final TypeToken<Listing<T>> token) throws Exception {
    final HttpGet get = new HttpGet(fixup(url));
    try {/*from  w  ww  .  j  a  va 2s.  c  om*/
        return http.execute(get, new ResponseHandler<Listing<T>>() {
            @SuppressWarnings("unchecked")
            @Override
            public Listing<T> handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                final StatusLine sl = response.getStatusLine();
                assertThat(sl.getStatusCode(), equalTo(HttpStatus.SC_OK));

                return serializer.listingFromStream(response.getEntity().getContent(), "UTF-8", token);
            }
        });
    } finally {
        get.abort();
    }
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ACIResultUploader.java

/**
 * {@inheritDoc}//from   w  ww  . java  2s.  c o m
 */
@Override
public void upload(final EnricherJob job, final GeneratorResult result) throws Exception {
    String file = ((ACIGeneratorResult) result).generateFile(job.getProcessedPath(), baseEncoding);

    HttpPost httpPost = new HttpPost(new URI(addUri + "?" + URLEncoder.encode(file, baseEncoding)));

    httpPost.setHeader(HEADER_USER_AGENT, userAgent);
    httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_ENCODED);

    HttpResponse response = httpClient.execute(httpPost, new ResponseHandler<HttpResponse>() {
        @Override
        public HttpResponse handleResponse(final HttpResponse response)
                throws ClientProtocolException, IOException {
            return response;
        }
    });

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream inputStream = entity.getContent();

        try {
            if (logger.isDebugEnabled()) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                logger.debug("Received entity response from server for result path: " + reader.readLine());
            }
        } catch (IOException e) {
            // No connection to release - simply rethrow the exception

            throw e;
        } catch (RuntimeException e) {
            // Abort the HTTP request in order to release the connection

            httpPost.abort();

            throw e;
        } finally {
            // Trigger a connection release

            inputStream.close();
        }
    }

    if (response.getStatusLine().getStatusCode() != HTTP_STATUS_SUCCESS)
        throw new Exception("Generated result could not be uploaded because of status "
                + response.getStatusLine().getStatusCode() + " (" + response.getStatusLine().getReasonPhrase()
                + ")");
    else if (logger.isDebugEnabled())
        logger.debug("Result path " + file + " sent to the indexer");
}

From source file:org.ldp4j.server.ServerFrontendTestHelper.java

public Metadata httpRequest(final HttpUriRequest request) throws Exception {
    final Metadata metadata = new Metadata();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            metadata.body = responseBody;
            Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            if (etagHeader != null) {
                metadata.etag = etagHeader.getValue();
            }/*  w  ww.j ava  2 s. com*/
            Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
            if (lastModifiedHeader != null) {
                metadata.lastModified = lastModifiedHeader.getValue();
            }
            Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
            if (locationHeader != null) {
                metadata.location = locationHeader.getValue();
            }
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return metadata;
}

From source file:org.eclipse.vorto.repository.RestClient.java

@SuppressWarnings("restriction")
public <Result> Result executePost(String query, HttpEntity content,
        final Function<String, Result> responseConverter) throws ClientProtocolException, IOException {

    CloseableHttpClient client = HttpClients.custom().build();

    HttpUriRequest request = RequestBuilder.post().setConfig(createProxyConfiguration())
            .setUri(createQuery(query)).addHeader(createSecurityHeader()).setEntity(content).build();

    return client.execute(request, new ResponseHandler<Result>() {

        @Override//from ww  w  .  j  av a 2 s  .  c  om
        public Result handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            return responseConverter.apply(IOUtils.toString(response.getEntity().getContent()));
        }
    });
}

From source file:com.att.voice.AttDigitalLife.java

public String getDeviceGUID(String device, Map<String, String> authMap) {
    try {//w ww  . j  a  v a 2s.c  o  m
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices");

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject jsonObject = new JSONObject(json);

        JSONArray array = jsonObject.getJSONArray("content");

        for (int i = 0; i <= array.length(); i++) {
            JSONObject d = array.getJSONObject(i);
            String type = d.getString("deviceType");
            if (type.equalsIgnoreCase(device)) {
                return d.getString("deviceGuid");
            }
        }
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
    return null;
}

From source file:org.ldp4j.server.testing.ServerFrontendTestHelper.java

public Metadata httpRequest(final HttpUriRequest request) throws Exception {
    final Metadata metadata = new Metadata();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            metadata.status = response.getStatusLine().getStatusCode();
            metadata.body = responseBody;
            Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            if (etagHeader != null) {
                metadata.etag = etagHeader.getValue();
            }/*from   www . j  av a2 s  .c  o  m*/
            Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
            if (lastModifiedHeader != null) {
                metadata.lastModified = lastModifiedHeader.getValue();
            }
            Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
            if (locationHeader != null) {
                metadata.location = locationHeader.getValue();
            }
            Header contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
            if (contentType != null) {
                metadata.contentType = contentType.getValue();
            }
            Header contentLanguage = response.getFirstHeader(HttpHeaders.CONTENT_LANGUAGE);
            if (contentLanguage != null) {
                metadata.language = Locale.forLanguageTag(contentLanguage.getValue());
            }
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return metadata;
}

From source file:com.github.woki.payments.adyen.action.Endpoint.java

static <ResType extends Error, ReqType> ResType invoke(final ClientConfig config, final ReqType request,
        final Class<ResType> responseClass, final Options opts) throws IOException {
    Request httpRequest = createRequest(config, request, opts);
    Executor invoker = createExecutor(config);
    return invoker.execute(httpRequest).handleResponse(new ResponseHandler<ResType>() {
        public ResType handleResponse(HttpResponse response) throws IOException {
            ResType res = Endpoint.handleResponse(response, responseClass);
            if (LOG.isDebugEnabled()) {
                LOG.debug("response: {}", res);
            }//from  w  ww .ja  va2 s  . c  o  m
            return res;
        }
    });
}

From source file:org.talend.license.LicenseRetriver.java

Collection<File> checkout(final String version, final File root, final String url) {
    try {//from  w w  w.  j  av a2 s  .co  m
        return connector.doGet(url, new ResponseHandler<Collection<File>>() {

            public Collection<File> handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                Collection<File> files = new LinkedList<File>();
                InputStream stream = response.getEntity().getContent();
                ZipInputStream zip = new ZipInputStream(stream);
                String regex = Configer.getLicenseFile().replaceAll("%version", version);
                Pattern pattern = Pattern.compile(regex);
                while (true) {
                    ZipEntry entry = zip.getNextEntry();
                    if (null == entry) {
                        break;
                    }
                    try {
                        String name = entry.getName();
                        Matcher matcher = pattern.matcher(name);
                        if (matcher.find()) {
                            int count = matcher.groupCount();
                            String fname = null;
                            for (int i = 1; i <= count; i++) {
                                fname = matcher.group(i);
                                if (StringUtils.isEmpty(fname)) {
                                    continue;
                                }
                                break;
                            }

                            logger.info("found a available license {}", fname);
                            File target = new File(root, fname);
                            if (target.exists()) {
                                files.add(target);// TODO
                                continue;
                            }
                            FileOutputStream fos = new FileOutputStream(target);
                            IOUtils.copy(zip, fos);
                            IOUtils.closeQuietly(fos);
                            files.add(target);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                }
                return files;
            }
        });
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

public String doGet(String url) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {/*from  www  . j a  va2 s  .  c  o m*/
        _LOG.debug("Request URL [" + url + "]");
        String _result = _httpClient.execute(RequestBuilder.get().setUri(url).build(),
                new ResponseHandler<String>() {

                    public String handleResponse(HttpResponse response) throws IOException {
                        return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
                    }

                });
        _LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

From source file:opendap.auth.RemotePDP.java

@Override
public boolean evaluate(String userId, String resourceId, String queryString, String actionId) {

    boolean result = false;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from w  w  w .  j a  v a2 s  .  c  om

        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append(_pdpServiceEndpoint);
        requestUrl.append("?uid=").append(userId);
        requestUrl.append("&resourceId=").append(resourceId);
        requestUrl.append("&query=").append(queryString);
        requestUrl.append("&action=").append(actionId);

        HttpGet httpget = new HttpGet(requestUrl.toString());

        _log.debug("evaluate() - Executing HTTP request: " + httpget.getRequestLine());

        // ----------- Create a custom response handler ----------
        ResponseHandler<Boolean> responseHandler = new ResponseHandler<Boolean>() {

            public Boolean handleResponse(final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {

                    HttpEntity entity = response.getEntity();
                    _log.debug(entity != null ? EntityUtils.toString(entity) : "null");

                    return true;
                } else {
                    return false;
                }
            }

        };
        // -------------------------------------------------------

        result = httpclient.execute(httpget, responseHandler);
    } catch (Exception e) {
        _log.error("evaluate() - Caught {} Message: {}", e.getClass().getName(), e.getMessage());
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            _log.error("evaluate() - Caught {} Message: {}", e.getClass().getName(), e.getMessage());
            // oh well...
        }
    }

    return result;
}