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:org.apache.camel.component.syslog.Rfc3164SyslogConverter.java

public static SyslogMessage parseMessage(byte[] bytes) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    byteBuffer.put(bytes);// ww w. jav  a 2s.  c  o m
    byteBuffer.rewind();

    SyslogMessage syslogMessage = new SyslogMessage();
    Character charFound = (char) byteBuffer.get();

    while (charFound != '<') {
        //Ignore noise in beginning of message.
        charFound = (char) byteBuffer.get();
    }
    char priChar = 0;
    if (charFound == '<') {
        int facility = 0;

        while (Character.isDigit(priChar = (char) (byteBuffer.get() & 0xff))) {
            facility *= 10;
            facility += Character.digit(priChar, 10);
        }
        syslogMessage.setFacility(SyslogFacility.values()[facility >> 3]);
        syslogMessage.setSeverity(SyslogSeverity.values()[facility & 0x07]);
    }

    if (priChar != '>') {
        //Invalid character - this is not a well defined syslog message.
        LOG.error("Invalid syslog message, missing a > in the Facility/Priority part");
    }

    //Done parsing severity and facility
    //<169>Oct 22 10:52:01 TZ-6 scapegoat.dmz.example.org 10.1.2.3 sched[0]: That's All Folks!
    //Need to parse the date.

    /**
     The TIMESTAMP field is the local time and is in the format of "Mmm dd
     hh:mm:ss" (without the quote marks) where:
            
     Mmm is the English language abbreviation for the month of the
     year with the first character in uppercase and the other two
     characters in lowercase.  The following are the only acceptable
     values:
            
     Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
            
     dd is the day of the month.  If the day of the month is less
     than 10, then it MUST be represented as a space and then the
     number.  For example, the 7th day of August would be
     represented as "Aug  7", with two spaces between the "g" and
     the "7".
            
     hh:mm:ss is the local time.  The hour (hh) is represented in a
     24-hour format.  Valid entries are between 00 and 23,
     inclusive.  The minute (mm) and second (ss) entries are between
     00 and 59 inclusive.
            
            
     */

    char[] month = new char[3];
    for (int i = 0; i < 3; i++) {
        month[i] = (char) (byteBuffer.get() & 0xff);
    }
    charFound = (char) byteBuffer.get();
    if (charFound != ' ') {
        //Invalid Message - missing mandatory space.
        LOG.error("Invalid syslog message, missing a mandatory space after month");
    }
    charFound = (char) (byteBuffer.get() & 0xff);

    int day = 0;
    if (charFound == ' ') {
        //Extra space for the day - this is okay.
        //Just ignored per the spec.
    } else {
        day *= 10;
        day += Character.digit(charFound, 10);
    }

    while (Character.isDigit(charFound = (char) (byteBuffer.get() & 0xff))) {
        day *= 10;
        day += Character.digit(charFound, 10);
    }

    int hour = 0;
    while (Character.isDigit(charFound = (char) (byteBuffer.get() & 0xff))) {
        hour *= 10;
        hour += Character.digit(charFound, 10);
    }

    int minute = 0;
    while (Character.isDigit(charFound = (char) (byteBuffer.get() & 0xff))) {
        minute *= 10;
        minute += Character.digit(charFound, 10);
    }

    int second = 0;
    while (Character.isDigit(charFound = (char) (byteBuffer.get() & 0xff))) {
        second *= 10;
        second += Character.digit(charFound, 10);
    }

    //The host is the char sequence until the next ' '

    StringBuilder host = new StringBuilder();
    while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {
        host.append(charFound);
    }

    syslogMessage.setHostname(host.toString());

    StringBuilder msg = new StringBuilder();
    while (byteBuffer.hasRemaining()) {
        charFound = (char) (byteBuffer.get() & 0xff);
        msg.append(charFound);
    }

    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.MONTH, monthValueMap.get(String.valueOf(month).toLowerCase()).ordinal());
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.SECOND, second);

    syslogMessage.setTimestamp(calendar.getTime());

    syslogMessage.setLogMessage(msg.toString());
    if (LOG.isTraceEnabled()) {
        LOG.trace("Syslog message : " + syslogMessage.toString());
    }

    return syslogMessage;
}

From source file:org.onlab.util.ImmutableByteSequence.java

/**
 * Creates a new immutable byte sequence copying bytes from the given
 * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
 * bytes will be copied in reverse order.
 *
 * @param original a byte buffer/*from ww w . j  a va2 s. c om*/
 * @return a new byte buffer object
 */
public static ImmutableByteSequence copyFrom(ByteBuffer original) {
    checkArgument(original != null && original.capacity() > 0, "Cannot copy from an empty or null byte buffer");

    byte[] bytes = new byte[original.capacity()];

    // copy bytes from original buffer
    original.rewind();
    original.get(bytes);

    if (original.order() == ByteOrder.LITTLE_ENDIAN) {
        // FIXME: this can be improved, e.g. read bytes in reverse order from original
        reverse(bytes);
    }

    return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
}

From source file:com.atilika.kuromoji.trie.DoubleArrayTrie.java

/**
 * Load Stored data// www  . j  av  a 2 s.c om
 *
 * @param input  input stream to read the double array trie from
 * @return double array trie, not null
 * @throws IOException if an IO error occured during reading the double array trie
 */
public static DoubleArrayTrie read(InputStream input) throws IOException {
    DoubleArrayTrie trie = new DoubleArrayTrie();
    DataInputStream dis = new DataInputStream(new BufferedInputStream(input));

    trie.compact = dis.readBoolean();
    int baseCheckSize = dis.readInt(); // Read size of baseArr and checkArr
    int tailSize = dis.readInt(); // Read size of tailArr
    ReadableByteChannel channel = Channels.newChannel(dis);

    ByteBuffer tmpBaseBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    channel.read(tmpBaseBuffer);
    tmpBaseBuffer.rewind();
    trie.baseBuffer = tmpBaseBuffer.asIntBuffer();

    ByteBuffer tmpCheckBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    channel.read(tmpCheckBuffer);
    tmpCheckBuffer.rewind();
    trie.checkBuffer = tmpCheckBuffer.asIntBuffer();

    ByteBuffer tmpTailBuffer = ByteBuffer.allocate(tailSize * 2);
    channel.read(tmpTailBuffer);
    tmpTailBuffer.rewind();
    trie.tailBuffer = tmpTailBuffer.asCharBuffer();

    input.close();
    return trie;
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;//from   www.  j a  v a  2s .c  om
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:org.apache.cassandra.Util.java

public static ByteBuffer getBytes(int v) {
    byte[] bytes = new byte[4];
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.putInt(v);/* w ww  .  j  a  v a2s  .  c o m*/
    bb.rewind();
    return bb;
}

From source file:org.apache.cassandra.Util.java

public static ByteBuffer getBytes(long v) {
    byte[] bytes = new byte[8];
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.putLong(v);//from   www .  j av  a 2 s  . c om
    bb.rewind();
    return bb;
}

From source file:com.inmobi.messaging.util.AuditUtil.java

public static void attachHeaders(Message m, Long timestamp) {
    byte[] b = m.getData().array();
    int messageSize = b.length;
    int totalSize = messageSize + HEADER_LENGTH;
    ByteBuffer buffer = ByteBuffer.allocate(totalSize);

    // writing version
    buffer.put((byte) currentVersion);
    // writing magic bytes
    buffer.put(magicBytes);/*from  w  w  w. j  a  v a  2  s . co m*/
    // writing timestamp
    long time = timestamp;
    buffer.putLong(time);

    // writing message size
    buffer.putInt(messageSize);
    // writing message
    buffer.put(b);
    buffer.rewind();
    m.set(buffer);
    // return new Message(buffer);

}

From source file:com.glaf.core.util.BinaryUtils.java

/**
 * Returns a copy of all the bytes from the given <code>ByteBuffer</code>,
 * from the beginning to the buffer's limit; or null if the input is null.
 * <p>/*from w w  w. j a  v a 2 s.c om*/
 * The internal states of the given byte buffer will be restored when this
 * method completes execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to
 * call the {@link #copyBytesFrom(ByteBuffer)} instead of
 * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
 * of the input <code>ByteBuffer</code>. The opposite is typically true,
 * however, when handling <code>ByteBuffer</code> from withint the
 * unmarshallers of the low-level clients.
 */
public static byte[] copyAllBytesFrom(ByteBuffer bb) {
    if (bb == null)
        return null;
    if (bb.hasArray())
        return Arrays.copyOf(bb.array(), bb.limit());
    bb.mark();
    // the default ByteBuffer#mark() and reset() won't work, as the
    // rewind would discard the mark position
    final int marked = bb.position();
    try {
        byte[] dst = new byte[bb.rewind().remaining()];
        bb.get(dst);
        return dst;
    } finally {
        bb.position(marked);
    }
}

From source file:org.apache.hadoop.hbase.io.encoding.TestDataBlockEncoders.java

static ByteBuffer encodeKeyValues(DataBlockEncoding encoding, List<KeyValue> kvs,
        HFileBlockEncodingContext encodingContext, boolean useOffheapData) throws IOException {
    DataBlockEncoder encoder = encoding.getEncoder();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(HFILEBLOCK_DUMMY_HEADER);
    DataOutputStream dos = new DataOutputStream(baos);
    encoder.startBlockEncoding(encodingContext, dos);
    for (KeyValue kv : kvs) {
        encoder.encode(kv, encodingContext, dos);
    }/*from  w w w  .  ja va2 s.c o  m*/
    encoder.endBlockEncoding(encodingContext, dos, baos.getBuffer());
    byte[] encodedData = new byte[baos.size() - ENCODED_DATA_OFFSET];
    System.arraycopy(baos.toByteArray(), ENCODED_DATA_OFFSET, encodedData, 0, encodedData.length);
    if (useOffheapData) {
        ByteBuffer bb = ByteBuffer.allocateDirect(encodedData.length);
        bb.put(encodedData);
        bb.rewind();
        return bb;
    }
    return ByteBuffer.wrap(encodedData);
}

From source file:xbird.storage.io.RemoteVarSegments.java

public static void handleResponse(final TrackReadRequestMessage request, final ProtocolEncoderOutput out,
        final ConcurrentMap<String, FileChannel> fdCacheMap,
        final ConcurrentMap<String, IDescriptor> directoryCache) throws IOException {
    final String filePath = request.filePath;
    final long[] idxs = request.idxs;
    final int size = idxs.length;

    // look-up directory
    final File dataFile = new File(filePath);
    final long[] offsets = new long[size];
    IDescriptor directory = directoryCache.get(filePath);
    try {/*from ww w.j  a v a2 s .c  o  m*/
        if (directory == null) {
            directory = VarSegments.initDescriptor(dataFile);
            directoryCache.put(filePath, directory);
        }
        for (int i = 0; i < size; i++) {
            offsets[i] = directory.getRecordAddr(idxs[i]);
        }
    } catch (IOException e) {
        LOG.error(e);
        throw e;
    }

    FileChannel fileChannel = fdCacheMap.get(filePath);
    if (fileChannel == null) {
        if (!dataFile.exists()) {
            throw new IllegalStateException("file not exists: " + filePath);
        }
        final RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(dataFile, "r");
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
        fileChannel = raf.getChannel();
        fdCacheMap.put(filePath, fileChannel);
    }

    for (int i = 0; i < size; i++) {
        final long offset = offsets[i];
        // get data length
        final ByteBuffer tmpBuf = ByteBuffer.allocate(4);
        try {
            fileChannel.read(tmpBuf, offset);
        } catch (IOException e) {
            LOG.error(e);
            throw e;
        }
        tmpBuf.flip();
        final int length = tmpBuf.getInt();
        tmpBuf.rewind();
        IoBuffer ioBuf = IoBuffer.wrap(tmpBuf);
        out.write(ioBuf);
        // attempt zero-copy sendfile
        long position = offset + 4;
        long count = length;
        FileRegion fileRegion = new DefaultFileRegion(fileChannel, position, count);
        out.write(fileRegion);
    }
}