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

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

Introduction

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

Prototype

public static String getStatusText(int statusCode) 

Source Link

Document

Get the reason phrase for a particular status code.

Usage

From source file:org.mskcc.cbio.portal.servlet.PatientView.java

private static List<String> extractLinksByPattern(String reportsUrl, Pattern p) {
    HttpClient client = ConnectionManager.getHttpClient(20000);
    GetMethod method = new GetMethod(reportsUrl);
    try {/*w  w  w.ja v a  2s. c o  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader bufReader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream()));
            List<String> dirs = new ArrayList<String>();
            for (String line = bufReader.readLine(); line != null; line = bufReader.readLine()) {
                Matcher m = p.matcher(line);
                if (m.find()) {
                    if (m.groupCount() > 0) {
                        dirs.add(m.group(1));
                    }
                }
            }
            return dirs;
        } else {
            //  Otherwise, throw HTTP Exception Object
            logger.error(
                    statusCode + ": " + HttpStatus.getStatusText(statusCode) + " Base URL:  " + reportsUrl);
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    } finally {
        //  Must release connection back to Apache Commons Connection Pool
        method.releaseConnection();
    }

    return Collections.emptyList();
}

From source file:org.mskcc.pathdb.task.ImportExternalDbTask.java

private void checkUrl(ExternalDatabaseRecord dbRecord, ProgressMonitor pMonitor) {
    try {//from   w  ww .j av a2s  . com
        int statusCode = ExternalDbLinkTester.checkSampleLink(dbRecord);
        pMonitor.setCurrentMessage(
                "-->  Response:  " + statusCode + ", " + HttpStatus.getStatusText(statusCode) + "\n");
        if (statusCode != HttpStatus.SC_OK) {
            pMonitor.setCurrentMessage(WARNING_MSG);
        }
    } catch (HttpException e) {
        pMonitor.setCurrentMessage(
                WARNING_MSG + "  Error Message:  " + e.getReasonCode() + ", " + e.getReason());
    } catch (IOException e) {
        pMonitor.setCurrentMessage(WARNING_MSG + "  Error Message:  " + e.getMessage());
    }
}

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

public void setStatusLine(final HttpVersion ver, int statuscode, final String phrase) {
    if (ver == null) {
        throw new IllegalArgumentException("HTTP version may not be null");
    }//from  w ww .j  av  a2 s. c  o  m
    if (statuscode <= 0) {
        throw new IllegalArgumentException("Status code may not be negative or zero");
    }
    this.ver = ver;
    this.statusCode = statuscode;
    if (phrase != null) {
        this.phrase = phrase;
    } else {
        this.phrase = HttpStatus.getStatusText(statuscode);
    }
}

From source file:org.onecmdb.utils.wsdl.CMDBChangeUpload.java

public void sendFiles(String targetURL, String files[]) {
    PostMethod filePost = new PostMethod(targetURL);

    /*//from  www .j a  v  a2s. co m
      filePost.getParams().setBooleanParameter(
         HttpMethodParams.USE_EXPECT_CONTINUE,
         cbxExpectHeader.isSelected());
      */
    try {
        List<Part> partList = new ArrayList<Part>();
        for (String file : files) {
            System.out.println("Send file : " + file);
            File f = new File(file);
            partList.add(new FilePart(f.getName(), f));
        }
        Part[] parts = partList.toArray(new Part[0]);
        /*
        Part[] parts = {
         new FilePart(targetFile.getName(), targetFile)
        };
        */
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }

}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req/*from w w  w .  j  a  v  a  2  s.  c o  m*/
 * @param url if null, ignored
 * @param redirCount number of redirs we've done
 */
public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl,
        int redirCount, int timeout)
        throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.
              
      if (res != null) {
    res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    }
    */

    try {

        // TODO: [2002-01-09 bloch] cope with cache-control
        // response headers (no-store, no-cache, must-revalidate, 
        // proxy-revalidate).

        if (surl == null) {
            surl = getURL(req);
        }
        if (surl == null || surl.equals("")) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="url is empty or null"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                            "051018-312"));
        }

        String reqType = "";
        String headers = "";

        if (req != null) {
            reqType = req.getParameter("reqtype");
            headers = req.getParameter("headers");
        }

        boolean isPost = false;
        mLogger.debug("reqtype = " + reqType);

        if (reqType != null && reqType.equals("POST")) {
            request = new LZPostMethod();
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            isPost = true;
            mLogger.debug("setting POST req method");
        } else if (reqType != null && reqType.equals("PUT")) {
            request = new LZPutMethod();
            // todo [hqm 2007] treat PUT like POST? 
            isPost = true;
            mLogger.debug("setting PUT req method");
        } else if (reqType != null && reqType.equals("DELETE")) {
            request = new LZDeleteMethod();
            mLogger.debug("setting DELETE req method");
        } else {
            mLogger.debug("setting GET (default) req method");
            request = new LZGetMethod();
        }

        request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0);

        // Proxy the request headers
        if (req != null) {
            LZHttpUtils.proxyRequestHeaders(req, request);
        }

        // Set headers from query string
        if (headers != null && headers.length() > 0) {
            StringTokenizer st = new StringTokenizer(headers, "\n");
            while (st.hasMoreTokens()) {
                String h = st.nextToken();
                int i = h.indexOf(":");
                if (i > -1) {
                    String n = h.substring(0, i);
                    String v = h.substring(i + 2, h.length());
                    request.setRequestHeader(n, v);
                    mLogger.debug(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes="setting header " + p[0] + "=" + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-359", new Object[] { n, v }));
                }
            }
        }

        mLogger.debug("Parsing url");
        URI uri = LZHttpUtils.newURI(surl);
        try {
            hcfg.setHost(uri);
        } catch (Exception e) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="can't form uri from " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376",
                            new Object[] { surl }));
        }

        // This gets us the url-encoded (escaped) path and query string
        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded path:  " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389",
                        new Object[] { path }));
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded query: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397",
                        new Object[] { query }));

        // This call takes a decoded (unescaped) path
        request.setPath(path);

        boolean hasQuery = (query != null && query.length() > 0);

        String rawcontent = null;
        // Newer rawpost protocol puts lzpostbody as a separate
        // top level query arg in the request.
        rawcontent = req.getParameter("lzpostbody");

        if (isPost) {
            // Older rawpost protocol put the "lzpostbody" arg
            // embedded in the "url" args's query args
            if (rawcontent == null && hasQuery) {
                rawcontent = findQueryArg("lzpostbody", query);
            }
            if (rawcontent != null) {
                // Get the unescaped query string
                ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent));
            } else if (hasQuery) {
                StringTokenizer st = new StringTokenizer(query, "&");
                while (st.hasMoreTokens()) {
                    String it = st.nextToken();
                    int i = it.indexOf("=");
                    if (i > 0) {
                        String n = it.substring(0, i);
                        String v = it.substring(i + 1, it.length());
                        // POST encodes values during request
                        ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
                    } else {
                        mLogger.warn(
                                /* (non-Javadoc)
                                 * @i18n.test
                                 * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                                 */
                                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                        "051018-429", new Object[] { it }));
                    }
                }
            }
        } else {
            // This call takes an encoded (escaped) query string
            request.setQueryString(query);
        }

        // Put in the If-Modified-Since headers
        if (since != -1) {
            String lms = LZHttpUtils.getDateString(since);
            request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="proxying lms: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450",
                            new Object[] { lms }));
        }

        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting up http client"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460"));
        HttpClient htc = null;
        if (mConnectionMgr != null) {
            htc = new HttpClient(mConnectionMgr);
        } else {
            htc = new HttpClient();
        }

        htc.setHostConfiguration(hcfg);

        // This is the data timeout
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="timeout set to " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478",
                        new Object[] { timeout }));
        htc.getParams().setSoTimeout(timeout);

        // Set connection timeout the same
        htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout);

        // Set timeout for getting a connection
        htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout);

        // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
        if (!isPost) {
            request.setFollowRedirects(mFollowRedirects > 0);
        }

        long t1 = System.currentTimeMillis();
        mLogger.debug("starting remote request");
        int rc = htc.executeMethod(hcfg, request);
        String status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="remote response status: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504",
                        new Object[] { status }));

        HttpData data = null;
        if (isRedirect(rc) && mFollowRedirects > redirCount) {
            String loc = request.getResponseHeader("Location").toString();
            String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Following URL from redirect: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517",
                            new Object[] { hostURI }));
            long t2 = System.currentTimeMillis();
            if (timeout > 0) {
                timeout -= (t2 - t1);
                if (timeout < 0) {
                    throw new InterruptedIOException(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-529", new Object[] { surl, loc }));
                }
            }

            data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
        } else {
            data = new HttpData(request, rc);
        }

        if (req != null && res != null) {
            // proxy response headers
            LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
        }

        return data;

    } catch (ConnectTimeoutException ce) {
        // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
        if (request != null) {
            request.releaseConnection();
        }
        throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557",
                        new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout }));
    } catch (HttpRecoverableException hre) {
        if (request != null) {
            request.releaseConnection();
        }
        throw hre;
    } catch (HttpException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    } catch (IOException ie) {
        if (request != null) {
            request.releaseConnection();
        }
        throw ie;
    } catch (RuntimeException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    }
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * utility/*from  w  ww  . j  a  v  a2s .c om*/
 */
private static String errorMessage(int code) {
    return
    /* (non-Javadoc)
     * @i18n.test
     * @org-mes="HTTP Status code: " + p[0] + ":" + p[1]
     */
    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-592",
            new Object[] { code, HttpStatus.getStatusText(code) });
}

From source file:org.openlaszlo.servlets.HistoryServlet.java

private void doSendHistory(HttpServletRequest req, HttpServletResponse res, Document doc) {
    mLogger.info("doSendHistory");
    Element el = doc.getRootElement().getChild("root").getChild("history");

    ServletOutputStream out = null;//w w  w  .j  a  va2s . c o m
    GetMethod request = null;
    String status = null;
    String body = null;
    try {
        out = res.getOutputStream();

        request = new MyGetMethod();

        String url = mURL + "?lzt=agentmessage" + "&url=" + URLEncoder.encode(mAgentURL) + "&group="
                + mAgentGroup + "&to=*&range=user" + "&dset=" + mClientDataset + "&msg="
                + URLEncoder.encode(getXMLHistory());

        mLogger.debug("url: " + url);
        URI uri = new URI(url.toCharArray());
        HostConfiguration hcfg = new HostConfiguration();
        hcfg.setHost(uri);

        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();

        mLogger.debug("path: " + path);
        mLogger.debug("query: " + query);

        request.setPath(path);
        request.setQueryString(query);

        HttpClient htc = new HttpClient(mConnectionMgr);
        htc.setHostConfiguration(hcfg);
        int rc = htc.executeMethod(hcfg, request);

        status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug("remote response status: " + status);

        body = request.getResponseBodyAsString();

        mLogger.debug("response body: " + body);
    } catch (HttpRecoverableException e) {
        mLogger.debug("HttpRecoverableException: " + e.getMessage());
        sendError(out, "<status message=\"HttpRecoverableException " + e.getMessage() + "\" />");
    } catch (HttpException e) {
        mLogger.debug("HttpException: " + e.getMessage());
        sendError(out, "<status message=\"HttpException " + e.getMessage() + "\" />");
    } catch (IOException e) {
        mLogger.debug("IOException: " + e.getMessage());
        sendError(out, "<status message=\"IOException " + e.getMessage() + "\" />");
    } finally {
        if (request != null) {
            request.releaseConnection();
        }
    }

    try {
        if (status != null && status.equals("OK")) {
            out.println("<status message=\"ok\">" + (body != null ? body : "") + "</status>");
        } else {
            out.println("<status message=\"" + mURL + "?lzt=agentmessage" + " " + status + "\" />");
        }
        out.flush();
    } catch (IOException e) {
        mLogger.debug("Client IOException");
        // ignore client ioexception
    } finally {
        close(out);
    }
}

From source file:org.openmicroscopy.is.HttpImageServer.java

private void executeCall(MultipartPostMethod post) throws ImageServerException {
    int status = 0;

    try {//from   w ww  .j av  a2s.  co  m
        post.addParameter("SessionKey", sessionKey);
        status = client.executeMethod(post);
    } catch (IOException e) {
        e.printStackTrace();
        throw new ImageServerException(e.getMessage());
    }

    if (status != HttpStatus.SC_OK) {
        throw new ImageServerException(HttpStatus.getStatusText(status));
    }
}

From source file:org.openmicroscopy.shoola.svc.proxy.Reply.java

/**
 * Checks the status of the response.//www  .j  a va 2 s  .c o  m
 * 
 * @param response   The response to handle.
 * @return The message from server.
 * @throws TransportException If an error occurred while transferring data.
 */
protected static String checkStatusCode(HttpMethod response) throws TransportException {
    int status = response.getStatusCode();
    if (status != -1) {//HttpStatus.SC_OK) {
        Reader reader = null;
        try {
            reader = new InputStreamReader(response.getResponseBodyAsStream());
            char[] buf = new char[32678];
            StringBuilder str = new StringBuilder();
            for (int n; (n = reader.read(buf)) != -1;)
                str.append(buf, 0, n);
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception ex) {
            }
            return str.toString();
        } catch (Exception e) {
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception ex) {
            }

            throw new TransportException("Couldn't handle request: " + HttpStatus.getStatusText(status) + ".");
        }
    }
    return null;
}

From source file:org.pmedv.core.util.UploadUtils.java

public static boolean uploadFile(File sourceFile, String targetURL, UploadMonitor monitor) {

    log.info("uploading " + sourceFile + " to " + targetURL);

    PostMethod filePost = new PostMethod(targetURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    filePost.getParams().setContentCharset("ISO-8859-15");

    try {//from  w ww  .  j  av a 2  s. c o  m

        Part[] parts = { new CustomizableFilePart(sourceFile.getName(), sourceFile, monitor) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(hostname, port, AuthScope.ANY_REALM), defaultcreds);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            log.info("Upload failed, response=" + HttpStatus.getStatusText(status));
            return false;
        }

    } catch (Exception ex) {
        log.error("An exception occured :");
        log.error(ResourceUtils.getStackTrace(ex));
        return false;
    } finally {
        filePost.releaseConnection();
    }

    return true;

}