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.apache.tika.parser.iwork.IWorkPackageParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    ZipArchiveInputStream zip = new ZipArchiveInputStream(stream);
    ZipArchiveEntry entry = zip.getNextZipEntry();

    while (entry != null) {
        if (!IWORK_CONTENT_ENTRIES.contains(entry.getName())) {
            entry = zip.getNextZipEntry();
            continue;
        }/*from w  ww  .ja v  a  2  s  .  c o m*/

        InputStream entryStream = new BufferedInputStream(zip, 4096);
        entryStream.mark(4096);
        IWORKDocumentType type = IWORKDocumentType.detectType(entryStream);
        entryStream.reset();

        if (type != null) {
            XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
            ContentHandler contentHandler;

            switch (type) {
            case KEYNOTE:
                contentHandler = new KeynoteContentHandler(xhtml, metadata);
                break;
            case NUMBERS:
                contentHandler = new NumbersContentHandler(xhtml, metadata);
                break;
            case PAGES:
                contentHandler = new PagesContentHandler(xhtml, metadata);
                break;
            case ENCRYPTED:
                // We can't do anything for the file right now
                contentHandler = null;
                break;
            default:
                throw new TikaException("Unhandled iWorks file " + type);
            }

            metadata.add(Metadata.CONTENT_TYPE, type.getType().toString());
            xhtml.startDocument();
            if (contentHandler != null) {
                context.getSAXParser().parse(new CloseShieldInputStream(entryStream),
                        new OfflineContentHandler(contentHandler));
            }
            xhtml.endDocument();
        }

        entry = zip.getNextZipEntry();
    }
    // Don't close the zip InputStream (TIKA-1117).
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

@Override
public boolean isValid(InputStream documentStream) throws Exception {
    if (!documentStream.markSupported()) {
        throw new IOException("Only markeable input stream expected!");
    }/*  ww  w .  ja  v a2s  .c o m*/
    documentStream.mark(Integer.MAX_VALUE);
    InputStream cloneStream = new ByteArrayInputStream(IOUtils.toByteArray(documentStream));
    documentStream.reset();
    Document document = getDocumentForSource(cloneStream);
    return isValid(document);
}

From source file:org.apache.fop.plan.PreloaderPlan.java

private ImageInfo getImage(String uri, Source src, ImageContext context) throws IOException {

    InputStream in = new UnclosableInputStream(ImageUtil.needInputStream(src));
    try {//  ww w.  j  av  a2 s . c  o m
        Document planDoc = getDocument(in);
        Element rootEl = planDoc.getDocumentElement();
        if (!PlanElementMapping.NAMESPACE.equals(rootEl.getNamespaceURI())) {
            in.reset();
            return null;
        }

        //Have to render the plan to know its size
        PlanRenderer pr = new PlanRenderer();
        Document svgDoc = pr.createSVGDocument(planDoc);
        float width = pr.getWidth();
        float height = pr.getHeight();

        //Return converted SVG image
        ImageInfo info = new ImageInfo(uri, "image/svg+xml");
        final ImageSize size = new ImageSize();
        size.setSizeInMillipoints(Math.round(width * 1000), Math.round(height * 1000));
        //Set the resolution to that of the FOUserAgent
        size.setResolution(context.getSourceResolution());
        size.calcPixelsFromSize();
        info.setSize(size);

        //The whole image had to be loaded for this, so keep it
        Image image = new ImageXMLDOM(info, svgDoc, svgDoc.getDocumentElement().getNamespaceURI());
        info.getCustomObjects().put(ImageInfo.ORIGINAL_IMAGE, image);

        return info;
    } catch (TransformerException e) {
        try {
            in.reset();
        } catch (IOException ioe) {
            // we're more interested in the original exception
        }
        log.debug("Error while trying to parsing a Plan file: " + e.getMessage());
        return null;
    }
}

From source file:com.vmware.photon.controller.api.frontend.lib.image.ImageLoader.java

/**
 * Peak into the stream for the OVA signature.
 *
 * @param inputStream//  ww  w.j av  a2  s .c o m
 * @return
 * @throws IOException
 */
private boolean isTarFile(InputStream inputStream) throws IOException {
    inputStream.mark(TarFileStreamReader.TAR_FILE_GRANULARITY);
    TarFileStreamReader tar = new TarFileStreamReader(inputStream);
    boolean isTar = tar.iterator().hasNext();
    inputStream.reset();
    return isTar;
}

From source file:pt.lunacloud.auth.AWS4Signer.java

public void sign(Request<?> request, LunacloudCredentials credentials) throws LunacloudClientException {
    // annonymous credentials, don't sign
    if (credentials instanceof AnonymousAWSCredentials) {
        return;/* ww  w. j a v  a2  s . c o m*/
    }

    LunacloudCredentials sanitizedCredentials = sanitizeCredentials(credentials);
    if (sanitizedCredentials instanceof AWSSessionCredentials) {
        addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
    }

    SimpleDateFormat dateStampFormat = new SimpleDateFormat("yyyyMMdd");
    dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));

    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));

    String regionName = extractRegionName(request.getEndpoint());
    String serviceName = extractServiceName(request.getEndpoint());

    // AWS4 requires that we sign the Host header so we
    // have to have it in the request by the time we sign.
    String hostHeader = request.getEndpoint().getHost();
    if (HttpUtils.isUsingNonDefaultPort(request.getEndpoint())) {
        hostHeader += ":" + request.getEndpoint().getPort();
    }
    request.addHeader("Host", hostHeader);

    Date date = getSignatureDate(request.getTimeOffset());
    if (overriddenDate != null)
        date = overriddenDate;

    String dateTime = dateTimeFormat.format(date);
    String dateStamp = dateStampFormat.format(date);

    InputStream payloadStream = getBinaryRequestPayloadStream(request);
    payloadStream.mark(-1);
    String contentSha256 = BinaryUtils.toHex(hash(payloadStream));
    try {
        payloadStream.reset();
    } catch (IOException e) {
        throw new LunacloudClientException("Unable to reset stream after calculating AWS4 signature", e);
    }

    request.addHeader("X-Amz-Date", dateTime);
    request.addHeader("x-amz-content-sha256", contentSha256);

    String canonicalRequest = request.getHttpMethod().toString() + "\n"
            + super.getCanonicalizedResourcePath(request.getResourcePath()) + "\n"
            + getCanonicalizedQueryString(request) + "\n" + getCanonicalizedHeaderString(request) + "\n"
            + getSignedHeadersString(request) + "\n" + contentSha256;

    log.debug("AWS4 Canonical Request: '\"" + canonicalRequest + "\"");

    String scope = dateStamp + "/" + regionName + "/" + serviceName + "/" + TERMINATOR;
    String signingCredentials = sanitizedCredentials.getLunacloudAccessKeyId() + "/" + scope;
    String stringToSign = ALGORITHM + "\n" + dateTime + "\n" + scope + "\n"
            + BinaryUtils.toHex(hash(canonicalRequest));
    log.debug("AWS4 String to Sign: '\"" + stringToSign + "\"");

    // AWS4 uses a series of derived keys, formed by hashing different pieces of data
    byte[] kSecret = ("AWS4" + sanitizedCredentials.getLunacloudSecretKey()).getBytes();
    byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256);
    byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256);
    byte[] kService = sign(serviceName, kRegion, SigningAlgorithm.HmacSHA256);
    byte[] kSigning = sign(TERMINATOR, kService, SigningAlgorithm.HmacSHA256);

    byte[] signature = sign(stringToSign.getBytes(), kSigning, SigningAlgorithm.HmacSHA256);

    String credentialsAuthorizationHeader = "Credential=" + signingCredentials;
    String signedHeadersAuthorizationHeader = "SignedHeaders=" + getSignedHeadersString(request);
    String signatureAuthorizationHeader = "Signature=" + BinaryUtils.toHex(signature);

    String authorizationHeader = ALGORITHM + " " + credentialsAuthorizationHeader + ", "
            + signedHeadersAuthorizationHeader + ", " + signatureAuthorizationHeader;

    request.addHeader("Authorization", authorizationHeader);
}

From source file:jetbrains.exodus.entitystore.FileSystemBlobVaultOld.java

@Override
public void flushBlobs(@Nullable final LongHashMap<InputStream> blobStreams,
        @Nullable final LongHashMap<File> blobFiles, @Nullable final LongSet deferredBlobsToDelete,
        @NotNull final Transaction txn) throws Exception {
    if (blobStreams != null) {
        blobStreams.forEachEntry(new ObjectProcedureThrows<Map.Entry<Long, InputStream>, Exception>() {
            @Override//from w ww  . ja  v  a2s. c o m
            public boolean execute(final Map.Entry<Long, InputStream> object) throws Exception {
                final InputStream stream = object.getValue();
                stream.reset();
                setContent(object.getKey(), stream);
                return true;
            }
        });
    }
    // if there were blob files then move them
    if (blobFiles != null) {
        blobFiles.forEachEntry(new ObjectProcedureThrows<Map.Entry<Long, File>, Exception>() {
            @Override
            public boolean execute(final Map.Entry<Long, File> object) throws Exception {
                setContent(object.getKey(), object.getValue());
                return true;
            }
        });
    }
    // if there are deferred blobs to delete then defer their deletion
    if (deferredBlobsToDelete != null) {
        final LongSet copy = new LongHashSet();
        final LongIterator it = deferredBlobsToDelete.iterator();
        while (it.hasNext()) {
            copy.add(it.nextLong());
        }
        final Environment environment = txn.getEnvironment();
        environment.executeTransactionSafeTask(new Runnable() {
            @Override
            public void run() {
                DeferredIO.getJobProcessor().queue(new Job() {
                    @Override
                    protected void execute() throws Throwable {
                        final LongIterator it = copy.iterator();
                        while (it.hasNext()) {
                            delete(it.nextLong());
                        }
                    }

                    @Override
                    public String getName() {
                        return "Delete obsolete blob files";
                    }

                    @Override
                    public String getGroup() {
                        return environment.getLocation();
                    }
                });
            }
        });
    }
}

From source file:com.intuit.karate.LoggingFilter.java

@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
    int id = counter.get();
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" < ").append(response.getStatus()).append('\n');
    logHeaders(sb, id, '<', response.getHeaders());
    if (response.hasEntity() && isPrintable(response.getMediaType())) {
        InputStream is = response.getEntityStream();
        if (!is.markSupported()) {
            is = new BufferedInputStream(is);
        }/*from  w  w w.  j av  a 2 s.co  m*/
        is.mark(Integer.MAX_VALUE);
        String buffer = IOUtils.toString(is, getCharset(response.getMediaType()));
        sb.append(buffer).append('\n');
        is.reset();
        response.setEntityStream(is); // in case it was swapped
    }
    logger.debug(sb.toString());
}

From source file:com.armorize.hackalert.extractor.msword.MSExtractor.java

/**
 * Extracts properties and text from an MS Document input stream
 *//*from  w w  w  .j a  va 2s. com*/
protected void extract(InputStream input) throws Exception {
    // First, extract properties
    this.reader = new POIFSReader();
    this.properties = new PropertiesBroker();
    this.reader.registerListener(new PropertiesReaderListener(this.properties),
            SummaryInformation.DEFAULT_STREAM_NAME);
    input.reset();
    if (input.available() > 0) {
        reader.read(input);
    }
    // Then, extract text
    input.reset();
    this.text = extractText(input);
}

From source file:edu.utah.further.core.xml.chain.UnmarshallRequestProcessorImpl.java

/**
 * @param inputStream//from w w w .j  a v  a 2s . c om
 */
private void printInputXmlForDebugging(final InputStream inputStream) {
    if (log.isTraceEnabled() && inputStream.markSupported()) {
        inputStream.mark(0);
        log.trace("Unmarshalling input is " + IoUtil.getInputStreamAsString(inputStream));
        try {
            inputStream.reset();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.adaptris.core.lms.StreamWrapperCase.java

@Test
public void testInputStream_Mark() throws Exception {
    StreamWrapper wrapper = createWrapper(false);
    File file = writeFile(TempFileUtils.createTrackedFile(wrapper));
    InputStream in = wrapper.openInputStream(file, NO_OP);
    try (InputStream closeable = in) {
        tryQuietly(() -> {/*from  w  ww  .  ja  v  a2  s .  c  o  m*/
            in.markSupported();
        });
        tryQuietly(() -> {
            in.mark(10);
        });
        tryQuietly(() -> {
            in.reset();
        });
    }
}