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:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print a particular selected PO Quote as a PDF.
 *
 * @param mapping An ActionMapping/*  ww w .j a v a 2s.  co  m*/
 * @param form An ActionForm -- The PO Quote must be selected here.
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // String poDocId = request.getParameter("docId");
    // PurchaseOrderDocument po = (PurchaseOrderDocument)
    // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
    // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
    PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            poVendorQuote.setPdfDisplayedToUserOnce(false);

            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(KFSConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

@Test
public void testDu() throws IOException {
    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
    DistributedFileSystem fs = cluster.getFileSystem();
    PrintStream psBackup = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream psOut = new PrintStream(out);
    System.setOut(psOut);//from ww  w.  j a v a  2 s . co m
    FsShell shell = new FsShell();
    shell.setConf(conf);

    try {
        Path myPath = new Path("/test/dir");
        assertTrue(fs.mkdirs(myPath));
        assertTrue(fs.exists(myPath));
        Path myFile = new Path("/test/dir/file");
        writeFile(fs, myFile);
        assertTrue(fs.exists(myFile));
        Path myFile2 = new Path("/test/dir/file2");
        writeFile(fs, myFile2);
        assertTrue(fs.exists(myFile2));

        String[] args = new String[2];
        args[0] = "-du";
        args[1] = "/test/dir";
        int val = -1;
        try {
            val = shell.run(args);
        } catch (Exception e) {
            System.err.println("Exception raised from DFSShell.run " + e.getLocalizedMessage());
        }
        assertTrue(val == 0);
        String returnString = out.toString();
        out.reset();
        // Check if size matchs as expected
        assertTrue(returnString.contains("22"));
        assertTrue(returnString.contains("23"));

    } finally {
        System.setOut(psBackup);
        cluster.shutdown();
    }

}

From source file:com.msopentech.odatajclient.testservice.utils.AbstractUtilities.java

public InputStream addOrReplaceEntity(final String key, final String entitySetName, final InputStream is)
        throws Exception {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(is, bos);// w  w  w.  j  a va  2 s  .co m
    is.close();

    // -----------------------------------------
    // 0. Retrieve navigation links to be mantained
    // -----------------------------------------
    Set<String> linksToBeMantained;
    try {
        linksToBeMantained = Commons.linkInfo.get(version).getNavigationLinkNames(entitySetName);
    } catch (Exception e) {
        linksToBeMantained = Collections.<String>emptySet();
    }

    for (String availableLink : new HashSet<String>(linksToBeMantained)) {
        try {
            fsManager.resolve(
                    Commons.getLinksPath(version, entitySetName, key, availableLink, Accept.JSON_FULLMETA));
        } catch (Exception e) {
            linksToBeMantained.remove(availableLink);
        }
    }

    for (String linkName : retrieveAllLinkNames(new ByteArrayInputStream(bos.toByteArray()))) {
        linksToBeMantained.remove(linkName);
    }
    // -----------------------------------------

    // -----------------------------------------
    // 1. Get default entry key and path (N.B. operation will consume/close the stream; use a copy instead)
    // -----------------------------------------
    final String entityKey = key == null
            ? getDefaultEntryKey(entitySetName, new ByteArrayInputStream(bos.toByteArray()), getDefaultFormat())
            : key;

    final String path = entitySetName + File.separatorChar + Commons.getEntityKey(entityKey)
            + File.separatorChar;
    // -----------------------------------------

    // -----------------------------------------
    // 2. Retrieve navigation info
    // -----------------------------------------
    final NavigationLinks links = retrieveNavigationInfo(entitySetName,
            new ByteArrayInputStream(bos.toByteArray()));
    // -----------------------------------------

    // -----------------------------------------
    // 3. Normalize navigation info; add edit link; ... and save entity ....
    // -----------------------------------------
    final InputStream createdEntity = saveSingleEntity(entityKey, entitySetName,
            new ByteArrayInputStream(bos.toByteArray()), links);
    // -----------------------------------------

    bos.reset();
    IOUtils.copy(createdEntity, bos);

    // -----------------------------------------
    // 4. Add navigation links to be mantained
    // -----------------------------------------
    final InputStream normalizedEntity = addLinks(entitySetName, entityKey,
            new ByteArrayInputStream(bos.toByteArray()), linksToBeMantained);
    // -----------------------------------------

    IOUtils.closeQuietly(bos);

    // -----------------------------------------
    // 5. save the entity
    // -----------------------------------------
    final FileObject fo = fsManager.putInMemory(normalizedEntity,
            fsManager.getAbsolutePath(path + ENTITY, getDefaultFormat()));
    // -----------------------------------------

    // -----------------------------------------
    // 4. Create links file and provided inlines
    // -----------------------------------------
    for (Map.Entry<String, List<String>> link : links.getLinks()) {
        putLinksInMemory(path, entitySetName, entityKey, link.getKey(), link.getValue());
    }

    for (Map.Entry<String, List<InputStream>> inlineEntry : links.getInlines()) {
        final String inlineEntitySetName = Commons.linkInfo.get(version).getTargetName(entitySetName,
                inlineEntry.getKey());

        final List<String> hrefs = new ArrayList<String>();

        for (InputStream stream : inlineEntry.getValue()) {
            final ByteArrayOutputStream inlineBos = new ByteArrayOutputStream();
            IOUtils.copy(stream, inlineBos);
            IOUtils.closeQuietly(stream);

            final String inlineEntryKey = getDefaultEntryKey(inlineEntitySetName,
                    new ByteArrayInputStream(inlineBos.toByteArray()), getDefaultFormat());

            addOrReplaceEntity(inlineEntryKey, inlineEntitySetName,
                    new ByteArrayInputStream(inlineBos.toByteArray()));

            hrefs.add(inlineEntitySetName + "(" + inlineEntryKey + ")");
        }

        putLinksInMemory(path, entitySetName, entityKey, inlineEntry.getKey(), hrefs);
    }
    // -----------------------------------------

    return fo.getContent().getInputStream();
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, byte[] eofBytes) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[1024];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }/*  w  w w .  j  a v a  2s . c om*/
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // look for eofBytes, starting where we last appended
                if (findEOFBytes(sink, len, eofBytes)) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Found desired EOF bytes: {}", asciiDebugValue(eofBytes));
                    }
                    return true;
                }
                eventLog.debug("Looking for EOF bytes {}", asciiDebugValue(eofBytes));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes {} in buffer {}", new Object[] { magicBytes.length,
                        asciiDebugValue(magicBytes), asciiDebugValue(sink.toByteArray()) });
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                int count = buf.length;
                count = Math.min(buf.length, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (findEOFBytes(sink, len, eofBytes)) {
                    // we got all the data here... we're done
                    return true;
                }
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.debug("Looking for bytes {}, buffer: {}",
                (append ? asciiDebugValue(eofBytes) : asciiDebugValue(magicBytes)),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}

From source file:org.apache.olingo.fit.utils.AbstractUtilities.java

public InputStream addOrReplaceEntity(final String key, final String entitySetName, final InputStream is,
        final Entity entry) throws Exception {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(is, bos);/*from  ww w  .  j  av  a2  s .  c  om*/
    IOUtils.closeQuietly(is);

    final Map<String, NavigationProperty> navigationProperties = metadata
            .getNavigationProperties(entitySetName);

    // -----------------------------------------
    // 0. Retrieve navigation links to be kept
    // -----------------------------------------
    Set<String> linksToBeKept;
    try {
        linksToBeKept = new HashSet<String>(navigationProperties.keySet());
    } catch (NullPointerException e) {
        linksToBeKept = Collections.<String>emptySet();
    }

    for (String availableLink : new HashSet<String>(linksToBeKept)) {
        try {
            fsManager.resolve(Commons.getLinksPath(entitySetName, key, availableLink, Accept.JSON_FULLMETA));
        } catch (Exception e) {
            linksToBeKept.remove(availableLink);
        }
    }

    for (String linkName : retrieveAllLinkNames(new ByteArrayInputStream(bos.toByteArray()))) {
        linksToBeKept.remove(linkName);
    }
    // -----------------------------------------

    // -----------------------------------------
    // 1. Get default entry key and path (N.B. operation will consume/close the stream; use a copy instead)
    // -----------------------------------------
    final String entityKey = key == null ? getDefaultEntryKey(entitySetName, entry) : key;

    final String path = Commons.getEntityBasePath(entitySetName, entityKey);
    // -----------------------------------------

    // -----------------------------------------
    // 2. Retrieve navigation info
    // -----------------------------------------
    final NavigationLinks links = retrieveNavigationInfo(entitySetName,
            new ByteArrayInputStream(bos.toByteArray()));
    // -----------------------------------------

    // -----------------------------------------
    // 3. Normalize navigation info; add edit link; ... and save entity ....
    // -----------------------------------------
    final InputStream createdEntity = saveSingleEntity(entityKey, entitySetName,
            new ByteArrayInputStream(bos.toByteArray()), links);
    // -----------------------------------------

    bos.reset();
    IOUtils.copy(createdEntity, bos);

    // -----------------------------------------
    // 4. Add navigation links to be kept
    // -----------------------------------------
    final InputStream normalizedEntity = addLinks(entitySetName, entityKey,
            new ByteArrayInputStream(bos.toByteArray()), linksToBeKept);
    // -----------------------------------------

    IOUtils.closeQuietly(bos);

    // -----------------------------------------
    // 5. save the entity
    // -----------------------------------------
    final FileObject fo = fsManager.putInMemory(normalizedEntity,
            fsManager.getAbsolutePath(path + Constants.get(ConstantKey.ENTITY), getDefaultFormat()));
    // -----------------------------------------

    // -----------------------------------------
    // 4. Create links file and provided inlines
    // -----------------------------------------
    for (Map.Entry<String, List<String>> link : links.getLinks()) {
        putLinksInMemory(path, entitySetName, entityKey, link.getKey(), link.getValue());
    }

    final List<String> hrefs = new ArrayList<String>();

    for (final Link link : entry.getNavigationLinks()) {
        final NavigationProperty navProp = navigationProperties == null ? null
                : navigationProperties.get(link.getTitle());
        if (navProp != null) {
            final String inlineEntitySetName = navProp.getTarget();
            if (link.getInlineEntity() != null) {
                final String inlineEntryKey = getDefaultEntryKey(inlineEntitySetName, link.getInlineEntity());

                addOrReplaceEntity(inlineEntryKey, inlineEntitySetName, toInputStream(link.getInlineEntity()),
                        link.getInlineEntity());

                hrefs.add(inlineEntitySetName + "(" + inlineEntryKey + ")");
            } else if (link.getInlineEntitySet() != null) {
                for (Entity subentry : link.getInlineEntitySet().getEntities()) {
                    final String inlineEntryKey = getDefaultEntryKey(inlineEntitySetName, subentry);

                    addOrReplaceEntity(inlineEntryKey, inlineEntitySetName, toInputStream(subentry), subentry);

                    hrefs.add(inlineEntitySetName + "(" + inlineEntryKey + ")");
                }
            }

            if (!hrefs.isEmpty()) {
                putLinksInMemory(path, entitySetName, entityKey, link.getTitle(), hrefs);
            }
        }
    }
    // -----------------------------------------

    return fo.getContent().getInputStream();
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStore.java

private void convertBlobToId(InputStream in, ByteArrayOutputStream idStream, int level, long totalLength)
        throws IOException {
    int count = 0;
    // try to re-use the block (but not concurrently)
    byte[] block = blockBuffer.getAndSet(null);
    if (block == null || block.length != blockSize) {
        // not yet initialized yet, already in use, or wrong size:
        // create a new one
        block = new byte[blockSize];
    }// ww w .  j  av  a  2s. c  om
    while (true) {
        int blockLen = IOUtils.readFully(in, block, 0, block.length);
        count++;
        if (blockLen == 0) {
            break;
        } else if (blockLen < blockSizeMin) {
            idStream.write(TYPE_DATA);
            IOUtils.writeVarInt(idStream, blockLen);
            idStream.write(block, 0, blockLen);
            totalLength += blockLen;
        } else {
            MessageDigest messageDigest;
            try {
                messageDigest = MessageDigest.getInstance(HASH_ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                throw new IOException(e);
            }
            messageDigest.update(block, 0, blockLen);
            byte[] digest = messageDigest.digest();
            idStream.write(TYPE_HASH);
            IOUtils.writeVarInt(idStream, level);
            if (level > 0) {
                // level > 0: total size (size of all sub-blocks)
                // (see class level javadoc for details)                    
                IOUtils.writeVarLong(idStream, totalLength);
            }
            // level = 0: size (size of this block)
            // level > 0: size of the indirection block
            // (see class level javadoc for details)                
            IOUtils.writeVarLong(idStream, blockLen);
            totalLength += blockLen;
            IOUtils.writeVarInt(idStream, digest.length);
            idStream.write(digest);

            long start = System.nanoTime();
            storeBlock(digest, level, Arrays.copyOf(block, blockLen));
            statsCollector.uploaded(System.nanoTime() - start, TimeUnit.NANOSECONDS, blockLen);
        }
        if (idStream.size() > blockSize / 2) {
            // convert large ids to a block, but ensure it can be stored as
            // one block (otherwise the indirection no longer works)
            byte[] idBlock = idStream.toByteArray();
            idStream.reset();
            convertBlobToId(new ByteArrayInputStream(idBlock), idStream, level + 1, totalLength);
            count = 1;
        }
    }
    // re-use the block
    blockBuffer.set(block);
    if (count > 0 && idStream.size() > blockSizeMin) {
        // at the very end, convert large ids to a block,
        // because large block ids are not handy
        // (specially if they are used to read data in small chunks)
        byte[] idBlock = idStream.toByteArray();
        idStream.reset();
        convertBlobToId(new ByteArrayInputStream(idBlock), idStream, level + 1, totalLength);
    }
    in.close();
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, int readLength) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[Math.min(readLength, 1024)];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }/*from   www  . j a v a  2s  . co  m*/
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // if we've collected at least desiredSize bytes, we're done
                if (sinkSize >= readLength) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Got desired {}  bytes of data: {}", readLength,
                                asciiDebugValue(sink.toByteArray()));
                    }
                    return true;
                }
                eventLog.debug("Looking for {} more bytes of data", (readLength - sinkSize));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes 0x{}", magicBytes.length,
                        Hex.encodeHexString(magicBytes));
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                // skip over magic bytes
                magicIdx += magicBytes.length;

                int count = readLength;
                count = Math.min(readLength, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (sinkSize >= readLength) {
                    // we got all the data here... we're done
                    return true;
                }
                eventLog.trace("Need {} more bytes of data", (readLength - sinkSize));
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length - 1, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Need {} more bytes of data, buffer: {}", (readLength - sinkSize),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}

From source file:org.dbgl.gui.MainWindow.java

private void doExportTemplates() {
    try {//ww  w  .  java 2 s .co m
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);

        java.util.List<ExpTemplate> expTemplateList = new ArrayList<ExpTemplate>();
        for (Template template : templatesList) {
            Conf conf = new Conf(template, DosboxVersion.findById(dbversionsList, template.getDbversionId()),
                    ps);
            expTemplateList.add(new ExpTemplate(-1, conf, template));
        }
        DOMSource doc = new DOMSource(XmlUtils.getFullTemplatesXML(expTemplateList, dbversionsList,
                "DBGL default templates", StringUtils.EMPTY, "rcblanke"));
        XmlUtils.saveDomSource(doc, FileUtils.getDefaultTemplatesXmlFile(), null);

        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(shell, bos.toString());
            bos.reset();
        }
    } catch (Exception e) {
        GeneralPurposeDialogs.fatalMessage(shell, e.toString(), e);
    }
}

From source file:org.apache.pig.builtin.Utf8StorageConverter.java

private Tuple consumeTuple(PushbackInputStream in, ResourceFieldSchema fieldSchema) throws IOException {
    if (fieldSchema == null) {
        throw new IOException("Schema is null");
    }/*w ww  .java 2s. c  om*/
    int buf;
    ByteArrayOutputStream mOut;

    while ((buf = in.read()) != '(' || buf == '}') {
        if (buf == -1) {
            throw new IOException("Unexpect end of tuple");
        }
        if (buf == '}') {
            in.unread(buf);
            return null;
        }
    }
    Tuple t = TupleFactory.getInstance().newTuple();
    if (fieldSchema.getSchema() != null && fieldSchema.getSchema().getFields().length != 0) {
        ResourceFieldSchema[] fss = fieldSchema.getSchema().getFields();
        // Interpret item inside tuple one by one based on the inner schema
        for (int i = 0; i < fss.length; i++) {
            Object field;
            ResourceFieldSchema fs = fss[i];
            int delimit = ',';
            if (i == fss.length - 1)
                delimit = ')';

            if (DataType.isComplex(fs.getType())) {
                field = consumeComplexType(in, fs);
                while ((buf = in.read()) != delimit) {
                    if (buf == -1) {
                        throw new IOException("Unexpect end of tuple");
                    }
                }
            } else {
                mOut = new ByteArrayOutputStream(BUFFER_SIZE);
                while ((buf = in.read()) != delimit) {
                    if (buf == -1) {
                        throw new IOException("Unexpect end of tuple");
                    }
                    if (buf == delimit)
                        break;
                    mOut.write(buf);
                }
                field = parseSimpleType(mOut.toByteArray(), fs);
            }
            t.append(field);
        }
    } else {
        // No inner schema, treat everything inside tuple as bytearray
        Deque<Character> level = new LinkedList<Character>(); // keep track of nested tuple/bag/map. We do not interpret, save them as bytearray
        mOut = new ByteArrayOutputStream(BUFFER_SIZE);
        while (true) {
            buf = in.read();
            if (buf == -1) {
                throw new IOException("Unexpect end of tuple");
            }
            if (buf == '[' || buf == '{' || buf == '(') {
                level.push((char) buf);
                mOut.write(buf);
            } else if (buf == ')' && level.isEmpty()) // End of tuple
            {
                DataByteArray value = new DataByteArray(mOut.toByteArray());
                t.append(value);
                break;
            } else if (buf == ',' && level.isEmpty()) {
                DataByteArray value = new DataByteArray(mOut.toByteArray());
                t.append(value);
                mOut.reset();
            } else if (buf == ']' || buf == '}' || buf == ')') {
                if (level.peek() == findStartChar((char) buf))
                    level.pop();
                else
                    throw new IOException("Malformed tuple");
                mOut.write(buf);
            } else
                mOut.write(buf);
        }
    }
    return t;
}