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:com.foglyn.fogbugz.Request.java

private <T> T request(String url, HttpMethod method, IProgressMonitor monitor, ResponseProcessor<T> processor)
        throws FogBugzException {
    Utils.checkCancellation(monitor);//from   w w w . j a v  a2  s  .c  om

    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, repositoryLocation,
            monitor);

    if (allowGzip) {
        method.addRequestHeader("Accept-Encoding", "gzip");
    }

    InputStream responseStream = null;
    CancellableInputStream cancellableStream = null;
    try {
        log.debug("Sending request to server");
        int code = WebUtil.execute(httpClient, hostConfiguration, method, monitor);

        log.debug("Got " + code + " response");

        if (!processor.checkHttpStatus(code)) {
            Map<String, String> headers = Utils.convertHeadersToMap(method);

            method.abort();

            throw unexpectedStatus(code, url, headers);
        }

        log.debug("Downloading data");

        responseStream = method.getResponseBodyAsStream();

        InputStream processed = responseStream;

        // may be null, for example for HEAD request
        if (processed != null) {
            Header contentEncoding = method.getResponseHeader("Content-Encoding");
            if (allowGzip && contentEncoding != null && "gzip".equals(contentEncoding.getValue())) {
                processed = new GZIPInputStream(processed);
            }

            cancellableStream = new CancellableInputStream(processed, monitor, threadFactory);
            processed = cancellableStream;
        }

        log.debug("Processing response");

        return processor.processResponse(url, method, processed);
    } catch (RuntimeException e) {
        // also catches OperationCanceledException

        // we don't know what happened to method, so we better abort processing
        method.abort();

        log.error("Error while executing request", e);

        throw e;
    } catch (IOException e) {
        // we don't know what happened... better abort connection
        method.abort();

        log.error("IO Error while executing request", e);

        throw ioError(e, url);
    } finally {
        if (cancellableStream != null) {
            cancellableStream.shutdownBackgroundThread();
        }

        // don't use cancellable stream to close responseStream -- because in case of cancelled monitor, it would ignore close request 
        Utils.close(responseStream);

        method.releaseConnection();
    }
}

From source file:de.innovationgate.webgate.api.rss2.SimpleRSS.java

private InputStream retrievePage(String url, NativeQueryOptions nativeOptions) throws WGQueryException {

    try {/*from w  ww .  j  av  a  2 s.co  m*/

        // Retrieve from web
        HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
        client.setConnectionTimeout(10000);
        if (_useProxy) {
            client.getHostConfiguration().setProxy(_proxyHost, _proxyPort);
            if (_proxyCredentials != null) {
                Credentials credentials;
                if (_proxyDomain != null) {
                    List elements = WGUtils.deserializeCollection(_proxyCredentials, ":");
                    credentials = new NTCredentials((String) elements.get(0), (String) elements.get(1),
                            _proxyHost, _proxyDomain);
                } else {
                    credentials = new UsernamePasswordCredentials(_proxyCredentials);

                }
                client.getState().setProxyCredentials(null, _proxyHost, credentials);

            }
        }
        HttpMethod method = new GetMethod(url);
        method.setFollowRedirects(true);
        method.setStrictMode(false);

        if (nativeOptions.containsKey(QUERYOPTION_USER) && nativeOptions.containsKey(QUERYOPTION_PWD)) {
            method.setDoAuthentication(true);
            client.getParams().setAuthenticationPreemptive(true);
            client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    nativeOptions.get(QUERYOPTION_USER), nativeOptions.get(QUERYOPTION_PWD)));
        }

        client.executeMethod(method);

        // Read response. Wrap content decoder if necessary.
        InputStream inStream = method.getResponseBodyAsStream();

        // Return InputStream from given URL
        return inStream;
    } catch (MalformedURLException e) {
        throw new WGQueryException("Malformed feed URL", url, e);
    } catch (IOException e) {
        throw new WGQueryException("IO Exception retrieving feed", url, e);
    }
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.OaiAggregator.java

/**
 * Get a list of all aggregate sets that an AggregateList object knows about.<br><br>
 * // w  w  w  .  j av  a2  s  .c  o  m
 * NOTE: I am using HttpMethod.getResponseBodyAsString() instead of HttpMethod.getResponseBodyAsStream(), to make it easy to parse, 
 * unfortunately it reads the entire response at once. Is this a potential memory overflow? Since we are reading text not large
 * binary files, such as a pdf or an image, hopefully we be OK. TBD
 * <br>
 * The response is of type...
 * <br>
 *   <?xml version="1.0" encoding="UTF-8"?>
 *   <OAI-PMH xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd">
 *     <responseDate>2011-06-06T08:46:07Z</responseDate>
 * 
 *     <request verb="ListSets"  resumptionToken="">http://adr.coalliance.org/codu/fez/oai.php</request>
 *     <ListSets> 
 *       <set>
 *         <setSpec>oai:adr.coalliance.org:codu:37742</setSpec>
 *         <setName>A Nation In Time And Space</setName>
 *       </set>
 *       <set>
 *             inject our aggregate set spec and name
 *       </set> 0..n
 *     </ListSets>
 *   </OAI-PMH>
 * 
 * @param getString the get url string
 * @param response
 * @param authenicate
 * @param set
 * @param metadataPrefix
 * @throws IOException 
 */
private void executeOaiListSetsWithAggregates(String getString, HttpServletResponse response,
        boolean authenicate) throws IOException {

    HttpClient theClient = new HttpClient();

    HttpMethod method = new GetMethod(getString);

    AggregateList aggregateSets = new AggregateList();

    FedoraDatastream_get.setDefaultHeaders(method);

    FedoraDatastream_get.setAdrCredentials(theClient, authenicate);

    try {
        theClient.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            response.setHeader(header.getName(), header.getValue());
        }

        // Write the body, flush and close

        InputStream is = method.getResponseBodyAsStream();

        String sets = method.getResponseBodyAsString();

        Iterator<AggregateSet> aggreateSetsIterator = aggregateSets.getIterator();
        StringBuffer aggSetsString = new StringBuffer();

        while (aggreateSetsIterator.hasNext()) {
            AggregateSet currentAggSet = aggreateSetsIterator.next();

            aggSetsString.append("<set>\n");
            aggSetsString.append("<setSpec>" + currentAggSet.getUniqueID() + "</setSpec>\n");
            aggSetsString.append("<setName>" + currentAggSet.getSetName() + "</setName>\n");
            aggSetsString.append("</set>");
        }

        String allSets = sets.replace("<resumptionToken>", aggSetsString.toString() + "\n<resumptionToken>");

        response.getWriter().print(allSets);

        //      response.getOutputStream().flush();
        //      response.getOutputStream().close();

    } finally {
        method.releaseConnection();
    }

}

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override/*ww w  .j  a  v a2 s .co  m*/
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

private HttpResponse executeHttpMethod(HttpMethod method) throws HttpException, IOException {
    HttpResponse response = new HttpResponse();
    String responseHeader = null;

    response.setResponseCode(httpClient.executeMethod(method));
    try {//from w  ww  .  j  av  a2  s  .co m
        responseHeader = method.getResponseHeader(Constants.CONTENT_TYPE).getValue();
    } catch (NullPointerException e) {
        logger.debug("ResponseHeader was null");
    }

    if (responseHeader != null)
        response.setContentType(responseHeader);
    //    response.setResponseBody(method.getResponseBody());
    response.setResponseHeaders(method.getResponseHeaders());
    response.setResponseStatusLine(response.getResponseStatusLine());
    Header contentLength = method.getResponseHeader(Constants.CONTENT_LENGTH);
    if (contentLength != null)
        response.setContentLength(contentLength.getValue());

    if (response.getContentLength() > -1) {
        InputStream stream = null;
        byte[] body = new byte[response.getContentLength()];
        try {
            stream = method.getResponseBodyAsStream();

            int offset = 0;
            int i = -1;
            while ((i = stream.read(body, offset, 1024)) != -1)
                offset += i;
            response.setResponseBody(body);
        } catch (Exception e) {
            logger.error("Could not read entire response body", e);
        } finally {
            if (stream != null)
                stream.close();
        }
    } else {
        logger.debug("Content-length unknown");

        InputStream stream = null;
        ByteArrayOutputStream body = new ByteArrayOutputStream();
        try {
            stream = method.getResponseBodyAsStream();

            int i = -1;
            while ((i = stream.read()) != -1)
                body.write(i);

            response.setResponseBody(body.toByteArray());
            response.setContentLength(body.size());
        } catch (Exception e) {
            logger.error("Could not read entire response body", e);
        } finally {
            body.close();
            if (stream != null)
                stream.close();
        }
    }

    return response;
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException      Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 *//* w ww.ja  v a2  s .  c  om*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

/**
 * Response/*  w  w w  .j  av a2  s.  c om*/
 * 
 * @param httpMethod
 * @return
 */
String getContent(HttpMethod httpMethod) throws UnsupportedEncodingException {
    StringBuilder contentBuilder = new StringBuilder();
    if (isZipContent(httpMethod)) {
        // 
        InputStream is = null;
        GZIPInputStream gzin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = httpMethod.getResponseBodyAsStream();
            gzin = new GZIPInputStream(is);
            isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // 
            br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            int readlen = -1;
            while ((readlen = br.read(buffer, 0, 4096)) != -1) {
                contentBuilder.append(buffer, 0, readlen);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                isr.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                gzin.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                is.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    } else {
        // 
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
        } catch (Exception e) {
            log.error("", e);
        }
        if (null == content) {
            return null;
        }
        contentBuilder.append(content);
    }
    return StringEscapeUtils.unescapeHtml(contentBuilder.toString());
}

From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

/**
 * ?Response??//  ww w .ja v  a2 s .c o  m
 * 
 * @param httpMethod
 * @return
 */
String getContent(HttpMethod httpMethod) throws UnsupportedEncodingException {
    StringBuilder contentBuilder = new StringBuilder();
    if (isZipContent(httpMethod)) {
        // ???
        InputStream is = null;
        GZIPInputStream gzin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = httpMethod.getResponseBodyAsStream();
            gzin = new GZIPInputStream(is);
            isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // ?????
            br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            int readlen = -1;
            while ((readlen = br.read(buffer, 0, 4096)) != -1) {
                contentBuilder.append(buffer, 0, readlen);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                isr.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                gzin.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                is.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    } else {
        // ???
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
        } catch (Exception e) {
            log.error("???", e);
        }
        if (null == content) {
            return null;
        }
        contentBuilder.append(content);
    }
    return StringEscapeUtils.unescapeHtml(contentBuilder.toString());
}

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs an HTTP request against an URL.
 *
 * @param url         the URL to call//from ww  w.  ja  v a 2  s . com
 * @param method      the HTTP method to execute
 * @param body        the body of a POST or PUT request, can be <code>null</code>
 * @param queryParams a Hash with the query parameter, can be <code>null</code>
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 */
@SuppressWarnings("deprecation")
public String execute(String url, HttpRequest.HttpMethod method, String body, Map<String, String> queryParams) {

    NameValuePair[] query = null;

    if (queryParams != null) {
        query = new NameValuePair[queryParams.size()];

        int counter = 0;
        for (Entry<String, String> queryParam : queryParams.entrySet()) {
            query[counter] = new NameValuePair(queryParam.getKey(), queryParam.getValue());
            counter++;
        }
    }

    org.apache.commons.httpclient.HttpMethod request = null;

    if (method == HttpMethod.GET) {
        request = new GetMethod(url);
    } else if (method == HttpMethod.POST) {
        PostMethod postRequest = new PostMethod(url);
        if (body != null) {
            postRequest.setRequestBody(body);
        }
        request = postRequest;
    } else if (method == HttpMethod.PUT) {
        PutMethod putRequest = new PutMethod(url);
        if (body != null) {
            putRequest.setRequestBody(body);
        }
        request = putRequest;
    } else if (method == HttpMethod.DELETE) {
        request = new DeleteMethod(url);
    }

    request.setRequestHeader("Content-type", "application/xml;charset=utf-8");
    if (query != null) {
        request.setQueryString(query);
    }

    int resultCode = 0;
    StringBuilder resultBodyBuilder = new StringBuilder();

    try {
        resultCode = this.httpClient.executeMethod(request);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getResponseBodyAsStream(), Charset.forName("UTF-8")));
        String line = null;
        while ((line = reader.readLine()) != null) {
            resultBodyBuilder.append(line);
        }

        if (resultCode != 200) {
            throw new HttpException(resultBodyBuilder.toString(), null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP request failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP request failed", ioException);
    } catch (NullPointerException npe) {
        throw new HttpException("HTTP request failed", npe);
    } finally {
        request.releaseConnection();
    }

    return resultBodyBuilder.toString();
}

From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java

protected Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Throwable {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("starting remote method {}.{}", method.getDeclaringClass(), method.getName());
    }//from   www  .j  a  v a  2  s  . com
    RequestId requestId = new RequestId(this.proxyId);
    int retries = RETRY_COUNT;
    int state = SEND_PARAMETERS_STATE;
    Exception lastException = null;
    boolean checkServerStatus = false;
    while (retries > 0) {
        InputStream is = null;
        byte status = StreamBasedInvocator.FAULT_STATUS;
        Object returned = null;
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(this.url);
        httpClient.getState().addCookies(this.cookies);
        boolean gotResult = false;
        HttpMethod postMethod = null;
        try {
            OutputStreamWriter writer = null;
            switch (state) {
            case SEND_PARAMETERS_STATE:
                writer = new ParameterWriter(proxy, method, args, requestId);
                break;
            case RECEIVE_RESULT_STATE:
                writer = new ResultResendWriter(requestId);
                break;
            }
            postMethod = this.getPostMethod(writer);

            this.setMethodTimeout(postMethod, method);

            httpClient.executeMethod(postMethod);

            this.cookies = httpClient.getState().getCookies();

            state = RECEIVE_RESULT_STATE;

            int code = postMethod.getStatusCode();

            if (code != 200) {
                checkServerStatus = true;
                this.analyzeServerErrorAndThrow(code, postMethod);
            }

            is = postMethod.getResponseBodyAsStream();

            //if (CAUSE_RANDOM_ERROR) if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!");

            status = (byte) is.read();
            if (status != StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS) {
                returned = this.getResult(method, args, is);
            }
            gotResult = true;
            is.close();
            is = null;
            postMethod.releaseConnection();
            postMethod = null;
        } catch (SocketTimeoutException e) {
            LOGGER.debug("Socket timeout reached for JRPIP invocation", e);
            throw new JrpipTimeoutException("Remote method " + method.getName() + " timed out." + this.url, e);
        } catch (NotSerializableException e) {
            throw new JrpipRuntimeException("Method arguments are not serializable!", e);
        } catch (ClassNotFoundException e) {
            throw new JrpipRuntimeException("Method call successfully completed but result class not found", e);
        } catch (Exception e) {
            retries--;
            lastException = e;
            LOGGER.debug("Exception in JRPIP invocation. Retries left {}", retries, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.debug("Could not close stream. See previous exception for cause", e);
                }
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        if (gotResult) {
            switch (status) {
            case StreamBasedInvocator.OK_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method normally {}.{}", method.getDeclaringClass(),
                            method.getName());
                }
                return returned;
            case StreamBasedInvocator.FAULT_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method {}.{} with exception {}", method.getDeclaringClass(),
                            method.getName(), returned.getClass().getName(),
                            new JrpipRuntimeException("for tracing local invocation context"));
                }
                Class[] exceptions = method.getExceptionTypes();
                for (int i = 0; i < exceptions.length; i++) {
                    if (exceptions[i].isAssignableFrom(returned.getClass())) {
                        throw (Throwable) returned;
                    }
                }
                if (RuntimeException.class.isAssignableFrom(returned.getClass())) {
                    throw (RuntimeException) returned;
                }
                if (Error.class.isAssignableFrom(returned.getClass())) {
                    throw (Error) returned;
                }
                if (Throwable.class.isAssignableFrom(returned.getClass())
                        && !Exception.class.isAssignableFrom(returned.getClass())) {
                    throw (Throwable) returned;
                }
                throw new JrpipRuntimeException(
                        "Could not throw returned exception, as it was not declared in the method signature for method "
                                + method.getName(),
                        (Throwable) returned);
            case StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS:
                state = SEND_PARAMETERS_STATE;
                break;
            }
        } else {
            checkServerStatus = true;
        }
        if (checkServerStatus) {
            this.determineServerStatus(state == RECEIVE_RESULT_STATE);
            checkServerStatus = false;
        }
    }
    throw new JrpipRuntimeException(
            "Could not invoke remote method " + method.getName() + " while accessing " + this.url,
            lastException);
}