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

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

Introduction

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

Prototype

@Override
public InputStream getResponseBodyAsStream() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as an InputStream .

Usage

From source file:org.deegree.portal.owswatch.validator.WCSGetCoverageValidator.java

@Override
public ValidatorResponse validateAnswer(HttpMethodBase method, int statusCode) {

    String lastMessage = null;//from w ww.  j  a  va  2 s . c om
    Status status = null;
    String contentType = method.getResponseHeader("Content-Type").getValue();
    if (contentType.contains("image")) {
        try {
            InputStream stream = copyStream(method.getResponseBodyAsStream());
            stream.reset();
            ImageIO.read(stream);
            status = Status.RESULT_STATE_AVAILABLE;
            lastMessage = status.getStatusMessage();
            return new ValidatorResponse(lastMessage, status);
        } catch (Exception e) {
            status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
            lastMessage = e.getLocalizedMessage();
            return new ValidatorResponse(lastMessage, status);
        }
    } else if (contentType.contains("xml")) {
        return validateXml(method);
    } else {
        StringBuilder builder = new StringBuilder("Response content is: ");
        builder.append(contentType);
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        lastMessage = Messages.getMessage("ERROR_INCORRECT_RESP_CONTENT2", contentType, "image", "xml");
        return new ValidatorResponse(lastMessage, status);
    }
}

From source file:org.deegree.portal.owswatch.validator.WMSGetMapValidator.java

@Override
public ValidatorResponse validateAnswer(HttpMethodBase method, int statusCode) {

    String contentType = method.getResponseHeader("Content-Type").getValue();
    String lastMessage = null;/* w ww .  ja  va 2 s.  c  o m*/
    Status status = null;

    if (!contentType.contains("image")) {
        if (!contentType.contains("xml")) {
            status = Status.RESULT_STATE_UNEXPECTED_CONTENT;
            lastMessage = StringTools.concat(100, "Error: Response Content is ", contentType, " not image");
            return new ValidatorResponse(lastMessage, status);
        } else {
            return validateXmlServiceException(method);
        }
    }

    try {
        InputStream stream = copyStream(method.getResponseBodyAsStream());
        stream.reset();
        ImageIO.read(stream);
        status = Status.RESULT_STATE_AVAILABLE;
        lastMessage = status.getStatusMessage();
        return new ValidatorResponse(lastMessage, status);
    } catch (Exception e) {
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        lastMessage = e.getLocalizedMessage();
        return new ValidatorResponse(lastMessage, status);
    }
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

public static InputStream getResponseBodyAsStream(HttpMethodBase method, IProgressMonitor monitor)
        throws IOException {
    //      return method.getResponseBodyAsStream();
    monitor = Policy.monitorFor(monitor);
    return new PollingInputStream(
            new TimeoutInputStream(method.getResponseBodyAsStream(), BUFFER_SIZE, POLL_INTERVAL, CLOSE_TIMEOUT),
            POLL_ATTEMPTS, monitor);/*from  w  ww  .j  a  v  a  2s.com*/
}

From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java

/**
 * Exposed at connector level via IOslcCoreConnector.getAvailableServices()
 */// w  w  w  .  j a va 2s. c o m
public List<OslcServiceProvider> getAvailableServices(String url, IProgressMonitor monitor)
        throws CoreException {

    RequestHandler<List<OslcServiceProvider>> handler = new RequestHandler<List<OslcServiceProvider>>(
            "Requesting Available Services") { //$NON-NLS-1$

        @Override
        public List<OslcServiceProvider> run(HttpMethodBase method, IProgressMonitor monitor)
                throws CoreException {
            try {
                final List<OslcServiceProvider> result = new ArrayList<OslcServiceProvider>();
                parseServices(method.getResponseBodyAsStream(), result, monitor);
                return result;
            } catch (IOException e) {
                throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN,
                        "Network error occurred retrieving available services: " + e.getMessage(), e)); //$NON-NLS-1$
            }
        }
    };

    return executeMethod(createGetMethod(url), handler, monitor);
}

From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java

protected Document getDocumentFromMethod(HttpMethodBase method) throws CoreException {
    try {//w w w.  j  a  va2 s  .  c o m
        return getDocumentFromStream(method.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN,
                "Network error obtaining response from server: " + e.getMessage(), e)); //$NON-NLS-1$
    }
}

From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java

/**
 * Populate the provided configuration with new data from the remote repository.
 *//*www.  java  2  s  .  c  o m*/
protected void downloadServiceDescriptor(final OslcServiceDescriptor config, IProgressMonitor monitor)
        throws CoreException {

    RequestHandler<OslcServiceDescriptor> handler = new RequestHandler<OslcServiceDescriptor>(
            "Retrieving Service Descriptor") { //$NON-NLS-1$

        @Override
        public OslcServiceDescriptor run(HttpMethodBase method, IProgressMonitor monitor)
                throws CoreException, IOException {
            config.clear();
            parseServiceDescriptor(method.getResponseBodyAsStream(), config, monitor);
            return config;
        }
    };

    executeMethod(createGetMethod(config.getAboutUrl()), handler, monitor);

}

From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java

public Collection<AbstractChangeRequest> performQuery(String query, IProgressMonitor monitor)
        throws CoreException {
    try {/*from w  w  w.j  a  v  a2 s  .c  om*/
        query = URLEncoder.encode(query, "UTF-8"); //$NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
        query = URLEncoder.encode(query);
    }
    final String requestUrl = getConfiguration(monitor).getSimpleQueryUrl() + "?oslc_cm.query=" + query; //$NON-NLS-1$

    RequestHandler<Collection<AbstractChangeRequest>> handler = new RequestHandler<Collection<AbstractChangeRequest>>(
            "Performing Query") { //$NON-NLS-1$

        @Override
        public Collection<AbstractChangeRequest> run(HttpMethodBase method, IProgressMonitor monitor)
                throws CoreException, IOException {
            Collection<AbstractChangeRequest> result = new ArrayList<AbstractChangeRequest>();
            parseQueryResponse(method.getResponseBodyAsStream(), result, monitor);
            return result;
        }
    };

    return executeMethod(createGetMethod(requestUrl), handler, monitor);

}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

private InputStream createConnectionReleasingInputStream(final HttpMethodBase method) throws IOException {
    return new FilterInputStream(method.getResponseBodyAsStream()) {
        @Override/*w  w w.  j ava  2  s.  c  o m*/
        public void close() throws IOException {
            try {
                super.close();
            } finally {
                method.releaseConnection();
            }
        }
    };
}

From source file:org.eclipse.rtp.configurator.rest.RestTemplate.java

private SourceProvider getProvider(HttpMethodBase method) {
    InputStream responseStream = null;
    try {//  w w  w.  j  av a  2  s. c o m
        try {
            responseStream = method.getResponseBodyAsStream();
        } catch (IOException e) {
            throw new IllegalStateException("Error querying REST interface.");
        }
        return this.unMarshaller.marshal(responseStream);
    } finally {
        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (IOException e) {
                // closing input stream failed.
            }
        }
    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Creates new object and fills it with retrieved URL information.
 * /*from w  w w  .  jav a 2  s .  c o m*/
 * @param http
 *          HTTP protocol options HTTP to retrieve
 * @param filterProcessor
 *          filters to perform
 * @param urlString
 *          the url string
 * 
 * @throws IOException
 *           if error while retrieving URL occur
 */
public HttpResponse(HttpBase http, String urlString, FilterProcessor filterProcessor) throws IOException {
    _http = http;
    _urlString = urlString;
    HttpMethodBase httpMethod = null;
    try {
        httpMethod = getHttpMethod();
        setHttpParameters(http, httpMethod);
        _statusCode = Http.getClient().executeMethod(httpMethod);
        final Header[] headers = httpMethod.getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            _headers.set(headers[i].getName(), headers[i].getValue());
        }
        // Content-Type filter should go here
        // TODO: Guess content type when Content-Type header is empty
        boolean contentTypeMatches = true;
        final String contentType = _headers.get(Response.CONTENT_TYPE);
        if ((contentType != null) && (filterProcessor != null)) {
            contentTypeMatches = filterProcessor.evaluateContentTypeFilters(contentType);
            LOG.debug("Content type header: " + contentType + ", passed filters: " + contentTypeMatches);
        }
        if (contentTypeMatches) {
            // always read content. Sometimes content is useful to find a cause for error.
            try {
                final InputStream in = httpMethod.getResponseBodyAsStream();
                if (in != null) {
                    final byte[] buffer = new byte[HttpBase.BUFFER_SIZE];
                    int totalRead = 0;
                    final ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int tryAndRead = calculateTryToRead(totalRead);
                    int bufferFilled = in.read(buffer, 0, buffer.length);
                    while (bufferFilled != -1 && tryAndRead > 0) {
                        totalRead += bufferFilled;
                        out.write(buffer, 0, bufferFilled);
                        tryAndRead = calculateTryToRead(totalRead);
                        bufferFilled = in.read(buffer, 0, buffer.length);
                    }
                    _content = out.toByteArray();
                    in.close();
                }
            } catch (HttpException exception) {
                LOG.error("Http error occured ", exception);
                throw new IOException(exception.toString());
            } catch (IOException exception) {
                if (_statusCode == HttpResponseCode.CODE_200) {
                    throw new IOException(exception.toString());
                }
                // for codes other than 200 OK, we are fine with empty content
            }
            if (_content != null) {
                // check if we have to uncompress it
                final String contentEncoding = _headers.get(Response.CONTENT_ENCODING);
                if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
                if (("application/x-gzip".equals(contentType)) || ("application/gzip".equals(contentType))) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
            }
        } else {
            // URL wasn't fetched
            _statusCode = -1;
        }
    } catch (ProtocolException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } catch (URISyntaxException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}