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

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

Introduction

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

Prototype

public abstract byte[] getResponseBody() throws IOException;

Source Link

Usage

From source file:de.juwimm.cms.content.modules.ModuleFactoryStandardImpl.java

public Module loadPlugins(String classname, List<String> additionalJarFiles) {
    Module module = null;/*from ww w . j  a  v a2 s .c  o  m*/
    Communication comm = ((Communication) getBean(Beans.COMMUNICATION));
    SiteValue site = comm.getCurrentSite();
    String urlPath = site.getDcfUrl();
    final String userHome = System.getProperty("user.home");
    final String fileSeparator = System.getProperty("file.separator");

    StringBuffer pluginCachePath = new StringBuffer(userHome);
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(".tizzitCache");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append("plugins");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(Constants.SERVER_HOST);
    pluginCachePath.append(fileSeparator);

    final String pluginPath = pluginCachePath.toString();

    final int addSize = additionalJarFiles.size();

    /* enthaelt alle Jar files die sich nicht auf dem lokalen Rechner befinden */
    ArrayList<String> httpLoad = new ArrayList<String>();

    for (int i = 0; i < addSize; i++) {
        String filePath = pluginPath + additionalJarFiles.get(i);
        File tempFile = new File(filePath);
        if (!tempFile.exists()) {
            httpLoad.add(additionalJarFiles.get(i));
        }
    }

    if (httpLoad.size() > 0) {
        File dir = new File(pluginPath);
        if (!dir.exists()) {
            if (log.isDebugEnabled())
                log.debug("Going to create plugin directory...");
            boolean ret = dir.mkdirs();
            if (!ret) {
                log.warn("Could not create plugin directory");
            }
        }

        /* laedt die Jarfiles auf den lokalen Rechner herunter */
        HttpClient httpclient = new HttpClient();
        for (int i = 0; i < httpLoad.size(); i++) {
            String url = urlPath + httpLoad.get(i);
            if (log.isDebugEnabled())
                log.debug("Plugin URL " + url);
            HttpMethod method = new GetMethod(url);
            try {
                int status = httpclient.executeMethod(method);
                if (status == HttpStatus.SC_OK) {
                    File file = new File(pluginPath + httpLoad.get(i));
                    byte[] data = method.getResponseBody();
                    if (log.isDebugEnabled())
                        log.debug("Received " + data.length + " bytes of data");
                    FileOutputStream output = new FileOutputStream(file);
                    output.write(data);
                    output.close();
                } else {
                    log.warn("No OK received");
                }
            } catch (HttpException htex) {
                log.warn("HTTP exception " + htex.getMessage());
            } catch (IOException ioe) {
                log.warn("IO exception " + ioe.getMessage());
            }
            method.releaseConnection();
        }
    }

    try {
        if (log.isDebugEnabled())
            log.debug("Creating URL");

        URL[] url = new URL[addSize];
        for (int i = 0; i < addSize; i++) {
            String jarModule = additionalJarFiles.get(i);
            String jarPath = "file:///" + pluginPath + jarModule;
            if (log.isDebugEnabled())
                log.debug("Jar path " + jarPath);
            url[i] = new URL(jarPath);
        }
        URLClassLoader cl = this.getURLClassLoader(url);
        //URLClassLoader cl = new URLClassLoader(url, this.getClass().getClassLoader());
        if (log.isDebugEnabled())
            log.debug("Created URL classloader");
        Class c = cl.loadClass(classname);
        if (log.isDebugEnabled())
            log.debug("Created class");
        module = (Module) c.newInstance();
        if (log.isDebugEnabled())
            log.debug("Got the module");
    } catch (Exception loadex) {
        log.warn(loadex.getClass().toString());
        log.error("Cannot load from URL " + loadex.getMessage(), loadex);
    }
    return module;
}

From source file:com.npower.dm.msm.tools.PackageCheckerImpl.java

public PackageMetaInfo getPackageMetaInfo(String url) throws DMException {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    PackageMetaInfo metaInfo = new PackageMetaInfo();
    metaInfo.setUrl(url);/*from  ww w  .j  a va2s.  c o m*/
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        metaInfo.setServerStatus(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            // System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));

        Header mimeType = method.getResponseHeader("Content-Type");
        if (mimeType != null) {
            metaInfo.setMimeType(mimeType.getValue());
        }

        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength != null && StringUtils.isNotEmpty(contentLength.getValue())) {
            metaInfo.setSize(Integer.parseInt(contentLength.getValue()));
        }

    } catch (HttpException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return metaInfo;
}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

@Test
public void testCachingHeadersSet() throws IOException {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertNotNull(httpMethod.getResponseHeader("Last-Modified"));
    assertNotNull(httpMethod.getResponseHeader("Expires"));
    assertEquals("max-age=3600", httpMethod.getResponseHeader("Cache-Control").getValue());
    assertFalse("this did not get overriden".equals(httpMethod.getResponseHeader("Last-Modified").getValue()));
}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Get a JHOVE Document from a URL source
 * @param _url  a resource URL/*from   ww  w.jav  a2s.  co  m*/
 * @return a JDOM Document
 * @throws IOException 
 * @throws JDOMException 
 */
public Document getDocument(URL _url) throws IOException, JDOMException {
    // Create an HttpClient.
    HttpClient client = new HttpClient();

    // Issue a GET HTTP method.
    HttpMethod method = new GetMethod(_url.toExternalForm());
    int status_code = client.executeMethod(method);

    if (status_code != 200) {
        RepInfo representation = new RepInfo(_url.toExternalForm());
        representation
                .setMessage(new ErrorMessage("Status code returned [" + String.valueOf(status_code) + "]."));
        representation.setWellFormed(RepInfo.FALSE);
        return getDocumentFromRepresentation(representation);
    }

    byte[] response = method.getResponseBody();
    return this.getDocument(new ByteArrayInputStream(response), _url.toExternalForm());
}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * Tests whether the page is gzipped using the rawer HttpClient library.
 * Lets us check that the responseBody is really gzipped.
 *///from  ww w. j  a  va 2 s  . co m
@Test
public void testCachedPageIsGzippedWhenEncodingHeaderSet() throws IOException {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip"));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertTrue(PageInfo.isGzipped(responseBody));
}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * Tests whether the page is gzipped using the rawer HttpClient library.
 * Lets us check that the responseBody is really not gzipped.
 *//*from  www.j a  va2  s  . c  om*/
@Test
public void testCachedPageIsNotGzippedWhenEncodingHeaderNotSet() throws IOException {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    //httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip"));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertFalse(PageInfo.isGzipped(responseBody));
}

From source file:edu.utah.further.core.ws.HttpResponseTo.java

/**
 * Copy-constructor from an {@link HttpMethod}.
 * /*w  ww .  j  a v  a2  s.co  m*/
 * @param method
 *            method to copy fields from
 */
public HttpResponseTo(final HttpMethod method) throws IOException {
    this.httpMethod = edu.utah.further.core.api.ws.HttpMethod.valueOf(method.getName());
    this.statusLine = method.getStatusLine();

    for (final Header header : method.getResponseHeaders()) {
        this.responseHeaders.addHeader(new Header(header.getName(), header.getValue()));
    }

    this.path = method.getPath();
    this.queryString = method.getQueryString();
    this.responseBody = method.getResponseBody();
    setParams(method.getParams());
}

From source file:com.qubole.rubix.hadoop1.Hadoop1ClusterManager.java

@Override
public void initialize(Configuration conf) {
    super.initialize(conf);
    nnPort = conf.getInt(nnPortConf, nnPort);

    nodesSupplier = Suppliers.memoizeWithExpiration(new Supplier<List<String>>() {
        @Override//ww w  .ja v a2 s .  co  m
        public List<String> get() {
            if (!isMaster) {
                // First time all nodes start assuming themselves as master and down the line figure out their role
                // Next time onwards, only master will be fetching the list of nodes
                return ImmutableList.of();
            }

            HttpClient httpclient = new HttpClient();
            HttpMethod method = new GetMethod(
                    "http://localhost:" + nnPort + "/dfsnodelist.jsp?whatNodes=LIVE&status=NORMAL");
            int sc;
            try {
                sc = httpclient.executeMethod(method);
            } catch (IOException e) {
                // not reachable => worker
                sc = -1;
            }

            if (sc != 200) {
                LOG.debug("Could not reach dfsnodelist.jsp, setting worker role");
                isMaster = false;
                return ImmutableList.of();
            }

            LOG.debug("Reached dfsnodelist.jsp, setting master role");
            isMaster = true;
            String html;
            try {
                byte[] buf = method.getResponseBody();
                html = new String(buf);
            } catch (IOException e) {
                throw Throwables.propagate(e);
            }

            List<String> nodes = extractNodes(html);
            return nodes;
        }
    }, 10, TimeUnit.SECONDS);
    nodesSupplier.get();
}

From source file:de.avanux.livetracker.statistics.TrackingStatistics.java

private void setCountryCode(float lat, float lon) {
    Document doc = null;//from www. ja va  2  s. co m
    HttpMethod method = null;
    InputStream responseBodyStream = null;
    String responseBodyString = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        String uri = "http://www.geoplugin.net/extras/location.gp?lat=" + lat + "&long=" + lon + "&format=xml";
        log.debug("Retrieving country from " + uri);

        HttpClient client = new HttpClient();
        method = new GetMethod(uri);
        client.executeMethod(method);
        byte[] responseBodyBytes = method.getResponseBody();

        responseBodyString = new String(responseBodyBytes);
        log.debug("Content retrieved: " + responseBodyString);

        // the content is declared as UTF-8 but it seems to be iso-8859-1
        responseBodyString = new String(responseBodyBytes, "iso-8859-1");

        responseBodyStream = new StringBufferInputStream(responseBodyString);
        doc = builder.parse(responseBodyStream);

        XPath xpath = XPathFactory.newInstance().newXPath();
        this.countryCode = ((Node) xpath.evaluate("/geoPlugin/geoplugin_countryCode/text()", doc,
                XPathConstants.NODE)).getNodeValue();
        log.debug("countryCode=" + this.countryCode);
    } catch (Exception e) {
        if (responseBodyString != null) {
            log.error("unparsed xml=" + responseBodyString);
        }
        if (doc != null) {
            log.error("parsed xml=" + getDocumentAsString(doc));
        }
        log.error("Error getting country code.", e);
    } finally {
        try {
            if (responseBodyStream != null) {
                responseBodyStream.close();
            }
            if (method != null) {
                method.releaseConnection();
            }
        } catch (IOException e) {
            log.error("Error releasing resources: ", e);
        }
    }
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

private void logResponseInfo(HttpMethod method) throws IOException {
    if (!mDebugEnabled) {
        return;/*from  w  w w .ja v  a2 s .  c om*/
    }
    StringBuilder responseLog = new StringBuilder();
    responseLog.append("WebDAV response:\n").append(method.getStatusLine()).append('\n');
    Header headers[] = method.getResponseHeaders();
    if (headers != null && headers.length > 0) {
        for (Header hdr : headers) {
            String hdrName = hdr.getName();
            responseLog.append(hdrName).append('=');
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                responseLog.append("*** REPLACED ***\n");
            } else {
                responseLog.append(hdr.getValue()).append('\n');
            }
        }
    }
    if (method.getResponseBody() == null || !ZimbraLog.dav.isTraceEnabled()) {
        ZimbraLog.dav.debug(responseLog.toString());
    } else {
        ZimbraLog.dav.debug("%s\n%s", responseLog.toString(), new String(method.getResponseBody(), "UTF-8"));
    }
}