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:com.ooyala.api.OoyalaApiClient.java

/**
 * Response Handler// w  w  w . ja  v a2  s. c o  m
 *
 * @return
 */
private ResponseHandler<String> createResponseHandler() {
    return new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            responseCode = response.getStatusLine().getStatusCode();
            if (entity != null) {
                return EntityUtils.toString(entity);
            } else {
                return null;
            }
        }
    };
}

From source file:org.commonjava.web.json.test.WebFixture.java

public void get(final String url, final int expectedStatus) throws Exception {
    logger.info("WebFixture: GET '{}', expecting: {}", url, expectedStatus);
    final HttpGet get = new HttpGet(url);
    try {/*from   w  ww  . j  a v a  2 s.co m*/
        http.execute(get, new ResponseHandler<Void>() {
            @Override
            public Void handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                final StatusLine sl = response.getStatusLine();
                assertThat(sl.getStatusCode(), equalTo(expectedStatus));

                return null;
            }
        });
    } finally {
        get.abort();
    }
}

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

/**
 * {@inheritDoc}/*from   w w  w  .  ja  v  a2s.  co m*/
 */
@Override
public void deleteByDocId(final EnricherJob job, final String[] documents) throws Exception {
    HttpPost httpPost = new HttpPost(new URI(deleteDocIdUri + "?dredbname=" + job.getDatabaseName() + "&docs="
            + URLEncoder.encode(StringUtils.join(documents, " "), 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;
        }
    });

    if (response.getStatusLine().getStatusCode() != HTTP_STATUS_SUCCESS)
        throw new Exception("Given document(s) could not be deleted because of status "
                + response.getStatusLine().getStatusCode() + " (" + response.getStatusLine().getReasonPhrase()
                + ")");
    else if (logger.isDebugEnabled())
        logger.debug("Result document(s) delete request sent to the indexer");
}

From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java

/**
 * @see eu.esdihumboldt.hale.io.geoserver.rest.ResourceManager#create(java.util.Map)
 *//*from   ww  w.j a va  2  s  . co m*/
@Override
public URL create(Map<String, String> parameters) {
    checkResourceSet();

    try {
        URI requestUri = buildRequestUri(getResourceListURL(), parameters);

        ByteArrayEntity entity = new ByteArrayEntity(resource.asByteArray());
        entity.setContentType(resource.contentType().getMimeType());

        return executor.execute(Request.Post(requestUri).body(entity))
                .handleResponse(new ResponseHandler<URL>() {

                    /**
                     * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse)
                     */
                    @Override
                    public URL handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (statusLine.getStatusCode() == 201) {
                            Header locationHeader = response.getFirstHeader("Location");
                            if (locationHeader != null) {
                                return new URL(locationHeader.getValue());
                            }
                        }
                        return null;
                    }
                });
    } catch (Exception e) {
        throw new ResourceException(e);
    }
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void test302() throws Exception {
    responses.add(new BasicHttpResponse(_302));
    client.execute(new HttpGet("http://example.com/302"), new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_302.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }/*  w  w w . j  av  a2s.  c o  m*/
    });
}

From source file:edu.ucsb.nceas.ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls uning this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 * @throws EZIDException if authentication fails for any reason
 *///w w  w . jav a 2  s.  c  o  m
public void login(String username, String password) throws EZIDException {
    try {
        URI serviceUri = new URI(loginServiceEndpoint);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        HttpClientContext localcontext = HttpClientContext.create();
        localcontext.setAuthCache(authCache);
        localcontext.setCredentialsProvider(credsProvider);

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(loginServiceEndpoint);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        String msg = parseIdentifierResponse(message);
    } catch (URISyntaxException e) {
        throw new EZIDException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new EZIDException(e.getMessage());
    } catch (IOException e) {
        throw new EZIDException(e.getMessage());
    }
}

From source file:com.highstreet.technologies.test.client.impl.TestClientBuilder.java

private JSONObject restConfServerConnectionTest() {

    CloseableHttpClient httpclient = TestClientImpl.getRestConfClient(this.restConfServer);

    try {/*from  ww w  . j  av  a 2s  .c  o  m*/
        String path = "/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/controller-config";

        URI uri = new URIBuilder(TestClientImpl.getTarget(this.restConfServer).toURI()).setPath(path).build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Content-Type", "application/json");
        httpget.setHeader("Accept", "application/json");

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

            @Override
            public JSONObject handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return new JSONObject(EntityUtils.toString(entity));
                } else {
                    JSONObject error = new JSONObject();
                    error.put("status", status);
                    error.put("reason", reason);
                    return error;
                }
            }
        };
        JSONObject result = httpclient.execute(httpget, responseHandler);
        if (!result.has("status")) {
            result = this.mountPointTest();
        } else {
            // error
            JSONObject checks = new JSONObject();
            checks.put("description", "RestConf connection to OpendayLight failed! ");
            checks.put("check#1", "ping " + this.restConfServer.getIpAddress());
            checks.put("check#2",
                    "User credentials: see https://wiki.opendaylight.org/view/AAA:Changing_Account_Passwords");
            checks.put("check#3", "Please paste into browser address field" + path);
            result.put("please-check", checks);
            System.out.println(result.toString(1));
        }
        return result;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:org.apache.marmotta.platform.core.services.content.HTTPContentReader.java

/**
 * Check whether the specified resource has content of the specified mimetype for this reader. Returns true
 * in this case, false otherwise.//from  w w w.  j  a v a2s. co  m
 *
 * @param resource the resource to check
 * @param mimetype the mimetype to look for
 * @return true if content of this mimetype is associated with the resource, false otherwise
 */
@Override
public boolean hasContent(Resource resource, String mimetype) {
    try {
        RepositoryConnection conn = sesameService.getConnection();
        try {
            MediaContentItem mci = FacadingFactory.createFacading(conn).createFacade(resource,
                    MediaContentItem.class);

            String location = mci.getContentLocation();

            // if no location is explicitly specified, use the resource URI itself
            if (location == null && resource instanceof URI && resource.stringValue().startsWith("http://")) {
                location = resource.stringValue();
            }

            try {
                if (location != null) {
                    log.info("reading remote resource {}", location);
                    HttpHead head = new HttpHead(location);
                    head.setHeader("Accept", mimetype);

                    return httpClientService.execute(head, new ResponseHandler<Boolean>() {
                        @Override
                        public Boolean handleResponse(HttpResponse response)
                                throws ClientProtocolException, IOException {
                            return response.getStatusLine().getStatusCode() == 200;
                        }
                    });

                } else
                    return false;
            } catch (IOException ex) {
                return false;
            }
        } finally {
            conn.commit();
            conn.close();
        }
    } catch (RepositoryException ex) {
        handleRepositoryException(ex, FileSystemContentReader.class);
        return false;
    }
}

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

public String getAttribute(Map<String, String> authMap, String deviceGUID, String attribute) {
    try {/* w  ww. jav  a2 s  .  c  om*/
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices/" + deviceGUID + "/" + attribute);

        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 content = new JSONObject(json);
        return content.getJSONObject("content").getString("value");
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}