Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:client.MultiplexingClient.java

/**
 * Creates a new packet with a size chosen randomly between
 * MIN_SIZE and MAX_SIZE. /*from www  . ja v  a  2  s .c  o m*/
 */
private ByteBuffer generateNextPacket() {
    // Generate a random size between 
    int size = MIN_SIZE + r.nextInt(maxPcktSize - MIN_SIZE);
    ByteBuffer buffer = ByteBuffer.allocate(size);
    buffer.put(SimpleProtocolDecoder.STX);
    for (int i = 0; i < size - 2; i++) {
        buffer.put((byte) ('0' + (i % 10)));
    }
    buffer.put(SimpleProtocolDecoder.ETX);
    buffer.limit(buffer.position());
    buffer.flip();
    return buffer;
}

From source file:org.apache.metron.profiler.hbase.SaltyRowKeyBuilderTest.java

/**
 * Build a row key that includes two groups.
 *//*w w  w . j a v a 2  s .  c  om*/
@Test
public void testRowKeyWithTwoGroups() throws Exception {
    // setup
    measurement.withGroups(Arrays.asList("group1", "group2"));

    // the expected row key
    ByteBuffer buffer = ByteBuffer.allocate(100)
            .put(SaltyRowKeyBuilder.getSalt(measurement.getPeriod(), saltDivisor))
            .put(measurement.getProfileName().getBytes()).put(measurement.getEntity().getBytes())
            .put("group1".getBytes()).put("group2".getBytes()).putLong(1635701L);

    buffer.flip();
    final byte[] expected = new byte[buffer.limit()];
    buffer.get(expected, 0, buffer.limit());

    // validate
    byte[] actual = rowKeyBuilder.rowKey(measurement);
    Assert.assertTrue(Arrays.equals(expected, actual));
}

From source file:com.sm.connector.server.ServerStore.java

public void writeExistBlock(CacheBlock<byte[]> block) throws IOException {
    ByteBuffer dataBuf = ByteBuffer.wrap(block.getData());
    // don't use flip() before it write when use wrap
    //dataBuf.flip();
    dataChannel.write(dataBuf, block.getDataOffset());
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    int off = 9;//from   w  w  w.  j a v a2s.c  om
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE - off);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    // must flip() before it write
    buf.flip();
    indexChannel.write(buf, pos + off);
}

From source file:com.neovisionaries.security.DigestTest.java

@Test
public void test10() {
    ByteBuffer byteBuffer = ByteBuffer.allocate(10);
    byteBuffer.put(new byte[] { 1, 2, 3, 4, 5 });
    byteBuffer.flip();

    // Ensure there is no infinite loop.
    Digest.getInstanceSHA256().update("Hello, world.", new String[] { "Hello", "world" },

            Boolean.TRUE, new boolean[] { true, false }, new Boolean[] { Boolean.TRUE, Boolean.FALSE },

            Byte.valueOf((byte) 0), new byte[] { (byte) 0, (byte) 1 },
            new Byte[] { Byte.valueOf((byte) 0), Byte.valueOf((byte) 1) }, byteBuffer,

            Character.valueOf('b'), new char[] { 'a', 'b' },
            new Character[] { Character.valueOf('a'), Character.valueOf('b') },

            Double.valueOf(0.0), new double[] { 0.0, 1.0 },
            new Double[] { Double.valueOf(0.0), Double.valueOf(1.0) },

            Float.valueOf(0.0F), new float[] { 0.0F, 1.0F },
            new Float[] { Float.valueOf(0.0F), Float.valueOf(1.0F) },

            Integer.valueOf(1), new int[] { 1, 2 }, new Integer[] { Integer.valueOf(0), Integer.valueOf(1) },

            Long.valueOf(0L), new long[] { 0L, 1L }, new Long[] { Long.valueOf(0L), Long.valueOf(1L) },

            Short.valueOf((short) 0), new short[] { (short) 0, (short) 1 },
            new Short[] { Short.valueOf((short) 0), Short.valueOf((short) 1) },

            new Object[] { new boolean[] { true, false }, new byte[] { (byte) 0, (byte) 1 } },
            new Object[] { new Object[] { new char[] { 'a', 'b' }, new short[] { 10, 20 } },
                    new Object[] { new float[] { 1.0F, 2.0F }, new double[] { 3.0, 4.0 } } });

    assertTrue(true);/*ww w .j  a v a2s .  c o m*/
}

From source file:com.offbynull.portmapper.pcp.PcpController.java

private <T extends PcpResponse> T performRequest(int sendAttempts, PcpRequest request, Creator<T> creator)
        throws InterruptedException {
    Validate.inclusiveBetween(1, 9, sendAttempts);

    ByteBuffer sendBuffer = ByteBuffer.allocate(1100);

    request.dump(sendBuffer, selfAddress);
    sendBuffer.flip();

    for (int i = 1; i <= sendAttempts; i++) {
        T response = attemptRequest(sendBuffer, i, creator);
        if (response != null) {
            return response;
        }/*  w ww .  jav  a  2  s  .  c  o m*/
    }

    throw new ResponseException();
}

From source file:com.sm.connector.server.ServerStore.java

private void writeIndexBlock(CacheBlock<byte[]> block, long keyOffset2Len, FileChannel channel)
        throws IOException {
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    checkFileSize(pos, RECORD_SIZE);/*from   w w  w .  j  a  va 2s  . c om*/
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    buf.put(block.getStatus());
    buf.putLong(keyOffset2Len);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    buf.flip();
    channel.write(buf, pos);
}

From source file:net.cellcloud.talk.stuff.PrimitiveSerializer.java

/** ??
 *///  w ww .ja va 2s  .c o m
public static void write(OutputStream stream, Primitive primitive) {
    /*
    ??
    [version]{sutff}...{stuff}[dialect@tracker]
    
    [01.00]{sub=cloud:string}{pre=add:string}[Action@Ambrose]
    */

    try {
        // 
        stream.write((int) TOKEN_OPEN_BRACKET);
        byte[] version = { '0', '1', TOKEN_POINT, '0', '0' };
        stream.write(version);
        stream.write((int) TOKEN_CLOSE_BRACKET);

        ByteBuffer buf = ByteBuffer.allocate(BLOCK);
        int bufLength = 0;

        // 
        List<SubjectStuff> subjects = primitive.subjects();
        if (null != subjects) {
            Iterator<SubjectStuff> iter = subjects.iterator();
            while (iter.hasNext()) {
                SubjectStuff stuff = iter.next();
                stream.write((int) TOKEN_OPEN_BRACE);
                stream.write(STUFFTYPE_SUBJECT_BYTES);
                stream.write((int) TOKEN_OPERATE_ASSIGN);

                bufLength = reviseValue(buf, stuff.value.getBytes(Charset.forName("UTF-8")));
                buf.flip();
                byte[] d = new byte[bufLength];
                buf.get(d, 0, bufLength);
                stream.write(d);
                buf.clear();

                stream.write((int) TOKEN_OPERATE_DECLARE);
                stream.write(parseLiteralBase(stuff.literalBase));
                stream.write((int) TOKEN_CLOSE_BRACE);
            }
        }
        List<PredicateStuff> predicates = primitive.predicates();
        if (null != predicates) {
            Iterator<PredicateStuff> iter = predicates.iterator();
            while (iter.hasNext()) {
                PredicateStuff stuff = iter.next();
                stream.write((int) TOKEN_OPEN_BRACE);
                stream.write(STUFFTYPE_PREDICATE_BYTES);
                stream.write((int) TOKEN_OPERATE_ASSIGN);

                bufLength = reviseValue(buf, stuff.value.getBytes(Charset.forName("UTF-8")));
                buf.flip();
                byte[] d = new byte[bufLength];
                buf.get(d, 0, bufLength);
                stream.write(d);
                buf.clear();

                stream.write((int) TOKEN_OPERATE_DECLARE);
                stream.write(parseLiteralBase(stuff.literalBase));
                stream.write((int) TOKEN_CLOSE_BRACE);
            }
        }
        List<ObjectiveStuff> objectives = primitive.objectives();
        if (null != objectives) {
            Iterator<ObjectiveStuff> iter = objectives.iterator();
            while (iter.hasNext()) {
                ObjectiveStuff stuff = iter.next();
                stream.write((int) TOKEN_OPEN_BRACE);
                stream.write(STUFFTYPE_OBJECTIVE_BYTES);
                stream.write((int) TOKEN_OPERATE_ASSIGN);

                bufLength = reviseValue(buf, stuff.value.getBytes(Charset.forName("UTF-8")));
                buf.flip();
                byte[] d = new byte[bufLength];
                buf.get(d, 0, bufLength);
                stream.write(d);
                buf.clear();

                stream.write((int) TOKEN_OPERATE_DECLARE);
                stream.write(parseLiteralBase(stuff.literalBase));
                stream.write((int) TOKEN_CLOSE_BRACE);
            }
        }
        List<AdverbialStuff> adverbials = primitive.adverbials();
        if (null != adverbials) {
            Iterator<AdverbialStuff> iter = adverbials.iterator();
            while (iter.hasNext()) {
                AdverbialStuff stuff = iter.next();
                stream.write((int) TOKEN_OPEN_BRACE);
                stream.write(STUFFTYPE_ADVERBIAL_BYTES);
                stream.write((int) TOKEN_OPERATE_ASSIGN);

                bufLength = reviseValue(buf, stuff.value.getBytes(Charset.forName("UTF-8")));
                buf.flip();
                byte[] d = new byte[bufLength];
                buf.get(d, 0, bufLength);
                stream.write(d);
                buf.clear();

                stream.write((int) TOKEN_OPERATE_DECLARE);
                stream.write(parseLiteralBase(stuff.literalBase));
                stream.write((int) TOKEN_CLOSE_BRACE);
            }
        }
        List<AttributiveStuff> attributives = primitive.attributives();
        if (null != attributives) {
            Iterator<AttributiveStuff> iter = attributives.iterator();
            while (iter.hasNext()) {
                AttributiveStuff stuff = iter.next();
                stream.write((int) TOKEN_OPEN_BRACE);
                stream.write(STUFFTYPE_ATTRIBUTIVE_BYTES);
                stream.write((int) TOKEN_OPERATE_ASSIGN);

                bufLength = reviseValue(buf, stuff.value.getBytes(Charset.forName("UTF-8")));
                buf.flip();
                byte[] d = new byte[bufLength];
                buf.get(d, 0, bufLength);
                stream.write(d);
                buf.clear();

                stream.write((int) TOKEN_OPERATE_DECLARE);
                stream.write(parseLiteralBase(stuff.literalBase));
                stream.write((int) TOKEN_CLOSE_BRACE);
            }
        }
        List<ComplementStuff> complements = primitive.complements();
        if (null != complements) {
            Iterator<ComplementStuff> iter = complements.iterator();
            while (iter.hasNext()) {
                ComplementStuff stuff = iter.next();
                stream.write((int) TOKEN_OPEN_BRACE);
                stream.write(STUFFTYPE_COMPLEMENT_BYTES);
                stream.write((int) TOKEN_OPERATE_ASSIGN);

                bufLength = reviseValue(buf, stuff.value.getBytes(Charset.forName("UTF-8")));
                buf.flip();
                byte[] d = new byte[bufLength];
                buf.get(d, 0, bufLength);
                stream.write(d);
                buf.clear();

                stream.write((int) TOKEN_OPERATE_DECLARE);
                stream.write(parseLiteralBase(stuff.literalBase));
                stream.write((int) TOKEN_CLOSE_BRACE);
            }
        }

        // 
        Dialect dialect = primitive.getDialect();
        if (null != dialect) {
            stream.write(TOKEN_OPEN_BRACKET);
            stream.write(dialect.getName().getBytes(Charset.forName("UTF-8")));
            stream.write(TOKEN_AT);
            stream.write(dialect.getTracker().getBytes(Charset.forName("UTF-8")));
            stream.write(TOKEN_CLOSE_BRACKET);
        }

        stream.flush();
    } catch (IOException e) {
        Logger.log(PrimitiveSerializer.class, e, LogLevel.ERROR);
    }
}

From source file:com.rs.worldserver.io.IOClient.java

public void read(ByteBuffer buffer) {
    inStream.currentOffset = 0;//  w w w .ja va 2  s.c o m
    buffer.flip();
    buffer.get(inStream.buffer, 0, buffer.limit());
    inStream.length = buffer.limit();
    try {
        try {
            System.out.println("Processing");
            process();
        } catch (Exception e) {
            e.printStackTrace();
            Server.getIoThread().destroySocket(Server.getIoThread().socketFor(this), connectedFrom.toString(),
                    true);
        }
    } catch (Exception e) {
    }
}

From source file:org.apache.hadoop.ipc.RpcSSLEngineAbstr.java

protected ByteBuffer handleBufferUnderflow(ByteBuffer buffer) {
    // If there is no size issue, return the same buffer and let the
    // peer read more data
    if (sslEngine.getSession().getPacketBufferSize() < buffer.limit()) {
        return buffer;
    } else {// w  w w  .jav  a2  s .  co  m
        ByteBuffer newBuffer = enlargePacketBuffer(buffer);
        buffer.flip();
        newBuffer.put(buffer);
        return newBuffer;
    }
}

From source file:com.zotoh.maedr.device.apache.StreamingNHttpEntity.java

private void sockItDown(ContentDecoder decoder) throws IOException {

    tlog().debug("StreamingNHttpEntity: sockItDown()");

    ByteBuffer buffer;
    int cnt;//  w  ww . jav  a  2  s.  co m

    buffer = _alloctor.allocate(4096);
    do {

        buffer.clear();

        if ((cnt = decoder.read(buffer)) == -1)
            break;

        if (cnt == 0) {

            if (buffer.hasRemaining())
                break;
            else
                continue;
        }

        // 
        buffer.flip();
        byte[] bits = new byte[4096];
        int len;

        while (buffer.hasRemaining()) {
            len = Math.min(4096, buffer.remaining());
            buffer.get(bits, 0, len);
            storeBytes(bits, len);
        }
    } while (true);

}