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.offbynull.portmapper.pcp.ThirdPartyPcpOption.java

private static ByteBuffer toDataSection(InetAddress internalIpAddress) {
    Validate.notNull(internalIpAddress);
    ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.put(NetworkUtils.convertToIpv6Array(internalIpAddress));

    return buffer;
}

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

/**
 * Convert the long to a byte []/* w w w .  ja v a2s .  com*/
 * @param i
 * @return
 */
public static byte[] toBytes(long i) {
    int bytes = Long.SIZE / 8;

    return ByteBuffer.allocate(bytes).putLong(i).array();
}

From source file:ConversionUtil.java

public static byte[] convertToByteArray(double value) {
    byte[] bytes = new byte[8];
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.putDouble(value);/*  w  ww . java  2 s. co  m*/
    return buffer.array();
    // buffer.get(bytes);
    // return bytes;
    //return convertToByteArray(Double.doubleToLongBits(value));
}

From source file:net.fenyo.mail4hotspot.dns.Msg.java

private byte[] process(final AdvancedServices advancedServices, final Inet4Address address)
        throws GeneralException {
    // log.debug("processing message of type " + input_buffer[0]);
    // for (byte b : input_buffer) log.debug("received byte: [" + b + "]");

    if (input_buffer.length == 0)
        throw new GeneralException("invalid size");
    if (input_buffer[0] == 0) {
        // UTF-8 message type

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);//w  w w . j a  va  2 s  . com
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        // log.debug("RECEIVED query: [" + query + "]");

        final String reply = advancedServices.processQueryFromClient(query, address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill output_buffer
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply);
        ob.get(output_buffer = new byte[ob.limit()]);

        output_size = output_buffer.length;

    } else {
        // binary message type
        // log.debug("processing binary message");

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]);
        bb.put(input_buffer, 1, input_buffer[0]);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        //      log.debug("RECEIVED query: [" + query + "]");

        final BinaryMessageReply reply = advancedServices.processBinaryQueryFromClient(query,
                Arrays.copyOfRange(input_buffer, input_buffer[0] + 1, input_buffer.length), address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill string_part
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply.reply_string);
        final byte[] string_part = new byte[ob.limit()];
        ob.get(string_part);

        if (string_part.length > 255)
            throw new GeneralException("string_part too long");
        output_buffer = new byte[string_part.length + reply.reply_data.length + 1];
        output_buffer[0] = (byte) string_part.length;
        for (int i = 0; i < string_part.length; i++)
            output_buffer[i + 1] = string_part[i];
        for (int i = 0; i < reply.reply_data.length; i++)
            output_buffer[string_part.length + i + 1] = reply.reply_data[i];
        output_size = output_buffer.length;
    }

    synchronized (compressed) {
        // http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#deflate(byte[])
        // log.debug("processing binary message: length before compressing: " + output_buffer.length);
        final Deflater compresser = new Deflater();
        compresser.setInput(output_buffer);
        compresser.finish();
        final int nbytes = compresser.deflate(compressed);
        //         log.debug("RET: " + nbytes);
        //         log.debug("COMPRESSED: " + compressed.length);
        // log.debug("processing binary message: length after compressing: " + nbytes);
        if (compressed.length == nbytes) {
            log.error("compressed buffer too small...");
            throw new GeneralException("compressed buffer too small...");
        }
        output_buffer = Arrays.copyOf(compressed, nbytes);
        output_size = output_buffer.length;
    }

    synchronized (is_processed) {
        is_processed = true;
    }

    return new byte[] { 'E', 0 }; // 'E'rror 0 == OK
}

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

private long getNumber(byte[] arg0) throws Exception {
    byte[] by = hex.decode(arg0);
    ByteBuffer bb = ByteBuffer.allocate(by.length);
    bb.put(by);/*w ww  .  j  a v  a  2s  . c  om*/
    bb.position(0);
    switch (by.length) {
    case 1:
        return (long) bb.get();
    case 2:
        return (long) bb.getShort();
    case 4:
        return (long) bb.getInt();
    case 8:
        return (long) bb.getLong();
    }
    throw new UnexpectedException("couldn't determine datatype");
}

From source file:org.jmangos.sniffer.handler.PKTLogHandler.java

/**
 * (non-Javadoc)//from   ww w .j  a  v a2s .c  o m
 * 
 * @see org.jmangos.sniffer.handler.PacketLogHandler#onDecodePacket(org.jmangos
 *      .sniffer.network.model.NetworkChannel,
 *      org.jmangos.sniffer.enums.Direction, java.lang.Integer,
 *      java.lang.Integer, byte[], int)
 */
@Override
public void onDecodePacket(final NetworkChannel channel, final Direction direction, final Integer size,
        final Integer opcode, final byte[] data, final int frame) {
    if (!isInit()) {
        init();
    }
    try {
        final ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 4 + 4 + 4 + data.length + 4);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put(direction.getValue());
        buffer.putInt(channel.hashCode());
        buffer.putInt(frame);
        buffer.putInt(0);
        buffer.putInt(data.length + 4);
        buffer.putInt(opcode);
        buffer.put(data);
        this.fous.write(buffer.array());
    } catch (final IOException e) {
        e.printStackTrace();
    }
}

From source file:net.servicestack.client.Utils.java

public static byte[] toGuidBytes(UUID theUuid) {
    ByteBuffer first8 = ByteBuffer.allocate(8);
    first8.putLong(theUuid.getMostSignificantBits());
    first8.rewind();/*from ww w  .  ja va 2 s .  c om*/

    byte[] first4 = new byte[4];
    first8.get(first4);
    reverse(first4);

    byte[] second2 = new byte[2];
    first8.get(second2);
    reverse(second2);

    byte[] third2 = new byte[2];
    first8.get(third2);
    reverse(third2);

    ByteBuffer converted16 = ByteBuffer.allocate(16).put(first4).put(second2).put(third2);

    ByteBuffer last8 = ByteBuffer.allocate(8);
    last8.putLong(theUuid.getLeastSignificantBits());
    last8.rewind();

    converted16.put(last8);

    return converted16.array();
}

From source file:io.card.development.recording.ManifestEntry.java

private static byte[] decompress(byte[] compressed) {
    /*//  w w w . ja va 2s . co  m
     * DO NOT EVER USE THIS METHOD IN PRODUCTION This is horribly inefficient, but written only
     * for testing purposes.
     */

    Bitmap b = BitmapFactory.decodeByteArray(compressed, 0, compressed.length);
    ByteBuffer bb = ByteBuffer.allocate(b.getWidth() * b.getHeight() * 4);
    b.copyPixelsToBuffer(bb);
    b.recycle();

    byte[] ba = bb.array();
    byte[] singleChannel = new byte[ba.length / 4]; // 4 channels
    for (int i = 0; i < singleChannel.length; i++) {
        singleChannel[i] = ba[i * 4 + 1];
    }

    return singleChannel;
}

From source file:io.druid.segment.writeout.WriteOutBytesTest.java

@Test
public void testCrossBufferRandomAccess() throws IOException {
    WriteOutBytes writeOutBytes = segmentWriteOutMedium.makeWriteOutBytes();
    for (int i = 0; i < ByteBufferWriteOutBytes.BUFFER_SIZE; i++) {
        writeOutBytes.write('0');
    }/*w w  w.j  a v  a 2  s .com*/
    writeOutBytes.write('1');
    writeOutBytes.write('2');
    writeOutBytes.write('3');
    ByteBuffer bb = ByteBuffer.allocate(4);
    writeOutBytes.readFully(ByteBufferWriteOutBytes.BUFFER_SIZE - 1, bb);
    bb.flip();
    Assert.assertEquals("0123", StringUtils.fromUtf8(bb));
}

From source file:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??//  ww w. j a  v a 2 s.  co m
        SocketChannel sc = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(selector, SelectionKey.OP_READ);
                doWrite(sc);
            } else {
                System.exit(1);// 
            }
        }
        if (key.isReadable()) {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String body = new String(bytes, "UTF-8");
                System.out.println("Now is : " + body);
                this.stop = true;
            } else if (readBytes < 0) {
                // 
                key.cancel();
                sc.close();
            } else {
                ; // 0
            }
        }
    }

}