Example usage for org.apache.commons.httpclient HttpException getMessage

List of usage examples for org.apache.commons.httpclient HttpException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.prashsoft.javakiva.KivaUtil.java

public static Object getBeanResponse(String urlSuffix, String urlMethod, String urlParams) {

    Object bean = null;// w  w w . j  a  v a 2 s  .  c om

    String url = createKivaAPIUrl(urlSuffix, urlMethod, urlParams);

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println(url + " :: Method failed! : " + method.getStatusLine());
            return null;
        }

        // Read the response body.

        InputStream is = method.getResponseBodyAsStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));

        String datastr = null;
        StringBuffer sb = new StringBuffer();

        String inputLine;

        while ((inputLine = in.readLine()) != null)
            sb.append(inputLine);

        in.close();
        is.close();

        String response = sb.toString();

        // Deal with the response.
        JSONObject jsonObject = JSONObject.fromObject(response);

        bean = JSONObject.toBean(jsonObject);

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("Fatal general error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return bean;

}

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient.java

public static String getEngineComplianceVersion(String url)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;/*w  ww  .j a  v  a  2s.  com*/
    HttpClient client;
    PostMethod method;
    NameValuePair[] nameValuePairs;

    version = null;
    client = new HttpClient();
    method = new PostMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", "complianceVersion") }; //$NON-NLS-1$ //$NON-NLS-2$

    method.setRequestBody(nameValuePairs);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient.serviceFailed"), //$NON-NLS-1$
                    method.getStatusLine().toString(), method.getResponseBodyAsString());
        } else {
            version = method.getResponseBodyAsString();
        }

    } catch (HttpException e) {
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.5", e.getMessage())); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.6", e.getMessage())); //$NON-NLS-1$
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return version;
}

From source file:com.ephesoft.dcma.util.WebServiceCaller.java

/**
 * Api to simply hit webservice. It will return true or false if Webservice hit was successful or unsuccessful respectively
 * //from w ww.  j  a  v a 2  s .  c o  m
 * @param serviceURL
 * @return
 */
private static boolean hitWebservice(final String serviceURL) {
    LOGGER.debug("Giving a hit at webservice URL.");
    boolean isActive = false;
    if (!EphesoftStringUtil.isNullOrEmpty(serviceURL)) {

        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        PostMethod method = new PostMethod(serviceURL);

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode == HttpStatus.SC_OK) {
                isActive = true;
            } else {
                LOGGER.info(EphesoftStringUtil.concatenate("Execute Method failed: ", method.getStatusLine()));
            }
        } catch (HttpException httpException) {
            LOGGER.error(
                    EphesoftStringUtil.concatenate("Fatal protocol violation: ", httpException.getMessage()));
        } catch (IOException ioException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Fatal transport error: ", ioException.getMessage()));
        } finally {
            // Release the connection.
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return isActive;
}

From source file:fr.eurecom.nerd.core.proxy.ExtractivClient.java

/**
 * Get the output from the REST server/*ww w  .j  av a  2  s  .  c  o m*/
 */
private static InputStream fetchHttpRequest(final HttpMethodBase method) throws BadInputException {
    try {

        final int statusCode = getClient().executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new BadInputException(
                    "webpage status " + HttpStatus.getStatusText(statusCode) + "(" + statusCode + ")");
        }

        final InputStream is = new ByteArrayInputStream(method.getResponseBody());
        final GZIPInputStream zippedInputStream = new GZIPInputStream(is);
        return zippedInputStream;
    } catch (HttpException e) {
        throw new BadInputException("Fatal protocol violation " + e.getMessage(), e);
    } catch (IOException e) {
        //e.g. www.google.assadsaddsa
        throw new BadInputException("Fatal transport error " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:fr.cls.atoll.motu.library.misc.cas.TestCASRest.java

public static Cookie[] validateFromCAS2(String username, String password) throws Exception {

    String url = casServerUrlPrefix + "/v1/tickets?";

    String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and
    // re-created, using a persistence mechanism of choice,
    // Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient();

    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443);

    URI uri = new URI(url + s, true);
    // use relative url only
    PostMethod httpget = new PostMethod(url);
    httpget.addParameter("username", username);
    httpget.addParameter("password", password);

    HostConfiguration hc = new HostConfiguration();
    hc.setHost("atoll-dev.cls.fr", 8443, easyhttps);
    // client.executeMethod(hc, httpget);

    client.setState(initialState);/*from  www.  j  a va  2s .c  om*/

    // Create a method instance.
    System.out.println(url + s);

    GetMethod method = new GetMethod(url + s);
    // GetMethod method = new GetMethod(url );

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //           
    // client.getState().setProxyCredentials(authScope, credentials);
    Cookie[] cookies = null;

    try {
        // Execute the method.
        // int statusCode = client.executeMethod(method);
        int statusCode = client.executeMethod(hc, httpget);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        for (Header header : method.getRequestHeaders()) {
            System.out.println(header.getName());
            System.out.println(header.getValue());
        }
        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

        System.out.println("Response status code: " + statusCode);
        // Get all the cookies
        cookies = client.getState().getCookies();
        // Display the cookies
        System.out.println("Present cookies: ");
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(" - " + cookies[i].toExternalForm());
        }

        Assertion assertion = AssertionHolder.getAssertion();
        if (assertion == null) {
            System.out.println("<p>Assertion is null</p>");
        }

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return cookies;

}

From source file:com.tribune.uiautomation.testscripts.Photo.java

public static Photo find(String namespace, String slug) throws JSONException {
    if (namespace == null || slug == null) {
        return null;
    }/* ww w .ja  v a  2  s  .  co m*/
    GetMethod get = new GetMethod(constructResourceUrl(namespace, slug));
    setRequestHeaders(get);
    Photo photo = null;

    try {
        HttpClient client = new HttpClient();
        int status = client.executeMethod(get);

        log.debug("Photo Service find return status: " + get.getStatusLine());

        if (status == HttpStatus.SC_OK) {
            photo = new Photo();
            processResponse(photo, get.getResponseBodyAsStream());
            photo.setPersisted(true);
        }
    } catch (HttpException e) {
        log.fatal("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.fatal("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        get.releaseConnection();
    }

    return photo;
}

From source file:com.gisgraphy.domain.geoloc.importer.ImporterHelper.java

/**
 * @param URL the HTTP URL/*from   ww  w.  jav a2  s. co  m*/
 * @return The size of the HTTP file using HTTP head method.
 */
public static long getHttpFileSize(String URL) {
    HeadMethod headMethod = new HeadMethod(URL);

    try {
        client.executeMethod(headMethod);
        Header[] contentLengthHeaders = headMethod.getResponseHeaders("Content-Length");
        if (contentLengthHeaders.length == 1) {
            logger.error("HTTP file " + URL + " = " + contentLengthHeaders[0].getValue());
            return new Long(contentLengthHeaders[0].getValue());
        } else if (contentLengthHeaders.length <= 0) {
            return -1L;
        }
    } catch (HttpException e) {
        logger.error("can not execute head method for " + URL + " : " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("can not execute head method for " + URL + " : " + e.getMessage(), e);
    } finally {
        headMethod.releaseConnection();
    }
    return -1;

}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java

/**
 * /*from   ww  w. j  a  va2  s .c om*/
 * execute the HTTP Get method and return response as Input stream
 * 
 * @param httpclient
 *            HTTPClient
 * @param get
 *            GetMethod
 * @return
 * @throws IOException
 * @throws HttpException
 */

private static InputStream executeHTTPMethod(HttpClient httpclient, GetMethod get,
        String authorizationServerURL) {
    try {
        httpclient.executeMethod(get);
    } catch (HttpException e) {
        ApexUnitUtils.shutDownWithDebugLog(e,
                "Encountered HTTP exception when executing get method using OAuth authentication for the url "
                        + authorizationServerURL + ". The error says: " + e.getMessage());
    } catch (IOException e) {
        ApexUnitUtils.shutDownWithDebugLog(e,
                "Encountered IO exception when executing get method using OAuth authentication for the url "
                        + authorizationServerURL + ". The error says: " + e.getMessage());
    }
    LOG.info("Status code : " + get.getStatusCode() + "   Status message from the get request:"
            + get.getStatusText() + " Reason phrase: " + get.getStatusLine().getReasonPhrase());

    InputStream instream = null;
    try {
        // don't delete the below line --i.e. getting response body as
        // string. Getting response as stream fails upon deleting the below
        // line! strange!
        String respStr;
        respStr = get.getResponseBodyAsString();
        instream = get.getResponseBodyAsStream();
    } catch (IOException e) {

        ApexUnitUtils.shutDownWithDebugLog(e,
                "Encountered IO exception when obtaining response body for the get method. The error says: "
                        + e.getMessage());
    }
    return instream;
}

From source file:edu.utah.further.core.ws.HttpUtil.java

/**
 * Open an HTTP GET method connection to a URL and read the returned response into an
 * object.//from   w w w  .  jav a 2s  .com
 * 
 * @param <T>
 *            return type
 * @param url
 *            remote URL (usually a web service's URL)
 * @param timeoutSecs
 *            HTTP socket connection timeout [seconds]
 * @return <code>HttpClient</code> {@link HttpMethod} transfer object, containing the
 *         response headers and body
 * @throws WsException
 *             if an error as occurred either in transport or protocol
 */
public static HttpResponseTo getHttpGetResponseBody(final String url, final int timeoutSecs)
        throws WsException {
    // Create an instance of HttpClient with appropriate parameters
    final SimpleHttpConnectionManager cm = new SimpleHttpConnectionManager();
    final HttpConnectionManagerParams params = cm.getParams();
    params.setConnectionTimeout(timeoutSecs * 1000);
    params.setSoTimeout(timeoutSecs * 1000);
    cm.setParams(params);
    final HttpClient client = new HttpClient(cm);

    // Create a method instance
    final GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false));
    try {
        // Execute the method
        /* final int statusCode = */client.executeMethod(method);
        // if (statusCode != HttpStatus.SC_OK)
        // {
        // log.error("Method failed: " + method.getStatusLine());
        // }
        return new HttpResponseTo(method);
    } catch (final HttpException e) {
        // HTTP protocol violation (e.g. bad method?!)
        throw new WsException(PROTOCOL_VIOLATION, e.getMessage());
    } catch (final IOException e) {
        // Transport error. Could be an invalid URL
        throw new WsException(TRANSPORT_ERROR, e.getMessage());
    } catch (final Throwable e) {
        // Exceptions
        throw new WsException(SERVER_ERROR, e.getMessage());
    } finally {
        // Important: release the connection
        method.releaseConnection();
    }
}

From source file:com.gisgraphy.importer.ImporterHelper.java

/**
 * @param URL the HTTP URL//  w ww.j av a 2  s .c o  m
 * @return The size of the HTTP file using HTTP head method 
 * or -1 if error or the file doesn't exists
 */
public static long getHttpFileSize(String URL) {
    HeadMethod headMethod = new HeadMethod(URL);
    //we can not follow redirect because Geonames send a 302 found HTTP status code when a file doen't exists
    headMethod.setFollowRedirects(false);
    try {
        int code = client.executeMethod(headMethod);
        int firstDigitOfCode = code / 100;
        switch (firstDigitOfCode) {
        case 4:
            logger.error("Can not determine HTTP file size of " + URL + " because it does not exists (" + code
                    + ")");
            return -1;
        //needed to catch 3XX code because Geonames send a 302 found HTTP status code when a file doen't exists
        case 3:
            logger.error("Can not determine HTTP file size of " + URL + " because it does not exists (" + code
                    + ")");
            return -1;
        case 5:
            logger.error(
                    "Can not determine HTTP file size of " + URL + " because the server send an error " + code);
            return -1;

        default:
            break;
        }
        Header[] contentLengthHeaders = headMethod.getResponseHeaders("Content-Length");
        if (contentLengthHeaders.length == 1) {
            logger.info("HTTP file size of " + URL + " = " + contentLengthHeaders[0].getValue());
            return new Long(contentLengthHeaders[0].getValue());
        } else if (contentLengthHeaders.length <= 0) {
            return -1L;
        }
    } catch (HttpException e) {
        logger.error("can not execute head method for " + URL + " : " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("can not execute head method for " + URL + " : " + e.getMessage(), e);
    } finally {
        headMethod.releaseConnection();
    }
    return -1;
}