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:Main.java

public static String determineEncoding(InputStream stream) throws IOException {
    stream.mark(20000);/*from  w  w w .j  a  va2 s  .  com*/
    try {
        int b0 = stream.read();
        int b1 = stream.read();
        int b2 = stream.read();
        int b3 = stream.read();

        if (b0 == 0xFE && b1 == 0xFF)
            return "UTF-16BE";
        else if (b0 == 0xFF && b1 == 0xFE)
            return "UTF-16LE";
        else if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF)
            return "UTF-8";
        else if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x3F)
            return "UTF-16BE";
        else if (b0 == 0x3C && b1 == 0x00 && b2 == 0x3F && b3 == 0x00)
            return "UTF-16LE";
        else if (b0 == 0x3C && b1 == 0x3F && b2 == 0x78 && b3 == 0x6D) {
            //            UTF-8, ISO 646, ASCII, some part of ISO 8859, Shift-JIS, EUC, or any other 7-bit, 8-bit, or mixed-width encoding 
            //            which ensures that the characters of ASCII have their normal positions, width, and values; the actual encoding 
            //            declaration must be read to detect which of these applies, but since all of these encodings use the same bit patterns 
            //            for the relevant ASCII characters, the encoding declaration itself may be read reliably
            InputStreamReader rdr = new InputStreamReader(stream, "US-ASCII");
            String hdr = readFirstLine(rdr);
            return extractEncoding(hdr);
        } else
            return null;
    } finally {
        stream.reset();
    }
}

From source file:eu.europa.ec.markt.dss.validation.SignedDocumentValidator.java

/**
 * Guess the document format and return an appropriate document
 * //  w  ww  . j  a  v a  2  s . c  o  m
 * @param document
 * @return
 */
public static SignedDocumentValidator fromDocument(Document document) throws IOException {

    InputStream input = null;

    try {
        if (document.getName() != null && document.getName().toLowerCase().endsWith(".xml")) {
            try {
                return new XMLDocumentValidator(document);
            } catch (ParserConfigurationException e) {
                throw new IOException("Not a valid XML");
            } catch (SAXException e) {
                throw new IOException("Not a valid XML");
            }
        }

        input = new BufferedInputStream(document.openStream());
        input.mark(5);
        byte[] preamble = new byte[5];
        int read = input.read(preamble);
        input.reset();
        if (read < 5) {
            throw new RuntimeException("Not a signed document");
        }
        String preambleString = new String(preamble);
        byte[] xmlPreable = new byte[] { '<', '?', 'x', 'm', 'l' };
        byte[] xmlUtf8 = new byte[] { -17, -69, -65, '<', '?' };
        if (Arrays.equals(preamble, xmlPreable) || Arrays.equals(preamble, xmlUtf8)) {
            try {
                return new XMLDocumentValidator(document);
            } catch (ParserConfigurationException e) {
                throw new IOException("Not a valid XML");
            } catch (SAXException e) {
                throw new IOException("Not a valid XML");
            }
        } else if (preambleString.equals("%PDF-")) {
            return new PDFDocumentValidator(document);
        } else if (preamble[0] == 'P' && preamble[1] == 'K') {
            try {
                input.close();
            } catch (IOException e) {
            }
            input = null;
            return getInstanceForAsics(document);
        } else if (preambleString.getBytes()[0] == 0x30) {
            try {
                return new CMSDocumentValidator(document);
            } catch (CMSException e) {
                throw new IOException("Not a valid CAdES file");
            }
        } else {
            throw new RuntimeException("Document format not recognized/handled");
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }

}

From source file:edu.umd.cfar.lamp.viper.util.StringHelp.java

/** 
 * Checks to see if the stream begins with an xml processing directive, eg
 * <code>&lt;?xml?&gt;</code>. This method does not check to see that the 
 * stream is well-formed, or even if the processing directive is good, just that
 * the first non-whitespace characters are "&lt;?xml".
 *
 * @param f The file to check for xml processing directive
 * @throws IOException if there is an error while reading the file, eg FileNotFoundException
 * @return <code>true</code> if the directive was found. 
 *//*w w w  .  j  av a 2 s.c  om*/
public static boolean isXMLFormat(InputStream f) throws IOException {
    final int LIMIT = 4024;
    f.mark(LIMIT);
    InputStreamReader isr = new InputStreamReader(f);
    char n;
    do {
        n = (char) isr.read();
    } while (Character.isWhitespace(n));
    boolean xml = (n == '<' && isr.read() == '?' && (char) isr.read() == 'x' && (char) isr.read() == 'm'
            && (char) isr.read() == 'l');
    f.reset();
    return xml;
}

From source file:de.uzk.hki.da.cb.SendToPresenterAction.java

/**
 * @param urn/*from  w  w w  . jav a2 s  .c  om*/
 * @param objectId
 * @param collection
 * @param packagePath
 * @param contractorShortName
 * @param packageType
 * @param sets
 * @return
 * @throws RepositoryException
 * @throws IOException
 */
private boolean ingestPackage(String urn, String objectId, String collection, Path packagePath,
        String contractorShortName, String packageType, String[] sets) throws RepositoryException, IOException {

    // check if pip exists
    File pack = packagePath.toFile();
    if (!pack.exists()) {
        throw new IOException("Directory " + packagePath + " does not exist");
    }

    // create object for package in fedora if it does not already exist
    if (!repositoryFacade.objectExists(objectId, collection)) {
        repositoryFacade.createObject(objectId, collection, contractorShortName);
    }

    // walk package and add files as datastreams recursively
    ingestDir(objectId, collection, pack, packagePath.toString(), packageType);

    // add identifiers to DC datastream
    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
    Document doc;
    try {
        InputStream in = repositoryFacade.retrieveFile(objectId, collection, DC);

        try {
            in.reset();
        } catch (IOException io) {
        }
        doc = builder.build(in);
    } catch (JDOMException e) {
        throw new RuntimeException(e);
    }

    try {
        doc.getRootElement().addContent(new Element(IDENTIFIER, DC, PURL_ORG_DC).setText(urn));
    } catch (Exception e) {
        throw new RepositoryException("Failed to add identifiers to object in repository", e);
    }
    String content = new XMLOutputter().outputString(doc);
    repositoryFacade.updateMetadataFile(objectId, collection, DC, content, DC + ".xml", "text/xml");
    logger.info("Successfully added identifiers to DC datastream");

    // add RELS-EXT relationships
    try {

        // add urn as owl:sameAs
        repositoryFacade.addRelationship(objectId, collection, C.OWL_SAMEAS, urn);
        logger.debug("Added relationship: " + C.OWL_SAMEAS + " " + urn);

        // add collection membership
        String collectionUri;
        if (preservationSystem.getClosedCollectionName().equals(collection)) {
            collectionUri = CLOSED_COLLECTION_URI;
        } else {
            collectionUri = OPEN_COLLECTION_URI;
        }
        repositoryFacade.addRelationship(objectId, collection, MEMBER_COLLECTION, collectionUri);
        logger.debug("Added relationship: " + MEMBER_COLLECTION + " " + collectionUri);

        // add oai identifier
        if (!(preservationSystem.getClosedCollectionName() + ":").equals(collection) &&
        // don't add test packages to OAI-PMH
                !testContractors.contains(contractorShortName)) {
            String oaiId = C.OAI_DANRW_DE + objectId;
            repositoryFacade.addRelationship(objectId, collection, OPENARCHIVES_OAI_IDENTIFIER, oaiId);
            logger.debug("Added relationship: " + OPENARCHIVES_OAI_IDENTIFIER + " " + oaiId);
        }

        // add oai sets
        if (sets != null)
            for (String set : sets) {
                repositoryFacade.addRelationship(objectId, collection, MEMBER, "info:fedora/set:" + set);
                logger.debug("Added relationship: " + MEMBER + " info:fedora/set:" + set);
            }

    } catch (Exception e) {
        throw new RepositoryException("Failed to add relationships for package " + packagePath + " in fedora",
                e);
    }

    return true;
}

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

@Override
public Response executeRequest(Request request) throws RestException {

    Assert.notNull(request, "Request argument cannot be null.");

    int retryCount = 0;
    URI redirectUri = null;//from  w w w. j  a  v  a  2s  .com
    HttpEntity entity = null;
    RestException exception = null;

    // Make a copy of the original request params and headers so that we can
    // permute them in the loop and start over with the original every time.
    QueryString originalQuery = new QueryString();
    originalQuery.putAll(request.getQueryString());

    HttpHeaders originalHeaders = new HttpHeaders();
    originalHeaders.putAll(request.getHeaders());

    while (true) {

        if (redirectUri != null) {
            request = new DefaultRequest(request.getMethod(), redirectUri.toString(), null, null,
                    request.getBody(), request.getHeaders().getContentLength());
        }

        if (retryCount > 0) {
            request.setQueryString(originalQuery);
            request.setHeaders(originalHeaders);
        }

        // Sign the request
        this.requestAuthenticator.authenticate(request);

        HttpRequestBase httpRequest = this.httpClientRequestFactory.createHttpClientRequest(request, entity);

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

        HttpResponse httpResponse = null;
        try {
            // We don't want to treat a redirect like a retry,
            // so if redirectUri is not null, we won't pause
            // before executing the request below.
            if (retryCount > 0 && redirectUri == null) {
                pauseExponentially(retryCount, exception);
                if (entity != null) {
                    InputStream content = entity.getContent();
                    if (content.markSupported()) {
                        content.reset();
                    }
                }
            }

            // reset redirectUri so that if there is an exception, we will pause on retry
            redirectUri = null;
            exception = null;
            retryCount++;

            httpResponse = httpClient.execute(httpRequest);

            if (isRedirect(httpResponse)) {
                Header[] locationHeaders = httpResponse.getHeaders("Location");
                String location = locationHeaders[0].getValue();
                log.debug("Redirecting to: {}", location);
                redirectUri = URI.create(location);
                httpRequest.setURI(redirectUri);
            } else {

                Response response = toSdkResponse(httpResponse);

                int httpStatus = response.getHttpStatus();

                if (httpStatus == 429) {
                    throw new RestException(
                            "HTTP 429: Too Many Requests.  Exceeded request rate limit in the allotted amount of time.");
                }
                if ((httpStatus == 503 || httpStatus == 504) && retryCount <= this.numRetries) {
                    //allow the loop to continue to execute a retry request
                    continue;
                }

                return response;
            }
        } catch (Throwable t) {
            log.warn("Unable to execute HTTP request: ", t.getMessage(), t);

            if (t instanceof RestException) {
                exception = (RestException) t;
            }

            if (!shouldRetry(httpRequest, t, retryCount)) {
                throw new RestException("Unable to execute HTTP request: " + t.getMessage(), t);
            }
        } finally {
            try {
                httpResponse.getEntity().getContent().close();
            } catch (Throwable ignored) { // NOPMD
            }
        }
    }
}

From source file:com.stormpath.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

@Override
public Response executeRequest(Request request) throws RestException {

    Assert.notNull(request, "Request argument cannot be null.");

    int retryCount = 0;
    URI redirectUri = null;//  w  w  w  .  jav  a 2s.  co m
    HttpEntity entity = null;
    RestException exception = null;

    // Make a copy of the original request params and headers so that we can
    // permute them in the loop and start over with the original every time.
    QueryString originalQuery = new QueryString();
    originalQuery.putAll(request.getQueryString());

    HttpHeaders originalHeaders = new HttpHeaders();
    originalHeaders.putAll(request.getHeaders());

    while (true) {

        if (redirectUri != null) {
            request = new DefaultRequest(request.getMethod(), redirectUri.toString(), null, null,
                    request.getBody(), request.getHeaders().getContentLength());
        }

        if (retryCount > 0) {
            request.setQueryString(originalQuery);
            request.setHeaders(originalHeaders);
        }

        // Sign the request
        this.requestAuthenticator.authenticate(request);

        HttpRequestBase httpRequest = this.httpClientRequestFactory.createHttpClientRequest(request, entity);

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

        HttpResponse httpResponse = null;
        try {
            // We don't want to treat a redirect like a retry,
            // so if redirectUri is not null, we won't pause
            // before executing the request below.
            if (retryCount > 0 && redirectUri == null) {
                pauseExponentially(retryCount, exception);
                if (entity != null) {
                    InputStream content = entity.getContent();
                    if (content.markSupported()) {
                        content.reset();
                    }
                }
            }

            // reset redirectUri so that if there is an exception, we will pause on retry
            redirectUri = null;
            exception = null;
            retryCount++;

            httpResponse = httpClient.execute(httpRequest);

            if (isRedirect(httpResponse)) {
                Header[] locationHeaders = httpResponse.getHeaders("Location");
                String location = locationHeaders[0].getValue();
                log.debug("Redirecting to: {}", location);
                redirectUri = request.getResourceUrl().resolve(location);
                httpRequest.setURI(redirectUri);
            } else {

                Response response = toSdkResponse(httpResponse);

                int httpStatus = response.getHttpStatus();

                if (httpStatus == 429) {
                    throw new RestException(
                            "HTTP 429: Too Many Requests.  Exceeded request rate limit in the allotted amount of time.");
                }
                if ((httpStatus == 503 || httpStatus == 504) && retryCount <= this.numRetries) {
                    //allow the loop to continue to execute a retry request
                    continue;
                }

                return response;
            }
        } catch (Throwable t) {
            log.warn("Unable to execute HTTP request: ", t.getMessage(), t);

            if (t instanceof RestException) {
                exception = (RestException) t;
            }

            if (!shouldRetry(httpRequest, t, retryCount)) {
                throw new RestException("Unable to execute HTTP request: " + t.getMessage(), t);
            }
        } finally {
            try {
                httpResponse.getEntity().getContent().close();
            } catch (Throwable ignored) {
            }
        }
    }
}

From source file:com.zotoh.crypto.MICUte.java

/**
 * Calculates a Message Integrity Check (Message Disposition)
 *
 * @param content The content across which the MIC is calculated. This can
 *                   be of type InputStream, String, byte[], or a Multipart (multipart/signed)
 * @param algorithm  The algorithm to use to calculate the MIC (e.g. sha1, md5)
 * @param addcrlfToString If true, adds a CRLF on the String data
 *                   since the receiving MTA uses canonicalized data to calculate MIC
 * @param addcrlfTobyte If true, adds a CRLF on the byte data
 *                   since the receiving MTA uses canonicalized data to calculate MIC
 * @return The base 64 encoded MIC value
 * @exception Exception/*from   w  ww .  j  av a 2 s  . c om*/
 */
public static String calc(Object content, Certificate[] certs, String algo, boolean addcrlfToString,
        boolean addcrlfToBytes) throws Exception {
    InputStream micStream = null;
    byte micBits[] = null;
    boolean addcrlf = false;

    if (content instanceof byte[]) {
        micBits = fromBytes((byte[]) content, addcrlfToBytes);
    } else if (content instanceof String) {
        micBits = fromString((String) content, addcrlfToString);
    } else if (content instanceof InputStream) {
        if (addcrlfToBytes || addcrlfToString)
            addcrlf = true;
        micStream = (InputStream) content;
    } else if (CryptoUte.isSigned(content)) {
        return fromSMP(certs, content);
    } else if (content instanceof Multipart) {
        Object rc = fromMP((Multipart) content);
        if (rc instanceof InputStream)
            micStream = (InputStream) rc;
        else if (rc instanceof byte[])
            micBits = (byte[]) rc;
    } else {
        error(content);
    }

    MessageDigest messageDigest = MessageDigest.getInstance(algo);
    byte[] mic;

    if (micBits != null) {
        mic = messageDigest.digest(micBits);
    } else {
        byte[] buf = new byte[4096];
        int c;
        while ((c = micStream.read(buf)) > 0) {
            messageDigest.update(buf, 0, c);
        }

        if (addcrlf) {
            messageDigest.update(CRLFBITS);
        }

        if (micStream.markSupported())
            micStream.reset();

        mic = messageDigest.digest();
    }

    return Base64.encodeBase64String(mic);
}

From source file:fr.mby.utils.common.io.StreamRepositoryTest.java

/** Not thread safe ! */
@Test/*from w ww . ja  va  2 s  .com*/
@Ignore
public void loadTest() throws Exception {

    final StreamRepository repo = new StreamRepository();

    final InputStream inputStream = repo.getInputStream();
    final OutputStream outputStream = repo.getOutputStream();

    new LoadRunner<StreamRepositoryTest, Void>(500, 10, this) {

        @Override
        protected Void loadTest(final StreamRepositoryTest unitTest) throws Exception {
            IOUtils.toString(inputStream);
            outputStream.write(StreamRepositoryTest.BYTE_WORD_1);
            outputStream.flush();
            IOUtils.toString(inputStream);
            outputStream.write(StreamRepositoryTest.BYTE_WORD_3);
            inputStream.reset();
            outputStream.write(StreamRepositoryTest.BYTE_WORD_2);
            outputStream.flush();

            return null;
        }

    };
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

/**
 * Reads the beginning of the stream to parse the label.
 *
 * @param inputStream a stream that must either support mark or be a StreamCache so that it can be reset.
 *
 * @return the label parsed from the stream
 *
 * @throws IllegalMessageStructureException if the label cannot be parsed or if the stream cannot be
 * reset after the label has been parsed.
 *///  ww w  . j a v a 2s.co  m
public ShsLabel parseLabel(InputStream inputStream) throws IllegalMessageStructureException {

    try {
        // Mark might not be supported
        inputStream.mark(4096);
        byte[] buffer = new byte[4096];
        IOUtils.read(inputStream, buffer, 0, 4096);

        // Will throw IOException if the InputStream mark has been invalidated
        // or if the stream does not support mark and is not a StreamCache
        inputStream.reset();

        String xml = StringUtils.substringBetween(new String(buffer, Charset.forName("ISO-8859-1")),
                "<shs.label ", "</shs.label>");
        if (xml == null) {
            throw new IllegalMessageStructureException("shs label not found in: " + new String(buffer));
        }
        ShsLabel label = shsLabelMarshaller.unmarshal("<shs.label " + xml + "</shs.label>");
        return label;
    } catch (IOException e) {
        throw new IllegalMessageStructureException("Error parsing label xml", e);
    }
}

From source file:com.akalizakeza.apps.ishusho.activity.NewPostUploadTaskFragment.java

public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException {
    InputStream stream = new BufferedInputStream(
            mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());//from   w w  w  .j  a va2  s  .c  o m
    BitmapFactory.Options options = new BitmapFactory.Options();
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}