Example usage for java.nio ByteBuffer rewind

List of usage examples for java.nio ByteBuffer rewind

Introduction

In this page you can find the example usage for java.nio ByteBuffer rewind.

Prototype

public final Buffer rewind() 

Source Link

Document

Rewinds this buffer.

Usage

From source file:jext2.SymlinkInode.java

@NotThreadSafe(useLock = true)
private void writeSlowSymlink(String link, int size) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge {
    ByteBuffer buf = ByteBuffer.allocate(Ext2fsDataTypes.getStringByteLength(link));
    Ext2fsDataTypes.putString(buf, link, buf.capacity(), 0);
    buf.rewind();
    writeData(buf, 0);/*from w  w  w  .  ja  v a2  s  .  c  o m*/
}

From source file:com.sm.store.utils.FileStore.java

private void reset() throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    long pos = OFFSET + (long) (totalRecord - 1) * RECORD_SIZE;
    indexChannel.read(buf, pos);//from  w  ww  .  j a v a2  s.com
    buf.rewind();
    byte status = buf.get();
    long keyLen = buf.getLong();
    byte[] keys = readChannel(keyLen, keyChannel);
    long data = buf.getLong();
    long block2version = buf.getLong();
    CacheBlock block = new CacheBlock(totalRecord, data, block2version, status);
    byte[] datas = readChannel(block.getDataOffset2Len(), dataChannel);

}

From source file:org.jasig.cas.ticket.registry.support.kryo.serial.AttributeMapSerializerTests.java

private void printBuffer(final ByteBuffer buffer) {
    final byte[] bytes = new byte[buffer.limit()];
    buffer.get(bytes);/*from   w  ww  .j  ava2  s.  c o m*/
    try {
        logger.debug(new String(bytes, "UTF-8"));
    } catch (Exception e) {
        logger.error("Error printing buffer as string.");
    }
    buffer.rewind();
}

From source file:org.openteufel.file.mpq.MPQFileSector.java

public int getDecompressed(ByteBuffer out) throws DataFormatException, IOException {
    // If the file is encrypted, each sector (after compression/implosion, if applicable) is encrypted with the file's key.
    // Each sector is encrypted using the key + the 0-based index of the sector in the file.
    // NOTE compression type byte (if existing) is encrypted as well!
    ByteBuffer dataDecrypted;
    if (this.encryptionSeed != null)
        dataDecrypted = MPQEncryptionUtils.decrypt(dataRaw, encryptionSeed);
    else/* ww  w .  ja  v a  2s .  c  o m*/
        dataDecrypted = dataRaw;
    dataDecrypted.rewind();

    switch (compression) {
    case Uncompressed: {
        out.put(dataDecrypted);
        return dataDecrypted.capacity();
    }
    case Imploded: {
        byte[] buf = new byte[sizeUncompressed];
        int numDecompressed = Exploder.pkexplode(dataDecrypted.array(), buf);
        if (numDecompressed != this.sizeUncompressed)
            throw new IllegalStateException();
        out.put(buf, 0, sizeUncompressed);
        return sizeUncompressed;
    }
    case ZLib: {
        int numDecompressed = 0;
        byte[] buf = new byte[1024];
        Inflater inflater = new Inflater();
        inflater.setInput(dataDecrypted.array());
        while (!inflater.finished()) {
            int decompressedBytes = inflater.inflate(buf);
            numDecompressed += decompressedBytes;
            out.put(buf, 0, decompressedBytes);
        }
        inflater.end();
        if (numDecompressed != this.sizeUncompressed)
            throw new IllegalStateException();
        return numDecompressed;
    }
    case BZip2: {
        int numDecompressed = 0;
        byte[] buf = new byte[1024];
        InputStream inputStream = new ByteArrayInputStream(dataDecrypted.array());
        BZip2CompressorInputStream uncompressStream = new BZip2CompressorInputStream(inputStream);
        while (true) {
            int decompressedBytes = uncompressStream.read(buf);
            if (decompressedBytes < 0)
                break;
            numDecompressed += decompressedBytes;
            out.put(buf, 0, decompressedBytes);
        }
        uncompressStream.close();
        inputStream.close();
        if (numDecompressed != sizeUncompressed)
            throw new IllegalStateException();
        return numDecompressed;
    }
    default:
        throw new IllegalStateException("Unknown Compression");
    }
}

From source file:com.serenegiant.media.TLMediaEncoder.java

/**
 * convert ByteBuffer into String/*from w w  w  .java  2s  .c  o m*/
 * @param buffer
 * @return
 */
private static final String asString(final ByteBuffer buffer) {
    final byte[] temp = new byte[16];
    final StringBuilder sb = new StringBuilder();
    int n = (buffer != null ? buffer.limit() : 0);
    if (n > 0) {
        buffer.rewind();
        int sz = (n > 16 ? 16 : n);
        n -= sz;
        for (; sz > 0; sz = (n > 16 ? 16 : n), n -= sz) {
            buffer.get(temp, 0, sz);
            for (int i = 0; i < sz; i++) {
                sb.append(temp[i]).append(',');
            }
        }
    }
    return sb.toString();
}

From source file:voldemort.store.cachestore.voldeimpl.StoreIterator.java

private boolean checkSignature(FileChannel channel) throws IOException {
    ByteBuffer intBytes = ByteBuffer.allocate(OFFSET);
    if (channel.size() == 0) {
        throw new StoreException("File size is 0");
    } else {/*  w ww.j a v a 2 s .com*/
        channel.read(intBytes);
        intBytes.rewind();
        if (intBytes.getInt() != MAGIC)
            throw new StoreException("Header mismatch expect " + MAGIC + " read " + intBytes.getInt());
    }
    return true;
}

From source file:AutoDJ.metaReader.OggIndexer.java

/**
 * Extracts the Image from a FLAC picture structure
 * http://flac.sourceforge.net/format.html#metadata_block_picture
 * Expects a base64 encoded string/*from   ww w  .  ja  v  a 2 s .  co  m*/
 * 
 * @param String pictureBlock (base64)
 * @return BufferedImage
 */
BufferedImage readAlbumImage(String pictureBlock) {
    if (pictureBlock == null || pictureBlock.isEmpty())
        return null;

    byte[] pictureBytes = Base64.decodeBase64(pictureBlock);
    BufferedImage img = null;

    String mimeString = "", description = "";
    ByteBuffer picBuff = ByteBuffer.allocate(pictureBytes.length);
    picBuff.put(pictureBytes);
    picBuff.rewind();

    /*int picType = */picBuff.getInt(); // not interesting, discard

    // read the mime type string
    int mimeStrLength = picBuff.getInt();
    byte[] mimeBytes = new byte[mimeStrLength];
    picBuff.get(mimeBytes);
    mimeString = new String(mimeBytes);

    // read the string describing the image 
    int descStrLength = picBuff.getInt();
    byte[] descBytes = new byte[descStrLength];
    picBuff.get(descBytes);
    try {
        description = new String(descBytes, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }

    // skip over some unnecessary information
    /*int picWidth  = */picBuff.getInt();
    /*int picHeight = */picBuff.getInt();
    /*int colDepth  = */picBuff.getInt();
    /*int idxColors = */picBuff.getInt();

    // read the image data
    int picDataLength = picBuff.getInt();
    byte[] picBytes = new byte[picDataLength];
    picBuff.get(picBytes);
    try {
        img = ImageIO.read(new ByteArrayInputStream(picBytes));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return img;
}

From source file:com.healthmarketscience.jackcess.PageChannel.java

/**
 * Write a page (or part of a page) to disk
 * @param page Page to write/*  w  ww  .  ja v a2s.  co m*/
 * @param pageNumber Page number to write the page to
 * @param pageOffset offset within the page at which to start writing the
 *                   page data
 */
public void writePage(ByteBuffer page, int pageNumber, int pageOffset) throws IOException {
    validatePageNumber(pageNumber);

    page.rewind();

    if ((page.remaining() - pageOffset) > getFormat().PAGE_SIZE) {
        throw new IllegalArgumentException("Page buffer is too large, size " + (page.remaining() - pageOffset));
    }

    ByteBuffer encodedPage = page;
    if (pageNumber == 0) {
        // re-mask header
        applyHeaderMask(page);
    } else {
        // re-encode page
        encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset);
    }
    try {
        encodedPage.position(pageOffset);
        _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset));
        if (_autoSync) {
            flush();
        }
    } finally {
        if (pageNumber == 0) {
            // de-mask header
            applyHeaderMask(page);
        }
    }
}

From source file:org.minig.imap.impl.MailboxNameUTF7Converter.java

/**
 * Encode the mailbox name in the IMAP UTF-7 style charset.
 * /*from  www. j a  v  a 2 s  . c  o  m*/
 * @param mailboxName
 * @return the IMAP UTF-7 representation
 */
public static String encode(String mailboxName) {
    int dataBits = 0;
    int mode = PRINTABLE;
    // Allocate a bytebuffer that must be at max
    // twice the length of characters in the string
    // because of utf-16 encoding and add 2 more
    // bytes in order to have a length that can be
    // devided by 3. This is necessary to avoid the
    // padding in base64 which is forbidden in
    // modified UTF-7 encoding.
    ByteBuffer buffer = ByteBuffer.allocate(mailboxName.length() * 4 + 4);

    StringBuilder result = new StringBuilder();
    char c;

    for (int i = 0; i < mailboxName.length(); i++) {
        c = mailboxName.charAt(i);

        if (isPrintable(c)) {
            if (mode != PRINTABLE && buffer.position() > 0) {
                // pad buffer with zero
                // logger.info("vor put oben " + buffer.capacity() +
                // ":" + buffer.remaining());
                if (buffer.position() % 3 != 0) {
                    buffer.put(new byte[3 - (buffer.position() % 3)]);
                }
                // logger.info("nach put oben " + buffer.capacity() +
                // ":" + buffer.remaining());
                buffer.limit(buffer.position());
                // logger.info("nach limit " + buffer.capacity() +
                // ":" + buffer.remaining());

                // encode in base64
                String encoded = Base64.encodeBase64String(buffer.array());
                buffer.rewind();

                // do the modifications
                String rawEncoded = encoded.replace('/', ',');

                // cut the end to a valid base64 character
                // base64: 6 bits per character

                int encodedBits = rawEncoded.length() * 6;
                int superfluentChars = (encodedBits - dataBits) / 6;

                if (superfluentChars > 0) {
                    rawEncoded = rawEncoded.substring(0, rawEncoded.length() - superfluentChars);
                    dataBits = 0;
                }

                result.append(rawEncoded);

                // switch back to PRINTABLE mode
                mode = PRINTABLE;
                result.append('-');
                // logger.info("result so far :" + result);
            }

            // write the character
            if (c == '&') {
                result.append("&-");
            } else {
                result.append(c);
            }
        } else {
            if (mode != BASE64) {
                result.append('&');
                mode = BASE64;
            }

            try {
                if (buffer.remaining() < 2) {
                    buffer.limit(buffer.limit() + (2 - buffer.remaining()));
                }
                // logger.info("vor put " + buffer.capacity() + ":" +
                // buffer.remaining());
                byte[] utfBytes = mailboxName.substring(i, i + 1).getBytes("UTF-16");
                if (utfBytes[0] != -2) {
                    buffer.put(utfBytes[0]);
                    buffer.put(utfBytes[1]);

                    dataBits += 16;
                }
                if (buffer.remaining() == 0) {
                    buffer.limit(buffer.limit() + 1);
                }
                buffer.put(utfBytes[2]);
                // logger.info("nach put " + buffer.capacity() + ":"
                // + buffer.remaining());
                if (buffer.remaining() == 0) {
                    buffer.limit(buffer.limit() + 1);
                }
                buffer.put(utfBytes[3]);

                dataBits += 16;
            } catch (UnsupportedEncodingException e) {
                // will never happen
            }
        }
    }

    if (mode != PRINTABLE) {
        // pad buffer with zeros
        if (buffer.remaining() == 0) {
            buffer.limit(buffer.limit() + 3);
        }
        if (buffer.position() % 3 != 0) {
            buffer.put(new byte[3 - (buffer.position() % 3)]);
        }
        buffer.limit(buffer.position());

        // encode in base64
        String encoded = Base64.encodeBase64String(buffer.array());
        buffer.rewind();

        // do the modifications
        String rawEncoded = encoded.replace('/', ',');

        // cut the end to a valid base64 character
        // base64: 6 bits per character

        int encodedBits = rawEncoded.length() * 6;
        int superfluentChars = (encodedBits - dataBits) / 6;

        if (superfluentChars > 0) {
            rawEncoded = rawEncoded.substring(0, rawEncoded.length() - superfluentChars);
        }

        result.append(rawEncoded);

        // switch back to PRINTABLE mode
        mode = PRINTABLE;
        result.append('-');
    }

    String returnString = result.toString();
    // logger.info("schluendlich :" + returnString);
    return returnString;
}

From source file:com.sm.store.utils.FileStore.java

private boolean checkSignature(FileChannel channel) throws IOException {
    ByteBuffer intBytes = ByteBuffer.allocate(OFFSET);
    if (channel.size() == 0) {
        intBytes.putInt(MAGIC);// ww  w  .ja v a 2 s. c  o  m
        intBytes.flip();
        channel.write(intBytes);
        return true;
    } else {
        channel.read(intBytes);
        intBytes.rewind();
        if (intBytes.getInt() != MAGIC)
            throw new StoreException("Header mismatch expect " + MAGIC + " read " + intBytes.getInt());
    }
    return true;
}