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.geotools.data.wfs.protocol.http.DefaultHTTPProtocol.java

/**
 * /*  w w w .  j  av  a 2 s  .  c om*/
 * @param httpRequest
 *            either a {@link HttpMethod} or {@link PostMethod} set up with the request to be
 *            sent
 * @return
 * @throws IOException
 */
private HTTPResponse issueRequest(final HttpMethodBase httpRequest) throws IOException {
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Executing HTTP request: " + httpRequest.getURI());
    }
    if (client == null) {
        client = new HttpClient();
        client.getParams().setParameter("http.useragent",
                "GeoTools " + GeoTools.getVersion() + " WFS DataStore");
    }
    if (timeoutMillis > 0) {
        client.getParams().setSoTimeout(timeoutMillis);
    }

    // TODO: remove this
    System.err.println("Executing HTTP request: " + httpRequest);

    if (isTryGzip()) {
        LOGGER.finest("Adding 'Accept-Encoding=gzip' header to request");
        httpRequest.addRequestHeader("Accept-Encoding", "gzip");
    }

    int statusCode;
    try {
        statusCode = client.executeMethod(httpRequest);
    } catch (IOException e) {
        httpRequest.releaseConnection();
        throw e;
    }

    if (statusCode != HttpStatus.SC_OK) {
        httpRequest.releaseConnection();
        String statusText = HttpStatus.getStatusText(statusCode);
        throw new IOException("Request failed with status code " + statusCode + "(" + statusText + "): "
                + httpRequest.getURI());
    }

    HTTPResponse httpResponse = new HTTPClientResponse(httpRequest);
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Got " + httpResponse);
    }
    return httpResponse;
}

From source file:org.globus.cog.abstraction.impl.file.http.FileResourceImpl.java

public void getFile(FileFragment remote, FileFragment local, ProgressMonitor progressMonitor)
        throws FileResourceException {
    checkNoPartialTransfers(remote, local, "http");
    GetMethod m = new GetMethod(contact + '/' + remote.getFile());
    try {/*from   w  w  w .  ja v  a  2s .  co m*/
        int code = client.executeMethod(m);
        try {
            if (code != HttpStatus.SC_OK) {
                throw new FileResourceException("Failed to get " + remote.getFile() + " from " + contact
                        + ". Server returned " + code + " (" + HttpStatus.getStatusText(code) + ").");
            }
            long total = -1;
            Header clh = m.getResponseHeader("Content-Length");
            if (clh != null && clh.getValue() != null) {
                total = Long.parseLong(clh.getValue());
            }
            boolean pm = (progressMonitor != null) && total != -1;
            InputStream is = m.getResponseBodyAsStream();
            FileOutputStream fos = new FileOutputStream(local.getFile());
            byte buf[] = new byte[16384];
            long crt = 0;
            int read = 0;
            while (read != -1) {
                read = is.read(buf);
                if (read != -1) {
                    fos.write(buf, 0, read);
                    crt += read;
                    if (pm) {
                        progressMonitor.progress(crt, total);
                    }
                } else {
                    if (pm) {
                        progressMonitor.progress(total, total);
                    }
                }
            }
            fos.close();
        } finally {
            m.releaseConnection();
        }
    } catch (FileResourceException e) {
        throw e;
    } catch (Exception e) {
        throw new FileResourceException(e);
    }
}

From source file:org.globus.cog.abstraction.impl.file.http.FileResourceImpl.java

public GridFile getGridFile(String fileName) throws FileResourceException {
    HeadMethod m = new HeadMethod(contact + '/' + fileName);
    try {/* w  ww  .  j a  v a2s  . co m*/
        int code = client.executeMethod(m);
        try {
            if (code != HttpStatus.SC_OK) {
                throw new FileResourceException("Failed to get file information about " + fileName + " from "
                        + contact + ". Server returned " + code + " (" + HttpStatus.getStatusText(code) + ").");
            }
            GridFile gf = new GridFileImpl();
            gf.setName(fileName);
            Header clh = m.getResponseHeader("Content-Length");
            gf.setSize(Long.parseLong(clh.getValue()));
            return gf;
        } finally {
            m.releaseConnection();
        }
    } catch (FileResourceException e) {
        throw e;
    } catch (Exception e) {
        throw new FileResourceException(e);
    }
}

From source file:org.jabsorb.client.HTTPSession.java

public JSONObject sendAndReceive(JSONObject message) {
    try {/*from   www.  ja  v a  2 s . c  o  m*/
        if (log.isDebugEnabled()) {
            log.debug("Sending: " + message.toString(2));
        }
        PostMethod postMethod = new PostMethod(uri.toString());
        postMethod.setRequestHeader("Content-Type", "text/plain");

        RequestEntity requestEntity = new StringRequestEntity(message.toString(), JSON_CONTENT_TYPE, null);
        postMethod.setRequestEntity(requestEntity);
        //      http().getHostConfiguration().setProxy(proxyHost, proxyPort);
        http().executeMethod(null, postMethod, state);
        int statusCode = postMethod.getStatusCode();
        if (statusCode != HttpStatus.SC_OK)
            throw new ClientError(
                    "HTTP Status - " + HttpStatus.getStatusText(statusCode) + " (" + statusCode + ")");
        JSONTokener tokener = new JSONTokener(postMethod.getResponseBodyAsString());
        Object rawResponseMessage = tokener.nextValue();
        JSONObject responseMessage = (JSONObject) rawResponseMessage;
        if (responseMessage == null)
            throw new ClientError("Invalid response type - " + rawResponseMessage.getClass());
        return responseMessage;
    } catch (HttpException e) {
        throw new ClientError(e);
    } catch (IOException e) {
        throw new ClientError(e);
    } catch (JSONException e) {
        throw new ClientError(e);
    }
}

From source file:org.jetbrains.tfsIntegration.exceptions.ConnectionFailedException.java

public String getMessage() {
    if (myMessage != null) {
        return myMessage;
    }/*w  ww  . j a  v a 2  s .  c  o  m*/

    String message = super.getMessage();
    if (message != null) {
        return message;
    }

    if (myHttpStatusCode != CODE_UNDEFINED) {
        return HttpStatus.getStatusText(myHttpStatusCode);
    }
    return null;
}

From source file:org.mskcc.cbio.cgds.scripts.ImportUniProtIdMapping.java

private int getLengthOfUniprotEntry(String uniprotId) throws IOException {
    String strURL = "http://www.uniprot.org/uniprot/" + uniprotId + ".fasta";
    MultiThreadedHttpConnectionManager connectionManager = ConnectionManager.getConnectionManager();
    HttpClient client = new HttpClient(connectionManager);
    GetMethod method = new GetMethod(strURL);

    try {//from   w w w  . jav  a2  s.c om
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader bufReader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream()));
            String line = bufReader.readLine();
            if (line == null || !line.startsWith(">")) {
                return 0;
            }

            int len = 0;
            for (line = bufReader.readLine(); line != null; line = bufReader.readLine()) {
                len += line.length();
            }
            return len;
        } else {
            //  Otherwise, throw HTTP Exception Object
            throw new HttpException(
                    statusCode + ": " + HttpStatus.getStatusText(statusCode) + " Base URL:  " + strURL);
        }
    } finally {
        //  Must release connection back to Apache Commons Connection Pool
        method.releaseConnection();
    }
}

From source file:org.mskcc.cbio.cgds.scripts.ImportUniProtIdMapping.java

private Set<String> getSwissProtAccessionHuman() throws IOException {
    String strURL = "http://www.uniprot.org/uniprot/?query="
            + "taxonomy%3ahuman+AND+reviewed%3ayes&force=yes&format=list";

    MultiThreadedHttpConnectionManager connectionManager = ConnectionManager.getConnectionManager();
    HttpClient client = new HttpClient(connectionManager);
    GetMethod method = new GetMethod(strURL);

    try {//from   w  w  w.  ja va  2s.  c  o m
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader bufReader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream()));
            Set<String> accs = new HashSet<String>();
            for (String line = bufReader.readLine(); line != null; line = bufReader.readLine()) {
                accs.add(line);
            }
            return accs;
        } else {
            //  Otherwise, throw HTTP Exception Object
            throw new HttpException(
                    statusCode + ": " + HttpStatus.getStatusText(statusCode) + " Base URL:  " + strURL);
        }
    } finally {
        //  Must release connection back to Apache Commons Connection Pool
        method.releaseConnection();
    }
}

From source file:org.mskcc.cbio.portal.network.NetworkIO.java

public static Network readNetworkFromCPath2(Set<String> genes, boolean removeSelfEdge)
        throws DaoException, IOException {
    String cPath2Url = getCPath2URL(genes);

    MultiThreadedHttpConnectionManager connectionManager = ConnectionManager.getConnectionManager();
    HttpClient client = new HttpClient(connectionManager);

    GetMethod method = new GetMethod(cPath2Url);
    try {//from w  w  w  . j a  v a2s  .c  o  m
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            Network network = readNetworkFromCPath2(method.getResponseBodyAsStream(), true);
            Set<Node> seedNodes = addMissingGenesAndReturnSeedNodes(network, genes);
            classifyNodes(network, seedNodes);
            return network;
        } else {
            //  Otherwise, throw HTTP Exception Object
            throw new HttpException(
                    statusCode + ": " + HttpStatus.getStatusText(statusCode) + " Base URL:  " + cPath2Url);
        }

    } finally {
        //  Must release connection back to Apache Commons Connection Pool
        method.releaseConnection();
    }
}

From source file:org.mskcc.cbio.portal.remote.CgdsProtocol.java

/**
 * Connects to remote data server with the specified list of name / value pairs.
 *
 * @param data Array of NameValuePair Objects.
 * @return Text Response.//from   w  w w.  ja  v  a 2  s .c om
 * @throws IOException IO / Network Error.
 */
public String connect(NameValuePair[] data, XDebug xdebug) throws IOException {

    //  Create a key, based on the NameValuePair[] data
    String key = createKey(data);
    xdebug.logMsg(this, "Using Cache Key:  " + key);

    //  Check Cache
    CacheManager singletonManager = CacheManager.getInstance();
    Cache memoryCache = singletonManager.getCache("memory_cache");
    xdebug.logMsg(this, "Cache Status:  " + memoryCache.getStatus().toString());

    //  If Content is found in cache, return it
    Element element = memoryCache.get(key);

    if (element != null) {
        xdebug.logMsg(this, "Cache Hit.  Using Memory.");
        return (String) element.getObjectValue();
    } else {
        xdebug.logMsg(this, "Cache Miss.  Connecting to Web API.");
        //  Otherwise, connect to Web API

        //  Get CGDS URL Property
        String cgdsUrl = Config.getInstance().getProperty("cgds.url");

        MultiThreadedHttpConnectionManager connectionManager = ConnectionManager.getConnectionManager();
        xdebug.logMsg(this, "Number of connections in pool:  " + connectionManager.getConnectionsInPool());
        xdebug.logMsg(this, "Max Connections per host:  "
                + connectionManager.getParams().getDefaultMaxConnectionsPerHost());

        HttpClient client = new HttpClient(connectionManager);

        //  Create GET / POST Method
        method = new PostMethod(cgdsUrl);
        method.setRequestBody(data);
        try {

            //  Extract HTTP Status Code
            int statusCode = client.executeMethod(method);

            //  If all is OK, extract the response text
            if (statusCode == HttpStatus.SC_OK) {
                String content = ResponseUtil.getResponseString(method);
                Element newElement = new Element(key, content);
                xdebug.logMsg(this, "Placing text in cache.");
                memoryCache.put(newElement);
                return content;
            } else {
                //  Otherwise, throw HTTP Exception Object
                throw new HttpException(
                        statusCode + ": " + HttpStatus.getStatusText(statusCode) + " Base URL:  " + cgdsUrl);
            }
        } finally {
            //  Must release connection back to Apache Commons Connection Pool
            method.releaseConnection();
        }
    }
}

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

private String getTissueImageIframeUrl(String cancerStudyId, String caseId) {
    if (!caseId.toUpperCase().startsWith("TCGA-")) {
        return null;
    }/*  w  ww.j  a  va 2s  .c  o m*/

    // test if images exist for the case
    String metaUrl = GlobalProperties.getDigitalSlideArchiveMetaUrl(caseId);

    HttpClient client = ConnectionManager.getHttpClient(5000);

    GetMethod method = new GetMethod(metaUrl);

    Pattern p = Pattern.compile("<data total_count='([0-9]+)'>");
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader bufReader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream()));
            for (String line = bufReader.readLine(); line != null; line = bufReader.readLine()) {
                Matcher m = p.matcher(line);
                if (m.find()) {
                    int count = Integer.parseInt(m.group(1));
                    return count > 0 ? GlobalProperties.getDigitalSlideArchiveIframeUrl(caseId) : null;
                }
            }

        } else {
            //  Otherwise, throw HTTP Exception Object
            logger.error(statusCode + ": " + HttpStatus.getStatusText(statusCode) + " Base URL:  " + metaUrl);
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    } finally {
        //  Must release connection back to Apache Commons Connection Pool
        method.releaseConnection();
    }

    return null;
}