Example usage for java.io ByteArrayOutputStream reset

List of usage examples for java.io ByteArrayOutputStream reset

Introduction

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

Prototype

public synchronized void reset() 

Source Link

Document

Resets the count field of this ByteArrayOutputStream to zero, so that all currently accumulated output in the output stream is discarded.

Usage

From source file:ReadWriteStreams.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {//from   w ww  . j a  va2 s.c o m
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

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

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

From source file:com.basho.riak.client.response.TestFetchResponse.java

@Test
public void returns_streamed_collection_on_streaming_300_response() throws IOException {
    final ByteArrayInputStream is = new ByteArrayInputStream(SIBLING_BODY.getBytes());

    when(mockHttpResponse.getStatusCode()).thenReturn(300);
    when(mockHttpResponse.getBucket()).thenReturn(BUCKET);
    when(mockHttpResponse.getKey()).thenReturn(KEY);
    when(mockHttpResponse.getHttpHeaders()).thenReturn(SIBLING_HEADERS);
    when(mockHttpResponse.isStreamed()).thenReturn(true);
    when(mockHttpResponse.getStream()).thenReturn(is);

    FetchResponse impl = new FetchResponse(mockHttpResponse, mockRiakClient);
    assertTrue(impl.hasSiblings());/*from   www.  jav a 2 s  .c o  m*/
    assertTrue(impl.getSiblings() instanceof StreamedSiblingsCollection);

    Iterator<RiakObject> siblings = impl.getSiblings().iterator();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    RiakObject o;
    o = siblings.next();
    ClientUtils.copyStream(o.getValueStream(), os);

    assertSame(mockRiakClient, o.getRiakClient());
    assertEquals(BUCKET, o.getBucket());
    assertEquals(KEY, o.getKey());
    assertEquals("text/plain", o.getContentType());
    assertEquals("bar", os.toString());
    assertEquals(1, o.numLinks());
    assertFalse(o.hasUsermeta());
    assertEquals("Tue, 22 Dec 2009 19:24:18 GMT", o.getLastmod());
    assertEquals("a85hYGBgzmDKBVIsDPKZOzKYEhnzWBlaJyw9wgcVZtWdug4q/GgGXJitOYmh6u0rZIksAA==", o.getVclock());
    assertEquals("55SrI4GjdnGfyuShLBWjuf", o.getVtag());

    o = siblings.next();
    os.reset();
    ClientUtils.copyStream(o.getValueStream(), os);
    assertSame(mockRiakClient, o.getRiakClient());
    assertEquals(BUCKET, o.getBucket());
    assertEquals(KEY, o.getKey());
    assertEquals("application/octect-stream", o.getContentType());
    assertEquals("foo", os.toString());
    assertEquals("Tue, 22 Dec 2009 18:48:37 GMT", o.getLastmod());
    assertFalse(o.hasLinks());
    assertEquals(1, o.numUsermetaItems());
    assertEquals("value", o.getUsermetaItem("test"));
    assertEquals("a85hYGBgzmDKBVIsDPKZOzKYEhnzWBlaJyw9wgcVZtWdug4q/GgGXJitOYmh6u0rZIksAA==", o.getVclock());
    assertEquals("4d5y9wqQK2Do0RK5ezwCJD", o.getVtag());
}

From source file:com.basho.riak.client.http.response.TestFetchResponse.java

@Test
public void returns_streamed_collection_on_streaming_300_response() throws IOException {
    final ByteArrayInputStream is = new ByteArrayInputStream(utf8StringToBytes(SIBLING_BODY));

    when(mockHttpResponse.getStatusCode()).thenReturn(300);
    when(mockHttpResponse.getBucket()).thenReturn(BUCKET);
    when(mockHttpResponse.getKey()).thenReturn(KEY);
    when(mockHttpResponse.getHttpHeaders()).thenReturn(SIBLING_HEADERS);
    when(mockHttpResponse.isStreamed()).thenReturn(true);
    when(mockHttpResponse.getStream()).thenReturn(is);

    FetchResponse impl = new FetchResponse(mockHttpResponse, mockRiakClient);
    assertTrue(impl.hasSiblings());/*from w  w  w. j a v a 2s  .c o  m*/
    assertTrue(impl.getSiblings() instanceof StreamedSiblingsCollection);

    Iterator<RiakObject> siblings = impl.getSiblings().iterator();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    RiakObject o;
    o = siblings.next();
    ClientUtils.copyStream(o.getValueStream(), os);

    assertSame(mockRiakClient, o.getRiakClient());
    assertEquals(BUCKET, o.getBucket());
    assertEquals(KEY, o.getKey());
    assertEquals("text/plain", o.getContentType());
    assertEquals("bar", os.toString());
    assertEquals(1, o.numLinks());
    assertFalse(o.hasUsermeta());
    assertEquals("Tue, 22 Dec 2009 19:24:18 GMT", o.getLastmod());
    assertEquals("a85hYGBgzmDKBVIsDPKZOzKYEhnzWBlaJyw9wgcVZtWdug4q/GgGXJitOYmh6u0rZIksAA==", o.getVclock());
    assertEquals("55SrI4GjdnGfyuShLBWjuf", o.getVtag());

    o = siblings.next();
    os.reset();
    ClientUtils.copyStream(o.getValueStream(), os);
    assertSame(mockRiakClient, o.getRiakClient());
    assertEquals(BUCKET, o.getBucket());
    assertEquals(KEY, o.getKey());
    assertEquals("application/octect-stream", o.getContentType());
    assertEquals("foo", os.toString());
    assertEquals("Tue, 22 Dec 2009 18:48:37 GMT", o.getLastmod());
    assertFalse(o.hasLinks());
    assertEquals(1, o.numUsermetaItems());
    assertEquals("value", o.getUsermetaItem("test"));
    assertEquals("a85hYGBgzmDKBVIsDPKZOzKYEhnzWBlaJyw9wgcVZtWdug4q/GgGXJitOYmh6u0rZIksAA==", o.getVclock());
    assertEquals("4d5y9wqQK2Do0RK5ezwCJD", o.getVtag());
}

From source file:Main.java

/**
 * /*  w w  w . j  a va2  s  .  c o  m*/
 * @param elementName
 * @param is
 * @param onlyValues
 * @return Collection
 * @throws XMLStreamException
 * @throws UnsupportedEncodingException
 */
public static Collection<String> getElements(final String elementName, final InputStream is,
        final boolean onlyValues) throws XMLStreamException, UnsupportedEncodingException {
    final Collection<String> elements = new ArrayList<>();
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final XMLEventReader reader = XMLInputFactory.newInstance()
            .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name()));
    final XMLEventWriter writer = XMLOutputFactory.newInstance()
            .createXMLEventWriter(new OutputStreamWriter(os, Charset.defaultCharset().name()));
    boolean read = false;
    String characters = null;

    while (reader.peek() != null) {
        final XMLEvent event = (XMLEvent) reader.next();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT: {
            // Ignore.
            break;
        }
        case XMLStreamConstants.START_ELEMENT: {
            read = read || elementName.equals(event.asStartElement().getName().getLocalPart());

            if (read && !onlyValues) {
                writer.add(event);
            }

            break;
        }
        case XMLStreamConstants.ATTRIBUTE: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            break;
        }
        case XMLStreamConstants.CHARACTERS: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            characters = event.asCharacters().getData();
            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            if (elementName.equals(event.asEndElement().getName().getLocalPart())) {
                writer.flush();

                if (characters != null) {
                    elements.add(characters);
                }

                os.reset();
                read = false;
            }
            break;
        }
        default: {
            // Ignore
            break;
        }
        }
    }

    return elements;
}

From source file:com.ririjin.adminmobile.fragment.UpdateImageFragment.java

private Bitmap compressImage(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// ?100???baos
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100) { // ??100kb,
        baos.reset();// ?baos?baos
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);// options%??baos
        options -= 10;// ??10
    }/*from  w ww.  jav a 2 s  .  co m*/
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// ??baosByteArrayInputStream
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// ByteArrayInputStream??
    return bitmap;
}

From source file:org.ow2.bonita.CMISDocumentManagerTest.java

public void testUploadBigFile2() throws DocumentAlreadyExistsException, DocumentationCreationException,
        InterruptedException, IOException, DocumentNotFoundException {
    byte[] bytes = null;
    // to create bytes array 62Mb size
    ByteArrayOutputStream baos = null;
    try {/*from   ww w.j av a 2 s .c o m*/
        baos = new ByteArrayOutputStream();
        for (int i = 0; i < 8192; i++) {
            baos.write(43); // '+' char
        }
        byte[] bytesTemp = baos.toByteArray();
        baos.reset();
        for (int i = 0; i < 7600; i++) {
            baos.write(bytesTemp);
        }
        bytes = baos.toByteArray();
    } finally {
        baos.close();
    }

    ProcessDefinitionUUID definitionUUID = new ProcessDefinitionUUID("bigProcess2");
    int length = bytes.length;
    Document document = manager.createDocument("testUploadBigFile2", definitionUUID,
            new ProcessInstanceUUID(definitionUUID, 1), "testUploadBigFile2.txt", "octet/stream", bytes);
    assertNotNull(document);
    byte[] content = manager.getContent(document);
    assertNotNull(content);
    assertEquals(length, content.length);

    // remove
    manager.deleteDocument(document.getId(), true);
}

From source file:org.jwifisd.transcend.TranscendWiFiSD.java

@Override
public void run() {
    try {/*from w ww .  j  a v a 2s .co m*/
        InputStream inputStream = westec.getInputStream();
        int oneByte;

        ByteArrayOutputStream lineBytes = new ByteArrayOutputStream();
        while (thread == Thread.currentThread()) {
            oneByte = inputStream.read();
            if (oneByte < 0) {
                break;
            }
            if (oneByte != 0) {
                lineBytes.write(oneByte);
            } else {
                // line complete
                byte[] lineByteArray = lineBytes.toByteArray();
                int offset = 0;
                while (lineByteArray[offset] == '>' || lineByteArray[offset] == '<') {
                    offset++;
                }
                String line = new String(lineByteArray, offset, lineByteArray.length - offset, "UTF-8");
                TranscendWifiSDFile wifiFile = new TranscendWifiSDFile(this, line);
                notifyNewFile(wifiFile);
                lineBytes.reset();
            }
        }
    } catch (Exception e) {
        LOG.error("TranscendWiFiSD event channel broke!", e);
    } finally {
        thread = null;
    }
}

From source file:org.apache.hadoop.hbase.regionserver.DataBlockEncodingTool.java

/**
 * Check decompress performance of a given algorithm and print it.
 * @param algorithm Compression algorithm.
 * @param name Name of algorithm.//from w ww  . j a v a2s  .  c  om
 * @param buffer Buffer to be compressed.
 * @param offset Position of the beginning of the data.
 * @param length Length of data in buffer.
 * @throws IOException
 */
public void benchmarkAlgorithm(Compression.Algorithm algorithm, String name, byte[] buffer, int offset,
        int length) throws IOException {
    System.out.println(name + ":");

    // compress it
    List<Long> compressDurations = new ArrayList<Long>();
    ByteArrayOutputStream compressedStream = new ByteArrayOutputStream();
    CompressionOutputStream compressingStream = algorithm.createPlainCompressionStream(compressedStream,
            compressor);
    try {
        for (int itTime = 0; itTime < benchmarkNTimes; ++itTime) {
            final long startTime = System.nanoTime();
            compressingStream.resetState();
            compressedStream.reset();
            compressingStream.write(buffer, offset, length);
            compressingStream.flush();
            compressedStream.toByteArray();

            final long finishTime = System.nanoTime();

            // add time record
            if (itTime >= benchmarkNOmit) {
                compressDurations.add(finishTime - startTime);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(
                String.format("Benchmark, or encoding algorithm '%s' cause some stream problems", name), e);
    }
    compressingStream.close();
    printBenchmarkResult(length, compressDurations, Manipulation.COMPRESSION);

    byte[] compBuffer = compressedStream.toByteArray();

    // uncompress it several times and measure performance
    List<Long> durations = new ArrayList<Long>();
    for (int itTime = 0; itTime < benchmarkNTimes; ++itTime) {
        final long startTime = System.nanoTime();
        byte[] newBuf = new byte[length + 1];

        try {
            ByteArrayInputStream downStream = new ByteArrayInputStream(compBuffer, 0, compBuffer.length);
            InputStream decompressedStream = algorithm.createDecompressionStream(downStream, decompressor, 0);

            int destOffset = 0;
            int nextChunk;
            while ((nextChunk = decompressedStream.available()) > 0) {
                destOffset += decompressedStream.read(newBuf, destOffset, nextChunk);
            }
            decompressedStream.close();

            // iterate over KeyValues
            KeyValue kv;
            for (int pos = 0; pos < length; pos += kv.getLength()) {
                kv = new KeyValue(newBuf, pos);
            }

        } catch (IOException e) {
            throw new RuntimeException(String.format("Decoding path in '%s' algorithm cause exception ", name),
                    e);
        }

        final long finishTime = System.nanoTime();

        // check correctness
        if (0 != Bytes.compareTo(buffer, 0, length, newBuf, 0, length)) {
            int prefix = 0;
            for (; prefix < buffer.length && prefix < newBuf.length; ++prefix) {
                if (buffer[prefix] != newBuf[prefix]) {
                    break;
                }
            }
            throw new RuntimeException(String.format("Algorithm '%s' is corrupting the data", name));
        }

        // add time record
        if (itTime >= benchmarkNOmit) {
            durations.add(finishTime - startTime);
        }
    }
    printBenchmarkResult(length, durations, Manipulation.DECOMPRESSION);
    System.out.println();
}

From source file:org.dragonet.net.DragonetSession.java

private synchronized void sendAllACK() {
    if (this.queueACK.isEmpty()) {
        return;/*ww  w.ja va2  s  . c  o m*/
    }
    int[] ackSeqs = ArrayUtils.toPrimitive(this.queueACK.toArray(new Integer[0]));
    Arrays.sort(ackSeqs);
    this.queueACK.clear();
    ByteArrayOutputStream allRecBos = new ByteArrayOutputStream();
    PEBinaryWriter allRecWriter = new PEBinaryWriter(allRecBos);
    try {
        int count = ackSeqs.length;
        int records = 0;
        if (count > 0) {
            int pointer = 1;
            int start = ackSeqs[0];
            int last = ackSeqs[0];
            ByteArrayOutputStream recBos = new ByteArrayOutputStream();
            PEBinaryWriter recWriter;
            while (pointer < count) {
                int current = ackSeqs[pointer++];
                int diff = current - last;
                if (diff == 1) {
                    last = current;
                } else if (diff > 1) { //Forget about duplicated packets (bad queues?)
                    recBos.reset();
                    recWriter = new PEBinaryWriter(recBos);
                    if (start == last) {
                        recWriter.writeByte((byte) 0x01);
                        recWriter.writeTriad(start);
                        start = last = current;
                    } else {
                        recWriter.writeByte((byte) 0x00);
                        recWriter.writeTriad(start);
                        recWriter.writeTriad(last);
                        start = last = current;
                    }
                    records++;
                }
            }
            if (start == last) {
                allRecWriter.writeByte((byte) 0x01);
                allRecWriter.writeTriad(start);
            } else {
                allRecWriter.writeByte((byte) 0x00);
                allRecWriter.writeTriad(start);
                allRecWriter.writeTriad(last);
            }
            records++;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PEBinaryWriter writer = new PEBinaryWriter(bos);
        writer.writeByte((byte) 0xC0);
        writer.writeShort((short) (records & 0xFFFF));
        writer.write(allRecBos.toByteArray());
        this.dServer.getNetworkHandler().send(bos.toByteArray(), this.remoteAddress);
    } catch (IOException e) {
    }
}

From source file:org.dragonet.net.DragonetSession.java

private synchronized void sendAllNACK() {
    if (this.queueNACK.isEmpty()) {
        return;//from  w w  w.j  ava 2s .  co m
    }
    int[] ackSeqs = ArrayUtils.toPrimitive(this.queueNACK.toArray(new Integer[0]));
    Arrays.sort(ackSeqs);
    this.queueNACK.clear();
    ByteArrayOutputStream allRecBos = new ByteArrayOutputStream();
    PEBinaryWriter allRecWriter = new PEBinaryWriter(allRecBos);
    try {
        int count = ackSeqs.length;
        int records = 0;
        if (count > 0) {
            int pointer = 1;
            int start = ackSeqs[0];
            int last = ackSeqs[0];
            ByteArrayOutputStream recBos = new ByteArrayOutputStream();
            PEBinaryWriter recWriter;
            while (pointer < count) {
                int current = ackSeqs[pointer++];
                int diff = current - last;
                if (diff == 1) {
                    last = current;
                } else if (diff > 1) { //Forget about duplicated packets (bad queues?)
                    recBos.reset();
                    recWriter = new PEBinaryWriter(recBos);
                    if (start == last) {
                        recWriter.writeByte((byte) 0x01);
                        recWriter.writeTriad(start);
                        start = last = current;
                    } else {
                        recWriter.writeByte((byte) 0x00);
                        recWriter.writeTriad(start);
                        recWriter.writeTriad(last);
                        start = last = current;
                    }
                    records++;
                }
            }
            if (start == last) {
                allRecWriter.writeByte((byte) 0x01);
                allRecWriter.writeTriad(start);
            } else {
                allRecWriter.writeByte((byte) 0x00);
                allRecWriter.writeTriad(start);
                allRecWriter.writeTriad(last);
            }
            records++;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PEBinaryWriter writer = new PEBinaryWriter(bos);
        writer.writeByte((byte) 0xA0);
        writer.writeShort((short) (records & 0xFFFF));
        writer.write(allRecBos.toByteArray());
        this.dServer.getNetworkHandler().send(bos.toByteArray(), this.remoteAddress);
    } catch (IOException e) {
    }
}