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:com.benfante.jslideshare.SlideShareConnectorImpl.java

public InputStream sendMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    HttpClient client = createHttpClient();
    PostMethod method = new PostMethod(url);
    method.addParameter("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        method.addParameter(entry.getKey(), entry.getValue());
    }//from w w  w.j a v  a 2  s  . c o m
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    method.addParameter("ts", ts);
    method.addParameter("hash", hash);
    logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(method.getParameters()));
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java

public static OORunResponse run(OORunRequest request) throws IOException, URISyntaxException {

    String urlString = StringUtils.slashify(request.getServer().getUrl()) + REST_SERVICES_URL_PATH
            + RUN_OPERATION_URL_PATH + StringUtils.unslashifyPrefix(request.getFlow().getId());

    final URI uri = OOBuildStep.URI(urlString);
    final HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(new JaxbEntity(request));
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml");
    //        if (OOBuildStep.getEncodedCredentials()!=null) {
    //            httpPost.addHeader("Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    //        }/*  w  w  w . j a v  a  2 s. co  m*/

    HttpResponse response;

    response = client.execute(httpPost);
    final int statusCode = response.getStatusLine().getStatusCode();
    final HttpEntity entity = response.getEntity();

    try {
        if (statusCode == HttpStatus.SC_OK) {

            return JAXB.unmarshal(entity.getContent(), OORunResponse.class);

        } else {

            throw new RuntimeException("unable to get run result from " + uri + ", response code: " + statusCode
                    + "(" + HttpStatus.getStatusText(statusCode) + ")");
        }
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:fedora.client.Downloader.java

/**
 * Get data via HTTP as an InputStream, following redirects, and supplying
 * credentials if the host is the Fedora server.
 */// w  w  w .  jav a 2 s  .  c  o  m
public InputStream get(String url) throws IOException {
    GetMethod get = null;
    boolean ok = false;
    try {
        m_cManager.getParams().setConnectionTimeout(20000);
        HttpClient client = new HttpClient(m_cManager);
        client.getState().setCredentials(m_authScope, m_creds);
        client.getParams().setAuthenticationPreemptive(true); // don't bother with challenges
        int redirectCount = 0; // how many redirects did we follow
        int resultCode = 300; // not really, but enter the loop that way
        Dimension d = null;
        while (resultCode > 299 && resultCode < 400 && redirectCount < 25) {
            get = new GetMethod(url);
            get.setDoAuthentication(true);
            get.setFollowRedirects(true);
            if (Administrator.INSTANCE != null) {
                d = Administrator.PROGRESS.getSize();
                // if they're using Administrator, tell them we're downloading...
                Administrator.PROGRESS.setString("Downloading " + url + " . . .");
                Administrator.PROGRESS.setValue(100);
                Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth() - 1, (int) d.getHeight() - 1);
            }
            resultCode = client.executeMethod(get);
            if (resultCode > 299 && resultCode < 400) {
                redirectCount++;
                url = get.getResponseHeader("Location").getValue();
            }
        }
        if (resultCode != 200) {
            System.err.println(get.getResponseBodyAsString());
            throw new IOException(
                    "Server returned error: " + resultCode + " " + HttpStatus.getStatusText(resultCode));
        }
        ok = true;
        if (Administrator.INSTANCE != null) {
            // cache it to a file
            File tempFile = File.createTempFile("fedora-client-download-", null);
            tempFile.deleteOnExit();
            HashMap PARMS = new HashMap();
            PARMS.put("in", get.getResponseBodyAsStream());
            PARMS.put("out", new FileOutputStream(tempFile));
            // do the actual download in a safe thread
            SwingWorker worker = new SwingWorker(PARMS) {

                @Override
                public Object construct() {
                    try {
                        StreamUtility.pipeStream((InputStream) parms.get("in"), (OutputStream) parms.get("out"),
                                8192);
                    } catch (Exception e) {
                        thrownException = e;
                    }
                    return "";
                }
            };
            worker.start();
            // The following code will run in the (safe)
            // Swing event dispatcher thread.
            int ms = 200;
            while (!worker.done) {
                try {
                    Administrator.PROGRESS.setValue(ms);
                    Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth() - 1,
                            (int) d.getHeight() - 1);
                    Thread.sleep(100);
                    ms = ms + 100;
                    if (ms >= 2000) {
                        ms = 200;
                    }
                } catch (InterruptedException ie) {
                }
            }
            if (worker.thrownException != null) {
                throw worker.thrownException;
            }
            Administrator.PROGRESS.setValue(2000);
            Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth() - 1, (int) d.getHeight() - 1);
            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
            return new FileInputStream(tempFile);
        }
        return get.getResponseBodyAsStream();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    } finally {
        if (get != null && !ok) {
            get.releaseConnection();
        }
        if (Administrator.INSTANCE != null) {
            Administrator.PROGRESS.setValue(0);
            Administrator.PROGRESS.setString("");
        }
    }

}

From source file:com.sun.faban.harness.agent.Download.java

private void downloadFile(URL url, File file) throws IOException {
    logger.finer("Downloading file " + url.toString());
    GetMethod get = new GetMethod(url.toString());
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
    int status = client.executeMethod(get);
    if (status != HttpStatus.SC_OK)
        throw new IOException(
                "Download request for " + url + " returned " + HttpStatus.getStatusText(status) + '.');
    InputStream in = get.getResponseBodyAsStream();
    FileOutputStream out = new FileOutputStream(file);

    int length = in.read(buffer);
    while (length != -1) {
        out.write(buffer, 0, length);// w  ww  . j av a 2 s. c  om
        length = in.read(buffer);
    }
    out.flush();
    out.close();
    in.close();
}

From source file:com._17od.upm.transport.HTTPTransport.java

public void put(String targetLocation, File file, String username, String password) throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "upload.php";

    PostMethod post = new PostMethod(targetLocation);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {//  w w w .  ja  va 2 s  . c o m

        Part[] parts = { new FilePart("userfile", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        //Set the HTTP authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL url = new URL(targetLocation);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        // This line makes the HTTP call
        int status = client.executeMethod(post);

        // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt
        // The second attempt works so lets just do that
        if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
            status = client.executeMethod(post);
        }

        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (FileNotFoundException e) {
        throw new TransportException(e);
    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:com.sdm.core.filter.AuthorizationRequestFilter.java

private Response buildResponse(int code, String description) {
    MessageModel message = new MessageModel(code, HttpStatus.getStatusText(code), description);
    return Response.status(code).entity(message).build();
}

From source file:com.eviware.soapui.impl.rest.panels.mock.RestMockResponseDesktopPanel.java

private CompleteHttpStatus(int statusCode) {
    this.statusCode = statusCode;
    this.description = HttpStatus.getStatusText(statusCode);
}

From source file:com.cognifide.maven.plugins.crx.CrxPackageAbstractMojo.java

/**
 * Performs post request to given URL with given parameters provided as a part lists.
 * //w  w  w.  j a  va  2s  .  c  om
 * @param targetURL Place where post action should be submitted
 * @param partList Parameters of post action
 * @return Response body
 * @throws MojoExecutionException
 */
protected String post(String targetURL, List<Part> partList) throws MojoExecutionException {
    PostMethod postMethod = new PostMethod(targetURL);

    try {
        Part[] parts = partList.toArray(new Part[partList.size()]);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

        int status = getHttpClient().executeMethod(postMethod);

        if (status == HttpStatus.SC_OK) {
            return IOUtils.toString(postMethod.getResponseBodyAsStream());
        } else {
            getLog().warn(postMethod.getResponseBodyAsString());
            throw new MojoExecutionException("Request to the repository failed, cause: "
                    + HttpStatus.getStatusText(status) + " (check URL, user and password)");
        }

    } catch (IOException ex) {
        throw new MojoExecutionException("Request to the repository failed, cause: " + ex.getMessage(), ex);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:edu.du.penrose.systems.fedora.client.Downloader.java

/**
 * Get data via HTTP as an InputStream, following redirects, and supplying 
 * credentials if the host is the Fedora server.
 *//*from   w ww .  jav a2  s.  c  o  m*/
public InputStream get(String url) throws IOException {
    GetMethod get = null;
    boolean ok = false;
    try {
        m_cManager.getParams().setConnectionTimeout(20000);
        HttpClient client = new HttpClient(m_cManager);
        client.getState().setCredentials(m_authScope, m_creds);
        client.getParams().setAuthenticationPreemptive(true); // don't bother with challenges
        int redirectCount = 0; // how many redirects did we follow
        int resultCode = 300; // not really, but enter the loop that way
        Dimension d = null;
        while (resultCode > 299 && resultCode < 400 && redirectCount < 25) {
            get = new GetMethod(url);
            get.setDoAuthentication(true);
            get.setFollowRedirects(true);

            //                if ( myAdministrator!=null) {
            //                    d=Administrator.PROGRESS.getSize();
            //                    // if they're using Administrator, tell them we're downloading...
            //                    Administrator.PROGRESS.setString("Downloading " + url + " . . .");
            //                    Administrator.PROGRESS.setValue(100);
            //                    Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth()-1, (int) d.getHeight()-1);
            //                }

            resultCode = client.executeMethod(get);
            if (resultCode > 299 && resultCode < 400) {
                redirectCount++;
                url = get.getResponseHeader("Location").getValue();
            }
        }
        if (resultCode != 200) {
            System.err.println(get.getResponseBodyAsString());
            throw new IOException(
                    "Server returned error: " + resultCode + " " + HttpStatus.getStatusText(resultCode));
        }
        ok = true;
        if (myAdministrator != null) {
            // cache it to a file
            File tempFile = File.createTempFile("fedora-client-download-", null);
            tempFile.deleteOnExit();
            HashMap PARMS = new HashMap();
            PARMS.put("in", get.getResponseBodyAsStream());
            PARMS.put("out", new FileOutputStream(tempFile));
            // do the actual download in a safe thread
            SwingWorker worker = new SwingWorker(PARMS) {
                public Object construct() {
                    try {
                        StreamUtility.pipeStream((InputStream) parms.get("in"), (OutputStream) parms.get("out"),
                                8192);
                    } catch (Exception e) {
                        thrownException = e;
                    }
                    return "";
                }
            };
            worker.start();
            // The following code will run in the (safe) 
            // Swing event dispatcher thread.
            int ms = 200;
            while (!worker.done) {
                try {

                    //                        Administrator.PROGRESS.setValue(ms);
                    //                        Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth()-1, (int) d.getHeight()-1);

                    Thread.sleep(100);
                    ms = ms + 100;
                    if (ms >= 2000)
                        ms = 200;
                } catch (InterruptedException ie) {
                }
            }
            if (worker.thrownException != null)
                throw worker.thrownException;

            //                Administrator.PROGRESS.setValue(2000);
            //                Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth()-1, (int) d.getHeight()-1);

            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
            return new FileInputStream(tempFile);
        }
        return get.getResponseBodyAsStream();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    } finally {
        if (get != null && !ok)
            get.releaseConnection();

        //            if (Administrator.INSTANCE!=null) {
        //                Administrator.PROGRESS.setValue(0);
        //                Administrator.PROGRESS.setString("");          
        //            }

    }

}

From source file:com.kagilum.plugins.icescrum.IceScrumSession.java

private void checkServerStatus(int code) throws IOException {
    switch (code) {
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
        throw new IOException(Messages.IceScrumSession_icescrum_http_unavailable());
    case HttpStatus.SC_UNAUTHORIZED:
        throw new IOException(Messages.IceScrumSession_icescrum_http_unauthorized());
    case HttpStatus.SC_FORBIDDEN:
        throw new IOException(Messages.IceScrumSession_icescrum_http_forbidden());
    case HttpStatus.SC_NOT_FOUND:
        throw new IOException(Messages.IceScrumSession_icescrum_http_notfound());
    default:// w ww.j  av  a  2  s .c o  m
        throw new IOException(
                Messages.IceScrumSession_icescrum_http_error() + " (" + HttpStatus.getStatusText(code) + ")");
    }
}