Example usage for org.apache.commons.httpclient StatusLine toString

List of usage examples for org.apache.commons.httpclient StatusLine toString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient StatusLine toString.

Prototype

public final String toString() 

Source Link

Usage

From source file:flex.messaging.services.http.proxy.ResponseFilter.java

protected void checkStatusCode(ProxyContext context) {
    int statusCode = context.getStatusCode();
    // FIXME: Why do this only for HTTP Proxy? Why not WebServices?
    if (statusCode >= 400 && statusCode != 401 & statusCode != 403 && !context.isSoapRequest()) {
        StatusLine statusLine = context.getHttpMethod().getStatusLine();
        String reason = null;/*from  w w w.j  a  v a 2s  . c o  m*/

        if (statusLine != null)
            reason = statusLine.toString();

        if (reason == null || "".equals(reason))
            reason = String.valueOf(statusCode);

        ProxyException pe = new ProxyException();
        pe.setMessage(STATUS_ERROR, new Object[] { reason });
        pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
        pe.setDetails(STATUS_ERROR, "1", new Object[] { reason });
        pe.setStatusCode(statusCode);
        throw pe;
    }
}

From source file:ait.ffma.service.preservation.riskmanagement.api.PreservationRiskmanagementServiceImpl.java

/**
 * This method tries to establish HTTP connection for passed URI
 * @param uri The URI to verify/*from  w ww  .  j  a  va  2  s. c om*/
 * @param responseLineList 
 *        This list collects response lines for broken URIs
 * @param brokenUriList
 *        This list collects broken URIs
 */
private void verifyUri(String uri, List<String> responseLineList, List<String> brokenUriList) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    try {
        HttpMethod method = new GetMethod(uri);
        method.setFollowRedirects(true);
        client.executeMethod(method);
        int response = method.getStatusCode();
        if (response != 200) {
            StatusLine responseLine = method.getStatusLine();
            log.info("uri: " + uri + ", response: " + response + ", responseLine: " + responseLine.toString());
            brokenUriList.add(uri);
            responseLineList.add(responseLine.toString());
        }
        method.releaseConnection();
    } catch (IOException e) {
        log.info("Unable to connect to " + uri + " verification error: " + e);
        brokenUriList.add(uri);
        responseLineList.add(e.getMessage());
    }
}

From source file:flex.messaging.services.http.proxy.SecurityFilter.java

private void sendSecurityInfo(ProxyContext context) {
    Target target = context.getTarget();
    String targetHost = target.getUrl().getHost();

    int statusCode = 200;

    boolean customAuth = target.useCustomAuthentication();

    StatusLine statusLine = context.getHttpMethod().getStatusLine();
    if (statusLine != null) {
        statusCode = statusLine.getStatusCode();
    }//ww w .  j a  v  a  2 s.c o  m

    context.setStatusCode(statusCode);

    if (statusCode == 401 || statusCode == 403) {
        if (!customAuth) {
            if (!context.isHttpRequest()) {
                throw new ProxyException(NO_BASIC_NOT_HTTP);
            } else if (context.isSoapRequest()) {
                // Note: if we remove this error, must do the proxyDomain/targetHost check as done above
                throw new ProxyException(NO_BASIC_FOR_SOAP);
            } else {
                // Don't allow a 401 (and 403, although this should never happen) to be sent to the client
                // if the service is not using custom authentication and the domains do not match

                if (!context.isLocalDomainAndPort()) {
                    HttpServletRequest clientRequest = FlexContext.getHttpRequest();

                    String errorMessage = ProxyConstants.DOMAIN_ERROR + " . The proxy domain:port is "
                            + clientRequest.getServerName() + ":" + clientRequest.getServerPort()
                            + " and the target domain:port is " + targetHost + ":" + target.getUrl().getPort();

                    Log.getLogger(HTTPProxyService.LOG_CATEGORY).error(errorMessage);

                    throw new ProxyException(DOMAIN_ERROR);
                } else {
                    //For BASIC Auth, send back the status code
                    HttpServletResponse clientResponse = FlexContext.getHttpResponse();
                    clientResponse.setStatus(statusCode);
                }
            }
        } else {
            String message = null;
            if (statusLine != null)
                message = statusLine.toString();

            if (statusCode == 401) {
                ProxyException se = new ProxyException();
                se.setCode("Client.Authentication");
                if (message == null) {
                    se.setMessage(LOGIN_REQUIRED);
                } else {
                    se.setMessage(EMPTY_ERROR, new Object[] { message });
                }

                Header header = context.getHttpMethod().getResponseHeader(ProxyConstants.HEADER_AUTHENTICATE);
                if (header != null)
                    se.setDetails(header.getValue());
                throw se;
            } else {
                ProxyException se = new ProxyException();
                se.setCode("Client.Authentication");
                if (message == null) {
                    se.setMessage(UNAUTHORIZED_ERROR);
                } else {
                    se.setMessage(EMPTY_ERROR, new Object[] { message });
                }
                throw se;
            }
        }
    }
}

From source file:nl.nn.adapterframework.http.HttpSender.java

public String sendMessageWithTimeoutGuarded(String correlationID, String message,
        ParameterResolutionContext prc) throws SenderException, TimeOutException {
    ParameterValueList pvl = null;/*from  w w w . j  a  v a2s.c o  m*/
    try {
        if (prc != null && paramList != null) {
            pvl = prc.getValues(paramList);
        }
    } catch (ParameterException e) {
        throw new SenderException(
                getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
    }
    URI uri;
    HttpMethod httpmethod;
    HostConfiguration hostconfiguration = new HostConfiguration(hostconfigurationBase);
    try {
        if (urlParameter != null) {
            String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
            uri = getURI(url);
        } else {
            uri = staticUri;
        }

        Map<String, String> headersParamsMap = new HashMap<String, String>();
        if (headersParams != null) {
            StringTokenizer st = new StringTokenizer(headersParams, ",");
            while (st.hasMoreElements()) {
                headersParamsMap.put(st.nextToken(), null);
            }
        }

        if (!isParamsInUrl()) {
            httpmethod = getPostMethodWithParamsInBody(uri, message, pvl, headersParamsMap, prc);
        } else {
            httpmethod = getMethod(uri, message, pvl, headersParamsMap);
            if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType())
                    && !"REPORT".equals(getMethodType())) {
                httpmethod.setFollowRedirects(isFollowRedirects());
            }
        }

        int port = getPort(uri);

        if (socketfactory != null && "https".equals(uri.getScheme())) {
            Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port);
            hostconfiguration.setHost(uri.getHost(), port, authhttps);
        } else {
            hostconfiguration.setHost(uri.getHost(), port, uri.getScheme());
        }
        log.info(getLogPrefix() + "configured httpclient for host [" + hostconfiguration.getHostURL() + "]");

        if (credentials != null) {
            httpState.setCredentials(null, uri.getHost(), credentials);
        }
    } catch (URIException e) {
        throw new SenderException(e);
    }

    String result = null;
    int statusCode = -1;
    int count = getMaxExecuteRetries();
    String msg = null;
    while (count-- >= 0 && statusCode == -1) {
        try {
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executing method");
            statusCode = httpclient.executeMethod(hostconfiguration, httpmethod, httpState);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executed method");

            if (statusCode != HttpServletResponse.SC_OK) {
                StatusLine statusline = httpmethod.getStatusLine();
                if (statusline != null) {
                    log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
                } else {
                    log.warn(getLogPrefix() + "no statusline found");
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "status [" + statusCode + "]");
            }
            HttpServletResponse response = null;
            if (isStreamResultToServlet()) {
                response = (HttpServletResponse) prc.getSession().get("restListenerServletResponse");
            }
            String fileName = null;
            if (StringUtils.isNotEmpty(getStreamResultToFileNameSessionKey())) {
                fileName = (String) prc.getSession().get(getStreamResultToFileNameSessionKey());
            }
            result = extractResult(httpmethod, prc, response, fileName);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "retrieved result [" + result + "]");
        } catch (HttpException e) {
            Throwable throwable = e.getCause();
            String cause = null;
            if (throwable != null) {
                cause = throwable.toString();
            }
            msg = e.getMessage();
            log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause
                    + "], executeRetries left [" + count + "]");
        } catch (IOException e) {
            httpmethod.abort();
            if (e instanceof SocketTimeoutException) {
                throw new TimeOutException(e);
            }
            throw new SenderException(e);
        } finally {
            // In case of storeResultAsStreamInSessionKey release connection
            // is done by ReleaseConnectionAfterReadInputStream.
            if (StringUtils.isEmpty(getStoreResultAsStreamInSessionKey())) {
                httpmethod.releaseConnection();
            }
        }
    }

    if (statusCode == -1) {
        if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
            //java.net.SocketTimeoutException: Read timed out
            throw new TimeOutException("Failed to recover from timeout exception");
        }
        throw new SenderException("Failed to recover from exception");
    }

    if (isXhtml() && StringUtils.isNotEmpty(result)) {
        result = XmlUtils.skipDocTypeDeclaration(result.trim());
        if (result.startsWith("<html>") || result.startsWith("<html ")) {
            CleanerProperties props = new CleanerProperties();
            HtmlCleaner cleaner = new HtmlCleaner(props);
            TagNode tagNode = cleaner.clean(result);
            result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);

            if (transformerPool != null) {
                log.debug(getLogPrefix() + " transforming result [" + result + "]");
                ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
                try {
                    result = transformerPool.transform(prc_xslt.getInputSource(), null);
                } catch (Exception e) {
                    throw new SenderException("Exception on transforming input", e);
                }
            }
        }
    }
    return result;
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

/**
 * Convert a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1">HTTP status line</a> into an xml element like this:
 * <p/>//  w  ww.  j av  a2 s . c o  m
 * < Status-line>
 * < HTTP-Version>HTTP/1.1< /HTTP-Version>
 * < Status-Code>200< /Status-Code>
 * < Reason-Phrase>Success - The action was successfully received, understood, and accepted< /Reason-Phrase>
 * < /Status-line></br>
 *
 * @param statusLine - the {@link org.apache.commons.httpclient.StatusLine} instance to be converted
 * @param doc        - the document to use to create new nodes
 * @return an Element
 */
public static Element statusLineToElement(Document doc, StatusLine statusLine) {
    Element statusLineEl = doc.createElementNS(null, "Status-Line");
    Element versionEl = doc.createElementNS(null, "HTTP-Version");
    Element codeEl = doc.createElementNS(null, "Status-Code");
    Element reasonEl = doc.createElementNS(null, "Reason-Phrase");
    Element originalEl = doc.createElementNS(null, "original");

    // wiring
    doc.appendChild(statusLineEl);
    statusLineEl.appendChild(versionEl);
    statusLineEl.appendChild(codeEl);
    statusLineEl.appendChild(reasonEl);
    statusLineEl.appendChild(originalEl);

    // values
    versionEl.setTextContent(statusLine.getHttpVersion());
    codeEl.setTextContent(String.valueOf(statusLine.getStatusCode()));
    reasonEl.setTextContent(statusLine.getReasonPhrase());
    // the line as received, not parsed
    originalEl.setTextContent(statusLine.toString());

    return statusLineEl;
}