Example usage for java.io InputStream markSupported

List of usage examples for java.io InputStream markSupported

Introduction

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

Prototype

public boolean markSupported() 

Source Link

Document

Tests if this input stream supports the mark and reset methods.

Usage

From source file:org.lockss.plugin.atypon.BaseAtyponRisFilterFactory.java

public InputStream createFilteredInputStream(ArchivalUnit au, InputStream in, String encoding)
        throws PluginException {

    InputStream inBuf = null; // to make sure mark() is supported
    /* //from   w  w w . j  a v  a2s  .c  om
     * RIS files are collected with content type text/plain (encoding) and so
     * we have to filter all text/plain and then determine if they're a RIS file 
     * here.  We are working on a different long-term solution by allowing us to verify
     * the URL against a regexp.
     */

    BufferedReader bReader;

    if (in.markSupported() != true) {
        inBuf = new BufferedInputStream(in); //wrap the one that came in
    } else {
        inBuf = in; //use the one passed in
    }
    int BUF_LEN = 2000;
    inBuf.mark(BUF_LEN); // not sure about the limit...just reading far enough to identify file type

    try {
        //Now create a BoundedInputReader to make sure that we don't overstep our reset mark
        bReader = new BufferedReader(new InputStreamReader(new BoundedInputStream(inBuf, BUF_LEN), encoding));

        String aLine = bReader.readLine();
        // The first tag in a RIS file must be "TY - "; be nice about WS
        // The specification doesn't allow for comments or other preceding characters

        // isBlank() checks if whitespace, empty or null
        // keep initial null check or you'd never exit loop if you hit the end of input!
        while (aLine != null && StringUtils.isBlank(aLine)) {
            aLine = bReader.readLine(); // get the next line
        }

        // do NOT close bReader - it would also close underlying inBuf!
        inBuf.reset();
        // if we have  data, see if it matches the RIS pattern
        if (aLine != null && RIS_PATTERN.matcher(aLine).find()) {
            return new RisFilterInputStream(inBuf, encoding, "Y2");
        }
        return inBuf; // If not a RIS file, just return reset file
    } catch (UnsupportedEncodingException e) {
        log.debug2("Internal error (unsupported encoding)", e);
        throw new PluginException("Unsupported encoding looking ahead in input stream", e);
    } catch (IOException e) {
        log.debug2("Internal error (IO exception)", e);
        throw new PluginException("IO exception looking ahead in input stream", e);
    }
}

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  w w .j av  a2  s . co m*/
 */
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:com.zimbra.cs.mime.Mime.java

private static Charset detectCharset(InputStream input, Charset defaultCharset) {
    assert (input.markSupported());

    if (defaultCharset == null) {
        defaultCharset = Charset.defaultCharset();
    }/*from  www  . j a v a  2  s. c  o m*/
    CharsetDetector detector = new CharsetDetector();
    try {
        detector.setText(input);
    } catch (IOException e) {
        return defaultCharset;
    }

    for (CharsetMatch match : detector.detectAll()) { // matches are sorted by confidence
        if (match.getConfidence() > 50) { // only trust good match
            try {
                return Charset.forName(match.getName());
            } catch (Exception ignore) {
            }
        } else {
            break;
        }
    }

    return defaultCharset;
}

From source file:org.xwiki.resource.servlet.AbstractServletResourceReferenceHandler.java

/**
 * Sends back the specified resource.//from   w w  w .  j  a  v  a 2 s.c  o  m
 *
 * @param resourceReference the reference of the requested resource
 * @param rawResourceStream the resource stream used to read the resource
 * @throws ResourceReferenceHandlerException if it fails to read the resource
 */
private void serveResource(R resourceReference, InputStream rawResourceStream)
        throws ResourceReferenceHandlerException {
    InputStream resourceStream = rawResourceStream;
    String resourceName = getResourceName(resourceReference);

    // Make sure the resource stream supports mark & reset which is needed in order be able to detect the
    // content type without affecting the stream (Tika may need to read a few bytes from the start of the
    // stream, in which case it will mark & reset the stream).
    if (!resourceStream.markSupported()) {
        resourceStream = new BufferedInputStream(resourceStream);
    }

    try {
        Response response = this.container.getResponse();
        setResponseHeaders(response, resourceReference);
        response.setContentType(this.tika.detect(resourceStream, resourceName));
        IOUtils.copy(resourceStream, response.getOutputStream());
    } catch (Exception e) {
        throw new ResourceReferenceHandlerException(String.format("Failed to read resource [%s]", resourceName),
                e);
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}

From source file:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

protected InputStream getBinaryRequestPayloadStreamWithoutQueryParams(Request<?> request) {
    try {//from  ww  w.j a v a2 s.c om
        InputStream content = request.getContent();
        if (content == null)
            return new ByteArrayInputStream(new byte[0]);

        if (content instanceof StringInputStream) {
            return content;
        }

        if (!content.markSupported()) {
            throw new AmazonClientException("Unable to read request payload to sign request.");
        }

        return request.getContent();
    } catch (Exception e) {
        throw new AmazonClientException("Unable to read request payload to sign request: " + e.getMessage(), e);
    }
}

From source file:org.archive.io.arc.ARCWriterTest.java

public void testArchiveRecordMarkSupport() throws Exception {
    ARCReader r = getSingleRecordReader("testArchiveRecordMarkSupport");
    ARCRecord record = getSingleRecord(r);
    record.setStrict(true);/*w  w  w  .  j a  v  a2s  .  co  m*/
    // ensure mark support
    InputStream stream = new BufferedInputStream(record);
    if (stream.markSupported()) {
        for (int i = 0; i < 3; i++) {
            this.readToEOS(stream);
            stream.mark(stream.available());
            stream.reset();
        }
        stream.close();
    }
    r.close();
}

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

protected InputStream getBinaryRequestPayloadStreamWithoutQueryParams(Request<?> request) {
    try {/*from  ww  w .ja va 2 s  .com*/
        InputStream content = request.getContent();
        if (content == null)
            return new ByteArrayInputStream(new byte[0]);

        if (content instanceof StringInputStream) {
            return content;
        }

        if (!content.markSupported()) {
            throw new LunacloudClientException("Unable to read request payload to sign request.");
        }

        return request.getContent();
    } catch (Exception e) {
        throw new LunacloudClientException("Unable to read request payload to sign request: " + e.getMessage(),
                e);
    }
}

From source file:org.powertac.logtool.LogtoolCore.java

/**
 * Reads state-log from given input stream using the DomainObjectReader.
 *//*  w  w  w.ja  v a 2 s .co m*/
public String readStateLog(InputStream inputStream, Analyzer... tools) {
    Reader inputReader;
    String line = null;

    log.info("Reading state log from stream for {}", tools[0].getClass().getName());
    simEnd = false;
    isInterrupted = false;

    try {
        // Stack compression logic if appropriate
        try {
            if (!inputStream.markSupported()) {
                inputStream = new BufferedInputStream(inputStream);
            }
            inputStream = compressFactory.createCompressorInputStream(inputStream);
        } catch (CompressorException x) {
            // Stream not compressed (or unknown compression scheme)
        }

        // Stack archive logic if appropriate
        try {
            if (!inputStream.markSupported()) {
                inputStream = new BufferedInputStream(inputStream);
            }
            ArchiveInputStream archiveStream = archiveFactory.createArchiveInputStream(inputStream);
            ArchiveEntry entry;
            inputStream = null;
            while ((entry = archiveStream.getNextEntry()) != null) {
                String name = entry.getName();
                if (entry.isDirectory() || !name.startsWith("log/") || !name.endsWith(".state")
                        || name.endsWith("init.state")) {
                    continue;
                }
                inputStream = archiveStream;
                break;
            }
            if (inputStream == null) {
                return "Cannot read archive, no valid state log entry";
            }
        } catch (ArchiveException x) {
            // Stream not archived (or unknown archiving scheme)
        }

        // Recycle repos from previous session
        List<DomainRepo> repos = SpringApplicationContext.listBeansOfType(DomainRepo.class);
        for (DomainRepo repo : repos) {
            repo.recycle();
        }

        // Now go read the state-log
        inputReader = new InputStreamReader(inputStream);
        for (Analyzer tool : tools) {
            log.info("Setting up {}", tool.getClass().getName());
            tool.setup();
        }
        BufferedReader in = new BufferedReader(inputReader);
        int lineNumber = 0;
        while (!simEnd) {
            synchronized (this) {
                if (isInterrupted) {
                    in.close();
                    break;
                }
            }
            line = in.readLine();
            if (null == line) {
                log.info("Last line " + lineNumber);
                break;
            }
            lineNumber += 1;
            reader.readObject(line);
        }
        builder.report();
        for (Analyzer tool : tools) {
            tool.report();
        }
    } catch (IOException e) {
        return "Error reading from stream";
    } catch (MissingDomainObject e) {
        return "MDO on " + line;
    }
    return null;
}

From source file:com.sina.auth.AbstractAWSSigner.java

protected InputStream getBinaryRequestPayloadStreamWithoutQueryParams(Request<?> request) {
    try {//from   w ww. j a  v a  2 s .  co  m
        InputStream content = request.getContent();
        if (content == null)
            return new ByteArrayInputStream(new byte[0]);

        if (content instanceof StringInputStream) {
            return content;
        }

        if (!content.markSupported()) {
            throw new SCSClientException("Unable to read request payload to sign request.");
        }

        return request.getContent();
    } catch (Exception e) {
        throw new SCSClientException("Unable to read request payload to sign request: " + e.getMessage(), e);
    }
}

From source file:org.apache.tika.parser.pkg.PackageExtractor.java

public void parse(InputStream stream) throws IOException, SAXException, TikaException {
    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();/*from  w w  w. j  a  v a  2s .  co  m*/

    // At the end we want to close the package/compression stream to
    // release any associated resources, but the underlying document
    // stream should not be closed
    stream = new CloseShieldInputStream(stream);

    // Capture two bytes to determine the packaging/compression format
    if (!stream.markSupported()) {
        stream = new BufferedInputStream(stream);
    }
    stream.mark(2);
    int a = stream.read();
    int b = stream.read();
    stream.reset();

    // Select decompression or unpacking mechanism based on the two bytes
    if (a == 'B' && b == 'Z') {
        metadata.set(Metadata.CONTENT_TYPE, "application/x-bzip");
        decompress(new BZip2CompressorInputStream(stream), xhtml);
    } else if (a == 0x1f && b == 0x8b) {
        metadata.set(Metadata.CONTENT_TYPE, "application/x-gzip");
        decompress(new GZIPInputStream(stream), xhtml);
    } else if (a == 'P' && b == 'K') {
        metadata.set(Metadata.CONTENT_TYPE, "application/zip");
        unpack(new ZipArchiveInputStream(stream), xhtml);
    } else if ((a == '0' && b == '7') || (a == 0x71 && b == 0xc7) || (a == 0xc7 && b == 0x71)) {
        metadata.set(Metadata.CONTENT_TYPE, "application/x-cpio");
        unpack(new CpioArchiveInputStream(stream), xhtml);
    } else if (a == '=' && (b == '<' || b == '!')) {
        metadata.set(Metadata.CONTENT_TYPE, "application/x-archive");
        unpack(new ArArchiveInputStream(stream), xhtml);
    } else {
        metadata.set(Metadata.CONTENT_TYPE, "application/x-tar");
        unpack(new TarArchiveInputStream(stream), xhtml);
    }

    xhtml.endDocument();
}