Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * Build a complete telegram for master/slave, master/master and broadcasts
 *
 * @param source// ww w  .j  a v a2 s  . co m
 * @param target
 * @param command
 * @param masterData
 * @param slaveData
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer buildCompleteTelegram(byte source, byte target, byte[] command, byte[] masterData,
        byte[] slaveData) throws EBusTypeException {

    boolean isMastereMaster = EBusUtils.isMasterAddress(target);
    boolean isBroadcast = target == EBusConsts.BROADCAST_ADDRESS;
    boolean isMasterSlave = !isMastereMaster && !isBroadcast;

    ByteBuffer buf = ByteBuffer.allocate(50);
    buf.put(buildPartMasterTelegram(source, target, command, masterData));

    // if used compute a complete telegram
    if (isMasterSlave && slaveData != null) {
        ByteBuffer slaveTelegramPart = buildPartSlave(slaveData);
        buf.put(slaveTelegramPart);

        buf.put(EBusConsts.ACK_OK);
        buf.put(EBusConsts.SYN);
    }

    if (isMastereMaster) {
        buf.put(EBusConsts.ACK_OK);
        buf.put(EBusConsts.SYN);
    }

    if (isBroadcast) {
        buf.put(EBusConsts.SYN);
    }

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:com.koda.integ.hbase.test.TestHFileBlockIndexer.java

@Override
protected void setUp() {
    if (buffer != null)
        return;/*from  ww w.ja v  a 2s .c om*/
    buffer = ByteBuffer.allocate(bufferSize);
    array = new KeyValue[N];
    populateData();
    serializeData();
    try {
        indexBlock();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.netflix.spectator.tdigest.Json.java

/** Encode the measurement using the generator. */
void encode(Map<String, String> commonTags, TDigestMeasurement m, JsonGenerator gen) throws IOException {
    TDigest digest = m.value();//from  w  w w.  java 2 s. c  om
    digest.compress();
    ByteBuffer buf = ByteBuffer.allocate(digest.byteSize());
    digest.asBytes(buf);

    gen.writeStartArray();
    gen.writeStartObject();
    gen.writeStringField("name", m.id().name());
    for (Map.Entry<String, String> e : commonTags.entrySet()) {
        gen.writeStringField(e.getKey(), e.getValue());
    }
    for (Tag t : m.id().tags()) {
        gen.writeStringField(t.key(), t.value());
    }
    gen.writeEndObject();
    gen.writeNumber(m.timestamp());
    gen.writeBinary(buf.array());
    gen.writeEndArray();
}

From source file:com.datatorrent.contrib.hdht.PurgeTest.java

@Test
public void testCacheWithPurge() {
    List<byte[]> dataList = Lists.newArrayList();
    byte[] deleted = HDHTWriter.DELETED;
    WriteCache cache = new WriteCache(new HDHTWriter.DefaultKeyComparator());
    for (int i = 0; i < 10; i++) {
        Slice s = new Slice(ByteBuffer.allocate(4).putInt(i).array());
        byte[] data = ByteBuffer.allocate(4).putInt(i).array();
        dataList.add(data);/*from   w  w  w .  ja  v a2 s  . c om*/
        cache.put(s, data);
    }
    Slice start = new Slice(ByteBuffer.allocate(4).putInt(2).array());
    Slice end = new Slice(ByteBuffer.allocate(4).putInt(5).array());

    Assert.assertEquals("Number of element in cache", 10, cache.size());
    cache.purge(start, end);
    Assert.assertEquals("Number of element in cache after purge", 6, cache.size());

    // data available after purge.
    byte[] data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(1).array()));
    Assert.assertEquals("Byte data ", data, dataList.get(1));

    // data at start of purge list
    data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(2).array()));
    Assert.assertEquals("Byte data ", data, HDHTWriter.DELETED);

    // data in between purge list
    data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(3).array()));
    Assert.assertEquals("Byte data ", data, HDHTWriter.DELETED);

    // data at end of purge list.
    data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(5).array()));
    Assert.assertEquals("Byte data ", data, HDHTWriter.DELETED);

    // just after purge end.
    data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(6).array()));
    Assert.assertEquals("Byte data ", data, dataList.get(6));

    // data not available should return null
    data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(10).array()));
    Assert.assertEquals("Invalid data", data, null);

    /**
     * Add a new data in the purge list
     * get on newly added data should return valid data.
     */
    cache.put(new Slice(ByteBuffer.allocate(4).putInt(3).array()), dataList.get(3));
    data = cache.get(new Slice(ByteBuffer.allocate(4).putInt(3).array()));
    Assert.assertEquals("Data added after purge is available", data, dataList.get(3));
}

From source file:com.dreamwork.web.FrontJsonController.java

private byte[] read(InputStream in) throws IOException {
    ByteBuffer fullBytesRed = ByteBuffer.allocate(0);
    int n;//from ww w .  j a v  a  2  s.  c  om
    while (true) {
        byte[] b = new byte[2048];
        n = in.read(b);
        if (n == -1) {
            break;
        }
        byte[] currBytes = fullBytesRed.array();
        fullBytesRed = ByteBuffer.allocate(currBytes.length + n);
        fullBytesRed.put(currBytes);
        fullBytesRed.put(b, 0, n);
    }
    byte[] data = fullBytesRed.array();
    return data;
}

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

/**
 * Constructs a {@link PreferFailurePcpOption}.
 */
public PreferFailurePcpOption() {
    super(2, ByteBuffer.allocate(0));
}

From source file:com.netflix.aegisthus.pig.AegisthusLoadCaster.java

@Override
public Float bytesToFloat(byte[] arg0) throws IOException {
    if (arg0 == null || arg0.length == 0) {
        return null;
    }//from  w  ww  .j  ava2 s. c  o m
    try {
        byte[] by = hex.decode(arg0);
        ByteBuffer bb = ByteBuffer.allocate(by.length);
        bb.put(by);
        bb.position(0);
        return bb.getFloat();
    } catch (Exception e) {
        LOG.error("failed to convert " + new String(arg0) + " to float");
        return null;
    }
}

From source file:com.github.neoio.net.message.staging.file.TestFileMessageStaging.java

@Test
public void test_primaryStage() throws Exception {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.flip();/* w w  w . ja v  a 2  s  .c  o  m*/
    staging.writePrimaryStaging(buffer, "Hello World".getBytes().length);

    buffer.clear();
    staging.getPrimaryStage().read(buffer);
    Assert.assertEquals("Hello World".getBytes().length, staging.getPrimaryStageSize());
    Assert.assertEquals("Hello World", new String(buffer.array(), 0, buffer.position()));

    staging.resetPrimaryStage();
    Assert.assertEquals(0, staging.getPrimaryStageSize());
}

From source file:org.lispmob.noroot.IPC.java

public void run() {
    int len = 0;//w  ww .j a v  a  2 s .c o m
    ByteBuffer buf = ByteBuffer.allocate(9000);
    while (!ipc_thread.isInterrupted()) {
        buf.clear();
        try {
            len = ipc_channel.read(buf);
            if (len == 0) {
                continue;
            }
            buf.flip();
            String json_str = EncodingUtils.getString(buf.array(), "utf8");
            JSONObject jObj = new JSONObject(json_str);
            int ipc_type = jObj.getInt("type");
            System.out.println("LISPmob: Received IPC message: " + ipc_type);
            switch (ipc_type) {
            case IPC_LOG_MSG:
                LISPmobVPNService.err_msg_code = jObj.getInt("err_msg_code");
                Thread.sleep(1000);
                if (LISPmobVPNService.err_msg_code != 0) {
                    /* If LISPmob is not the active windows, the error msg code is not clean
                     * and we send a notification of the error */
                    Resources res = vpn_service.getResources();
                    String[] err_msg = res.getStringArray(R.array.ErrMsgArray);
                    String msg = err_msg[LISPmobVPNService.err_msg_code];
                    //notifications.notify_msg( msg);
                }
                break;
            case IPC_PROTECT_SOCKS:
                int socket = jObj.getInt("socket");
                if (socket != -1) {
                    boolean sock_protect = false;
                    int retry = 0;
                    while (!sock_protect && retry < 30) {
                        if (!vpn_service.protect(socket)) {
                            retry++;
                            Thread.sleep(200);
                        } else {
                            sock_protect = true;
                            System.out.println(
                                    "LISPmob: The socket " + socket + " has been protected (VPN Service)");
                        }
                    }
                }
                break;
            default:
                System.out.println("***** Unknown IPC message: " + ipc_type);
                break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:at.tfr.securefs.client.ClientMessageHandlerImpl.java

public void write(InputStream is, final String path) throws IOException {

    final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker.createHalfDuplexPipe();
    final String uniqueKey = pipe.toString();

    pipe.getLeftSide().getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
        private final ByteBuffer buff = ByteBuffer.allocate(Constants.BUFFER_SIZE);

        public void handleEvent(StreamSourceChannel channel) {
            Message msg = null;/* w  w  w.jav  a2  s .  c  o m*/
            buff.clear();
            try {

                int count;
                while ((count = channel.read(buff)) > 0) {
                    buff.flip();
                    if (buff.hasRemaining()) {
                        msg = new Message(MessageType.DATA, path, buff).key(uniqueKey);
                        messageSender.send(msg);
                    }
                }
                if (count < 0) {
                    IoUtils.safeClose(channel);
                } else {
                    channel.resumeReads();
                }

            } catch (IOException e) {
                log.warn("cannot write message: " + msg, e);
                IoUtils.safeClose(channel);
            }
        }
    });

    pipe.getLeftSide().getCloseSetter().set(new ChannelListener<StreamSourceChannel>() {

        @Override
        public void handleEvent(StreamSourceChannel channel) {
            activeStreams.getStreams().remove(uniqueKey);
            messageSender.send(new Message(MessageType.CLOSE, path).key(uniqueKey));
        }
    });

    pipe.getRightSide().getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {
        private byte[] bytes = new byte[Constants.BUFFER_SIZE];

        @Override
        public void handleEvent(StreamSinkChannel channel) {
            try {
                int count = 0;
                while ((count = is.read(bytes, 0, bytes.length)) > 0) {
                    Channels.writeBlocking(channel, ByteBuffer.wrap(bytes, 0, count));
                }

                if (count < 0) {
                    IoUtils.safeClose(channel);
                } else {
                    channel.resumeWrites();
                }
            } catch (Exception e) {
                log.warn("cannot read from cypher: " + e, e);
                IoUtils.safeClose(channel);
            }
        }
    });

    try {
        messageSender.send(new Message(MessageType.OPEN, MessageSubType.WRITE, path).key(uniqueKey));
    } catch (Exception e) {
        IoUtils.safeClose(pipe.getLeftSide());
        IoUtils.safeClose(pipe.getRightSide());
        throw new IOException("cannot initiate OPEN: " + e, e);
    }

    activeStreams.getStreams().put(uniqueKey,
            new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe, path));

    // start sending data:
    pipe.getLeftSide().resumeReads();
    pipe.getRightSide().resumeWrites();
}