Example usage for org.apache.commons.httpclient HttpMethod getResponseHeader

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseHeader.

Prototype

public abstract Header getResponseHeader(String paramString);

Source Link

Usage

From source file:com.cloud.test.utils.TestClient.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8080";
    String testUrl = "/client/test";
    int numThreads = 1;

    try {/*from w  w  w  .  j av  a2 s  .c om*/
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-u")) {
                numOfUsers = Integer.parseInt(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }
        }

        final String server = host + ":" + port + testUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        if (numOfUsers > 0) {
            s_logger.info("Pre-generating users for test of size : " + numOfUsers);
            users = new String[numOfUsers];
            Random ran = new Random();
            for (int i = 0; i < numOfUsers; i++) {
                users[i] = Math.abs(ran.nextInt()) + "-user";
            }
        }

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            if (users != null) {
                                username = users[Math.abs(ran.nextInt()) % numOfUsers];
                            } else {
                                username = Math.abs(ran.nextInt()) + "-user";
                            }
                            NDC.push(username);

                            String url = server + "?email=" + username + "&password=" + username
                                    + "&command=deploy";
                            s_logger.info("Launching test for user: " + username + " with url: " + url);
                            HttpClient client = new HttpClient();
                            HttpMethod method = new GetMethod(url);
                            int responseCode = client.executeMethod(method);
                            boolean success = false;
                            String reason = null;
                            if (responseCode == 200) {
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up.

                                    s_logger.info("Begin Linux SSH test");
                                    reason = sshTest(method.getResponseHeader("linuxIP").getValue());

                                    if (reason == null) {
                                        s_logger.info("Linux SSH test successful");
                                        s_logger.info("Begin Windows SSH test");
                                        reason = sshWinTest(method.getResponseHeader("windowsIP").getValue());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info("Windows SSH test successful");
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }
                                    if (users == null) {
                                        s_logger.info("Sending cleanup command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=cleanup";
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=stopDomR";
                                    }
                                    method = new GetMethod(url);
                                    responseCode = client.executeMethod(method);
                                    if (responseCode == 200) {
                                        success = true;
                                    } else {
                                        reason = method.getStatusText();
                                    }
                                } else {
                                    // Just stop but don't destroy the VMs/Routers
                                    s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs");
                                    url = server + "?email=" + username + "&password=" + username
                                            + "&command=stop";
                                    responseCode = client.executeMethod(new GetMethod(url));
                                }
                            } else {
                                // Just stop but don't destroy the VMs/Routers
                                reason = method.getStatusText();
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                url = server + "?email=" + username + "&password=" + username + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");
                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                HttpClient client = new HttpClient();
                                String url = server + "?email=" + username + "&password=" + username
                                        + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:com.cerema.cloud2.lib.common.network.WebdavUtils.java

/**
 *
 * @param method//from  www . ja  va 2 s  . co  m
 * @return
 */
public static String getEtagFromResponse(HttpMethod method) {
    Header eTag = method.getResponseHeader("OC-ETag");
    if (eTag == null) {
        eTag = method.getResponseHeader("oc-etag");
    }
    if (eTag == null) {
        eTag = method.getResponseHeader("ETag");
    }
    if (eTag == null) {
        eTag = method.getResponseHeader("etag");
    }
    String result = "";
    if (eTag != null) {
        result = parseEtag(eTag.getValue());
    }
    return result;
}

From source file:br.org.acessobrasil.nucleuSilva.util.ObterPaginaLocal.java

/**
 * Mtodo que retorna o Content-type de uma pgina web.
 * @param metodo Uma instncia de org.apache.commons.httpclient.HttpMethod
 * inicializada pela pgina.//ww  w  .j a  va2 s. co  m
 * @return O Content-Type da pgina pesquisada.
 */
private static String getContentType(final HttpMethod metodo) {
    String type = "";
    Header header = metodo.getResponseHeader("Content-Type");
    if (header != null) {
        type = header.getValue();
    }
    return type;
}

From source file:jshm.util.PasteBin.java

public static String post(String name, String content) throws Exception {
    if (null == name)
        name = jshm.sh.Client.getUsername();

    HttpForm form = new HttpForm((Object) PASTEBIN_URL, "parent_pid", "", "format", "text", "code2", content,
            "poster", name, "expiry", "m", "paste", "Send") {

        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            try {
                if (response != 302)
                    throw new ClientException("expecting 302 response, got " + response);

                Header h = method.getResponseHeader("Location");

                if (null == h)
                    throw new ClientException("response did not have Location header");

                userData = h.getValue();
            } finally {
                method.releaseConnection();
            }/* ww w  . j  a  v a 2  s.c  o  m*/
        }
    };
    form.submit();

    return form.getUserData() != null ? form.getUserData().toString() : null;
}

From source file:com.xpn.xwiki.plugin.feed.XWikiFeedFetcher.java

/**
 * @param urlStr/*w w w  .java2 s .  co m*/
 * @param method
 * @return
 * @throws IOException
 * @throws HttpException
 * @throws FetcherException
 * @throws FeedException
 */
private static SyndFeed retrieveFeed(String urlStr, HttpMethod method)
        throws IOException, FetcherException, FeedException {

    InputStream stream = null;
    if ((method.getResponseHeader("Content-Encoding") != null)
            && ("gzip".equalsIgnoreCase(method.getResponseHeader("Content-Encoding").getValue()))) {
        stream = new GZIPInputStream(method.getResponseBodyAsStream());
    } else {
        stream = method.getResponseBodyAsStream();
    }
    try {
        XmlReader reader = null;
        if (method.getResponseHeader("Content-Type") != null) {
            reader = new XmlReader(stream, method.getResponseHeader("Content-Type").getValue(), true);
        } else {
            reader = new XmlReader(stream, true);
        }
        return new SyndFeedInput().build(reader);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
 * rewrite request method/*from w w  w.j  a v  a2s  . c o m*/
 * @param method
 * @return
 * @throws MalformedURLException
 */
private static HttpMethod rewrite(HttpMethod method) throws MalformedURLException {
    org.apache.commons.httpclient.Header location = method.getResponseHeader("location");
    if (location == null)
        return method;

    HostConfiguration config = method.getHostConfiguration();
    URL url;
    try {
        url = new URL(location.getValue());
    } catch (MalformedURLException e) {

        url = new URL(config.getProtocol().getScheme(), config.getHost(), config.getPort(),
                mergePath(method.getPath(), location.getValue()));
    }

    method = clone(method, url);

    return method;
}

From source file:net.sf.ehcache.server.util.WebTestUtil.java

/**
 * Orion returns a length of 0. Tomcat does not set content length at all.
 *
 * @param httpMethod//from   w  w w.  ja  va2s . c o m
 */
public static void checkNullOrZeroContentLength(HttpMethod httpMethod) {
    boolean nullContentLengthHeader = httpMethod.getResponseHeader("Content-Length") == null;
    if (!nullContentLengthHeader) {
        assertEquals("0", httpMethod.getResponseHeader("Content-Length").getValue());
    }
}

From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

private static String getContentLength(final HttpMethod metodo) {
    String retorno = "";
    Header header = metodo.getResponseHeader("Content-Length");
    if (header != null) {
        retorno = header.getValue().toString();
    }//  www  . ja v a  2  s  . com
    return retorno;
}

From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

private static String getLocation(final HttpMethod metodo) {
    String retorno = "";
    Header header = metodo.getResponseHeader("Location");
    if (header != null) {
        retorno = header.getValue().toString();
    }//from  w w  w . j  a  v a  2  s . com
    return retorno;
}

From source file:com.intellij.tasks.impl.httpclient.ResponseUtil.java

public static Reader getResponseContentAsReader(@Nonnull HttpMethod response) throws IOException {
    //if (!response.hasBeenUsed()) {
    //  return new StringReader("");
    //}//from  w w  w  . j  av a 2s. com
    InputStream stream = response.getResponseBodyAsStream();
    String charsetName = null;
    org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE);
    if (header != null) {
        // find out encoding
        for (HeaderElement part : header.getElements()) {
            NameValuePair pair = part.getParameterByName("charset");
            if (pair != null) {
                charsetName = pair.getValue();
            }
        }
    }
    return new InputStreamReader(stream, charsetName == null ? DEFAULT_CHARSET_NAME : charsetName);
}