Example usage for java.io ByteArrayInputStream reset

List of usage examples for java.io ByteArrayInputStream reset

Introduction

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

Prototype

public synchronized void reset() 

Source Link

Document

Resets the buffer to the marked position.

Usage

From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java

public static TLV getNextTLV(final ByteArrayInputStream stream) {
    if (stream.available() < 2) {
        throw new TlvException("Error parsing data. Available bytes < 2 . Length=" + stream.available());
    }/*from  w  ww  .  java  2 s.  c  o m*/

    // ISO/IEC 7816 uses neither '00' nor 'FF' as tag value.
    // Before, between, or after TLV-coded data objects,
    // '00' or 'FF' bytes without any meaning may occur
    // (for example, due to erased or modified TLV-coded data objects).

    stream.mark(0);
    int peekInt = stream.read();
    byte peekByte = (byte) peekInt;
    // peekInt == 0xffffffff indicates EOS
    while (peekInt != -1 && (peekByte == (byte) 0xFF || peekByte == (byte) 0x00)) {
        stream.mark(0); // Current position
        peekInt = stream.read();
        peekByte = (byte) peekInt;
    }
    stream.reset(); // Reset back to the last known position without 0x00 or 0xFF

    if (stream.available() < 2) {
        throw new TlvException("Error parsing data. Available bytes < 2 . Length=" + stream.available());
    }

    byte[] tagIdBytes = TlvUtil.readTagIdBytes(stream);

    // We need to get the raw length bytes.
    // Use quick and dirty workaround
    stream.mark(0);
    int posBefore = stream.available();
    // Now parse the lengthbyte(s)
    // This method will read all length bytes. We can then find out how many bytes was read.
    int length = TlvUtil.readTagLength(stream); // Decoded
    // Now find the raw (encoded) length bytes
    int posAfter = stream.available();
    stream.reset();
    byte[] lengthBytes = new byte[posBefore - posAfter];

    if (lengthBytes.length < 1 || lengthBytes.length > 4) {
        throw new TlvException("Number of length bytes must be from 1 to 4. Found " + lengthBytes.length);
    }

    stream.read(lengthBytes, 0, lengthBytes.length);

    int rawLength = BytesUtils.byteArrayToInt(lengthBytes);

    byte[] valueBytes;

    ITag tag = searchTagById(tagIdBytes);

    // Find VALUE bytes
    if (rawLength == 128) { // 1000 0000
        // indefinite form
        stream.mark(0);
        int prevOctet = 1;
        int curOctet;
        int len = 0;
        while (true) {
            len++;
            curOctet = stream.read();
            if (curOctet < 0) {
                throw new TlvException(
                        "Error parsing data. TLV " + "length byte indicated indefinite length, but EOS "
                                + "was reached before 0x0000 was found" + stream.available());
            }
            if (prevOctet == 0 && curOctet == 0) {
                break;
            }
            prevOctet = curOctet;
        }
        len -= 2;
        valueBytes = new byte[len];
        stream.reset();
        stream.read(valueBytes, 0, len);
        length = len;
    } else {
        if (stream.available() < length) {
            throw new TlvException("Length byte(s) indicated " + length + " value bytes, but only "
                    + stream.available() + " " + (stream.available() > 1 ? "are" : "is") + " available");
        }
        // definite form
        valueBytes = new byte[length];
        stream.read(valueBytes, 0, length);
    }

    // Remove any trailing 0x00 and 0xFF
    stream.mark(0);
    peekInt = stream.read();
    peekByte = (byte) peekInt;
    while (peekInt != -1 && (peekByte == (byte) 0xFF || peekByte == (byte) 0x00)) {
        stream.mark(0);
        peekInt = stream.read();
        peekByte = (byte) peekInt;
    }
    stream.reset(); // Reset back to the last known position without 0x00 or 0xFF

    return new TLV(tag, length, lengthBytes, valueBytes);
}

From source file:com.reydentx.core.common.PhotoUtils.java

public static byte[] resizeImage(ByteArrayInputStream data, int img_width, int img_height, boolean isPNG) {
    BufferedImage originalImage;//  w  ww  .  jav  a 2 s  .  co  m
    try {
        originalImage = ImageIO.read(data);
        Dimension origDimentsion = new Dimension(originalImage.getWidth(), originalImage.getHeight());
        Dimension fitDimentsion = new Dimension(img_width, img_height);

        // Dimension dimentsion = getScaledDimension(origDimentsion, fitDimentsion);
        Dimension dimentsion = fitDimentsion;
        if (origDimentsion.width != dimentsion.width || origDimentsion.height != dimentsion.height) {

            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            BufferedImage resizedImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT,
                    dimentsion.width, dimentsion.height, Scalr.OP_ANTIALIAS);

            if (isPNG) {
                ImageIO.write(resizedImage, "png", outstream);
            } else {
                ImageIO.write(resizedImage, "jpg", outstream);
            }

            return outstream.toByteArray();
        } else {
            data.reset();
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            byte[] read = new byte[2048];
            int i = 0;
            while ((i = data.read(read)) > 0) {
                byteArray.write(read, 0, i);
            }
            data.close();
            return byteArray.toByteArray();
        }
    } catch (Exception ex) {
    }
    return null;
}

From source file:io.aino.agents.wso2.mediator.factory.AinoMediatorFactory.java

private void initializeAinoAgent(ByteArrayInputStream confStream) {
    if (ainoInitLock.tryLock()) {
        try {/*from  w  w w  .  ja  va  2  s . c om*/
            if (ainoAgent != null)
                return;
            confStream.reset();
            ainoAgent = Agent.getFactory().setConfigurationBuilder(new InputStreamConfigBuilder(confStream))
                    .build();
            if (ainoAgent.isEnabled() && !ainoAgent.applicationExists("esb")) {
                throw new InvalidAgentConfigException("application with key 'esb' must be configured.");
            }
        } finally {
            ainoInitLock.unlock();
        }
    }
}

From source file:inti.core.codec.base64.Base64InputStreamPerformanceTest.java

public void readPerformance(int count, int bufferSize) throws Exception {
    byte[] data = new byte[bufferSize];
    long start, end;
    StringBuilder message = new StringBuilder();
    ByteArrayInputStream inputData;
    Base64 b64 = new Base64();

    for (int i = 0; i < bufferSize / 10; i++) {
        message.append("0123456789");
    }/* w  w w  . ja va 2 s.  c o m*/

    byte[] inputBytes = message.toString().getBytes(Charset.forName("utf-8"));

    inputData = new ByteArrayInputStream(inputBytes);

    for (int i = 0; i < 10; i++) {
        input.reset(inputData, null);
        inputData.reset();
        input.read(data);
    }

    for (int i = 0; i < 100; i++) {
        Thread.sleep(10);
    }

    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        input.reset(inputData, null);
        inputData.reset();
        input.read(data);
    }
    end = System.currentTimeMillis();
    System.out.format("readPerformance(Inti) - size: %d, duration: %dms, ratio: %#.4f", bufferSize, end - start,
            count / ((end - start) / 1000.0));
    System.out.println();

    for (int i = 0; i < 10; i++) {
        b64.decode(inputBytes);
    }

    for (int i = 0; i < 100; i++) {
        Thread.sleep(10);
    }

    start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        b64.decode(inputBytes);
    }
    end = System.currentTimeMillis();
    System.out.format("readPerformance(commons.decode) - size: %d, duration: %dms, ratio: %#.4f", bufferSize,
            end - start, count / ((end - start) / 1000.0));
    System.out.println();
}

From source file:J2MEWriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//w ww .j  ava2 s . c o  m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//ww w  .  ja  va 2  s .  c om
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:org.duracloud.integration.storageprovider.TestStorageProvider.java

private void addContent(String spaceId, String contentId, String mimeType, boolean checksumInAdvance) {
    byte[] content = CONTENT_DATA.getBytes();
    ByteArrayInputStream contentStream = new ByteArrayInputStream(content);

    String advChecksum = null;/* w w w  . j  a  v  a 2s  . co m*/
    if (checksumInAdvance) {
        ChecksumUtil util = new ChecksumUtil(ChecksumUtil.Algorithm.MD5);
        advChecksum = util.generateChecksum(contentStream);
        contentStream.reset();
    }

    String checksum = doAddContent(spaceId, contentId, content.length, contentStream, mimeType, advChecksum);

    if (checksumInAdvance) {
        assertEquals(advChecksum, checksum);
    }
}

From source file:org.rundeck.api.ApiCall.java

/**
 * Execute an HTTP GET request to the Rundeck instance, on the given path. We will login first, and then execute the
 * API call without appending the API_ENDPOINT to the URL.
 *
 * @param apiPath on which we will make the HTTP request - see {@link ApiPathBuilder}
 * @return a new {@link InputStream} instance, not linked with network resources
 * @throws RundeckApiException in case of error when calling the API
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 *//*from w  ww .ja v  a2s .c o m*/
public InputStream getNonApi(ApiPathBuilder apiPath)
        throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException {
    HttpGet request = new HttpGet(client.getUrl() + apiPath);
    if (null != apiPath.getAccept()) {
        request.setHeader("Accept", apiPath.getAccept());
    }
    ByteArrayInputStream response = execute(request);
    response.reset();

    return response;
}

From source file:ReadWriteStreams.java

public void readStream() {
    try {/*from   www  .  j a v a  2 s .c om*/
        // Careful: Make sure this is big enough!
        // Better yet, test and reallocate if necessary      
        byte[] recData = new byte[50];

        // Read from the specified byte array
        ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);

        // Read Java data types from the above byte array
        DataInputStream strmDataType = new DataInputStream(strmBytes);

        for (int i = 1; i <= rs.getNumRecords(); i++) {
            // Get data into the byte array
            rs.getRecord(i, recData, 0);

            // Read back the data types      
            System.out.println("Record #" + i);
            System.out.println("UTF: " + strmDataType.readUTF());
            System.out.println("Boolean: " + strmDataType.readBoolean());
            System.out.println("Int: " + strmDataType.readInt());
            System.out.println("--------------------");

            // Reset so read starts at beginning of array 
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:com.cyberway.issue.io.arc.ARCRecord.java

/**
* Read http header if present. Technique borrowed from HttpClient HttpParse
* class./*from  w w w  . j av a2  s . c  o m*/
* 
* @return ByteArrayInputStream with the http header in it or null if no
*         http header.
* @throws IOException
*/
private InputStream readHttpHeader() throws IOException {
    // If judged a record that doesn't have an http header, return
    // immediately.
    if (!getHeader().getUrl().startsWith("http") || getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) {
        return null;
    }
    byte[] statusBytes = HttpParser.readRawLine(getIn());
    int eolCharCount = getEolCharsCount(statusBytes);
    if (eolCharCount <= 0) {
        throw new IOException("Failed to read http status where one was expected: "
                + ((statusBytes == null) ? "" : new String(statusBytes)));
    }
    String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount,
            ARCConstants.DEFAULT_ENCODING);
    if ((statusLine == null) || !StatusLine.startsWithHTTP(statusLine)) {
        if (statusLine.startsWith("DELETED")) {
            // Some old ARCs have deleted records like following:
            // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202
            // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist
            // (follows ~29K spaces)
            // For now, throw a RecoverableIOException so if iterating over
            // records, we keep going.  TODO: Later make a legitimate
            // ARCRecord from the deleted record rather than throw
            // exception.
            throw new DeletedARCRecordIOException(statusLine);
        } else {
            throw new IOException("Failed parse of http status line.");
        }
    }
    this.httpStatus = new StatusLine(statusLine);

    // Save off all bytes read.  Keep them as bytes rather than
    // convert to strings so we don't have to worry about encodings
    // though this should never be a problem doing http headers since
    // its all supposed to be ascii.
    ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024);
    baos.write(statusBytes);

    // Now read rest of the header lines looking for the separation
    // between header and body.
    for (byte[] lineBytes = null; true;) {
        lineBytes = HttpParser.readRawLine(getIn());
        eolCharCount = getEolCharsCount(lineBytes);
        if (eolCharCount <= 0) {
            throw new IOException(
                    "Failed reading http headers: " + ((lineBytes != null) ? new String(lineBytes) : null));
        }
        // Save the bytes read.
        baos.write(lineBytes);
        if ((lineBytes.length - eolCharCount) <= 0) {
            // We've finished reading the http header.
            break;
        }
    }

    byte[] headerBytes = baos.toByteArray();
    // Save off where body starts.
    this.getMetaData().setContentBegin(headerBytes.length);
    ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes);
    if (!bais.markSupported()) {
        throw new IOException("ByteArrayInputStream does not support mark");
    }
    bais.mark(headerBytes.length);
    // Read the status line.  Don't let it into the parseHeaders function.
    // It doesn't know what to do with it.
    bais.read(statusBytes, 0, statusBytes.length);
    this.httpHeaders = HttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING);
    this.getMetaData().setStatusCode(Integer.toString(getStatusCode()));
    bais.reset();
    return bais;
}