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.jivesoftware.openfire.crowd.CrowdManager.java

private void handleHTTPError(HttpMethod method) throws RemoteException {
    int status = method.getStatusCode();
    String statusText = method.getStatusText();
    String body = null;//from ww w  .j a  v  a2s . c  o m
    try {
        body = method.getResponseBodyAsString();
    } catch (IOException ioe) {
        LOG.warn("Unable to retreive Crowd http response body", ioe);
    }

    StringBuilder strBuf = new StringBuilder();
    strBuf.append("Crowd returned HTTP error code:").append(status);
    strBuf.append(" - ").append(statusText);
    if (StringUtils.isNotBlank(body)) {
        strBuf.append("\n").append(body);
    }

    throw new RemoteException(strBuf.toString());
}

From source file:org.kalypso.util.net.URLGetter.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *//* w w  w.j a v a2s . co  m*/
@Override
public IStatus execute(final IProgressMonitor monitor) {
    final String urlAsString = m_url.toString();
    final HttpMethod method = new GetMethod(urlAsString);
    // do not forget the next line!
    method.setDoAuthentication(true);

    final Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                final HttpClient httpClient = getHttpClient();
                httpClient.executeMethod(method);
                setResult(method.getResponseBodyAsStream());
            } catch (final IOException e) {
                final IStatus status;

                String responseBodyAsString = Messages.getString("org.kalypso.util.net.URLGetter.1"); //$NON-NLS-1$
                try {
                    responseBodyAsString = method.getResponseBodyAsString();
                } catch (final IOException e1) {
                    final IStatus status2 = StatusUtilities.statusFromThrowable(e1);
                    KalypsoGisPlugin.getDefault().getLog().log(status2);
                }

                String message = Messages.getString("org.kalypso.util.net.URLGetter.2") + urlAsString; //$NON-NLS-1$
                if (responseBodyAsString != null && !responseBodyAsString.isEmpty())
                    message += "\n" + responseBodyAsString; //$NON-NLS-1$

                status = new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), 0, message, e);
                setStatus(status);
            }
        }
    };

    monitor.beginTask(urlAsString, IProgressMonitor.UNKNOWN);
    monitor.subTask(Messages.getString("org.kalypso.util.net.URLGetter.4")); //$NON-NLS-1$
    thread.start();
    while (thread.isAlive()) {
        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
            // should never happen, ignore
            e1.printStackTrace();
        }

        final String statusText;
        final StatusLine statusLine = method.getStatusLine();
        if (statusLine == null)
            statusText = Messages.getString("org.kalypso.util.net.URLGetter.5"); //$NON-NLS-1$
        else
            statusText = method.getStatusText();

        monitor.subTask(statusText);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            // TODO: this does not stop the thread!
            thread.interrupt();

            monitor.done();
            return Status.CANCEL_STATUS;
        }
    }

    monitor.done();
    return m_status;
}

From source file:org.mule.transport.as2.As2MessageDispatcher.java

@Override
protected void doDispatch(MuleEvent event) throws Exception {
    logger.debug("DBG: inside " + getClass() + ".doDispatch()");
    HttpMethod httpMethod = getMethod(event);
    as2Connector.setupClientAuthorizationLocal(event, httpMethod, client, endpoint);

    try {/*www.  j a  v  a 2s.  c o m*/
        execute(event, httpMethod);

        if (returnException(event, httpMethod)) {
            logger.error(httpMethod.getResponseBodyAsString());

            Exception cause = new Exception(String.format("Http call returned a status of: %1d %1s",
                    httpMethod.getStatusCode(), httpMethod.getStatusText()));
            throw new DispatchException(event, getEndpoint(), cause);
        } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) {
            if (logger.isInfoEnabled()) {
                logger.info("Received a redirect response code: " + httpMethod.getStatusCode() + " "
                        + httpMethod.getStatusText());
            }
        } else {
            logger.debug("DBG: response Body is: " + httpMethod.getResponseBodyAsString());
            /* Check the incoming synch MDN */
            MimeMultipart mdn = MDNBuilder.createMDNFromResponse(httpMethod.getResponseBodyAsStream(),
                    "multipart/report");
            if (MDNBuilder.identifyMdnType(mdn) != MdnType.PROCESSED) {
                throw new Exception("MDN is not of type PROCESSED");
            }
        }
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.mule.transport.http.HttpClientMessageDispatcher.java

@Override
protected void doDispatch(MuleEvent event) throws Exception {
    HttpMethod httpMethod = getMethod(event);
    httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint);

    try {//from  www  . j  a v  a2  s  .co m
        execute(event, httpMethod);

        if (returnException(event, httpMethod)) {
            logger.error(httpMethod.getResponseBodyAsString());

            Exception cause = new Exception(String.format("Http call returned a status of: %1d %1s",
                    httpMethod.getStatusCode(), httpMethod.getStatusText()));
            throw new DispatchException(event, getEndpoint(), cause);
        } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) {
            if (logger.isInfoEnabled()) {
                logger.info("Received a redirect response code: " + httpMethod.getStatusCode() + " "
                        + httpMethod.getStatusText());
            }
        }
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.mule.transport.http.HttpClientMessageDispatcher.java

@Override
protected MuleMessage doSend(MuleEvent event) throws Exception {
    HttpMethod httpMethod = getMethod(event);
    httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint);

    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new MuleHttpMethodRetryHandler());
    boolean releaseConn = false;
    try {/*from w w w  .  j a  va2 s.  c  om*/
        httpMethod = execute(event, httpMethod);

        DefaultExceptionPayload ep = null;

        if (returnException(event, httpMethod)) {
            ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(),
                    new HttpResponseException(httpMethod.getStatusText(), httpMethod.getStatusCode())));
        } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) {
            try {
                return handleRedirect(httpMethod, event);
            } catch (Exception e) {
                ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), e));
                return getResponseFromMethod(httpMethod, ep);
            }
        }
        releaseConn = httpMethod.getResponseBodyAsStream() == null;
        return getResponseFromMethod(httpMethod, ep);
    } catch (Exception e) {
        releaseConn = true;
        if (e instanceof DispatchException) {
            throw (DispatchException) e;
        }
        throw new DispatchException(event, getEndpoint(), e);
    } finally {
        if (releaseConn) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.mule.transport.http.HttpClientMessageDispatcher.java

protected MuleMessage handleRedirect(HttpMethod method, MuleEvent event)
        throws HttpResponseException, MuleException, IOException {
    String followRedirects = (String) endpoint.getProperty("followRedirects");
    if (followRedirects == null || "false".equalsIgnoreCase(followRedirects)) {
        if (logger.isInfoEnabled()) {
            logger.info("Received a redirect, but followRedirects=false. Response code: "
                    + method.getStatusCode() + " " + method.getStatusText());
        }/*from   w  w  w.  j a  va 2s .  co m*/
        return getResponseFromMethod(method, null);
    }
    Header locationHeader = method.getResponseHeader(HttpConstants.HEADER_LOCATION);
    if (locationHeader == null) {
        throw new HttpResponseException(method.getStatusText(), method.getStatusCode());
    }
    OutboundEndpoint out = new EndpointURIEndpointBuilder(locationHeader.getValue(),
            httpConnector.getMuleContext()).buildOutboundEndpoint();
    MuleEvent result = out.process(event);
    if (result != null && !VoidMuleEvent.getInstance().equals(result)) {
        return result.getMessage();
    } else {
        return null;
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

protected boolean getBoolean(HttpMethod method) throws IOException, RepositoryException,
        MalformedQueryException, UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<BooleanQueryResultFormat> booleanFormats = BooleanQueryResultParserRegistry.getInstance().getKeys();
    if (booleanFormats.isEmpty()) {
        throw new RepositoryException("No boolean query result parsers have been registered");
    }//from   w ww  . j a  va2 s . co m

    for (BooleanQueryResultFormat format : booleanFormats) {
        // Determine a q-value that reflects the user specified preference
        int qValue = 10;

        if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) {
            // Prefer specified format over other formats
            qValue -= 2;
        }

        for (String mimeType : format.getMIMETypes()) {
            String acceptParam = mimeType;

            if (qValue < 10) {
                acceptParam += ";q=0." + qValue;
            }

            method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
        }
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            BooleanQueryResultFormat format = BooleanQueryResultFormat.matchMIMEType(mimeType, booleanFormats);
            BooleanQueryResultParser parser = QueryResultIO.createParser(format);
            return parser.parse(method.getResponseBodyAsStream());
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (QueryResultParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
            throw new MalformedQueryException(errInfo.getErrorMessage());
        } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
            throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
        } else {
            throw new RepositoryException(method.getStatusText());
        }
    }
}

From source file:org.roda.wui.filter.CasClient.java

/**
 * Returns an error message for invalid response from CAS server.
 * /*from w  w w  . j  a  v a2 s.  c  om*/
 * @param method
 *          the HTTP method
 * @return a String with the error message.
 */
private String invalidResponseMessage(final HttpMethod method) {
    return String.format("Invalid response from CAS server: %s - %s", method.getStatusCode(),
            method.getStatusText());
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * /*from  w  w w.j  av  a 2 s.c o m*/
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}

From source file:org.smartfrog.projects.alpine.transport.http.HttpTransportFault.java

private void bind(HttpMethod method) {
    status = method.getStatusCode();/*www. j av  a 2  s  .co m*/
    statusLine = method.getStatusText();
    try {
        response = method.getResponseBodyAsString();
    } catch (IOException e) {
        log.warn("Could not read response of fault", e);
    }
    addDetail(FaultConstants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(status));
}