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:com.facebook.infrastructure.net.UdpConnection.java

public boolean write(Message message, EndPoint to) throws IOException {
    boolean bVal = true;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    Message.serializer().serialize(message, dos);
    byte[] data = bos.toByteArray();
    if (data.length > 0) {
        logger_.trace("Size of Gossip packet " + data.length);
        byte[] protocol = BasicUtilities.intToByteArray(protocol_);
        ByteBuffer buffer = ByteBuffer.allocate(data.length + protocol.length);
        buffer.put(protocol);// ww  w.  jav  a 2  s  . c  o  m
        buffer.put(data);
        buffer.flip();

        int n = socketChannel_.send(buffer, to.getInetAddress());
        if (n == 0) {
            bVal = false;
        }
    }
    return bVal;
}

From source file:com.honeywell.printer.net.autobaln_websocket.WebSocketWriter.java

/**
 * Create new WebSockets background writer.
 *
 * @param looper    The message looper of the background thread on which
 *                  this object is running.
 * @param master    The message handler of master (foreground thread).
 * @param socket    The socket channel created on foreground thread.
 * @param options   WebSockets connection options.
 *//*from w  w  w.  j a  v  a  2s  .  co m*/
public WebSocketWriter(Handler master, Socket socket, WebSocketOptions options, String threadName) {
    super(threadName);

    this.mWebSocketConnectionHandler = master;
    this.mWebSocketOptions = options;
    this.mSocket = socket;

    this.mApplicationBuffer = ByteBuffer.allocate(options.getMaxFramePayloadSize() + 14);

    Log.d(TAG, "WebSocket writer created.");
}

From source file:com.turn.ttorrent.client.TorrentByteStorage.java

public ByteBuffer read(int offset, int length) throws IOException {
    ByteBuffer data = ByteBuffer.allocate(length);
    int bytes = this.channel.read(data, offset);
    data.clear();//from ww w. j  av  a2s  .  co m
    data.limit(bytes >= 0 ? bytes : 0);
    return data;
}

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

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

    buffer.put("Hello World".getBytes("US-ASCII"));
    buffer.flip();//from w ww. java2 s.  c  o m
    Assert.assertEquals(11, staging.writeTempReadBytes(buffer));
    Assert.assertTrue(staging.hasTempReadBytes());
    buffer.clear();
    Assert.assertEquals(11, staging.readTempReadBytes(buffer));
    buffer.put("Hello World".getBytes("US-ASCII"));
    buffer.flip();
    staging.writePrimaryStaging(buffer, 22);
    buffer.clear();
    staging.getPrimaryStage().read(buffer);
    Assert.assertEquals("Hello WorldHello World", new String(buffer.array(), 0, 22));
}

From source file:com.bah.culvert.util.Bytes.java

/**
 * Convert a character to a byte[]// w  ww  . j a  v a2 s .  c om
 * @param c
 * @return
 */
public static byte[] toBytes(char c) {
    int bytes = Character.SIZE / 8;
    return ByteBuffer.allocate(bytes).putChar(c).array();
}

From source file:com.google.cloud.public_datasets.nexrad2.GcsUntar.java

private static File downloadFromGcs(String bucketName, String blobName, File tmpDir) throws IOException {
    Storage storage = StorageOptions.getDefaultInstance().getService();
    File fileName = File.createTempFile("download", "bytes", tmpDir);
    try (ReadChannel reader = storage.reader(bucketName, blobName);
            FileOutputStream writer = new FileOutputStream(fileName)) {
        ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
        while (reader.read(bytes) > 0) {
            bytes.flip();/*from w w  w.jav  a  2 s. c  om*/
            writer.getChannel().write(bytes);
            bytes.clear();
        }
    }
    return fileName;
}

From source file:edu.umn.cs.spatialHadoop.nasa.HDFRasterLayer.java

@Override
public void write(DataOutput out) throws IOException {
    super.write(out);
    out.writeLong(timestamp);/*from   w ww  . j ava  2s. co  m*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    ByteBuffer bbuffer = ByteBuffer.allocate(getHeight() * 2 * 8 + 8);
    bbuffer.putInt(getWidth());
    bbuffer.putInt(getHeight());
    gzos.write(bbuffer.array(), 0, bbuffer.position());
    for (int x = 0; x < getWidth(); x++) {
        bbuffer.clear();
        for (int y = 0; y < getHeight(); y++) {
            bbuffer.putLong(sum[x][y]);
            bbuffer.putLong(count[x][y]);
        }
        gzos.write(bbuffer.array(), 0, bbuffer.position());
    }
    gzos.close();

    byte[] serializedData = baos.toByteArray();
    out.writeInt(serializedData.length);
    out.write(serializedData);
}

From source file:com.jadarstudios.rankcapes.bukkit.CapePackValidator.java

/**
 * Utility method to detect if the bytes given are a zip file.
 *
 * @param bytes the bytes of the file/*from   w ww .  j  a v  a2  s .  co  m*/
 *
 * @return if it is a zip file
 */
public static boolean isZipFile(byte[] bytes) {
    ByteArrayInputStream input = new ByteArrayInputStream(bytes);

    ByteBuffer buffer = ByteBuffer.allocate(4);
    input.read(buffer.array(), 0, buffer.capacity());

    short packIdentifier = buffer.getShort();

    return packIdentifier == ZIP_IDENTIFIER;
}

From source file:eu.stratosphere.api.java.record.io.TextInputFormat.java

@Override
public void configure(Configuration parameters) {
    super.configure(parameters);

    // get the charset for the decoding
    String charsetName = parameters.getString(CHARSET_NAME, DEFAULT_CHARSET_NAME);
    if (charsetName == null || !Charset.isSupported(charsetName)) {
        throw new RuntimeException("Unsupported charset: " + charsetName);
    }/*from  ww  w .  j  a v  a  2s. co m*/

    if (charsetName.equals("ISO-8859-1") || charsetName.equalsIgnoreCase("ASCII")) {
        this.ascii = true;
    } else {
        this.decoder = Charset.forName(charsetName).newDecoder();
        this.byteWrapper = ByteBuffer.allocate(1);
    }

    // get the field position to write in the record
    this.pos = parameters.getInteger(FIELD_POS, 0);
    if (this.pos < 0) {
        throw new RuntimeException("Illegal configuration value for the target position: " + this.pos);
    }
}

From source file:com.unister.semweb.drums.api.DRUMSTest.java

/**
 * This method is for testing the binary search in DRUMS.findElementInReadBuffer()
 * //from   w w  w  .j a va 2s  . co m
 * @throws IOException
 * @throws ClassNotFoundException
 */
@Test
public void findElementInReadBufferTest() throws IOException, ClassNotFoundException {
    log.info("Test Binary search. findElementInReadBufferTest()");
    DRUMS<DummyKVStorable> table = DRUMSInstantiator.createOrOpenTable(hashFunction, TestUtils.gp);
    // create data
    DummyKVStorable d1 = DummyKVStorable.getInstance();
    d1.setKey(new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 });
    DummyKVStorable d2 = DummyKVStorable.getInstance();
    d2.setKey(new byte[] { 0, 0, 0, 0, 0, 0, 0, 2 });
    DummyKVStorable d3 = DummyKVStorable.getInstance();
    d3.setKey(new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 });
    ByteBuffer bb = ByteBuffer.allocate(3 * TestUtils.gp.getElementSize());
    bb.put(d1.toByteBuffer().array());
    bb.put(d2.toByteBuffer().array());
    bb.put(d3.toByteBuffer().array());

    Assert.assertEquals(-1, table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, 0));
    Assert.assertEquals(0, table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 }, 0));
    Assert.assertEquals(1 * TestUtils.gp.getElementSize(),
            table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 2 }, 0));
    Assert.assertEquals(2 * TestUtils.gp.getElementSize(),
            table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 }, 0));
    Assert.assertEquals(2 * TestUtils.gp.getElementSize(), table.findElementInReadBuffer(bb,
            new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 }, 1 * TestUtils.gp.getElementSize()));
    Assert.assertEquals(2 * TestUtils.gp.getElementSize(), table.findElementInReadBuffer(bb,
            new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 }, 2 * TestUtils.gp.getElementSize()));
    Assert.assertEquals(-1, table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 },
            3 * TestUtils.gp.getElementSize()));
}