Example usage for java.io InputStream mark

List of usage examples for java.io InputStream mark

Introduction

In this page you can find the example usage for java.io InputStream mark.

Prototype

public synchronized void mark(int readlimit) 

Source Link

Document

Marks the current position in this input stream.

Usage

From source file:org.gudy.azureus2.pluginsimpl.local.utils.xml.simpleparser.SimpleXMLParserDocumentImpl.java

private void create(InputStream _input_stream)

        throws SimpleXMLParserDocumentException {
    // make sure we can mark the stream to permit later recovery if needed

    if (!_input_stream.markSupported()) {

        _input_stream = new BufferedInputStream(_input_stream);
    }//w  ww  .j  ava2s .  c o m

    _input_stream.mark(100 * 1024);

    // prevent the parser from screwing with our stream by closing it

    UncloseableInputStream uc_is = new UncloseableInputStream(_input_stream);

    try {
        createSupport(uc_is);

    } catch (SimpleXMLParserDocumentException e) {

        String msg = Debug.getNestedExceptionMessage(e);

        if ((msg.contains("entity") && msg.contains("was referenced")) || msg.contains("entity reference")) {

            try {
                // nasty hack to try and handle HTML entities that some annoying feeds include :(

                _input_stream.reset();

                createSupport(new EntityFudger(_input_stream));

                return;

            } catch (Throwable f) {
            }
        }

        //Debug.out( e );

        throw (e);

    } finally {

        try {
            _input_stream.close();

        } catch (Throwable e) {
        }
    }
}

From source file:com.aliyun.odps.rest.RestClient.java

/**
 * RESTful API//from   w  ww .  j a  v  a  2  s.c om
 *
 * @param resource
 * @param method
 * @param params
 * @param headers
 * @param body
 *     InputStream, FileInputStream/ByteArrayInputStream
 * @param bodyLen
 *     InputStream?
 * @return
 * @throws OdpsException
 */
public Response request(String resource, String method, Map<String, String> params, Map<String, String> headers,
        InputStream body, long bodyLen) throws OdpsException {
    int retryTimes = 0;
    if (method.equalsIgnoreCase(Method.GET.toString()) || method.equalsIgnoreCase(Method.HEAD.toString())) {
        retryTimes = getRetryTimes();
        if (body != null && body.markSupported()) {
            body.mark(0);
        }
    }

    long retryWaitTime = getConnectTimeout() + getReadTimeout();

    long retryCount = 0;

    while (retryCount <= retryTimes) {
        long startTime = System.currentTimeMillis();
        try {
            Response resp = requestWithNoRetry(resource, method, params, headers, body, bodyLen);

            if (resp == null) {
                throw new OdpsException("Response is null.");
            }

            if (resp.getStatus() / 100 == 4) {
                retryTimes = 0;
                // IF THE HTTP CODE IS 4XX,
                // IT SHOULD NOT RETRY IF THE REQUEST NOT CHANGED
            }

            handleErrorResponse(resp);

            uploadDeprecatedLog();

            return resp;

        } catch (OdpsException e) {
            if (retryTimes == retryCount) {
                throw e;
            }

            resetBody(body);
            ++retryCount;

            if (logger != null) {
                logger.onRetryLog(e, retryCount, retryWaitTime);
            }

            try {
                long endTime = System.currentTimeMillis();
                long sleepTime = retryWaitTime * 1000 - (endTime - startTime);
                if (sleepTime > 0) {
                    Thread.sleep(sleepTime);
                }
            } catch (InterruptedException e1) {
            }
            continue;
        } catch (Error e) {
            if (retryTimes == retryCount) {
                throw e;
            }
            resetBody(body);
            ++retryCount;
            if (logger != null) {
                logger.onRetryLog(e, retryCount, retryWaitTime);
            }

            try {
                long endTime = System.currentTimeMillis();
                long sleepTime = retryWaitTime * 1000 - (endTime - startTime);
                if (sleepTime > 0) {
                    Thread.sleep(sleepTime);
                }
            } catch (InterruptedException e1) {
            }
            continue;
        }
    }
    throw new OdpsException("Failed in Connection Retry.");
}

From source file:org.obm.push.mail.MailBackendImpl.java

private InputStream loadEmailInMemory(SendEmail email) throws IOException {
    InputStream emailStream = new ByteArrayInputStream(FileUtils.streamBytes(email.getMessage(), true));
    emailStream.mark(0);
    return emailStream;
}

From source file:com.temenos.interaction.media.odata.xml.atom.AtomXMLProvider.java

/**
 * Method to verify if receieved stream has content or its empty
 * @param stream Stream to check/*  ww  w .  j  ava  2 s. co m*/
 * @return verified stream
 * @throws IOException
 */
private InputStream verifyContentReceieved(InputStream stream) throws IOException {

    if (stream == null) { // Check if its null
        LOGGER.debug("Request stream received as null");
        return null;
    } else if (stream.markSupported()) { // Check stream supports mark/reset
        // mark() and read the first byte just to check
        stream.mark(1);
        final int bytesRead = stream.read(new byte[1]);
        if (bytesRead != -1) {
            //stream not empty
            stream.reset(); // reset the stream as if untouched
            return stream;
        } else {
            //stream empty
            LOGGER.debug("Request received with empty body");
            return null;
        }
    } else {
        // Panic! this stream does not support mark/reset, try with PushbackInputStream as a last resort
        int bytesRead;
        PushbackInputStream pbs = new PushbackInputStream(stream);
        if ((bytesRead = pbs.read()) != -1) {
            // Contents detected, unread and return
            pbs.unread(bytesRead);
            return pbs;
        } else {
            // Empty stream detected
            LOGGER.debug("Request received with empty body!");
            return null;
        }
    }
}

From source file:com.amazon.s3.http.AmazonHttpClient.java

/**
 * Internal method to execute the HTTP method given.
 * //w  w w  . java  2 s . c o  m
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler,
 *      HttpResponseHandler)
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler,
 *      HttpResponseHandler, ExecutionContext)
 */
private <T extends Object> T executeHelper(Request<?> request,
        HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler,
        HttpResponseHandler<AmazonServiceException> errorResponseHandler, ExecutionContext executionContext)
        throws AmazonClientException, AmazonServiceException {

    /*
     * Depending on which response handler we end up choosing to handle the
     * HTTP response, it might require us to leave the underlying HTTP
     * connection open, depending on whether or not it reads the complete
     * HTTP response stream from the HTTP connection, or if delays reading
     * any of the content until after a response is returned to the caller.
     */
    boolean leaveHttpConnectionOpen = false;

    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    /*
     * add the service endpoint to the logs. You can infer service name from
     * service endpoint
     */
    awsRequestMetrics.addProperty(Field.ServiceName.name(), request.getServiceName());
    awsRequestMetrics.addProperty(Field.ServiceEndpoint.name(), request.getEndpoint());

    // Apply whatever request options we know how to handle, such as
    // user-agent.
    applyRequestData(request);

    int retryCount = 0;
    URI redirectedURI = null;
    HttpEntity entity = null;
    AmazonServiceException exception = null;

    // Make a copy of the original request params and headers so that we can
    // permute it in this loop and start over with the original every time.
    Map<String, String> originalParameters = new HashMap<String, String>();
    originalParameters.putAll(request.getParameters());
    Map<String, String> originalHeaders = new HashMap<String, String>();
    originalHeaders.putAll(request.getHeaders());

    while (true) {
        awsRequestMetrics.setCounter(Field.AttemptCount.name(), retryCount + 1);
        if (retryCount > 0) {
            request.setParameters(originalParameters);
            request.setHeaders(originalHeaders);
        }

        HttpRequestBase httpRequest = null;
        org.apache.http.HttpResponse response = null;

        try {
            // Sign the request if a signer was provided
            if (executionContext.getSigner() != null && executionContext.getCredentials() != null) {
                awsRequestMetrics.startEvent(Field.RequestSigningTime.name());
                executionContext.getSigner().sign(request, executionContext.getCredentials());
                awsRequestMetrics.endEvent(Field.RequestSigningTime.name());
            }

            Log.d(TAG, "Sending Request: " + request.toString());
            httpRequest = httpRequestFactory.createHttpRequest(request, config, entity, executionContext);

            if (httpRequest instanceof HttpEntityEnclosingRequest) {
                entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
            }

            if (redirectedURI != null) {
                httpRequest.setURI(redirectedURI);
            }

            if (retryCount > 0) {
                awsRequestMetrics.startEvent(Field.RetryPauseTime.name());
                pauseExponentially(retryCount, exception, executionContext.getCustomBackoffStrategy());
                awsRequestMetrics.endEvent(Field.RetryPauseTime.name());
            }

            if (entity != null) {
                InputStream content = entity.getContent();
                if (retryCount > 0) {
                    if (content.markSupported()) {
                        content.reset();
                        content.mark(-1);
                    }
                } else {
                    if (content.markSupported()) {
                        content.mark(-1);
                    }
                }
            }

            exception = null;

            awsRequestMetrics.startEvent(Field.HttpRequestTime.name());
            response = httpClient.execute(httpRequest);
            awsRequestMetrics.endEvent(Field.HttpRequestTime.name());

            if (isRequestSuccessful(response)) {

                awsRequestMetrics.addProperty(Field.StatusCode.name(),
                        response.getStatusLine().getStatusCode());

                /*
                 * If we get back any 2xx status code, then we know we
                 * should treat the service call as successful.
                 */
                leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen();
                return handleResponse(request, responseHandler, httpRequest, response, executionContext);
            } else if (isTemporaryRedirect(response)) {
                /*
                 * S3 sends 307 Temporary Redirects if you try to delete an
                 * EU bucket from the US endpoint. If we get a 307, we'll
                 * point the HTTP method to the redirected location, and let
                 * the next retry deliver the request to the right location.
                 */
                Header[] locationHeaders = response.getHeaders("location");
                String redirectedLocation = locationHeaders[0].getValue();
                Log.d(TAG, "Redirecting to: " + redirectedLocation);
                redirectedURI = URI.create(redirectedLocation);
                httpRequest.setURI(redirectedURI);
                awsRequestMetrics.addProperty(Field.StatusCode.name(),
                        response.getStatusLine().getStatusCode());
                awsRequestMetrics.addProperty(Field.RedirectLocation.name(), redirectedLocation);
                awsRequestMetrics.addProperty(Field.AWSRequestID.name(), null);

            } else {
                leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen();
                exception = handleErrorResponse(request, errorResponseHandler, httpRequest, response);
                awsRequestMetrics.addProperty(Field.AWSRequestID.name(), exception.getRequestId());
                awsRequestMetrics.addProperty(Field.AWSErrorCode.name(), exception.getErrorCode());
                awsRequestMetrics.addProperty(Field.StatusCode.name(), exception.getStatusCode());

                if (!shouldRetry(httpRequest, exception, retryCount)) {
                    throw exception;
                }
                resetRequestAfterError(request, exception);
            }
        } catch (IOException ioe) {
            Log.i(TAG, "Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            awsRequestMetrics.addProperty(Field.Exception.name(), ioe.toString());
            awsRequestMetrics.addProperty(Field.AWSRequestID.name(), null);

            if (!shouldRetry(httpRequest, ioe, retryCount)) {
                throw new AmazonClientException("Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            }
            resetRequestAfterError(request, ioe);
        } finally {
            retryCount++;

            /*
             * Some response handlers need to manually manage the HTTP
             * connection and will take care of releasing the connection on
             * their own, but if this response handler doesn't need the
             * connection left open, we go ahead and release the it to free
             * up resources.
             */
            if (!leaveHttpConnectionOpen) {
                try {
                    response.getEntity().getContent().close();
                } catch (Throwable t) {
                }
            }
        }
    } /* end while (true) */
}

From source file:core.com.qiniu.http.AmazonHttpClient.java

/**
 * Internal method to execute the HTTP method given.
 *
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler,
 *      HttpResponseHandler)/*from  w  w w. j  av a2s  . co  m*/
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler,
 *      HttpResponseHandler, ExecutionContext)
 */
<T> Response<T> executeHelper(Request<?> request,
        HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler,
        HttpResponseHandler<AmazonServiceException> errorResponseHandler, ExecutionContext executionContext)
        throws AmazonClientException, AmazonServiceException {
    /*
     * Depending on which response handler we end up choosing to handle the
     * HTTP response, it might require us to leave the underlying HTTP
     * connection open, depending on whether or not it reads the complete
     * HTTP response stream from the HTTP connection, or if delays reading
     * any of the content until after a response is returned to the caller.
     */
    boolean leaveHttpConnectionOpen = false;
    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    /*
     * add the service endpoint to the logs. You can infer service name from
     * service endpoint
     */
    awsRequestMetrics.addProperty(AWSRequestMetrics.Field.ServiceName, request.getServiceName());
    awsRequestMetrics.addProperty(AWSRequestMetrics.Field.ServiceEndpoint, request.getEndpoint());

    // Apply whatever request options we know how to handle, such as
    // user-agent.
    setUserAgent(request);
    request.addHeader(HEADER_SDK_TRANSACTION_ID, UUID.randomUUID().toString());
    int requestCount = 0;
    long lastBackoffDelay = 0;
    URI redirectedURI = null;
    AmazonClientException retriedException = null;

    // Make a copy of the original request params and headers so that we can
    // permute it in this loop and start over with the original every time.
    Map<String, String> originalParameters = new LinkedHashMap<String, String>(request.getParameters());
    Map<String, String> originalHeaders = new HashMap<String, String>(request.getHeaders());
    // mark input stream if supported
    InputStream originalContent = request.getContent();
    if (originalContent != null && originalContent.markSupported()) {
        originalContent.mark(-1);
    }

    final AWSCredentials credentials = executionContext.getCredentials();
    Signer signer = null;
    HttpResponse httpResponse = null;
    HttpRequest httpRequest = null;

    while (true) {
        ++requestCount;
        awsRequestMetrics.setCounter(AWSRequestMetrics.Field.RequestCount, requestCount);
        if (requestCount > 1) { // retry
            request.setParameters(originalParameters);
            request.setHeaders(originalHeaders);
            request.setContent(originalContent);
        }
        if (redirectedURI != null) {
            request.setEndpoint(URI.create(redirectedURI.getScheme() + "://" + redirectedURI.getAuthority()));
            request.setResourcePath(redirectedURI.getPath());
        }

        try {
            if (requestCount > 1) { // retry
                awsRequestMetrics.startEvent(AWSRequestMetrics.Field.RetryPauseTime);
                try {
                    lastBackoffDelay = pauseBeforeNextRetry(request.getOriginalRequest(), retriedException,
                            requestCount, config.getRetryPolicy());
                } finally {
                    awsRequestMetrics.endEvent(AWSRequestMetrics.Field.RetryPauseTime);
                }
                InputStream content = request.getContent();
                if (content != null && content.markSupported()) {
                    content.reset();
                }
            }
            request.addHeader(HEADER_SDK_RETRY_INFO, (requestCount - 1) + "/" + lastBackoffDelay);

            // Sign the request if a signer was provided
            if (signer == null)
                signer = executionContext.getSignerByURI(request.getEndpoint());
            if (signer != null && credentials != null) {
                awsRequestMetrics.startEvent(AWSRequestMetrics.Field.RequestSigningTime);
                try {
                    signer.sign(request, credentials);
                } finally {
                    awsRequestMetrics.endEvent(AWSRequestMetrics.Field.RequestSigningTime);
                }
            }

            if (requestLog.isDebugEnabled()) {
                requestLog.debug("Sending Request: " + request.toString());
            }

            httpRequest = requestFactory.createHttpRequest(request, config, executionContext);

            retriedException = null;
            awsRequestMetrics.startEvent(AWSRequestMetrics.Field.HttpRequestTime);
            try {
                httpResponse = httpClient.execute(httpRequest);
            } finally {
                awsRequestMetrics.endEvent(AWSRequestMetrics.Field.HttpRequestTime);
            }

            if (isRequestSuccessful(httpResponse)) {
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.StatusCode, httpResponse.getStatusCode());
                /*
                 * If we get back any 2xx status code, then we know we
                 * should treat the service call as successful.
                 */
                leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen();
                T response = handleResponse(request, responseHandler, httpResponse, executionContext);
                return new Response<T>(response, httpResponse);
            } else if (isTemporaryRedirect(httpResponse)) {
                /*
                 * S3 sends 307 Temporary Redirects if you try to delete an
                 * EU bucket from the US endpoint. If we get a 307, we'll
                 * point the HTTP method to the redirected location, and let
                 * the next retry deliver the request to the right location.
                 */
                String redirectedLocation = httpResponse.getHeaders().get("Location");
                log.debug("Redirecting to: " + redirectedLocation);
                // set redirect uri and retry
                redirectedURI = URI.create(redirectedLocation);
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.StatusCode, httpResponse.getStatusCode());
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.RedirectLocation, redirectedLocation);
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.AWSRequestID, null);
            } else {
                leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen();
                AmazonServiceException ase = handleErrorResponse(request, errorResponseHandler, httpResponse);
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.AWSRequestID, ase.getRequestId());
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.AWSErrorCode, ase.getErrorCode());
                awsRequestMetrics.addProperty(AWSRequestMetrics.Field.StatusCode, ase.getStatusCode());

                if (!shouldRetry(request.getOriginalRequest(), httpRequest.getContent(), ase, requestCount,
                        config.getRetryPolicy())) {
                    throw ase;
                }

                // Cache the retryable exception
                retriedException = ase;
                /*
                 * Checking for clock skew error again because we don't want
                 * to set the global time offset for every service
                 * exception.
                 */
                if (RetryUtils.isClockSkewError(ase)) {
                    int timeOffset = parseClockSkewOffset(httpResponse, ase);
                    SDKGlobalConfiguration.setGlobalTimeOffset(timeOffset);
                }
                resetRequestAfterError(request, ase);
            }
        } catch (IOException ioe) {
            if (log.isDebugEnabled()) {
                log.debug("Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            }
            awsRequestMetrics.incrementCounter(AWSRequestMetrics.Field.Exception);
            awsRequestMetrics.addProperty(AWSRequestMetrics.Field.Exception, ioe);
            awsRequestMetrics.addProperty(AWSRequestMetrics.Field.AWSRequestID, null);

            AmazonClientException ace = new AmazonClientException(
                    "Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            if (!shouldRetry(request.getOriginalRequest(), httpRequest.getContent(), ace, requestCount,
                    config.getRetryPolicy())) {
                throw ace;
            }

            // Cache the retryable exception
            retriedException = ace;
            resetRequestAfterError(request, ioe);
        } catch (RuntimeException e) {
            throw handleUnexpectedFailure(e, awsRequestMetrics);
        } catch (Error e) {
            throw handleUnexpectedFailure(e, awsRequestMetrics);
        } finally {
            /*
             * Some response handlers need to manually manage the HTTP
             * connection and will take care of releasing the connection on
             * their own, but if this response handler doesn't need the
             * connection left open, we go ahead and release the it to free
             * up resources.
             */
            if (!leaveHttpConnectionOpen && httpResponse != null) {
                try {
                    if (httpResponse.getRawContent() != null) {
                        httpResponse.getRawContent().close();
                    }
                } catch (IOException e) {
                    log.warn("Cannot close the response content.", e);
                }
            }
        }
    } /* end while (true) */
}

From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializer.java

boolean isArchiveStream(InputStream in) {
    if (in == null) {
        throw new IllegalArgumentException("Stream must not be null.");
    }//from   w  ww . jav  a 2 s.c o m

    if (!in.markSupported()) {
        throw new IllegalArgumentException("Mark is not supported.");
    }

    final byte[] signature = new byte[12];
    in.mark(signature.length);
    int signatureLength;
    try {
        signatureLength = IOUtils.readFully(in, signature);
        in.reset();
    } catch (IOException e) {
        throw new RuntimeException(String.format(ERR_UNMARSHALLING_STREAM, "<unknown>", e.getMessage()), e);
    }
    return ZipArchiveInputStream.matches(signature, signatureLength);
}

From source file:pt.lunacloud.http.AmazonHttpClient.java

/**
 * Internal method to execute the HTTP method given.
 *
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler)
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler, ExecutionContext)
 *///from  w w  w .j  ava 2  s .c o  m
private <T extends Object> T executeHelper(Request<?> request,
        HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler,
        HttpResponseHandler<LunacloudServiceException> errorResponseHandler, ExecutionContext executionContext)
        throws LunacloudClientException, LunacloudServiceException {

    /*
     * Depending on which response handler we end up choosing to handle the
     * HTTP response, it might require us to leave the underlying HTTP
     * connection open, depending on whether or not it reads the complete
     * HTTP response stream from the HTTP connection, or if delays reading
     * any of the content until after a response is returned to the caller.
     */
    boolean leaveHttpConnectionOpen = false;

    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    /* add the service endpoint to the logs. You can infer service name from service endpoint */
    awsRequestMetrics.addProperty(Field.ServiceName.name(), request.getServiceName());
    awsRequestMetrics.addProperty(Field.ServiceEndpoint.name(), request.getEndpoint());

    // Apply whatever request options we know how to handle, such as user-agent.
    applyRequestData(request);

    int retryCount = 0;
    URI redirectedURI = null;
    HttpEntity entity = null;
    LunacloudServiceException exception = null;

    // Make a copy of the original request params and headers so that we can
    // permute it in this loop and start over with the original every time.
    Map<String, String> originalParameters = new HashMap<String, String>();
    originalParameters.putAll(request.getParameters());
    Map<String, String> originalHeaders = new HashMap<String, String>();
    originalHeaders.putAll(request.getHeaders());

    while (true) {
        awsRequestMetrics.setCounter(Field.AttemptCount.name(), retryCount + 1);
        if (retryCount > 0) {
            request.setParameters(originalParameters);
            request.setHeaders(originalHeaders);
        }

        HttpRequestBase httpRequest = null;
        org.apache.http.HttpResponse response = null;

        try {
            // Sign the request if a signer was provided
            if (executionContext.getSigner() != null && executionContext.getCredentials() != null) {
                awsRequestMetrics.startEvent(Field.RequestSigningTime.name());
                executionContext.getSigner().sign(request, executionContext.getCredentials());
                awsRequestMetrics.endEvent(Field.RequestSigningTime.name());
            }

            if (requestLog.isDebugEnabled()) {
                requestLog.debug("Sending Request: " + request.toString());
            }

            httpRequest = httpRequestFactory.createHttpRequest(request, config, entity, executionContext);

            if (httpRequest instanceof HttpEntityEnclosingRequest) {
                entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
            }

            if (redirectedURI != null) {
                httpRequest.setURI(redirectedURI);
            }

            if (retryCount > 0) {
                awsRequestMetrics.startEvent(Field.RetryPauseTime.name());
                pauseExponentially(retryCount, exception, executionContext.getCustomBackoffStrategy());
                awsRequestMetrics.endEvent(Field.RetryPauseTime.name());
            }

            if (entity != null) {
                InputStream content = entity.getContent();
                if (retryCount > 0) {
                    if (content.markSupported()) {
                        content.reset();
                        content.mark(-1);
                    }
                } else {
                    if (content.markSupported()) {
                        content.mark(-1);
                    }
                }
            }

            exception = null;

            awsRequestMetrics.startEvent(Field.HttpRequestTime.name());
            response = httpClient.execute(httpRequest);
            awsRequestMetrics.endEvent(Field.HttpRequestTime.name());

            if (isRequestSuccessful(response)) {

                awsRequestMetrics.addProperty(Field.StatusCode.name(),
                        response.getStatusLine().getStatusCode());

                /*
                 * If we get back any 2xx status code, then we know we should
                 * treat the service call as successful.
                 */
                leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen();
                return handleResponse(request, responseHandler, httpRequest, response, executionContext);
            } else if (isTemporaryRedirect(response)) {
                /*
                 * S3 sends 307 Temporary Redirects if you try to delete an
                 * EU bucket from the US endpoint. If we get a 307, we'll
                 * point the HTTP method to the redirected location, and let
                 * the next retry deliver the request to the right location.
                 */
                Header[] locationHeaders = response.getHeaders("location");
                String redirectedLocation = locationHeaders[0].getValue();
                log.debug("Redirecting to: " + redirectedLocation);
                redirectedURI = URI.create(redirectedLocation);
                httpRequest.setURI(redirectedURI);
                awsRequestMetrics.addProperty(Field.StatusCode.name(),
                        response.getStatusLine().getStatusCode());
                awsRequestMetrics.addProperty(Field.RedirectLocation.name(), redirectedLocation);
                awsRequestMetrics.addProperty(Field.AWSRequestID.name(), null);

            } else {
                leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen();
                exception = handleErrorResponse(request, errorResponseHandler, httpRequest, response);
                awsRequestMetrics.addProperty(Field.AWSRequestID.name(), exception.getRequestId());
                awsRequestMetrics.addProperty(Field.AWSErrorCode.name(), exception.getErrorCode());
                awsRequestMetrics.addProperty(Field.StatusCode.name(), exception.getStatusCode());

                if (!shouldRetry(httpRequest, exception, retryCount)) {
                    throw exception;
                }
                resetRequestAfterError(request, exception);
            }
        } catch (IOException ioe) {
            log.info("Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            awsRequestMetrics.addProperty(Field.Exception.name(), ioe.toString());
            awsRequestMetrics.addProperty(Field.AWSRequestID.name(), null);

            if (!shouldRetry(httpRequest, ioe, retryCount)) {
                throw new LunacloudClientException("Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            }
            resetRequestAfterError(request, ioe);
        } finally {
            retryCount++;

            /*
             * Some response handlers need to manually manage the HTTP
             * connection and will take care of releasing the connection on
             * their own, but if this response handler doesn't need the
             * connection left open, we go ahead and release the it to free
             * up resources.
             */
            if (!leaveHttpConnectionOpen) {
                try {
                    response.getEntity().getContent().close();
                } catch (Throwable t) {
                }
            }
        }
    } /* end while (true) */
}

From source file:cn.ctyun.amazonaws.http.AmazonHttpClient.java

/**
 * Internal method to execute the HTTP method given.
 *
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler)
 * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler, ExecutionContext)
 *//*from  w  ww  . j  ava2  s. co  m*/
private <T extends Object> T executeHelper(Request<?> request,
        HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler,
        HttpResponseHandler<AmazonServiceException> errorResponseHandler, ExecutionContext executionContext)
        throws AmazonClientException, AmazonServiceException {

    /*
     * Depending on which response handler we end up choosing to handle the
     * HTTP response, it might require us to leave the underlying HTTP
     * connection open, depending on whether or not it reads the complete
     * HTTP response stream from the HTTP connection, or if delays reading
     * any of the content until after a response is returned to the caller.
     */
    boolean leaveHttpConnectionOpen = false;

    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    /* add the service endpoint to the logs. You can infer service name from service endpoint */
    awsRequestMetrics.addProperty(Field.ServiceName.name(), request.getServiceName());
    awsRequestMetrics.addProperty(Field.ServiceEndpoint.name(), request.getEndpoint());

    // Apply whatever request options we know how to handle, such as user-agent.
    setUserAgent(request);

    int retryCount = 0;
    URI redirectedURI = null;
    HttpEntity entity = null;
    AmazonServiceException exception = null;

    // Make a copy of the original request params and headers so that we can
    // permute it in this loop and start over with the original every time.
    Map<String, String> originalParameters = new HashMap<String, String>();
    originalParameters.putAll(request.getParameters());
    Map<String, String> originalHeaders = new HashMap<String, String>();
    originalHeaders.putAll(request.getHeaders());

    while (true) {
        awsRequestMetrics.setCounter(Field.AttemptCount.name(), retryCount + 1);
        if (retryCount > 0) {
            request.setParameters(originalParameters);
            request.setHeaders(originalHeaders);
        }

        HttpRequestBase httpRequest = null;
        org.apache.http.HttpResponse response = null;

        try {
            // Sign the request if a signer was provided
            if (executionContext.getSigner() != null && executionContext.getCredentials() != null) {
                awsRequestMetrics.startEvent(Field.RequestSigningTime.name());
                executionContext.getSigner().sign(request, executionContext.getCredentials());
                awsRequestMetrics.endEvent(Field.RequestSigningTime.name());
            }

            if (requestLog.isDebugEnabled()) {
                requestLog.debug("Sending Request: " + request.toString());
            }

            httpRequest = httpRequestFactory.createHttpRequest(request, config, entity, executionContext);

            if (httpRequest instanceof HttpEntityEnclosingRequest) {
                entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
            }

            if (redirectedURI != null) {
                httpRequest.setURI(redirectedURI);
            }

            if (retryCount > 0) {
                awsRequestMetrics.startEvent(Field.RetryPauseTime.name());
                pauseExponentially(retryCount, exception, executionContext.getCustomBackoffStrategy());
                awsRequestMetrics.endEvent(Field.RetryPauseTime.name());
            }

            if (entity != null) {
                InputStream content = entity.getContent();
                if (retryCount > 0) {
                    if (content.markSupported()) {
                        content.reset();
                        content.mark(-1);
                    }
                } else {
                    if (content.markSupported()) {
                        content.mark(-1);
                    }
                }
            }

            exception = null;

            awsRequestMetrics.startEvent(Field.HttpRequestTime.name());
            response = httpClient.execute(httpRequest);
            awsRequestMetrics.endEvent(Field.HttpRequestTime.name());

            if (isRequestSuccessful(response)) {

                awsRequestMetrics.addProperty(Field.StatusCode.name(),
                        response.getStatusLine().getStatusCode());

                /*
                 * If we get back any 2xx status code, then we know we should
                 * treat the service call as successful.
                 */
                leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen();
                return handleResponse(request, responseHandler, httpRequest, response, executionContext);
            } else if (isTemporaryRedirect(response)) {
                /*
                 * S3 sends 307 Temporary Redirects if you try to delete an
                 * EU bucket from the US endpoint. If we get a 307, we'll
                 * point the HTTP method to the redirected location, and let
                 * the next retry deliver the request to the right location.
                 */
                Header[] locationHeaders = response.getHeaders("location");
                String redirectedLocation = locationHeaders[0].getValue();
                log.debug("Redirecting to: " + redirectedLocation);
                redirectedURI = URI.create(redirectedLocation);
                httpRequest.setURI(redirectedURI);
                awsRequestMetrics.addProperty(Field.StatusCode.name(),
                        response.getStatusLine().getStatusCode());
                awsRequestMetrics.addProperty(Field.RedirectLocation.name(), redirectedLocation);
                awsRequestMetrics.addProperty(Field.AWSRequestID.name(), null);

            } else {
                leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen();
                exception = handleErrorResponse(request, errorResponseHandler, httpRequest, response);
                awsRequestMetrics.addProperty(Field.AWSRequestID.name(), exception.getRequestId());
                awsRequestMetrics.addProperty(Field.AWSErrorCode.name(), exception.getErrorCode());
                awsRequestMetrics.addProperty(Field.StatusCode.name(), exception.getStatusCode());

                if (!shouldRetry(httpRequest, exception, retryCount)) {
                    throw exception;
                }
                resetRequestAfterError(request, exception);
            }
        } catch (IOException ioe) {
            log.info("Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            awsRequestMetrics.addProperty(Field.Exception.name(), ioe.toString());
            awsRequestMetrics.addProperty(Field.AWSRequestID.name(), null);

            if (!shouldRetry(httpRequest, ioe, retryCount)) {
                throw new AmazonClientException("Unable to execute HTTP request: " + ioe.getMessage(), ioe);
            }
            resetRequestAfterError(request, ioe);
        } finally {
            retryCount++;

            /*
             * Some response handlers need to manually manage the HTTP
             * connection and will take care of releasing the connection on
             * their own, but if this response handler doesn't need the
             * connection left open, we go ahead and release the it to free
             * up resources.
             */
            if (!leaveHttpConnectionOpen) {
                try {
                    response.getEntity().getContent().close();
                } catch (Throwable t) {
                }
            }
        }
    } /* end while (true) */
}

From source file:org.sipfoundry.sipxconfig.phonebook.PhonebookManagerImpl.java

public String getEncoding(InputStream is) throws IOException {
    byte[] buffer = new byte[4096];
    is.mark(0);
    is.read(buffer);//from  w  w  w . ja  v a  2  s  . c  om
    is.reset();

    File tempFile = File.createTempFile("PhonebookFileEntryTemp", null);
    FileOutputStream out = new FileOutputStream(tempFile);
    out.write(buffer);
    out.flush();
    out.close();

    String encoding = CharsetToolkit.guessEncoding(tempFile, buffer.length).displayName();
    tempFile.delete();

    return encoding;
}