Example usage for org.apache.http.client HttpResponseException getMessage

List of usage examples for org.apache.http.client HttpResponseException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.dmsl.anyplace.googleapi.GooglePlaces.java

/**
 * Searching places//from w  w w .  j a  v  a  2s  .co  m
 * 
 * @param latitude
 *            - latitude of place
 * @params longitude - longitude of place
 * @param radius
 *            - radius of searchable area
 * @param types
 *            - type of place to search
 * @return list of places
 * @throws IOException
 * */
public static PlacesList autocomplete(double latitude, double longitude, double radius, String query_text)
        throws IOException {

    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_AUTOCOMPLETE_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("location", latitude + "," + longitude);
        request.getUrl().put("radius", radius); // in meters
        request.getUrl().put("sensor", "false");
        request.getUrl().put("input", query_text);
        PlacesList list = request.execute().parseAs(PlacesList.class);
        return list;

    } catch (HttpResponseException e) {
        Log.e("Error:", e.getMessage());
        return null;
    }

}

From source file:com.dmsl.anyplace.googleapi.GooglePlaces.java

/**
 * Searching places/*from  w w w . j  av a 2  s.  c  om*/
 * 
 * @param latitude
 *            - latitude of place
 * @params longitude - longitude of place
 * @param radius
 *            - radius of searchable area
 * @param types
 *            - type of place to search
 * @return list of places
 * @throws IOException
 * */
public static PlacesList search(double latitude, double longitude, double radius, String query_text)
        throws IOException {

    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("location", latitude + "," + longitude);
        request.getUrl().put("rankby", "distance"); // in meters
        request.getUrl().put("sensor", "false");
        request.getUrl().put("keyword", query_text);

        Log.d("Places status", "url: " + request.getUrl().toString());

        PlacesList list = request.execute().parseAs(PlacesList.class);
        // Check log cat for places response status
        Log.d("Places Status", "" + list.status + " size: " + list.results.size());
        return list;

    } catch (HttpResponseException e) {
        Log.e("Error:", e.getMessage());
        return null;
    }

}

From source file:com.dmsl.anyplace.googleapi.GooglePlaces.java

/**
 * Searching single place full details// w w  w .  j  a v  a  2s.c  o  m
 * 
 * @param reference
 *            - reference id of place - which you will get in search api
 *            request
 * */
public static PlaceDetails getPlaceDetails(String reference) throws Exception {
    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("reference", reference);
        request.getUrl().put("sensor", "false");

        PlaceDetails place = request.execute().parseAs(PlaceDetails.class);

        return place;

    } catch (HttpResponseException e) {
        Log.e("Error in Perform Details", e.getMessage());
        throw e;
    }
}

From source file:ch.cyberduck.core.http.HttpResponseExceptionMappingService.java

@Override
public BackgroundException map(final HttpResponseException failure) {
    final StringBuilder buffer = new StringBuilder();
    this.append(buffer, failure.getMessage());
    final int statusCode = failure.getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_UNAUTHORIZED:
        return new LoginFailureException(buffer.toString(), failure);
    case HttpStatus.SC_FORBIDDEN:
        return new AccessDeniedException(buffer.toString(), failure);
    case HttpStatus.SC_NOT_FOUND:
        return new NotfoundException(buffer.toString(), failure);
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
        return new QuotaException(buffer.toString(), failure);
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return new QuotaException(buffer.toString(), failure);
    case HttpStatus.SC_PAYMENT_REQUIRED:
        return new QuotaException(buffer.toString(), failure);
    case HttpStatus.SC_BAD_REQUEST:
        return new InteroperabilityException(buffer.toString(), failure);
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
        return new InteroperabilityException(buffer.toString(), failure);
    case HttpStatus.SC_NOT_IMPLEMENTED:
        return new InteroperabilityException(buffer.toString(), failure);
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        return new InteroperabilityException(buffer.toString(), failure);
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
        return new ConnectionRefusedException(buffer.toString(), failure);
    case HttpStatus.SC_REQUEST_TIMEOUT:
        return new ConnectionTimeoutException(buffer.toString(), failure);
    }//from  w w w  .  jav  a2 s .  co m
    return this.wrap(failure, buffer);
}

From source file:org.asqatasun.contentloader.DownloaderImpl.java

private String download(String url) {
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet(url);

    httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(10000));
    httpclient.getParams().setParameter("http.connection.timeout", Integer.valueOf(10000));

    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody;// w  ww.  j ava2  s  .  c  om
    try {
        responseBody = httpclient.execute(httpget, responseHandler);
    } catch (HttpResponseException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (UnknownHostException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (SSLPeerUnverifiedException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (IOException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    }
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
    return responseBody;
}

From source file:org.opens.tanaguru.contentloader.DownloaderImpl.java

private String download(String url) {
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet(url);

    httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(10000));
    httpclient.getParams().setParameter("http.connection.timeout", Integer.valueOf(10000));

    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = null;/*from  ww  w  .ja v a 2 s. c  om*/
    try {
        responseBody = httpclient.execute(httpget, responseHandler);
    } catch (HttpResponseException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (UnknownHostException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (SSLPeerUnverifiedException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (IOException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    }
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
    return responseBody;
}

From source file:de.mpg.imeji.presentation.servlet.ExportServlet.java

/**
 * {@inheritDoc}//from   w ww  .  ja  v  a2  s.c  o  m
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    SessionBean session = getSessionBean(req, resp);
    String instanceName = session.getInstanceName();
    User user = session.getUser();
    try {
        ExportManager exportManager = new ExportManager(resp.getOutputStream(), user, req.getParameterMap());
        String exportName = instanceName + "_";
        exportName += new Date().toString().replace(" ", "_").replace(":", "-");
        if (exportManager.getContentType().equalsIgnoreCase("application/xml")) {
            exportName += ".xml";
        }
        if (exportManager.getContentType().equalsIgnoreCase("application/zip")) {
            exportName += ".zip";
        }
        resp.setHeader("Connection", "close");
        resp.setHeader("Content-Type", exportManager.getContentType());
        resp.setHeader("Content-disposition", "filename=" + exportName);
        resp.setStatus(HttpServletResponse.SC_OK);
        SearchResult result = exportManager.search();
        exportManager.export(result);
        resp.getOutputStream().flush();
    } catch (HttpResponseException he) {
        resp.sendError(he.getStatusCode(), he.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.zenoss.metrics.reporter.HttpPosterTest.java

@Test
public void authPost() throws IOException {
    stubFor(post(urlEqualTo(URL_PATH)).withHeader("Accept", matching("application/json.*"))
            .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
                    .withHeader("Set-Cookie", "cookieName=cookieValue")
                    .withBody("<response>Some content</response>")));

    URL url = new URL("http", "localhost", MOCK_PORT, URL_PATH);
    HttpPoster poster = new Builder(url).setUsername("test_user").setPassword("test_pass").build();
    poster.start();// ww w.j  av  a 2 s . c  o  m

    MetricBatch batch = new MetricBatch(8);
    batch.addMetric(new Metric("mname", 8, 9999));

    poster.post(batch);

    verify(postRequestedFor(urlEqualTo(URL_PATH))
            .withHeader("Content-Type", equalTo("application/json; charset=UTF-8"))
            .withHeader("Authorization", equalTo("Basic dGVzdF91c2VyOnRlc3RfcGFzcw==")).withRequestBody(equalTo(
                    "{\"metrics\":[{\"metric\":\"mname\",\"timestamp\":8,\"value\":9999.0,\"tags\":{}}]}")));

    //verify cookie and auth header resent and basic auth not sent
    poster.post(batch);

    verify(postRequestedFor(urlEqualTo(URL_PATH))
            .withHeader("Content-Type", equalTo("application/json; charset=UTF-8"))
            .withHeader("Cookie", equalTo("cookieName=cookieValue")).withoutHeader("Authorization")
            .withRequestBody(equalTo(
                    "{\"metrics\":[{\"metric\":\"mname\",\"timestamp\":8,\"value\":9999.0,\"tags\":{}}]}")));

    //send 401 to verify re auth
    stubFor(post(urlEqualTo(URL_PATH)).willReturn(aResponse().withStatus(401)));

    try {
        poster.post(batch);
        Assert.fail("expected unauthorized");
    } catch (HttpResponseException e) {
        Assert.assertEquals(e.getMessage(), "Unauthorized");
    }
    //setup for reauthentication with different cookie
    stubFor(post(urlEqualTo(URL_PATH)).withHeader("Accept", matching("application/json.*"))
            .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
                    .withHeader("Set-Cookie", "cookieName=newCookie")
                    .withBody("<response>Some content</response>")));
    poster.post(batch);

    //verify auth sent and no cookies
    verify(postRequestedFor(urlEqualTo(URL_PATH))
            .withHeader("Content-Type", equalTo("application/json; charset=UTF-8"))
            .withHeader("Authorization", equalTo("Basic dGVzdF91c2VyOnRlc3RfcGFzcw==")).withoutHeader("Cookie")
            .withRequestBody(equalTo(
                    "{\"metrics\":[{\"metric\":\"mname\",\"timestamp\":8,\"value\":9999.0,\"tags\":{}}]}")));

    //verify no auth and new cookie sent
    poster.post(batch);

    verify(postRequestedFor(urlEqualTo(URL_PATH))
            .withHeader("Content-Type", equalTo("application/json; charset=UTF-8"))
            .withHeader("Cookie", notMatching("cookieName=cookieValue"))
            .withHeader("Cookie", equalTo("cookieName=newCookie")).withoutHeader("Authorization")
            .withRequestBody(equalTo(
                    "{\"metrics\":[{\"metric\":\"mname\",\"timestamp\":8,\"value\":9999.0,\"tags\":{}}]}")));
    poster.shutdown();

}

From source file:au.csiro.casda.sodalint.ValidateAsync.java

private String getAsyncContent(final Reporter reporter, URL address) {
    try {/* ww  w .  j  a  va 2s  .c  o  m*/
        String content = getXmlContentFromUrl(address.toString());
        if (content == null) {
            reporter.report(SodaCode.E_ASCO, "Async response contains no content");
        }
        return content;
    } catch (HttpResponseException e) {
        reporter.report(SodaCode.E_ASCO,
                "Unexpected http response: " + e.getStatusCode() + " Reason: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        reporter.report(SodaCode.E_ASCO, "Async response has an unexpected content type:" + e.getMessage());
    } catch (IOException e) {
        reporter.report(SodaCode.E_ASCO, "Unable to read async response: " + e.getMessage());
    }

    return null;
}

From source file:org.neo4j.ogm.integration.TransactionRequestHandlerTest.java

@Test
public void shouldRollbackExplicitTransactionWhenServerTransactionTimeout() throws InterruptedException {

    SessionFactory sessionFactory = new SessionFactory();
    session = sessionFactory.openSession(neo4jRule.url());

    try (Transaction tx = session.beginTransaction()) {
        // Wait for transaction to timeout on server
        Thread.sleep(3000);//  ww  w .j av  a2 s  .c o m
        // Try to purge database using timed-out transaction
        session.purgeDatabase();
        fail("Should have caught exception");
    } catch (ResultProcessingException rpe) {
        HttpResponseException cause = (HttpResponseException) rpe.getCause();
        assertEquals("Not Found", cause.getMessage());
        assertEquals(404, cause.getStatusCode());
    }
    // should pass, because previous transaction will be closed by try block
    session.purgeDatabase();
}