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:jsave.Utils.java

public static int read_uint16(final RandomAccessFile raf) throws IOException {
    byte[] data = new byte[2];
    raf.read(data);//from  w  ww  .j a  va 2s .  c o  m
    ByteBuffer bb = ByteBuffer.allocate(data.length);
    bb.put(data);
    return getUnsignedShort(bb);
}

From source file:com.alvermont.terraj.fracplanet.util.ByteBufferUtils.java

/**
 * The sizes of Java types are fixed and defined by the language spec so
 * this shouldn't be necessary but I'm going to do it anyway - so
 * there!/*from   ww w  .ja v a2s  . c o  m*/
 *
 * @return The number of bytes occupied by a float value
 */
public static int sizeofFloat() {
    final ByteBuffer buffer = ByteBuffer.allocate(10);

    buffer.putFloat(0.0f);

    return buffer.position();
}

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

public String debugContent() {
    String retval = "";

    if (input_buffer.length == 0)
        return "invalid null size";

    if (input_buffer[0] == 0) {
        // UTF-8 message type
        retval += "type=text;";

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);/*from w w w  .  j av a  2s .  c  o  m*/
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        retval += "query=" + query + ";";

    } else {
        // binary message type
        retval += "type=binary;";

        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();
        retval += "query=" + query + ";";
    }

    return retval;
}

From source file:org.sglover.nlp.EntityExtracter.java

private String getContent(ReadableByteChannel channel) throws IOException {
    StringBuilder sb = new StringBuilder();
    ByteBuffer bb = ByteBuffer.allocate(2048);
    int c = -1;/* w  w  w .  j  a va2 s  . c  o  m*/
    do {
        c = channel.read(bb);
        bb.flip();
        bb.clear();
        sb.append(new String(bb.array(), "UTF-8"));
    } while (c != -1);

    String content = sb.toString();
    return content;
}

From source file:io.blobkeeper.file.util.FileUtils.java

public static long getCrc(@NotNull File file) {
    CRC32 crc = new CRC32();

    while (true) {
        ByteBuffer buffer = ByteBuffer.allocate(CHUNK_SIZE);
        while (buffer.hasRemaining()) {
            int bytes = 0;
            try {
                bytes = file.getFileChannel().read(buffer);
            } catch (IOException e) {
                log.error("Can't read blob file " + file, e);
                throw new IllegalArgumentException(e);
            }/*from   w  w w.  j a va 2 s  .  c o  m*/
            if (bytes < 0) {
                break;
            }
        }
        buffer.flip();
        if (buffer.remaining() == 0) {
            break;
        } else {
            crc.update(buffer.array());
        }
    }

    return crc.getValue();
}

From source file:edu.uci.ics.hyracks.dataflow.std.sort.util.DeletableFrameTupleAppenderTest.java

@Test
public void testClear() throws Exception {
    ByteBuffer buffer = ByteBuffer.allocate(cap);
    appender.clear(buffer);/*  w  w  w  .  j  a v a  2  s  .co  m*/
    assertTrue(appender.getBuffer() == buffer);
    assertTrue(appender.getTupleCount() == 0);
    assertTrue(appender.getContiguousFreeSpace() == cap - 4 - 4);
}

From source file:com.hortonworks.registries.schemaregistry.serdes.avro.AvroSnapshotDeserializer.java

protected SchemaIdVersion retrieveSchemaIdVersion(InputStream payloadInputStream) throws SerDesException {
    // it can be enhanced to have respective protocol handlers for different versions
    // first byte is protocol version/id.
    // protocol format:
    // 1 byte  : protocol version
    // 8 bytes : schema metadata Id
    // 4 bytes : schema version
    ByteBuffer byteBuffer = ByteBuffer.allocate(13);
    try {/* w  w w.  j  a v  a 2  s. com*/
        payloadInputStream.read(byteBuffer.array());
    } catch (IOException e) {
        throw new SerDesException(e);
    }

    byte protocolId = byteBuffer.get();
    if (protocolId != AvroSchemaProvider.CURRENT_PROTOCOL_VERSION) {
        throw new SerDesException(
                "Unknown protocol id [" + protocolId + "] received while deserializing the payload");
    }
    long schemaMetadataId = byteBuffer.getLong();
    int schemaVersion = byteBuffer.getInt();

    return new SchemaIdVersion(schemaMetadataId, schemaVersion);
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected String receive() {
    SocketChannel socketChannel = null;

    try {/*from   w  w w .  j  a  va2 s  .  c om*/
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:com.offbynull.portmapper.common.ByteBufferUtils.java

/**
 * Copy the remaining content of a {@link ByteBuffer} in to a new non-direct {@link ByteBuffer}.
 * @param src buffer to copy//from   ww w.j av  a2 s  .  c  o m
 * @param incrementSrc of {@code true} increments {@code src}'s position
 * @param incrementDst of {@code true} increments {@code dst}'s position
 * @return new buffer with the remaining content in {@code src}
 * @throws NullPointerException if any arguments are {@code null}
 */
public static ByteBuffer copyContents(ByteBuffer src, boolean incrementSrc, boolean incrementDst) {
    Validate.notNull(src);
    if (!incrementSrc) {
        src.mark();
    }

    ByteBuffer dst = ByteBuffer.allocate(src.remaining());
    dst.put(src);

    if (!incrementSrc) {
        src.reset();
    }

    if (!incrementDst) {
        dst.flip();
    }

    return dst;
}

From source file:Main.java

public final static ByteBuffer borrowByteBufferMedium() {
    if (byteBuffersPoolMedium.isEmpty()) {
        return ByteBuffer.allocate(MAX_LINE_BYTES_MEDIUM);
    } else {/*w w  w.ja  v a2s .c o  m*/
        return byteBuffersPoolMedium.remove(0);
    }
}