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.dragoniade.deviantart.favorites.FavoritesDownloader.java

private String getDocumentUrl(Deviation da, AtomicBoolean download) {
    String downloadUrl = da.getDocumentDownloadUrl();
    GetMethod method = new GetMethod(downloadUrl);

    try {/*w ww  . jav  a  2  s . c  o m*/
        int sc = -1;
        do {
            method.setFollowRedirects(false);
            sc = client.executeMethod(method);
            requestCount++;

            if (sc >= 300 && sc <= 399) {
                String location = method.getResponseHeader("Location").getValue();
                method.releaseConnection();
                return location;
            } else {
                LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                int res = showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_CANCEL_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">" + downloadUrl
                            + " has an error" + "</a>";
                    setPaneText(text);
                    method.releaseConnection();
                    progress.incremTotal();
                    download.set(false);
                    return null;
                }
                if (res == JOptionPane.CANCEL_OPTION) {
                    return null;
                }
            }
        } while (true);
    } catch (HttpException e) {
        showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    } catch (IOException e) {
        showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

From source file:com.kaltura.client.KalturaClientBase.java

protected String executeMethod(HttpClient client, PostMethod method) throws KalturaApiException {
    String responseString = "";
    try {/*from w w w.  j av  a 2s . c  o m*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (logger.isEnabled()) {
            Header[] headers = method.getRequestHeaders();
            for (Header header : headers)
                logger.debug("Header [" + header.getName() + " value [" + header.getValue() + "]");
        }

        if (logger.isEnabled() && statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: " + method.getStatusLine());
            throw new KalturaApiException("Unexpected Http return code: " + statusCode);
        }

        // Read the response body
        InputStream responseBodyIS = null;
        if (isGzipResponse(method)) {
            responseBodyIS = new GZIPInputStream(method.getResponseBodyAsStream());
            if (logger.isEnabled())
                logger.debug("Using gzip compression to handle response for: " + method.getName() + " "
                        + method.getPath() + "?" + method.getQueryString());
        } else {
            responseBodyIS = method.getResponseBodyAsStream();
            if (logger.isEnabled())
                logger.debug("No gzip compression for this response");
        }
        String responseBody = readRemoteInvocationResult(responseBodyIS);
        responseHeaders = method.getResponseHeaders();

        // print server debug info
        String serverName = null;
        String serverSession = null;
        for (Header header : responseHeaders) {
            if (header.getName().compareTo("X-Me") == 0)
                serverName = header.getValue();
            else if (header.getName().compareTo("X-Kaltura-Session") == 0)
                serverSession = header.getValue();
        }
        if (serverName != null || serverSession != null)
            logger.debug("Server: [" + serverName + "], Session: [" + serverSession + "]");

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        responseString = new String(responseBody.getBytes(), UTF8_CHARSET); // Unicon: this MUST be set to UTF-8 charset -AZ
        if (logger.isEnabled()) {
            if (responseString.length() < MAX_DEBUG_RESPONSE_STRING_LENGTH) {
                logger.debug(responseString);
            } else {
                logger.debug("Received long response. (length : " + responseString.length() + ")");
            }
        }

        return responseString;

    } catch (HttpException e) {
        if (logger.isEnabled())
            logger.error("Fatal protocol violation: " + e.getMessage(), e);
        throw new KalturaApiException("Protocol exception occured while executing request");
    } catch (SocketTimeoutException e) {
        if (logger.isEnabled())
            logger.error("Fatal transport error: " + e.getMessage(), e);
        throw new KalturaApiException("Request was timed out");
    } catch (ConnectTimeoutException e) {
        if (logger.isEnabled())
            logger.error("Fatal transport error: " + e.getMessage(), e);
        throw new KalturaApiException("Connection to server was timed out");
    } catch (IOException e) {
        if (logger.isEnabled())
            logger.error("Fatal transport error: " + e.getMessage(), e);
        throw new KalturaApiException("I/O exception occured while reading request response");
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:com.borhan.client.BorhanClientBase.java

protected String executeMethod(HttpClient client, PostMethod method) throws BorhanApiException {
    String responseString = "";
    try {/*from   ww w .  j a v a 2  s. c  om*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (logger.isEnabled()) {
            Header[] headers = method.getRequestHeaders();
            for (Header header : headers)
                logger.debug("Header [" + header.getName() + " value [" + header.getValue() + "]");
        }

        if (logger.isEnabled() && statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: " + method.getStatusLine());
            throw new BorhanApiException("Unexpected Http return code: " + statusCode);
        }

        // Read the response body
        InputStream responseBodyIS = null;
        if (isGzipResponse(method)) {
            responseBodyIS = new GZIPInputStream(method.getResponseBodyAsStream());
            if (logger.isEnabled())
                logger.debug("Using gzip compression to handle response for: " + method.getName() + " "
                        + method.getPath() + "?" + method.getQueryString());
        } else {
            responseBodyIS = method.getResponseBodyAsStream();
            if (logger.isEnabled())
                logger.debug("No gzip compression for this response");
        }
        String responseBody = readRemoteInvocationResult(responseBodyIS);
        responseHeaders = method.getResponseHeaders();

        // print server debug info
        String serverName = null;
        String serverSession = null;
        for (Header header : responseHeaders) {
            if (header.getName().compareTo("X-Me") == 0)
                serverName = header.getValue();
            else if (header.getName().compareTo("X-Borhan-Session") == 0)
                serverSession = header.getValue();
        }
        if (serverName != null || serverSession != null)
            logger.debug("Server: [" + serverName + "], Session: [" + serverSession + "]");

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        responseString = new String(responseBody.getBytes(UTF8_CHARSET), UTF8_CHARSET); // Unicon: this MUST be set to UTF-8 charset -AZ
        if (logger.isEnabled()) {
            if (responseString.length() < MAX_DEBUG_RESPONSE_STRING_LENGTH) {
                logger.debug(responseString);
            } else {
                logger.debug("Received long response. (length : " + responseString.length() + ")");
            }
        }

        return responseString;

    } catch (HttpException e) {
        if (logger.isEnabled())
            logger.error("Fatal protocol violation: " + e.getMessage(), e);
        throw new BorhanApiException("Protocol exception occured while executing request");
    } catch (SocketTimeoutException e) {
        if (logger.isEnabled())
            logger.error("Fatal transport error: " + e.getMessage(), e);
        throw new BorhanApiException("Request was timed out");
    } catch (ConnectTimeoutException e) {
        if (logger.isEnabled())
            logger.error("Fatal transport error: " + e.getMessage(), e);
        throw new BorhanApiException("Connection to server was timed out");
    } catch (IOException e) {
        if (logger.isEnabled())
            logger.error("Fatal transport error: " + e.getMessage(), e);
        throw new BorhanApiException("I/O exception occured while reading request response");
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String getMethod(String url, String userId, String groupId, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    setHeaders(method, groupId, userId);

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

    String response = "";

    try {//  w w  w  . j a  v a2s . c o  m
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String putMethod(String url, String payload, String bonfireUserId, String bonfireGroupId,
        Boolean exception) {/*from   ww  w.j  a v  a 2 s .c o m*/
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PutMethod method = new PutMethod(url);
    setHeaders(method, bonfireGroupId, bonfireUserId);
    //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML);

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

    String response = "";

    try {
        // We set the payload
        StringRequestEntity payloadEntity = new StringRequestEntity(payload,
                SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8");
        method.setRequestEntity(payloadEntity);

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

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String postMethod(String url, String payload, String bonfireUserId, String bonfireGroupId,
        Boolean exception) {//from   w w w  .j a va 2 s.  co  m
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    setHeaders(method, bonfireGroupId, bonfireUserId);
    //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML);

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

    String response = "";

    try {
        // We set the payload
        StringRequestEntity payloadEntity = new StringRequestEntity(payload,
                SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8");
        method.setRequestEntity(payloadEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);
        logger.debug("Status Code: " + statusCode);

        if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:com.celamanzi.liferay.portlets.rails286.Rails286Portlet.java

private byte[] callRails(PortletRequest request, PortletResponse response) throws PortletException {

    /**//from   w w w  . j  av  a2s. c  om
     * Session storage.
     *
     * The current host, servlet and route are stored into the session.
     * The session is manipulated in the Render Filter.
     *
     * APPLICATION_SCOPE stores data across all user portlets in the same session.
     * PORTLET_SCOPE stores information only accessible to the user's RailsPortlet instance.
     *
     * @see javax.portlet.PortletSession
     * http://www.bluesunrise.com/portlet-api/javax/portlet/PortletSession.html
     *
     */
    PortletSession session = request.getPortletSession(true);

    /**
     * Host and route.
     *
     * Gets the base URL and the route from the session.
     */
    setRailsBaseUrl(session);
    setRailsRoute(session);
    setServlet(session);

    String railsHost = getRailsBaseUrl().getHost();

    byte[] railsBytes = new byte[] {};

    // check the server and route
    if (railsHost == null) {
        throw new PortletException("The host is undefined!");
    }
    if (getRailsRoute() == null) {
        log.warn("The requested route is undefined");
        setRailsRoute("/");
    }

    // are we in EDIT mode?
    if (request.getPortletMode().equals(PortletMode.EDIT)) {
        log.debug("Edit mode, defining preferences URL");
        definePreferencesURL(session);
        log.debug("RailsRoute: " + getRailsRoute());
    }

    // TODO: if the server is unreachable
    //if () {
    //  throw new PortletException("The server " + railsHost + " was unreachable.");
    //}

    try {
        java.net.URL requestUrl = getRequestURL();
        Map<String, Cookie> cookies = getCookies(session, request, response);

        /*
        // Retrieve servlet cookies.
        // Author Reinaldo Silva
        // Needs tests!
        Cookie[] servletCookies = OnlineUtils.getRequestCookies(request, requestUrl);
        for (int i = 0; i < servletCookies.length; i++) {
           if (!cookies.containsKey(servletCookies[i].getName()))
              cookies.put((String)servletCookies[i].getName(), (Cookie)servletCookies[i]);
        }
        */

        String requestMethod = getRequestMethod(session);
        URL httpReferer = getHttpReferer(session);
        java.util.Locale locale = request.getLocale();

        String x_request = (String) request.getAttribute("X_REQUESTED_WITH");
        boolean ajax = false;
        if ((x_request != null) && x_request.equals("XMLHttpRequest"))
            ajax = true;

        /**
         * Execute the request
         */
        setClient(new OnlineClient(requestUrl, cookies, httpReferer, locale, ajax));

        /**
         * GET
         */
        if (requestMethod.equals("get")) {
            railsBytes = executeGet(session, getClient());
        }

        /**
         * POST, PUT (PUT is sent as POST)
         */
        else if (requestMethod.equals("post") || requestMethod.equals("put")) {
            railsBytes = executePost(request, httpReferer, session, getClient());
        }

        // OPTIONS, HEAD, DELETE, TRACE, CONNECT
        else {
            throw new PortletException("Unsupported HTTP method: " + requestMethod);
        }

    } catch (HttpException e) {
        log.error("callRails: HttpException: " + e.getMessage() + "\n" + new String(railsBytes));
        railsBytes = e.getMessage().getBytes();
    } catch (IOException e) {
        log.error("callRails: IOException: " + e.getMessage() + "\n" + new String(railsBytes));
        railsBytes = e.getMessage().getBytes();
    }

    // set the response status code (for tests)
    responseStatusCode = client.getStatusCode();
    return railsBytes;
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context,
        String serverId) {/* www.j  a v a  2 s .  co  m*/
    ContextResult response = new ContextResult();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg(",serverId");
        return response;
    }
    if (log.isDebugEnabled())
        log.debug("processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + ","
                + serverId + ")");

    String postUrl = "/diamond-server/admin.do?method=postConfig";
    PostMethod post = new PostMethod(postUrl);
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        NameValuePair dataId_value = new NameValuePair("dataId", dataId);
        NameValuePair group_value = new NameValuePair("group", groupName);
        NameValuePair content_value = new NameValuePair("content", context);

        // 
        post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value });
        // 
        ConfigInfo configInfo = new ConfigInfo();
        configInfo.setDataId(dataId);
        configInfo.setGroup(groupName);
        configInfo.setContent(context);
        if (log.isDebugEnabled())
            log.debug("ConfigInfo: " + configInfo);
        // 
        response.setConfigInfo(configInfo);
        // http
        int status = client.executeMethod(post);
        response.setReceiveResult(post.getResponseBodyAsString());
        response.setStatusCode(status);
        log.info("" + status + "," + post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            response.setSuccess(true);
            response.setStatusMsg("");
            log.info(", dataId=" + dataId + ",group=" + groupName + ",content=" + context
                    + ",serverId=" + serverId);
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg(", :" + require_timeout + "");
            log.error(":" + require_timeout + ", dataId=" + dataId + ",group="
                    + groupName + ",content=" + context + ",serverId=" + serverId);
        } else {
            response.setSuccess(false);
            response.setStatusMsg(", :" + status);
            log.error(":" + response.getReceiveResult() + ",dataId=" + dataId + ",group="
                    + groupName + ",content=" + context + ",serverId=" + serverId);
        }
    } catch (HttpException e) {
        response.setStatusMsg("HttpException" + e.getMessage());
        log.error("HttpException: dataId=" + dataId + ",group=" + groupName + ",content=" + context
                + ",serverId=" + serverId, e);
    } catch (IOException e) {
        response.setStatusMsg("IOException" + e.getMessage());
        log.error("IOException: dataId=" + dataId + ",group=" + groupName + ",content=" + context
                + ",serverId=" + serverId, e);
    } finally {
        // 
        post.releaseConnection();
    }

    return response;
}

From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context,
        String serverId) {/*  w w  w .  j  a  va2  s.  c  o m*/
    ContextResult response = new ContextResult();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg(",??serverId?");
        return response;
    }
    if (log.isDebugEnabled())
        log.debug("processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + ","
                + serverId + ")?");

    String postUrl = "/diamond-server/admin.do?method=postConfig";
    PostMethod post = new PostMethod(postUrl);
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        NameValuePair dataId_value = new NameValuePair("dataId", dataId);
        NameValuePair group_value = new NameValuePair("group", groupName);
        NameValuePair content_value = new NameValuePair("content", context);

        // ?
        post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value });
        // ?
        ConfigInfo configInfo = new ConfigInfo();
        configInfo.setDataId(dataId);
        configInfo.setGroup(groupName);
        configInfo.setContent(context);
        if (log.isDebugEnabled())
            log.debug("?ConfigInfo: " + configInfo);
        // ??
        response.setConfigInfo(configInfo);
        // http??
        int status = client.executeMethod(post);
        response.setReceiveResult(post.getResponseBodyAsString());
        response.setStatusCode(status);
        log.info("??" + status + ",?" + post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            response.setSuccess(true);
            response.setStatusMsg("???");
            log.info("???, dataId=" + dataId + ",group=" + groupName + ",content=" + context
                    + ",serverId=" + serverId);
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("??, :" + require_timeout + "");
            log.error("??:" + require_timeout + ", dataId="
                    + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("??, ??:" + status);
            log.error("??:" + response.getReceiveResult() + ",dataId=" + dataId + ",group="
                    + groupName + ",content=" + context + ",serverId=" + serverId);
        }
    } catch (HttpException e) {
        response.setStatusMsg("???HttpException" + e.getMessage());
        log.error("???HttpException: dataId=" + dataId + ",group=" + groupName + ",content="
                + context + ",serverId=" + serverId, e);
    } catch (IOException e) {
        response.setStatusMsg("???IOException" + e.getMessage());
        log.error("???IOException: dataId=" + dataId + ",group=" + groupName + ",content="
                + context + ",serverId=" + serverId, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

/**
 * //from   w w  w . ja v a 2  s .c  o m
 * 
 * @param serverId
 * @param id
 * @return
 */
private ContextResult processDelete(String serverId, long id) {
    ContextResult response = new ContextResult();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg(",serverId");
        return response;
    }
    log.info("processDelete(" + serverId + "," + id);
    String url = "/diamond-server/admin.do?method=deleteConfig&id=" + id;
    GetMethod method = new GetMethod(url);
    configureGetMethod(method);
    try {

        int status = client.executeMethod(method);
        response.setStatusCode(status);
        switch (status) {
        case HttpStatus.SC_OK:
            response.setSuccess(true);
            response.setReceiveResult(getContent(method));
            response.setStatusMsg(", url=" + url);
            log.warn(", url=" + url);
            break;
        case HttpStatus.SC_REQUEST_TIMEOUT:
            response.setSuccess(false);
            response.setStatusMsg("" + require_timeout + "");
            log.error(":" + require_timeout + ", id=" + id + ",serverId="
                    + serverId);
            break;
        default:
            response.setSuccess(false);
            response.setStatusMsg("" + status);
            log.error("" + status + ", id=" + id + ",serverId=" + serverId);
            break;
        }

    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("," + e.getMessage());
        log.error(", id=" + id + ",serverId=" + serverId, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("," + e.getMessage());
        log.error(", id=" + id + ",serverId=" + serverId, e);
    } finally {
        // 
        method.releaseConnection();
    }

    return response;
}