Example usage for java.io InputStream reset

List of usage examples for java.io InputStream reset

Introduction

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

Prototype

public synchronized void reset() throws IOException 

Source Link

Document

Repositions this stream to the position at the time the mark method was last called on this input stream.

Usage

From source file:org.docx4j.openpackaging.io.LoadFromZipNG.java

/**
 * Get a Part (except a relationships part), but not its relationships part
 * or related parts.  Useful if you need quick access to just this part.
 * This can be called directly from outside the library, in which case 
 * the Part will not be owned by a Package until the calling code makes it so.  
 * @see  To get a Part and all its related parts, and add all to a package, use
 * getPart.// w  w w  .  jav  a  2s. c om
 * @param partByteArrays
 * @param ctm
 * @param resolvedPartUri
 * @param rel
 * @return
 * @throws Docx4JException including if result is null
 */
public static Part getRawPart(HashMap<String, ByteArray> partByteArrays, ContentTypeManager ctm,
        String resolvedPartUri, Relationship rel) throws Docx4JException {

    Part part = null;

    InputStream is = null;
    try {
        try {
            log.debug("resolved uri: " + resolvedPartUri);
            is = getInputStreamFromZippedPart(partByteArrays, resolvedPartUri);

            // Get a subclass of Part appropriate for this content type   
            // This will throw UnrecognisedPartException in the absence of
            // specific knowledge. Hence it is important to get the is
            // first, as we do above.
            part = ctm.getPart("/" + resolvedPartUri, rel);

            log.info("ctm returned " + part.getClass().getName());

            if (part instanceof org.docx4j.openpackaging.parts.ThemePart) {

                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcThemePart);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsCorePart) {

                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsCore);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsCustomPart) {

                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsCustom);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsExtendedPart) {

                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsExtended);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart) {

                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part)
                        .setJAXBContext(Context.jcCustomXmlProperties);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.digitalsignature.XmlSignaturePart) {

                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcXmlDSig);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.JaxbXmlPart) {

                // MainDocument part, Styles part, Font part etc

                //((org.docx4j.openpackaging.parts.JaxbXmlPart)part).setJAXBContext(Context.jc);
                ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) {

                log.debug("Detected BinaryPart " + part.getClass().getName());
                ((BinaryPart) part).setBinaryData(is);

            } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) {

                // Is it a part we know?
                try {

                    XMLInputFactory xif = XMLInputFactory.newInstance();
                    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
                    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception
                    XMLStreamReader xsr = xif.createXMLStreamReader(is);

                    Unmarshaller u = Context.jc.createUnmarshaller();
                    Object o = u.unmarshal(xsr);
                    log.debug(o.getClass().getName());

                    PartName name = part.getPartName();

                    if (o instanceof CoverPageProperties) {

                        part = new DocPropsCoverPagePart(name);
                        ((DocPropsCoverPagePart) part).setJaxbElement((CoverPageProperties) o);

                    } else if (o instanceof org.opendope.conditions.Conditions) {

                        part = new ConditionsPart(name);
                        ((ConditionsPart) part).setJaxbElement((org.opendope.conditions.Conditions) o);

                    } else if (o instanceof org.opendope.xpaths.Xpaths) {

                        part = new XPathsPart(name);
                        ((XPathsPart) part).setJaxbElement((org.opendope.xpaths.Xpaths) o);

                    } else if (o instanceof org.opendope.questions.Questionnaire) {

                        part = new QuestionsPart(name);
                        ((QuestionsPart) part).setJaxbElement((org.opendope.questions.Questionnaire) o);

                    } else if (o instanceof org.opendope.answers.Answers) {

                        part = new StandardisedAnswersPart(name);
                        ((StandardisedAnswersPart) part).setJaxbElement((org.opendope.answers.Answers) o);

                    } else if (o instanceof org.opendope.components.Components) {

                        part = new ComponentsPart(name);
                        ((ComponentsPart) part).setJaxbElement((org.opendope.components.Components) o);

                    } else if (o instanceof JAXBElement<?>
                            && XmlUtils.unwrap(o) instanceof org.docx4j.bibliography.CTSources) {
                        part = new BibliographyPart(name);
                        ((BibliographyPart) part)
                                .setJaxbElement((JAXBElement<org.docx4j.bibliography.CTSources>) o);

                    } else {

                        log.error("TODO: handle known CustomXmlPart part  " + o.getClass().getName());

                        CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory();
                        is.reset();
                        data.setDocument(is); // Not necessarily JAXB, that's just our method name
                        ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data);

                    }

                } catch (javax.xml.bind.UnmarshalException ue) {

                    log.warn("No JAXB model for this CustomXmlDataStorage part; " + ue.getMessage());

                    CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory();
                    is.reset();
                    data.setDocument(is); // Not necessarily JAXB, that's just our method name
                    ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data);
                }

            } else if (part instanceof org.docx4j.openpackaging.parts.XmlPart) {

                //               try {
                ((XmlPart) part).setDocument(is);

                // Experimental 22/6/2011; don't fall back to binary (which we used to) 

                //               } catch (Docx4JException d) {
                //                  // This isn't an XML part after all,
                //                  // even though ContentTypeManager detected it as such
                //                  // So get it as a binary part
                //                  part = getBinaryPart(partByteArrays, ctm, resolvedPartUri);
                //                  log.warn("Could not parse as XML, so using BinaryPart for " 
                //                        + resolvedPartUri);                  
                //                  ((BinaryPart)part).setBinaryData(is);
                //               }

            } else {
                // Shouldn't happen, since ContentTypeManagerImpl should
                // return an instance of one of the above, or throw an
                // Exception.

                log.error("No suitable part found for: " + resolvedPartUri);
                part = null;
            }

        } catch (PartUnrecognisedException e) {
            log.error("PartUnrecognisedException shouldn't happen anymore!", e);
            // Try to get it as a binary part
            part = getBinaryPart(partByteArrays, ctm, resolvedPartUri);
            log.warn("Using BinaryPart for " + resolvedPartUri);

            ((BinaryPart) part).setBinaryData(is);
        }
    } catch (Exception ex) {
        // IOException, URISyntaxException
        ex.printStackTrace();
        throw new Docx4JException("Failed to getPart", ex);

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    }

    if (part == null) {
        throw new Docx4JException(
                "cannot find part " + resolvedPartUri + " from rel " + rel.getId() + "=" + rel.getTarget());
    }

    return part;
}

From source file:com.smartsheet.api.internal.http.DefaultHttpClient.java

/**
 * Make an HTTP request and return the response.
 *
 * @param smartsheetRequest the smartsheet request
 * @return the HTTP response//  w  ww  .j  av  a2  s  .com
 * @throws HttpClientException the HTTP client exception
 */
public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException {
    Util.throwIfNull(smartsheetRequest);
    if (smartsheetRequest.getUri() == null) {
        throw new IllegalArgumentException("A Request URI is required.");
    }

    int attempt = 0;
    long start = System.currentTimeMillis();

    HttpRequestBase apacheHttpRequest;
    HttpResponse smartsheetResponse;

    InputStream bodyStream = null;
    if (smartsheetRequest.getEntity() != null && smartsheetRequest.getEntity().getContent() != null) {
        bodyStream = smartsheetRequest.getEntity().getContent();
    }
    // the retry logic will consume the body stream so we make sure it supports mark/reset and mark it
    boolean canRetryRequest = bodyStream == null || bodyStream.markSupported();
    if (!canRetryRequest) {
        try {
            // attempt to wrap the body stream in a input-stream that does support mark/reset
            bodyStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(bodyStream));
            // close the old stream (just to be tidy) and then replace it with a reset-able stream
            smartsheetRequest.getEntity().getContent().close();
            smartsheetRequest.getEntity().setContent(bodyStream);
            canRetryRequest = true;
        } catch (IOException ignore) {
        }
    }

    // the retry loop
    while (true) {

        apacheHttpRequest = createApacheRequest(smartsheetRequest);

        // Set HTTP headers
        if (smartsheetRequest.getHeaders() != null) {
            for (Map.Entry<String, String> header : smartsheetRequest.getHeaders().entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        HttpEntitySnapshot requestEntityCopy = null;
        HttpEntitySnapshot responseEntityCopy = null;
        // Set HTTP entity
        final HttpEntity entity = smartsheetRequest.getEntity();
        if (apacheHttpRequest instanceof HttpEntityEnclosingRequestBase && entity != null
                && entity.getContent() != null) {
            try {
                // we need access to the original request stream so we can log it (in the event of errors and/or tracing)
                requestEntityCopy = new HttpEntitySnapshot(entity);
            } catch (IOException iox) {
                logger.error("failed to make copy of original request entity - {}", iox);
            }

            InputStreamEntity streamEntity = new InputStreamEntity(entity.getContent(),
                    entity.getContentLength());
            streamEntity.setChunked(false); // why?  not supported by library?
            ((HttpEntityEnclosingRequestBase) apacheHttpRequest).setEntity(streamEntity);
        }

        // mark the body so we can reset on retry
        if (canRetryRequest && bodyStream != null) {
            bodyStream.mark((int) smartsheetRequest.getEntity().getContentLength());
        }

        // Make the HTTP request
        smartsheetResponse = new HttpResponse();
        HttpContext context = new BasicHttpContext();
        try {
            long startTime = System.currentTimeMillis();
            apacheHttpResponse = this.httpClient.execute(apacheHttpRequest, context);
            long endTime = System.currentTimeMillis();

            // Set request headers to values ACTUALLY SENT (not just created by us), this would include:
            // 'Connection', 'Accept-Encoding', etc. However, if a proxy is used, this may be the proxy's CONNECT
            // request, hence the test for HTTP method first
            Object httpRequest = context.getAttribute("http.request");
            if (httpRequest != null && HttpRequestWrapper.class.isAssignableFrom(httpRequest.getClass())) {
                HttpRequestWrapper actualRequest = (HttpRequestWrapper) httpRequest;
                switch (HttpMethod.valueOf(actualRequest.getMethod())) {
                case GET:
                case POST:
                case PUT:
                case DELETE:
                    apacheHttpRequest.setHeaders(((HttpRequestWrapper) httpRequest).getAllHeaders());
                    break;
                }
            }

            // Set returned headers
            smartsheetResponse.setHeaders(new HashMap<String, String>());
            for (Header header : apacheHttpResponse.getAllHeaders()) {
                smartsheetResponse.getHeaders().put(header.getName(), header.getValue());
            }
            smartsheetResponse.setStatus(apacheHttpResponse.getStatusLine().getStatusCode(),
                    apacheHttpResponse.getStatusLine().toString());

            // Set returned entities
            if (apacheHttpResponse.getEntity() != null) {
                HttpEntity httpEntity = new HttpEntity();
                httpEntity.setContentType(apacheHttpResponse.getEntity().getContentType().getValue());
                httpEntity.setContentLength(apacheHttpResponse.getEntity().getContentLength());
                httpEntity.setContent(apacheHttpResponse.getEntity().getContent());
                smartsheetResponse.setEntity(httpEntity);
                responseEntityCopy = new HttpEntitySnapshot(httpEntity);
            }

            long responseTime = endTime - startTime;
            logRequest(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy,
                    responseTime);

            if (traces.size() > 0) { // trace-logging of request and response (if so configured)
                RequestAndResponseData requestAndResponseData = RequestAndResponseData.of(apacheHttpRequest,
                        requestEntityCopy, smartsheetResponse, responseEntityCopy, traces);
                TRACE_WRITER.println(requestAndResponseData.toString(tracePrettyPrint));
            }

            if (smartsheetResponse.getStatusCode() == 200) {
                // call successful, exit the retry loop
                break;
            }

            // the retry logic might consume the content stream so we make sure it supports mark/reset and mark it
            InputStream contentStream = smartsheetResponse.getEntity().getContent();
            if (!contentStream.markSupported()) {
                // wrap the response stream in a input-stream that does support mark/reset
                contentStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(contentStream));
                // close the old stream (just to be tidy) and then replace it with a reset-able stream
                smartsheetResponse.getEntity().getContent().close();
                smartsheetResponse.getEntity().setContent(contentStream);
            }
            try {
                contentStream.mark((int) smartsheetResponse.getEntity().getContentLength());
                long timeSpent = System.currentTimeMillis() - start;
                if (!shouldRetry(++attempt, timeSpent, smartsheetResponse)) {
                    // should not retry, or retry time exceeded, exit the retry loop
                    break;
                }
            } finally {
                if (bodyStream != null) {
                    bodyStream.reset();
                }
                contentStream.reset();
            }
            // moving this to finally causes issues because socket is closed (which means response stream is closed)
            this.releaseConnection();

        } catch (ClientProtocolException e) {
            try {
                logger.warn("ClientProtocolException " + e.getMessage());
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                // if this is a PUT and was retried by the http client, the body content stream is at the
                // end and is a NonRepeatableRequest. If we marked the body content stream prior to execute,
                // reset and retry
                if (canRetryRequest && e.getCause() instanceof NonRepeatableRequestException) {
                    if (smartsheetRequest.getEntity() != null) {
                        smartsheetRequest.getEntity().getContent().reset();
                    }
                    continue;
                }
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        } catch (NoHttpResponseException e) {
            try {
                logger.warn("NoHttpResponseException " + e.getMessage());
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                // check to see if the response was empty and this was a POST. All other HTTP methods
                // will be automatically retried by the http client.
                // (POST is non-idempotent and is not retried automatically, but is safe for us to retry)
                if (canRetryRequest && smartsheetRequest.getMethod() == HttpMethod.POST) {
                    if (smartsheetRequest.getEntity() != null) {
                        smartsheetRequest.getEntity().getContent().reset();
                    }
                    continue;
                }
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        } catch (IOException e) {
            try {
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        }
    }
    return smartsheetResponse;
}