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.xwiki.filter.xar.internal.input.XARInputFilterStream.java

private Boolean isZip(InputStream stream) throws IOException {
    if (!stream.markSupported()) {
        // ZIP by default
        return null;
    }//from  w ww  .  j a v a  2 s  .co  m

    final byte[] signature = new byte[12];
    stream.mark(signature.length);
    int signatureLength = stream.read(signature);
    stream.reset();

    return ZipArchiveInputStream.matches(signature, signatureLength);
}

From source file:TypeUtil.java

public static byte[] readLine(InputStream in) throws IOException {
    byte[] buf = new byte[256];

    int i = 0;//from   w w  w  . java  2 s  . c  o  m
    int loops = 0;
    int ch = 0;

    while (true) {
        ch = in.read();
        if (ch < 0)
            break;
        loops++;

        // skip a leading LF's
        if (loops == 1 && ch == LF)
            continue;

        if (ch == CR || ch == LF)
            break;

        if (i >= buf.length) {
            byte[] old_buf = buf;
            buf = new byte[old_buf.length + 256];
            System.arraycopy(old_buf, 0, buf, 0, old_buf.length);
        }
        buf[i++] = (byte) ch;
    }

    if (ch == -1 && i == 0)
        return null;

    // skip a trailing LF if it exists
    if (ch == CR && in.available() >= 1 && in.markSupported()) {
        in.mark(1);
        ch = in.read();
        if (ch != LF)
            in.reset();
    }

    byte[] old_buf = buf;
    buf = new byte[i];
    System.arraycopy(old_buf, 0, buf, 0, i);

    return buf;
}

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

/**
 * @param inputStream/*ww w .j a  va 2  s . co  m*/
 */
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:org.apache.jackrabbit.core.data.DBDataStoreTest.java

public void testDbInputStreamReset() throws Exception {
    DataRecord record = store.getRecord(identifier);
    InputStream in = record.getStream();
    try {/*from w w  w  .j  av a2 s  .  co  m*/
        // test whether mark and reset works
        assertTrue(in.markSupported());
        in.mark(data.length);
        while (-1 != in.read()) {
            // loop
        }
        assertTrue(in.markSupported());
        try {
            in.reset();
        } catch (Exception e) {
            fail("Unexpected exception while resetting input stream: " + e.getMessage());
        }

        // test integrity of replayed bytes
        byte[] replayedBytes = new byte[data.length];
        int length = in.read(replayedBytes);
        assertEquals(length, data.length);

        for (int i = 0; i < data.length; i++) {
            log.append(i + " data: " + data[i] + " replayed: " + replayedBytes[i] + "\n");
            assertEquals(data[i], replayedBytes[i]);
        }

        assertEquals(-1, in.read());

    } finally {
        in.close();
        log.flush();
    }
}

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;/*from www  .ja v  a  2 s.  c  om*/
    }

    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:cn.vlabs.clb.server.ui.frameservice.image.ImageUtil.java

private List<String> validateImage(InputStream ins) {
    List<String> lines = new ArrayList<String>();
    try {/*from ww w .  ja v a  2s  .  c  o  m*/
        ins.mark(0);
        IMOperation op = new IMOperation();
        op.format(SUCCESS_PREFIX + " %m %w %h %n %p\n");
        IdentifyCmd idcmd = new IdentifyCmd(true);
        Pipe pipeIn = new Pipe(ins, null);
        ArrayListOutputConsumer output = new ArrayListOutputConsumer();
        idcmd.setInputProvider(pipeIn);
        idcmd.setOutputConsumer(output);
        op.addImage("-");
        idcmd.run(op);
        lines = output.getOutput();
    } catch (IOException | InterruptedException | IM4JavaException e) {
        LOG.error(e.getMessage(), e);
    } catch (RuntimeException e) {
        LOG.error(e.getMessage(), e);
    }
    return lines;
}

From source file:org.cytoscape.io.internal.read.GenericReaderManager.java

public R getReader(InputStream stream, String inputName) {
    try {/*from w  w  w  .j  a  v  a  2s  .co  m*/
        if (!stream.markSupported()) {
            stream = new BufferedInputStream(stream);
            stream.mark(1025);
        }

        for (T factory : factories) {
            CyFileFilter cff = factory.getFileFilter();
            logger.debug("trying READER: " + factory + " with filter: " + cff);

            // Because we don't know who will provide the file filter or
            // what they might do with the InputStream, we provide a copy
            // of the first 2KB rather than the stream itself.
            if (cff.accepts(CopyInputStream.copyKBytes(stream, 1), category)) {
                logger.debug("successfully matched READER " + factory);
                return (R) factory.createTaskIterator(stream, inputName).next();
            }
        }
    } catch (IOException ioe) {
        logger.warn("Error setting input stream", ioe);
    }

    logger.warn("No reader found for input stream");
    return null;
}

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

/**
 * Calculate the hash of the request's payload.
 * Subclass could override this method to provide different values for "x-amz-content-sha256" header
 * or do any other necessary set-ups on the request headers.
 * (e.g. aws-chunked uses a pre-defined header value, and needs to change some headers
 * relating to content-encoding and content-length.)
 *///ww w.  jav  a  2s.c  om
protected String calculateContentHash(Request<?> request) {
    InputStream payloadStream = getBinaryRequestPayloadStream(request);
    payloadStream.mark(-1);
    String contentSha256 = BinaryUtils.toHex(hash(payloadStream));
    try {
        payloadStream.reset();
    } catch (IOException e) {
        throw new AmazonClientException("Unable to reset stream after calculating AWS4 signature", e);
    }
    return contentSha256;
}

From source file:org.xmlactions.email.EMailParser.java

private void addContent(InputStream inputStream) throws DocumentException, IOException {

    if (inputStream.markSupported()) {
        inputStream.mark(inputStream.available());
    }/*  w w  w  .ja v a 2s  .  co  m*/

    String bodyContent = IOUtils.toString(inputStream);

    if (this.firstMessageProcessed == false) {
    }
    if (inputStream.markSupported()) {
        inputStream.reset();
    }
}

From source file:com.btoddb.chronicle.catchers.RestCatcherImpl.java

public boolean isJsonArray(InputStream inStream) {
    if (null == inStream) {
        return false;
    }/*from   w  w  w.  j  ava  2 s. co  m*/

    int count = 100;
    inStream.mark(count);
    int ch;
    try {
        do {
            ch = inStream.read();
        } while ('[' != ch && '{' != ch && Character.isWhitespace((char) ch) && -1 != ch && --count > 0);

        inStream.reset();
        if (0 == count) {
            Utils.logAndThrow(logger, "unrecognizable JSON, or too much whitespace before JSON doc starts");
        }
        return '[' == ch;
    } catch (IOException e) {
        Utils.logAndThrow(logger, "exception while looking for JSON in InputStream", e);
    }

    return false;
}