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

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

Introduction

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

Prototype

public abstract InputStream getResponseBodyAsStream() throws IOException;

Source Link

Usage

From source file:org.alfresco.encryption.DefaultEncryptionUtils.java

/**
 * {@inheritDoc}/*from w  ww .  j  av  a 2  s .  c  o m*/
 */
@Override
public byte[] decryptResponseBody(HttpMethod method) throws IOException {
    // TODO fileoutputstream if content is especially large?
    InputStream body = method.getResponseBodyAsStream();
    if (body != null) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileCopyUtils.copy(body, out);

        AlgorithmParameters params = decodeAlgorithmParameters(method);
        if (params != null) {
            byte[] decrypted = encryptor.decrypt(KeyProvider.ALIAS_SOLR, params, out.toByteArray());
            return decrypted;
        } else {
            throw new AlfrescoRuntimeException(
                    "Unable to decrypt response body, missing encryption algorithm parameters");
        }
    } else {
        return null;
    }
}

From source file:org.alfresco.rest.api.tests.client.AbstractHttp.java

/**
 * Extract JSON-object from the method's response.
 * @param method the method containing the response
 * @return the json object. Returns null if response is not JSON or no data-object
 *         is present.//w w  w .  j a  va  2  s  .c o m
 */
public JSONObject getObjectFromResponse(HttpMethod method) {
    JSONObject result = null;

    try {
        InputStream response = method.getResponseBodyAsStream();
        if (response != null) {
            Object object = new JSONParser().parse(new InputStreamReader(response, Charset.forName("UTF-8")));
            if (object instanceof JSONObject) {
                return (JSONObject) object;
            }
        }
    } catch (IOException error) {
        // Ignore errors, returning null
    } catch (ParseException error) {
        // Ignore errors, returning null
    }

    return result;
}

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

private void executeRequest(WebscriptResponseHandler handler, HttpMethod httpMethod,
        boolean ignoreUnauthorized) {
    long startTime = 0L;
    if (log.isDebugEnabled()) {
        startTime = System.currentTimeMillis();
    }/*from   ww w .  j a  v a2  s . c o m*/
    try {
        httpClient.executeMethod(httpMethod);

        if ((httpMethod.getStatusCode() == 401 || httpMethod.getStatusCode() == 403) && !ignoreUnauthorized) {
            discardResponse(httpMethod);

            this.getTicket(username, password);
            httpClient.executeMethod(httpMethod);
        }

        if (httpMethod.getStatusCode() == 200) {
            handler.handleResponse(httpMethod.getResponseBodyAsStream());
        } else {
            // Must read the response, even though we don't use it
            discardResponse(httpMethod);
        }
    } catch (RuntimeException ex) {
        log.error("Rethrowing runtime exception.", ex);
        throw ex;
    } catch (Exception ex) {
        log.error("Failed to make request to Alfresco web script", ex);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug(httpMethod.getName() + " request to " + httpMethod.getPath() + "?"
                    + httpMethod.getQueryString() + " completed in " + (System.currentTimeMillis() - startTime)
                    + "ms");
        }
        httpMethod.releaseConnection();
    }
}

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

void discardResponse(HttpMethod httpMethod) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Received non-OK response when invoking method on path " + httpMethod.getPath()
                + ". Response was:\n" + httpMethod.getResponseBodyAsString());
    } else {//from w  ww .  java 2 s.c  o  m
        byte[] buf = localBuffer.get();
        InputStream responseStream = httpMethod.getResponseBodyAsStream();
        while (responseStream.read(buf) != -1)
            ;
    }
}

From source file:org.apache.asterix.aoya.Utils.java

private static InputStream executeHTTPCall(HttpMethod method) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    HttpMethodRetryHandler noop = new HttpMethodRetryHandler() {
        @Override//  ww w  . ja v a  2  s . c  o  m
        public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
            return false;
        }
    };
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noop);
    client.executeMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:org.apache.camel.component.http.HttpPollingConsumer.java

protected Exchange doReceive(int timeout) {
    Exchange exchange = endpoint.createExchange();
    HttpMethod method = createMethod(exchange);

    // set optional timeout in millis
    if (timeout > 0) {
        method.getParams().setSoTimeout(timeout);
    }/*from   w w  w.j a va2  s  . c  o  m*/

    try {
        // execute request
        int responseCode = httpClient.executeMethod(method);

        Object body = HttpHelper.readResponseBodyFromInputStream(method.getResponseBodyAsStream(), exchange);

        // lets store the result in the output message.
        Message message = exchange.getOut();
        message.setBody(body);

        // lets set the headers
        Header[] headers = method.getResponseHeaders();
        HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
        for (Header header : headers) {
            String name = header.getName();
            // mapping the content-type
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            String value = header.getValue();
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
                message.setHeader(name, value);
            }
        }
        message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);

        return exchange;
    } catch (IOException e) {
        throw new RuntimeCamelException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.camel.component.http.HttpProducer.java

/**
 * Extracts the response from the method as a InputStream.
 *
 * @param method the method that was executed
 * @return the response either as a stream, or as a deserialized java object
 * @throws IOException can be thrown/*from  w  w  w . j ava2s  .  c  om*/
 */
protected static Object extractResponseBody(HttpMethod method, Exchange exchange)
        throws IOException, ClassNotFoundException {
    InputStream is = method.getResponseBodyAsStream();
    if (is == null) {
        return null;
    }

    Header header = method.getResponseHeader(Exchange.CONTENT_ENCODING);
    String contentEncoding = header != null ? header.getValue() : null;

    if (!exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
        is = GZIPHelper.uncompressGzip(contentEncoding, is);
    }

    // Honor the character encoding
    String contentType = null;
    header = method.getResponseHeader("content-type");
    if (header != null) {
        contentType = header.getValue();
        // find the charset and set it to the Exchange
        HttpHelper.setCharsetFromContentType(contentType, exchange);
    }
    InputStream response = doExtractResponseBodyAsStream(is, exchange);
    // if content type is a serialized java object then de-serialize it back to a Java object
    if (contentType != null && contentType.equals(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT)) {
        return HttpHelper.deserializeJavaObjectFromStream(response);
    } else {
        return response;
    }
}

From source file:org.apache.cloudstack.region.RegionsApiUtil.java

/**
 * Makes an api call using region service end_point, api command and params
 * Returns Account object on success/*from   w w  w  .  j  a v a  2s.  c  o m*/
 * @param region
 * @param command
 * @param params
 * @return
 */
protected static RegionAccount makeAccountAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            //Translate response to Account object
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("account", RegionAccount.class);
            xstream.alias("user", RegionUser.class);
            xstream.aliasField("id", RegionAccount.class, "uuid");
            xstream.aliasField("name", RegionAccount.class, "accountName");
            xstream.aliasField("accounttype", RegionAccount.class, "type");
            xstream.aliasField("domainid", RegionAccount.class, "domainUuid");
            xstream.aliasField("networkdomain", RegionAccount.class, "networkDomain");
            xstream.aliasField("id", RegionUser.class, "uuid");
            xstream.aliasField("accountId", RegionUser.class, "accountUuid");
            try (ObjectInputStream in = xstream.createObjectInputStream(is);) {
                return (RegionAccount) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}

From source file:org.apache.cloudstack.region.RegionsApiUtil.java

/**
 * Makes an api call using region service end_point, api command and params
 * Returns Domain object on success/*ww  w  .j  a va 2  s  .  c  om*/
 * @param region
 * @param command
 * @param params
 * @return
 */
protected static RegionDomain makeDomainAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            XStream xstream = new XStream(new DomDriver());
            //Translate response to Domain object
            xstream.alias("domain", RegionDomain.class);
            xstream.aliasField("id", RegionDomain.class, "uuid");
            xstream.aliasField("parentdomainid", RegionDomain.class, "parentUuid");
            xstream.aliasField("networkdomain", DomainVO.class, "networkDomain");
            try (ObjectInputStream in = xstream.createObjectInputStream(is);) {
                return (RegionDomain) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}

From source file:org.apache.cloudstack.region.RegionsApiUtil.java

/**
 * Makes an api call using region service end_point, api command and params
 * Returns UserAccount object on success
 * @param region/*from   w w w  .j  av a2  s.c  om*/
 * @param command
 * @param params
 * @return
 */
protected static UserAccount makeUserAccountAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("useraccount", UserAccountVO.class);
            xstream.aliasField("id", UserAccountVO.class, "uuid");
            try (ObjectInputStream in = xstream.createObjectInputStream(is);) {
                return (UserAccountVO) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}