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.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java

public static OOListResponse listFlows(OOServer s, String... folders) throws IOException {

    String foldersPath = "";

    for (String folder : folders) {
        foldersPath += folder + "/";
    }//  ww  w . ja  va  2  s.  c  om

    String url = StringUtils.slashify(s.getUrl()) + REST_SERVICES_URL_PATH + LIST_OPERATION_URL_PATH
            + foldersPath;

    final HttpResponse response = OOBuildStep.getHttpClient().execute(new HttpGet(OOBuildStep.URI(url)));

    final int statusCode = response.getStatusLine().getStatusCode();

    final HttpEntity entity = response.getEntity();

    try {

        if (statusCode == HttpStatus.SC_OK) {

            return JAXB.unmarshal(entity.getContent(), OOListResponse.class);
        } else {

            throw new RuntimeException("unable to get list of flows from " + url + ", response code: "
                    + statusCode + "(" + HttpStatus.getStatusText(statusCode) + ")");
        }
    } finally {
        EntityUtils.consume(entity);
    }
}

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

private void downloadDir(URL url, File dir) throws IOException {
    String dirName = dir.getName();
    logger.finer("Creating directory " + dirName + " from " + url.toString());
    dir.mkdir();/*  ww  w .  j a va2 s.c o m*/

    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 stream = get.getResponseBodyAsStream();
    DirectoryParser parser = new DirectoryParser();

    int length = 0;
    int bufEnd = 0;
    while (length != -1) {
        length = stream.read(buffer, bufEnd, buffer.length - bufEnd);
        if (length != -1)
            bufEnd += length;
        if (bufEnd > buffer.length / 4 * 3 || length == -1) {
            if (!parser.parse(buffer, bufEnd)) {
                String msg = "URL " + url.toString() + " is not a directory!";
                logger.severe(msg);
                throw new IOException(msg);
            }
            bufEnd = 0;
        }
    }
    stream.close();

    String[] entries = parser.getEntries();
    for (int i = 0; i < entries.length; i++) {
        String entry = entries[i];
        if ("META-INF/".equals(entry))
            continue;
        String name = entry.substring(0, entry.length() - 1);
        if (entry.endsWith("/")) { // Directory
            downloadDir(new URL(url, entry), new File(dir, name));
        } else {
            downloadFile(new URL(url, name), new File(dir, name));
        }
    }

}

From source file:com.apatar.flickr.function.UploadPhotoFlickrTable.java

public List<KeyInsensitiveMap> execute(FlickrNode node, Hashtable<String, Object> values, String strApi,
        String strSecret) throws IOException, XmlRpcException {
    byte[] photo = (byte[]) values.get("photo");

    int size = values.size() + 2;

    values.remove("photo");

    File newFile = ApplicationData.createFile("flicr", photo);

    PostMethod post = new PostMethod("http://api.flickr.com/services/upload");
    Part[] parts = new Part[size];

    parts[0] = new FilePart("photo", newFile);
    parts[1] = new StringPart("api_key", strApi);
    int i = 2;/*w  ww .  ja  v a  2s .com*/
    for (String key : values.keySet())
        parts[i++] = new StringPart(key, values.get(key).toString());

    values.put("api_key", strApi);

    parts[i] = new StringPart("api_sig", FlickrUtils.Sign(values, strApi, strSecret));

    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
        return null;
    } else {
        InputStream is = post.getResponseBodyAsStream();
        try {
            return createKeyInsensitiveMapFromElement(FlickrUtils.getRootElementFromInputStream(is));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.googlecode.fascinator.common.BasicHttpClient.java

/**
 * Sends an HTTP request//  ww  w .  j  a v a  2s  .c o  m
 * 
 * @param method an HTTP method
 * @param auth true to request with authentication, false to request without
 * @return HTTP status code
 * @throws IOException if an error occurred during the HTTP request
 */
public int executeMethod(HttpMethodBase method, boolean auth) throws IOException {
    log.trace("{} {}", method.getName(), method.getURI());
    int status = getHttpClient(auth).executeMethod(method);
    log.trace("{} {}", status, HttpStatus.getStatusText(status));
    return status;
}

From source file:com.kagilum.intellij.icescrum.IceScrumRepository.java

private void checkServerStatus(int code) throws IOException {
    switch (code) {
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
        throw new IOException("Web services aren't activated on your project...");
    case HttpStatus.SC_UNAUTHORIZED:
        throw new IOException("Wrong login/pass...");
    case HttpStatus.SC_FORBIDDEN:
        throw new IOException("You haven't access to this project...");
    case HttpStatus.SC_NOT_FOUND:
        throw new IOException("No project or iceScrum server found...");
    default://from w  ww .j  a va  2  s  .  c  om
        throw new IOException("Server error (" + HttpStatus.getStatusText(code) + ")");
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.ExecutionCourseDA.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final String executionCourseIDString = request.getParameter("executionCourseID");

    ExecutionCourse executionCourse = null;
    if (executionCourseIDString != null) {
        final DomainObject object = FenixFramework.getDomainObject(executionCourseIDString);
        if (object instanceof ExecutionCourse) {
            executionCourse = (ExecutionCourse) object;
        } else {//w w w.  ja v  a2s  .  com
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
            response.getWriter().close();
            return null;
        }
    } else {
        ExecutionCourseSite site = SiteMapper.getSite(request);
        executionCourse = site.getSiteExecutionCourse();
    }

    OldCmsSemanticURLHandler.selectSite(request, executionCourse.getSite());
    request.setAttribute("executionCourse", executionCourse);
    request.setAttribute("executionCourseID", executionCourse.getExternalId());

    return super.execute(mapping, actionForm, request, response);
}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

/**
 * Performs an HTTP GET on the given URL.
 *
 * @param url       The URL where to connect to.
 * @return          The HTTP response as a String if the HTTP response code was 200 (OK).
 * @throws MalformedURLException/*from   w  w w.  jav a 2s .c  o m*/
 */
public String get(String url) throws MalformedURLException {

    GetMethod httpMethod = null;
    try {
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        lastHttpStatus = client.executeMethod(httpMethod);
        if (lastHttpStatus == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            String response = IOUtils.toString(is);
            if (response.trim().length() == 0) { // sometime gs rest fails
                LOGGER.warn("ResponseBody is empty");
                return null;
            } else {
                return response;
            }
        } else {
            LOGGER.info("(" + lastHttpStatus + ") " + HttpStatus.getStatusText(lastHttpStatus) + " -- " + url);
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }

    return null;
}

From source file:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java

public void downloadFile(URL url, File outFile) throws IOException, EndUserException {
    URLConnection conn = null;//from w  w w .  ja v a  2s  .c o m
    try {
        Map<String, String> cookies = isSecurityAware() ? ServerContext.getRequestOwner().getIdentityCookies()
                : null;
        conn = URLDownload.makeConnection(url, cookies);
        conn.setRequestProperty("Accept", "*/*");
        URLDownload.getDataToFile(conn, outFile);

    } catch (MalformedURLException e) {
        LOGGER.error(e, "Bad URL");
        throw makeException(e, "WISE Query Failed - bad url.");

    } catch (FailedRequestException e) {
        LOGGER.error(e, e.toString());
        if (conn != null && conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            int respCode = httpConn.getResponseCode();
            String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode);
            throw new EndUserException("Search Failed: " + desc, e.getDetailMessage(), e);
        } else {
            throw makeException(e, "Query Failed - network error.");
        }
    } catch (IOException e) {
        if (conn != null && conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            int respCode = httpConn.getResponseCode();
            String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode);
            throw new EndUserException("Search Failed: " + desc, e.getMessage(), e);
        } else {
            throw makeException(e, "Query Failed - network error.");
        }
    }
}

From source file:fedora.test.integration.TestLargeDatastreams.java

private String upload() throws Exception {
    String url = fedoraClient.getUploadURL();
    EntityEnclosingMethod httpMethod = new PostMethod(url);
    httpMethod.setDoAuthentication(true);
    httpMethod.getParams().setParameter("Connection", "Keep-Alive");
    httpMethod.setContentChunked(true);//w  w w .  ja  va 2s .co  m
    Part[] parts = { new FilePart("file", new SizedPartSource()) };
    httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
    HttpClient client = fedoraClient.getHttpClient();
    try {

        int status = client.executeMethod(httpMethod);
        String response = new String(httpMethod.getResponseBody());

        if (status != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(status) + ": "
                    + replaceNewlines(response, " "));
        } else {
            response = response.replaceAll("\r", "").replaceAll("\n", "");
            return response;
        }
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:com.apatar.ui.JHelpDialog.java

private void addListeners() {
    sendButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            PostMethod filePost = new PostMethod(getUrl());

            // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            try {
                List<File> targetFiles = getAttachFiles();
                Part[] parts;//from w w  w.  j  a  v  a 2  s. c  o m
                if (targetFiles != null) {
                    parts = new Part[targetFiles.size() + 1];
                    int i = 1;
                    for (File targetFile : targetFiles) {
                        parts[i++] = new FilePart("file" + i, targetFile);
                    }
                    ;
                } else
                    parts = new Part[1];

                parts[0] = new StringPart("FeatureRequest", text.getText());

                filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(filePost);
                if (status != HttpStatus.SC_OK) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                            "Upload failed, response=" + HttpStatus.getStatusText(status));
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

        }

    });
}