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.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files)
        throws IOException, SlideShareErrorException {
    PostMethod method = new PostMethod(url);
    List<Part> partList = new ArrayList<Part>();
    partList.add(createStringPart("api_key", this.apiKey));
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    partList.add(createStringPart("ts", ts));
    partList.add(createStringPart("hash", hash));
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        partList.add(createStringPart(entry.getKey(), entry.getValue()));
    }/*from  w w  w . j  av  a 2  s. c  o m*/
    Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator();
    while (entryFileIt.hasNext()) {
        Map.Entry<String, File> entry = entryFileIt.next();
        partList.add(createFilePart(entry.getKey(), entry.getValue()));
    }
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(
            partList.toArray(new Part[partList.size()]), method.getParams());
    method.setRequestEntity(requestEntity);
    logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList);
    int statusCode = httpClient.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:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendGetMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    GetMethod method = new GetMethod(url);
    NameValuePair[] params = new NameValuePair[parameters.size() + 3];
    int i = 0;//from w  w  w . j a v a 2 s.co  m
    params[i++] = new NameValuePair("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        params[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    }
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    params[i++] = new NameValuePair("ts", ts);
    params[i++] = new NameValuePair("hash", hash);
    method.setQueryString(params);
    logger.debug("Sending GET message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(params));
    int statusCode = httpClient.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:org.apache.ambari.view.slider.rest.client.BaseHttpClient.java

@SuppressWarnings("deprecation")
public JsonElement doGetJson(String url, String path) throws HttpException, IOException {
    GetMethod get = new GetMethod(url + path);
    if (isNeedsAuthentication()) {
        get.setDoAuthentication(true);/*from  w  w  w  .  j a va2s .c o m*/
    }
    int executeMethod = getHttpClient().executeMethod(get);
    switch (executeMethod) {
    case HttpStatus.SC_OK:
        JsonElement jsonElement = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(get.getResponseBodyAsStream())));
        return jsonElement;
    case HttpStatus.SC_NOT_FOUND:
        return null;
    default:
        HttpException httpException = new HttpException(get.getResponseBodyAsString());
        httpException.setReason(HttpStatus.getStatusText(executeMethod));
        httpException.setReasonCode(executeMethod);
        throw httpException;
    }
}

From source file:org.apache.commons.httpclient.demo.SubmitHttpForm.java

public static void main(String[] args) {

    //Instantiate an HttpClient
    HttpClient client = new HttpClient();

    //Instantiate a GET HTTP method
    //HttpMethod method = new GetMethod(url);
    //Instantiate a POST HTTP method
    PostMethod method = new PostMethod(url);

    //Define name-value pairs to set into the QueryString
    NameValuePair nvp1 = new NameValuePair("firstName", "fname");
    NameValuePair nvp2 = new NameValuePair("lastName", "lname");
    NameValuePair nvp3 = new NameValuePair("email", "email@email.com");

    method.setQueryString(new NameValuePair[] { nvp1, nvp2, nvp3 });

    try {//  w  ww .j  a  v  a2  s.c o m
        int statusCode = client.executeMethod(method);

        System.out.println("QueryString>>> " + method.getQueryString());
        System.out.println("Status Text>>> " + HttpStatus.getStatusText(statusCode));

        //Get data as a String
        //
        String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));
        //
        System.out.println("===================================");
        System.out.println(":");
        System.out.println(response);
        System.out.println("===================================");

        //OR as a byte array
        byte[] res = method.getResponseBody();

        //write to file
        FileOutputStream fos = new FileOutputStream("donepage.html");
        fos.write(res);

        //release connection
        method.releaseConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

private void post(String targetURL, File file) throws MojoExecutionException {

    PostMethod filePost = new PostMethod(targetURL);
    try {//from   w w  w .jav a2 s  . co  m
        Part[] parts = { new FilePart(file.getName(), new FilePartSource(file.getName(), file)),
                new StringPart("_noredir_", "_noredir_") };
        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) {
            getLog().info("Bundle deployed");
        } else {
            String msg = "Deployment failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Deployment on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Install the bundle via POST to the Felix Web Console
 * @param targetURL the URL to the Felix Web Console Bundles listing
 * @param file the file to POST//from  ww w. ja v  a 2s  .c  o  m
 * @throws MojoExecutionException
 * @see <a href="http://felix.apache.org/documentation/subprojects/apache-felix-web-console/web-console-restful-api.html#post-requests">Webconsole RESTful API</a>
 * @see <a href="https://github.com/apache/felix/blob/trunk/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundlesServlet.java">BundlesServlet@Github</a>
 */
protected void postToFelix(String targetURL, File file) throws MojoExecutionException {

    // append pseudo path after root URL to not get redirected for nothing
    final PostMethod filePost = new PostMethod(targetURL + "/install");

    try {
        // set referrer
        filePost.setRequestHeader("referer", "about:blank");

        List<Part> partList = new ArrayList<Part>();
        partList.add(new StringPart("action", "install"));
        partList.add(new StringPart("_noredir_", "_noredir_"));
        partList.add(new FilePart("bundlefile", new FilePartSource(file.getName(), file)));
        partList.add(new StringPart("bundlestartlevel", bundleStartLevel));

        if (bundleStart) {
            partList.add(new StringPart("bundlestart", "start"));
        }

        if (refreshPackages) {
            partList.add(new StringPart("refreshPackages", "true"));
        }

        Part[] parts = partList.toArray(new Part[partList.size()]);

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

        int status = getHttpClient().executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            getLog().info("Bundle installed");
        } else {
            String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Perform the operation via POST to SlingPostServlet
 * @param targetURL the URL of the Sling instance to post the file to.
 * @param file the file being interacted with the POST to Sling.
 * @throws MojoExecutionException/*from   w w  w . jav a2s . c  o m*/
 */
protected void postToSling(String targetURL, File file) throws MojoExecutionException {

    /* truncate off trailing slash as this has special behaviorisms in
     * the SlingPostServlet around created node name conventions */
    if (targetURL.endsWith("/")) {
        targetURL = targetURL.substring(0, targetURL.length() - 1);
    }
    // append pseudo path after root URL to not get redirected for nothing
    final PostMethod filePost = new PostMethod(targetURL);

    try {

        Part[] parts = new Part[2];
        // Add content type to force the configured mimeType value
        parts[0] = new FilePart("*", new FilePartSource(file.getName(), file), mimeType, null);
        // Add TypeHint to have jar be uploaded as file (not as resource)
        parts[1] = new StringPart("*@TypeHint", "nt:file");

        /* Request JSON response from Sling instead of standard HTML, to
         * reduce the payload size (if the PostServlet supports it). */
        filePost.setRequestHeader("Accept", JSON_MIME_TYPE);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        int status = getHttpClient().executeMethod(filePost);
        // SlingPostServlet may return 200 or 201 on creation, accept both
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
            getLog().info("Bundle installed");
        } else {
            String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Puts the file via PUT (leveraging WebDAV). Creates the intermediate folders as well.
 * @param targetURL// w w w  . j  a  v a 2s  .  c  o  m
 * @param file
 * @throws MojoExecutionException
 * @see <a href="https://tools.ietf.org/html/rfc4918#section-9.7.1">RFC 4918</a>
 */
protected void putViaWebDav(String targetURL, File file) throws MojoExecutionException {

    boolean success = false;
    int status;

    try {
        status = performPut(targetURL, file);
        if (status >= 200 && status < 300) {
            success = true;
        } else if (status == HttpStatus.SC_CONFLICT) {

            getLog().debug(
                    "Bundle not installed due missing parent folders. Attempting to create parent structure.");
            createIntermediaryPaths(targetURL);

            getLog().debug("Re-attempting bundle install after creating parent folders.");
            status = performPut(targetURL, file);
            if (status >= 200 && status < 300) {
                success = true;
            }
        }

        if (!success) {
            String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

private void createIntermediaryPaths(String targetURL)
        throws HttpException, IOException, MojoExecutionException {
    // extract all intermediate URIs (longest one first)
    List<String> intermediateUris = IntermediateUrisExtractor.extractIntermediateUris(targetURL);

    // 1. go up to the node in the repository which exists already (HEAD request towards the root node)
    String existingIntermediateUri = null;
    // go through all intermediate URIs (longest first)
    for (String intermediateUri : intermediateUris) {
        // until one is existing
        int result = performHead(intermediateUri);
        if (result == HttpStatus.SC_OK) {
            existingIntermediateUri = intermediateUri;
            break;
        } else if (result != HttpStatus.SC_NOT_FOUND) {
            throw new MojoExecutionException("Failed getting intermediate path at " + intermediateUri + "."
                    + " Reason: " + HttpStatus.getStatusText(result));
        }//from w  w  w  .  ja v a 2s. co  m
    }

    if (existingIntermediateUri == null) {
        throw new MojoExecutionException(
                "Could not find any intermediate path up until the root of " + targetURL + ".");
    }

    // 2. now create from that level on each intermediate node individually towards the target path
    int startOfInexistingIntermediateUri = intermediateUris.indexOf(existingIntermediateUri);
    if (startOfInexistingIntermediateUri == -1) {
        throw new IllegalStateException(
                "Could not find intermediate uri " + existingIntermediateUri + " in the list");
    }

    for (int index = startOfInexistingIntermediateUri - 1; index >= 0; index--) {
        // use MKCOL to create the intermediate paths
        String intermediateUri = intermediateUris.get(index);
        int result = performMkCol(intermediateUri);
        if (result == HttpStatus.SC_CREATED || result == HttpStatus.SC_OK) {
            getLog().debug("Intermediate path at " + intermediateUri + " successfully created");
            continue;
        } else {
            throw new MojoExecutionException("Failed creating intermediate path at '" + intermediateUri + "'."
                    + " Reason: " + HttpStatus.getStatusText(result));
        }
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

protected void removeConfiguration(final HttpClient client, final String targetURL, String pid)
        throws MojoExecutionException {
    final String postUrl = targetURL + "/configMgr/" + pid;
    final PostMethod post = new PostMethod(postUrl);
    post.addParameter("apply", "true");
    post.addParameter("delete", "true");
    try {//from   ww  w.  j  a  v  a  2s  .co  m
        final int status = client.executeMethod(post);
        // we get a moved temporarily back from the configMgr plugin
        if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_OK) {
            getLog().debug("Configuration removed.");
        } else {
            getLog().error("Removing configuration failed, cause: " + HttpStatus.getStatusText(status));
        }
    } catch (HttpException ex) {
        throw new MojoExecutionException(
                "Removing configuration at " + postUrl + " failed, cause: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException(
                "Removing configuration at " + postUrl + " failed, cause: " + ex.getMessage(), ex);
    } finally {
        post.releaseConnection();
    }
}