Example usage for org.apache.commons.httpclient HttpMethod getStatusText

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusText

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getStatusText.

Prototype

public abstract String getStatusText();

Source Link

Usage

From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java

/** {@inheritDoc} */
public LinkValidationResult validateLink(LinkValidationItem lvi) {
    if (this.cl == null) {
        initHttpClient();/*from   w  ww.  j a va  2s.  c o m*/
    }

    if (this.http.getHttpClientParameters() != null) {
        for (Map.Entry<Object, Object> entry : this.http.getHttpClientParameters().entrySet()) {
            if (entry.getValue() != null) {
                System.setProperty(entry.getKey().toString(), entry.getValue().toString());
            }
        }
    }

    // Some web servers don't allow the default user-agent sent by httpClient
    System.setProperty(HttpMethodParams.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
    this.cl.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    String link = lvi.getLink();
    String anchor = "";
    int idx = link.indexOf('#');
    if (idx != -1) {
        anchor = link.substring(idx + 1);
        link = link.substring(0, idx);
    }

    try {
        if (link.startsWith("/")) {
            if (getBaseURL() == null) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn("Cannot check link [" + link + "] in page [" + lvi.getSource()
                            + "], as no base URL has been set!");
                }

                return new LinkValidationResult(LinkcheckFileResult.WARNING_LEVEL, false,
                        "No base URL specified");
            }

            link = getBaseURL() + link;
        }

        HttpMethod hm = null;
        try {
            hm = checkLink(link, 0);
        } catch (Throwable t) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Received: [" + t + "] for [" + link + "] in page [" + lvi.getSource() + "]", t);
            }

            return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false,
                    t.getClass().getName() + " : " + t.getMessage());
        }

        if (hm == null) {
            return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false,
                    "Cannot retreive HTTP Status");
        }

        if (hm.getStatusCode() == HttpStatus.SC_OK) {
            // lets check if the anchor is present
            if (anchor.length() > 0) {
                String content = hm.getResponseBodyAsString();

                if (!Anchors.matchesAnchor(content, anchor)) {
                    return new HTTPLinkValidationResult(LinkcheckFileResult.VALID_LEVEL, false,
                            "Missing anchor '" + anchor + "'");
                }
            }
            return new HTTPLinkValidationResult(LinkcheckFileResult.VALID_LEVEL, true, hm.getStatusCode(),
                    hm.getStatusText());
        }

        String msg = "Received: [" + hm.getStatusCode() + "] for [" + link + "] in page [" + lvi.getSource()
                + "]";
        // If there's a redirection ... add a warning
        if (hm.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                || hm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                || hm.getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) {
            LOG.warn(msg);

            return new HTTPLinkValidationResult(LinkcheckFileResult.WARNING_LEVEL, true, hm.getStatusCode(),
                    hm.getStatusText());
        }

        LOG.debug(msg);

        return new HTTPLinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, hm.getStatusCode(),
                hm.getStatusText());
    } catch (Throwable t) {
        String msg = "Received: [" + t + "] for [" + link + "] in page [" + lvi.getSource() + "]";
        if (LOG.isDebugEnabled()) {
            LOG.debug(msg, t);
        } else {
            LOG.error(msg);
        }

        return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, t.getMessage());
    } finally {
        System.getProperties().remove(HttpMethodParams.USER_AGENT);

        if (this.http.getHttpClientParameters() != null) {
            for (Map.Entry<Object, Object> entry : this.http.getHttpClientParameters().entrySet()) {
                if (entry.getValue() != null) {
                    System.getProperties().remove(entry.getKey().toString());
                }
            }
        }
    }
}

From source file:org.apache.roller.weblogger.util.Trackback.java

/**
 * Sends trackback from entry to remote URL.
 * See Trackback spec for details: http://www.sixapart.com/pronet/docs/trackback_spec
 *//*  w  ww  .j  a  va2  s  . c o m*/
public RollerMessages send() throws WebloggerException {

    RollerMessages messages = new RollerMessages();

    log.debug("Sending trackback to url - " + trackbackURL);

    // Construct data
    String title = entry.getTitle();
    String excerpt = StringUtils.left(Utilities.removeHTML(entry.getDisplayContent()), 255);
    String url = entry.getPermalink();
    String blog_name = entry.getWebsite().getName();

    // build trackback post parameters as query string
    Map params = new HashMap();
    params.put("title", URLUtilities.encode(title));
    params.put("excerpt", URLUtilities.encode(excerpt));
    params.put("url", URLUtilities.encode(url));
    params.put("blog_name", URLUtilities.encode(blog_name));
    String queryString = URLUtilities.getQueryString(params);

    log.debug("query string - " + queryString);

    // prepare http request
    HttpClient client = new HttpClient();
    client.setConnectionTimeout(45 * 1000);
    HttpMethod method = new PostMethod(trackbackURL);
    method.setQueryString(queryString);

    try {
        // execute trackback
        int statusCode = client.executeMethod(method);

        // read response
        byte[] response = method.getResponseBody();
        String responseString = Utilities.escapeHTML(new String(response, "UTF-8"));

        log.debug("result = " + statusCode + " " + method.getStatusText());
        log.debug("response:\n" + responseString);

        if (statusCode == HttpStatus.SC_OK) {
            // trackback request succeeded, message will give details
            try {
                messages = parseTrackbackResponse(new String(response, "UTF-8"), messages);
            } catch (Exception e) {
                // Cannot parse response, indicates failure
                messages.addError("weblogEdit.trackbackErrorParsing", responseString);
            }
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            // 404, invalid trackback url
            messages.addError("weblogEdit.trackbackError404");
        } else {
            // some other kind of error with url, like 500, 403, etc
            // just provide a generic error message and give the http response text
            messages.addError("weblogEdit.trackbackErrorResponse",
                    new String[] { "" + statusCode, method.getStatusText() });
        }

    } catch (IOException e) {
        // some kind of transport error sending trackback post
        log.debug("Error sending trackback", e);
        messages.addError("weblogEdit.trackbackErrorTransport");
    } finally {
        // release used connection
        method.releaseConnection();
    }

    return messages;
}

From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
        throws SolrServerException, IOException {
    HttpMethod method = null;
    InputStream is = null;/* w  w w  . j a  v a 2 s  .  co  m*/
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
        params = wparams;
    } else {
        params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
        params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = _baseURL + path;
                    boolean isMultipart = (streams != null && streams.size() > 1);

                    if (streams == null || isMultipart) {
                        PostMethod post = new PostMethod(url);
                        post.getParams().setContentCharset("UTF-8");
                        if (!this.useMultiPartPost && !isMultipart) {
                            post.addRequestHeader("Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<Part> parts = new LinkedList<Part>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (this.useMultiPartPost || isMultipart) {
                                        parts.add(new StringPart(p, v, "UTF-8"));
                                    } else {
                                        post.addParameter(p, v);
                                    }
                                }
                            }
                        }

                        if (isMultipart) {
                            int i = 0;
                            for (ContentStream content : streams) {
                                final ContentStream c = content;

                                String charSet = null;
                                PartSource source = new PartSource() {
                                    public long getLength() {
                                        return c.getSize();
                                    }

                                    public String getFileName() {
                                        return c.getName();
                                    }

                                    public InputStream createInputStream() throws IOException {
                                        return c.getStream();
                                    }
                                };

                                parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet));
                            }
                        }
                        if (parts.size() > 0) {
                            post.setRequestEntity(new MultipartRequestEntity(
                                    parts.toArray(new Part[parts.size()]), post.getParams()));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(params, false);
                        PostMethod post = new PostMethod(url + pstr);
                        //              post.setRequestHeader("connection", "close");

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setRequestEntity(new RequestEntity() {
                                public long getContentLength() {
                                    return -1;
                                }

                                public String getContentType() {
                                    return contentStream[0].getContentType();
                                }

                                public boolean isRepeatable() {
                                    return false;
                                }

                                public void writeRequest(OutputStream outputStream) throws IOException {
                                    ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                                }
                            });

                        } else {
                            is = contentStream[0].getStream();
                            post.setRequestEntity(
                                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                // This is generally safe to retry on
                method.releaseConnection();
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if ((tries < 1)) {
                    throw r;
                }
                //log.warn( "Caught: " + r + ". Retrying..." );
            }
        }
    } catch (IOException ex) {
        log.error("####request####", ex);
        throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
        method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }
    //    method.setRequestHeader("connection", "close");

    try {
        // Execute the method.
        //System.out.println( "EXECUTE:"+method.getURI() );

        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            StringBuilder msg = new StringBuilder();
            msg.append(method.getStatusLine().getReasonPhrase());
            msg.append("\n\n");
            msg.append(method.getStatusText());
            msg.append("\n\n");
            msg.append("request: " + method.getURI());
            throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
        }

        // Read the contents
        String charset = "UTF-8";
        if (method instanceof HttpMethodBase) {
            charset = ((HttpMethodBase) method).getResponseCharSet();
        }
        InputStream respBody = method.getResponseBodyAsStream();
        // Jakarta Commons HTTPClient doesn't handle any
        // compression natively.  Handle gzip or deflate
        // here if applicable.
        if (_allowCompression) {
            Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null) {
                String contentEncoding = contentEncodingHeader.getValue();
                if (contentEncoding.contains("gzip")) {
                    //log.debug( "wrapping response in GZIPInputStream" );
                    respBody = new GZIPInputStream(respBody);
                } else if (contentEncoding.contains("deflate")) {
                    //log.debug( "wrapping response in InflaterInputStream" );
                    respBody = new InflaterInputStream(respBody);
                }
            } else {
                Header contentTypeHeader = method.getResponseHeader("Content-Type");
                if (contentTypeHeader != null) {
                    String contentType = contentTypeHeader.getValue();
                    if (contentType != null) {
                        if (contentType.startsWith("application/x-gzip-compressed")) {
                            //log.debug( "wrapping response in GZIPInputStream" );
                            respBody = new GZIPInputStream(respBody);
                        } else if (contentType.startsWith("application/x-deflate")) {
                            //log.debug( "wrapping response in InflaterInputStream" );
                            respBody = new InflaterInputStream(respBody);
                        }
                    }
                }
            }
        }
        return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
        throw new SolrServerException(e);
    } catch (IOException e) {
        throw new SolrServerException(e);
    } finally {
        method.releaseConnection();
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.apache.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {/* w  w  w  . java 2  s.c o m*/
        HttpClient client = new HttpClient();

        // set the clients proxy values if needed
        ConnectionsPrefsManager.setProxySettings(client, properties);

        if (fUseProxyAuthentication) {
            if (fBase64Auth != null) {
                method.setRequestHeader("Authorization", fBase64Auth);
            } else {
                List<String> authPrefs = new ArrayList<String>(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);
                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                // send the basic authentication response even before the server gives an unauthorized response
                client.getParams().setAuthenticationPreemptive(true);
                // Pass our credentials to HttpClient
                client.getState().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(fProxyUsername, fProxyPassword));
            }
        }

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$
        method.removeRequestHeader("Content-Type");
        //method.setRequestHeader("Content-Type","application/json");
        //method.setRequestHeader("Referer", "");
        //method.removeRequestHeader("Referer");
        method.setRequestHeader("Accept", "*/*");

        int statusCode = client.executeMethod(method);

        //System.out.println("response="+method.getResponseBodyAsString());
        //System.out.println("method="+method.toString());
        //System.out.println("response="+method.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            Header hType = method.getResponseHeader("Content-Type");
            if (hType != null) {
                fContentType = hType.getValue();
            }
            // for now we are only expecting Strings
            //return method.getResponseBodyAsString();
            return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
                || statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' '
                    + method.getURI() + ' ' + method.getStatusText());
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText());
        }
    } catch (IOException e) {
        throw e;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.apache.wookie.util.gadgets.GadgetUtils.java

/**
 * Call a remote service/*www.j ava 2s  . c o m*/
 * @param method the method to invoke
 * @return the response from the remote service
 * @throws Exception
 */
private static String executeMethod(HttpMethod method) throws Exception {
    // Execute the method.
    System.out.println("executeMethod() start");
    try {
        HttpClient client = new HttpClient();

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$ 
        int statusCode = client.executeMethod(method);
        System.out.println("HTTP client returned status:" + statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            // for now we are only expecting Strings               
            return method.getResponseBodyAsString();
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText() + method.getResponseBodyAsString());
        }
    } catch (IOException e) {
        System.out.println("CaughtIOException");
        throw new Exception("ERROR_CONNECT", e);
    } finally {
        // Release the connection.
        System.out.println("executeMethod() end");
        method.releaseConnection();
    }
}

From source file:org.artifactory.cli.rest.RestClient.java

/**
 * Validates the expected returned status
 *
 * @param uri            Target URL/*w w w.  j a v  a2 s.  c  o m*/
 * @param expectedStatus Expected returned status
 * @param method         The method after execution (holds the returned status)
 */
private static void checkStatus(String uri, int expectedStatus, HttpMethod method) {
    int status = method.getStatusCode();
    if (status != expectedStatus) {
        throw new RemoteCommandException("\nUnexpected response status for request: " + uri + "\n"
                + "Expected status: " + expectedStatus + " (" + HttpStatus.getStatusText(expectedStatus) + ")"
                + "\n " + "Received status: " + status + " (" + HttpStatus.getStatusText(status) + ") - "
                + method.getStatusText() + "\n");
    }
}

From source file:org.bonitasoft.connectors.webdav.exo.common.ExoConnector.java

/**
 * process response to get statusCode, statusText and response string.
 * //  w w  w  .  ja  v a 2  s .com
 * @param httpMethod
 * @param getResponseAsString
 */
protected void processResponse(final HttpMethod httpMethod, final boolean getResponseAsString) {

    String statusCode = "-1";
    if (httpMethod.getStatusCode() > 0) {
        statusCode = String.valueOf(httpMethod.getStatusCode());
    }
    final String statusText = httpMethod.getStatusText();

    String responseString = "";
    if (getResponseAsString) {
        try {
            responseString = httpMethod.getResponseBodyAsString();
            if (responseString == null) {
                responseString = "";
            }
        } catch (final IOException e) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.warning("IOException while getting responseAsString: " + e.getMessage());
            }
            e.printStackTrace();
        }
    }

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("status CODE: " + statusCode + ", status TEXT: " + statusText + "\n response string: "
                + responseString);
    }
    this.statusCode = statusCode;
    this.statusText = statusText;
    this.response = responseString;
}

From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java

protected void execute(HttpMethod httpMethod) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    HttpClient client = new HttpClient();

    if (submissionMap != null) {
        String sessionid = submissionMap.get(ChibaAdapter.SESSION_ID).toString();
        if (sessionid != null) {
            HttpState state = client.getState();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            state.addCookie(new Cookie(httpMethod.getURI().getHost(), "JSESSIONID", sessionid,
                    httpMethod.getPath(), null, false));
            client.setState(state);//from  www .  j a v  a  2 s.com
        }
    }

    client.executeMethod(httpMethod);

    if (httpMethod.getStatusCode() >= 300) {
        throw new XFormsException(
                "HTTP status " + httpMethod.getStatusCode() + ": " + httpMethod.getStatusText());
    }
    this.handleHttpMethod(httpMethod);
}

From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java

private HTTPResponse convertResponse(HttpMethod method) {
    Headers headers = new Headers();
    for (Header header : method.getResponseHeaders()) {
        headers = headers.add(header.getName(), header.getValue());
    }/*from  w  w w .  j  a v  a 2  s  .c  o m*/
    InputStream stream = null;
    HTTPResponse response;
    try {
        stream = getInputStream(method);
        StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()),
                Status.valueOf(method.getStatusCode()), method.getStatusText());
        response = getResponseCreator().createResponse(line, headers, stream);
    } finally {
        if (stream == null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.craftercms.cstudio.publishing.processor.CacheInvalidatePostProcessor.java

@Override
public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target)
        throws PublishingException {
    HttpMethod cacheInvalidateGetMethod = new GetMethod(cacheInvalidateUrl);
    HttpClient client = new HttpClient();
    try {//from   w  w w . j  a va  2  s .  com
        int status = client.executeMethod(cacheInvalidateGetMethod);
        if (status != HttpServletResponse.SC_OK) {
            throw new PublishingException("Unable to invalidate cache: URL " + cacheInvalidateUrl
                    + " returned status '" + cacheInvalidateGetMethod.getStatusText() + "' with body \n"
                    + cacheInvalidateGetMethod.getResponseBodyAsString());
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Cache invalidated: URL " + cacheInvalidateUrl + " returned status '"
                        + cacheInvalidateGetMethod.getStatusText() + "'");
            }
        }
    } catch (IOException e) {
        throw new PublishingException(e);
    } finally {
        cacheInvalidateGetMethod.releaseConnection();
    }
}