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.github.maven.plugin.client.impl.GithubClientImpl.java

/**
 * Removes the given download from the repository download section.
 *
 * @param repositoryUrl The repository url.
 * @param artifactName The download name.
 *//*w ww. j  av a 2  s.  com*/
private void delete(String repositoryUrl, String artifactName) {
    final Map<String, Integer> downloads = retrieveDownloadsInfos(repositoryUrl);

    if (!downloads.containsKey(artifactName)) {
        throw new GithubArtifactNotFoundException(
                "The download " + artifactName + " cannot be found in " + repositoryUrl);
    }

    final String downloadUrl = String.format("%s/%d", toRepositoryDownloadUrl(repositoryUrl),
            downloads.get(artifactName));

    PostMethod githubDelete = new PostMethod(downloadUrl);
    githubDelete.setRequestBody(new NameValuePair[] { new NameValuePair("_method", "delete"),
            new NameValuePair("login", login), new NameValuePair("token", token) });

    try {
        int response = httpClient.executeMethod(githubDelete);
        if (response != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new GithubException("Unexpected error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubDelete.releaseConnection();
}

From source file:it.geosolutions.geofence.gui.server.service.impl.InstancesManagerServiceImpl.java

public String getURL(String url, String username, String pw) throws MalformedURLException {

    GetMethod httpMethod = null;/*from w  w w . j av  a2  s. c om*/
    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(httpMethod);
        if (status == 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("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + 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:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @return the cookies return from this request on the login page.
 * @throws MojoExecutionException//from   w  ww. jav a  2  s.  c o  m
 *             if any error occurs during this process.
 */
private Cookie[] getCookies() throws MojoExecutionException {
    Cookie[] cookie = null;
    GetMethod loginGet = new GetMethod(crxPath + "/login.jsp");
    loginGet.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("login to " + loginGet.getURI());
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(loginGet);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");
        if (status == HttpStatus.SC_OK) {
            getLog().info("Login page accessed");
            cookie = client.getState().getCookies();
        } else {
            logResponseDetails(loginGet);
            throw new MojoExecutionException("Login failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        loginGet.releaseConnection();
    }
    return cookie;
}

From source file:com.sun.faban.harness.util.CLI.java

private void makeRequest(HttpMethodBase method) throws IOException {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(method);
    String enc = method.getResponseCharSet();

    InputStream response = method.getResponseBodyAsStream();

    if (status == HttpStatus.SC_NOT_FOUND) {
        System.err.println("Not found!");
        return;/*  www .j a v  a 2  s.c o m*/
    } else if (status == HttpStatus.SC_NO_CONTENT) {
        System.err.println("Empty!");
        return;
    } else if (response != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response, enc));
        String line = null;
        while ((line = reader.readLine()) != null)
            System.out.println(line);
    } else if (status != HttpStatus.SC_OK)
        throw new IOException(HttpStatus.getStatusText(status));
}

From source file:eu.scape_project.arc2warc.ArcMigrator.java

private String constructPayloadHeader(ArcRecordBase jwatArcRecord) {
    String payloadHeader = "";
    if (jwatArcRecord.getHttpHeader() != null) {
        String statusCodeStr = jwatArcRecord.getHttpHeader().statusCodeStr;
        String httpVersionStr = jwatArcRecord.getHttpHeader().httpVersion;
        if (httpVersionStr != null && statusCodeStr != null) {
            Integer statusCode = jwatArcRecord.getHttpHeader().statusCode;
            payloadHeader += httpVersionStr + " " + statusCodeStr + " " + HttpStatus.getStatusText(statusCode)
                    + "\r\n";
        }//  w w  w .ja v a 2s  . c o m
        List<HeaderLine> headerList = jwatArcRecord.getHttpHeader().getHeaderList();
        if (headerList != null) {
            for (HeaderLine hl : headerList) {
                payloadHeader += hl.name + ": " + hl.value + "\r\n";
            }
        }
        payloadHeader += "\r\n"; // end of HTTP response header
    }
    return payloadHeader;
}

From source file:com.serena.rlc.provider.jira.client.JiraClient.java

private JiraClientException createHttpError(HttpResponse response) {
    String message;/*from  ww w .  ja  va2  s  .c om*/
    try {
        StatusLine statusLine = response.getStatusLine();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        StringBuffer responsePayload = new StringBuffer();
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            responsePayload.append(line);
        }

        message = String.format(" request not successful: %d %s. Reason: %s", statusLine.getStatusCode(),
                HttpStatus.getStatusText(statusLine.getStatusCode()), responsePayload);

        logger.debug(message);

        if (new Integer(HttpStatus.SC_UNAUTHORIZED).equals(statusLine.getStatusCode())) {
            return new JiraClientException("Invalid credentials provided.");
        } else if (new Integer(HttpStatus.SC_NOT_FOUND).equals(statusLine.getStatusCode())) {
            return new JiraClientException("JIRA: Request URL not found.");
        } else if (new Integer(HttpStatus.SC_BAD_REQUEST).equals(statusLine.getStatusCode())) {
            return new JiraClientException("JIRA: Bad request. " + responsePayload);
        }
    } catch (IOException e) {
        return new JiraClientException("JIRA: Can't read response");
    }

    return new JiraClientException(message);
}

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

public void delete(String targetLocation, String name, String username, String password)
        throws TransportException {

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

    PostMethod post = new PostMethod(targetLocation);
    post.addParameter("fileToDelete", name);

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

        //Set the 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);
        }

        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem deleting a file on 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 deleting a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } 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:gov.nih.nci.ncicb.tcga.dcc.qclive.webservice.client.impl.ShippedBiospecimenWSQueriesImpl.java

private <T> T handleClientResponse(final ClientResponse clientResponse, final Class<T> responseType) {
    T response = null;//from   w w  w .  j a  v a 2 s.  c  o  m
    int responseStatus = clientResponse.getStatus();
    StringBuilder errorMessage = null;
    if (HttpStatus.SC_OK == responseStatus) {
        response = clientResponse.getEntity(responseType);
    } else if (HttpStatus.SC_UNPROCESSABLE_ENTITY == responseStatus) {
        // this actually means the entity was not found which might
        // be a valid response, so just return null, don't assume it's an error
        // HttpStatus 400
    } else if (HttpStatus.SC_BAD_REQUEST == responseStatus) {
        errorMessage = new StringBuilder().append("Request returned HTTP response status of '")
                .append(responseStatus).append(" - ").append(HttpStatus.getStatusText(responseStatus))
                .append("'. Check the request and try again.");
        // HttpStatus 413
    } else if (HttpStatus.SC_REQUEST_TOO_LONG == responseStatus) {
        errorMessage = new StringBuilder().append("Request returned HTTP response status of '")
                .append(responseStatus).append(" - ").append(HttpStatus.getStatusText(responseStatus))
                .append("'. The number of requests to this web service has exceeded the DCC limits.")
                .append(" You should reduce the number of concurrent instances of the stand-alone validator running or use the -noremote flag.");
        if (qcContext != null) {
            qcContext.addError(errorMessage.toString());
        }
        throw new RuntimeException(errorMessage.toString());
    }

    if (errorMessage != null) {
        handleErrorMessage(errorMessage.toString());
    }

    return response;
}

From source file:com.sun.faban.harness.util.CLI.java

private String makeStringRequest(HttpMethodBase method) throws IOException {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(method);
    String enc = method.getResponseCharSet();

    InputStream response = method.getResponseBodyAsStream();
    StringBuilder buffer = new StringBuilder();
    if (status == HttpStatus.SC_NOT_FOUND) {
        System.err.println("Not found!");
        return buffer.toString();
    } else if (status == HttpStatus.SC_NO_CONTENT) {
        System.err.println("Empty!");
        return buffer.toString();
    } else if (response != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response, enc));
        String line = null;/*from w  ww  .j ava  2  s.  c om*/
        while ((line = reader.readLine()) != null)
            buffer.append(line).append('\n');
    } else if (status != HttpStatus.SC_OK)
        throw new IOException(HttpStatus.getStatusText(status));
    return buffer.toString();
}

From source file:com.openkm.extension.servlet.ZohoServlet.java

/**
 *   //from   w  w  w. j  a  va2 s .  c om
 */
private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang)
        throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException,
        IOException, OKMException {
    Map<String, String> result = new HashMap<String, String>();
    File tmp = null;

    try {
        String path = OKMRepository.getInstance().getNodePath(null, nodeUuid);
        String fileName = PathUtils.getName(path);
        tmp = File.createTempFile("okm", ".tmp");
        InputStream is = OKMDocument.getInstance().getContent(null, path, false);
        Document doc = OKMDocument.getInstance().getProperties(null, path);
        FileOutputStream fos = new FileOutputStream(tmp);
        IOUtils.copy(is, fos);
        fos.flush();
        fos.close();

        String id = UUID.randomUUID().toString();
        String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload";
        Part[] parts = { new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY),
                new StringPart("output", "url"), new StringPart("mode", "normaledit"),
                new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY),
                new StringPart("lang", lang), new StringPart("id", id),
                new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl) };

        PostMethod filePost = new PostMethod(zohoUrl);
        filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        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) {
            log.debug("OK: " + filePost.getResponseBodyAsString());
            ZohoToken zot = new ZohoToken();
            zot.setId(id);
            zot.setUser(getThreadLocalRequest().getRemoteUser());
            zot.setNode(nodeUuid);
            zot.setCreation(Calendar.getInstance());
            ZohoTokenDAO.create(zot);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                if (line.startsWith("URL=")) {
                    result.put("url", line.substring(4));
                    result.put("id", id);
                    break;
                }
            }

            rd.close();
        } else {
            String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString();
            log.error("ERROR: {}", error);
            throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error);
        }
    } finally {
        FileUtils.deleteQuietly(tmp);
    }

    return result;
}