Java Code Examples for java.nio.ByteBuffer.allocate()

The following are Jave code examples for showing how to use allocate() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: burstcoin   File: AT_API_Impl.java   View Source Code Vote up 6 votes
@Override
public void xor_A_with_B ( AT_Machine_State state ) {
	ByteBuffer a = ByteBuffer.allocate(32);
	a.order( ByteOrder.LITTLE_ENDIAN );
	a.put(state.get_A1());
	a.put(state.get_A2());
	a.put(state.get_A3());
	a.put(state.get_A4());
	a.clear();
	
	ByteBuffer b = ByteBuffer.allocate(32);
	b.order( ByteOrder.LITTLE_ENDIAN );
	b.put(state.get_B1());
	b.put(state.get_B2());
	b.put(state.get_B3());
	b.put(state.get_B4());
	b.clear();
	
	state.set_A1(AT_API_Helper.getByteArray(a.getLong(0) ^ b.getLong(0)));
	state.set_A2(AT_API_Helper.getByteArray(a.getLong(8) ^ b.getLong(8)));
	state.set_A3(AT_API_Helper.getByteArray(a.getLong(16) ^ b.getLong(16)));
	state.set_A4(AT_API_Helper.getByteArray(a.getLong(24) ^ b.getLong(24)));
}
 
Example 2
Project: memory   File: BufferInvariantsTest.java   View Source Code Vote up 6 votes
@Test
public void testRegion() {
  ByteBuffer byteBuffer = ByteBuffer.allocate(10);
  byteBuffer.limit(7);
  Buffer buff = Buffer.wrap(byteBuffer); //assuming buff has cap of 8
  assertEquals(buff.getCapacity(), 10); //wrong should be 8
  buff.getByte(); //pos moves to 1
  Buffer copyBuff = buff.region(); //pos: 0, start: 0, end: 6: cap: 7
  assertEquals(copyBuff.getEnd(), 6);
  assertEquals(copyBuff.getCapacity(), 6);
  assertEquals(copyBuff.getStart(), 0);
  assertEquals(copyBuff.getPosition(), 0);

  buff.setStartPositionEnd(1, 1, 5);
  buff.getByte();
  Buffer copyBuff2 = buff.region();
  assertEquals(copyBuff2.getEnd(), 3);
  assertEquals(copyBuff2.getCapacity(), 3);
  assertEquals(copyBuff2.getStart(), 0);
  assertEquals(copyBuff2.getPosition(), 0);
}
 
Example 3
Project: RISE-V2G   File: ByteUtils.java   View Source Code Vote up 6 votes
/**
 * Returns an integer value out of a byte array. 
 * 
 * @param byteArray The byte array to be converted into its decimal representation
 * @return The integer value representing the byte array
 */
public static int toIntFromByteArray(byte[] byteArray) {
	// Allocating a byte buffer holding 4 bytes for the int value
	ByteBuffer bb = ByteBuffer.allocate(4);
	
	/*
	 * The given byte array might hold less than 4 bytes, e.g. the SECC port of the SECC Discovery
	 * Response only holds 2 bytes. Thus, we must account for this and guarantee the Big Endian 
	 * byte order.
	 */
	bb.position(4 - byteArray.length);
	bb.put(byteArray);
	
	// Setting the current position to 0, otherwise getInt() would throw a BufferUnderflowException
	bb.position(0);
	
	return bb.getInt();
}
 
Example 4
Project: gnirehtet   File: IPv4PacketTest.java   View Source Code Vote up 6 votes
private static ByteBuffer createMockPacket() {
    ByteBuffer buffer = ByteBuffer.allocate(32);

    buffer.put((byte) ((4 << 4) | 5)); // versionAndIHL
    buffer.put((byte) 0); // ToS
    buffer.putShort((short) 32); // total length 20 + 8 + 4
    buffer.putInt(0); // IdFlagsFragmentOffset
    buffer.put((byte) 0); // TTL
    buffer.put((byte) 17); // protocol (UDP)
    buffer.putShort((short) 0); // checksum
    buffer.putInt(0x12345678); // source address
    buffer.putInt(0x42424242); // destination address

    buffer.putShort((short) 1234); // source port
    buffer.putShort((short) 5678); // destination port
    buffer.putShort((short) 4); // length
    buffer.putShort((short) 0); // checksum

    buffer.putInt(0x11223344); // payload

    return buffer;
}
 
Example 5
Project: openjdk-jdk10   File: AsyncSSLDelegate.java   View Source Code Vote up 6 votes
ByteBufferReference combine(ByteBufferReference ref1, ByteBufferReference ref2) {
    ByteBuffer buf1 = ref1.get();
    ByteBuffer buf2 = ref2.get();
    int avail1 = buf1.capacity() - buf1.remaining();
    if (buf2.remaining() < avail1) {
        buf1.compact();
        buf1.put(buf2);
        buf1.flip();
        ref2.clear();
        return ref1;
    }
    int newsize = buf1.remaining() + buf2.remaining();
    ByteBuffer newbuf = ByteBuffer.allocate(newsize); // getting rid of buffer pools
    newbuf.put(buf1);
    newbuf.put(buf2);
    newbuf.flip();
    ref1.clear();
    ref2.clear();
    return ByteBufferReference.of(newbuf);
}
 
Example 6
Project: hadoop-oss   File: HHUtil.java   View Source Code Vote up 5 votes
public static ByteBuffer allocateByteBuffer(boolean useDirectBuffer,
                                            int bufSize) {
  if (useDirectBuffer) {
    return ByteBuffer.allocateDirect(bufSize);
  } else {
    return ByteBuffer.allocate(bufSize);
  }
}
 
Example 7
Project: kafka-0.11.0.0-src-with-comment   File: FileRecordsTest.java   View Source Code Vote up 5 votes
private void append(FileRecords fileRecords, byte[][] values) throws IOException {
    long offset = 0L;
    for (byte[] value : values) {
        ByteBuffer buffer = ByteBuffer.allocate(128);
        MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.CURRENT_MAGIC_VALUE,
                CompressionType.NONE, TimestampType.CREATE_TIME, offset);
        builder.appendWithOffset(offset++, System.currentTimeMillis(), null, value);
        fileRecords.append(builder.build());
    }
    fileRecords.flush();
}
 
Example 8
Project: Lagerta   File: FileChecksumHelper.java   View Source Code Vote up 5 votes
/**
 * Calculated checksum for given data.
 *
 * @param content of file.
 * @return CRC32 checksum.
 */
public static byte[] calculateChecksum(byte[] content) {
    CRC32 crc = new CRC32();
    crc.update(content);
    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
    return buffer.putLong(crc.getValue()).array();
}
 
Example 9
Project: directory-ldap-api   File: ModifyDNResponseTest.java   View Source Code Vote up 5 votes
/**
 * Test the decoding of a ModifyDNResponse with no LdapResult
 */
@Test
public void testDecodeModifyDNResponseEmptyResult()
{
    Asn1Decoder ldapDecoder = new Asn1Decoder();

    ByteBuffer stream = ByteBuffer.allocate( 0x07 );

    stream.put( new byte[]
        { 0x30, 0x05, // LDAPMessage ::=SEQUENCE {
            0x02,
            0x01,
            0x01, // messageID MessageID
            0x6D,
            0x00 // CHOICE { ..., modifyDNResponse ModifyDNResponse,
        // ...
    } );

    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<ModifyDnResponseDecorator> ldapMessageContainer =
        new LdapMessageContainer<ModifyDnResponseDecorator>( codec );

    // Decode a ModifyDNResponse message
    try
    {
        ldapDecoder.decode( stream, ldapMessageContainer );
    }
    catch ( DecoderException de )
    {
        assertTrue( true );
        return;
    }

    fail( "We should not reach this point" );
}
 
Example 10
Project: s-store   File: ExecutionEngineIPC.java   View Source Code Vote up 5 votes
/** write the catalog as a UTF-8 byte string via connection */
@Override
public void loadCatalog(final String serializedCatalog) throws EEException {
    int result = ExecutionEngine.ERRORCODE_ERROR;
    m_data.clear();

    try {
        final byte catalogBytes[] = serializedCatalog.getBytes("UTF-8");
        if (m_data.capacity() < catalogBytes.length + 100) {
            m_data = ByteBuffer.allocate(catalogBytes.length + 100);
        }
        m_data.putInt(Commands.LoadCatalog.m_id);
        m_data.put(catalogBytes);
        m_data.put((byte)'\0');
    } catch (final UnsupportedEncodingException ex) {
        Logger.getLogger(ExecutionEngineIPC.class.getName()).log(
                Level.SEVERE, null, ex);
    }

    try {
        m_data.flip();
        m_connection.write();
        result = m_connection.readStatusByte();
    } catch (final IOException e) {
        System.out.println("Exception: " + e.getMessage());
        throw new RuntimeException(e);
    }
    checkErrorCode(result);
}
 
Example 11
Project: ditb   File: TestBoundedByteBufferPool.java   View Source Code Vote up 5 votes
@Test
public void testEquivalence() {
  ByteBuffer bb = ByteBuffer.allocate(1);
  this.reservoir.putBuffer(bb);
  this.reservoir.putBuffer(bb);
  this.reservoir.putBuffer(bb);
  assertEquals(3, this.reservoir.buffers.size());
}
 
Example 12
Project: IO   File: HashSection.java   View Source Code Vote up 5 votes
public byte[] getFullBytes() {
    ByteBuffer buffer = ByteBuffer.allocate(ADDITIONAL_SECTION_SIZE);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(md5Hash);
    buffer.put(padding);
    buffer.putInt(getSecondaryAdler32());
    return buffer.array();
}
 
Example 13
Project: util   File: ObjectId.java   View Source Code Vote up 5 votes
/**
 * Convert to a byte array. Note that the numbers are stored in big-endian
 * order.
 *
 * @return the byte array
 */
public byte[] toByteArray() {
	ByteBuffer buffer = ByteBuffer.allocate(12);
	putToByteBuffer(buffer);
	return buffer.array(); // using .allocate ensures there is a backing
							// array that can be returned
}
 
Example 14
Project: live_master   File: TemporalLevelEntry.java   View Source Code Vote up 5 votes
@Override
public ByteBuffer get() {
    ByteBuffer content = ByteBuffer.allocate(1);
    content.put((byte) (levelIndependentlyDecodable ? 0x80 : 0x00));
    content.rewind();
    return content;
}
 
Example 15
Project: ipack   File: NTRUSignerPrng.java   View Source Code Vote up 5 votes
/**
 * Returns <code>n</code> random bytes
 *
 * @param n number of bytes to return
 * @return the next <code>n</code> random bytes
 */
byte[] nextBytes(int n)
{
    ByteBuffer buf = ByteBuffer.allocate(n);

    while (buf.hasRemaining())
    {
        ByteBuffer cbuf = ByteBuffer.allocate(seed.length + 4);
        cbuf.put(seed);
        cbuf.putInt(counter);
        byte[] array = cbuf.array();
        byte[] hash = new byte[hashAlg.getDigestSize()];

        hashAlg.update(array, 0, array.length);

        hashAlg.doFinal(hash, 0);

        if (buf.remaining() < hash.length)
        {
            buf.put(hash, 0, buf.remaining());
        }
        else
        {
            buf.put(hash);
        }
        counter++;
    }

    return buf.array();
}
 
Example 16
Project: MetadataEditor   File: ID3v11Tag.java   View Source Code Vote up 5 votes
/**
 * Creates a new ID3v11 datatype.
 *
 * @param file
 * @param loggingFilename
 * @throws TagNotFoundException
 * @throws IOException
 */
public ID3v11Tag(RandomAccessFile file, String loggingFilename) throws TagNotFoundException, IOException
{
    setLoggingFilename(loggingFilename);
    FileChannel fc;
    ByteBuffer byteBuffer = ByteBuffer.allocate(TAG_LENGTH);

    fc = file.getChannel();
    fc.position(file.length() - TAG_LENGTH);

    fc.read(byteBuffer);
    byteBuffer.flip();
    read(byteBuffer);

}
 
Example 17
Project: hadoop-oss   File: DataOutputByteBuffer.java   View Source Code Vote up 5 votes
Buffer(int size, boolean direct) {
  this.direct = direct;
  this.size = size;
  current = direct
      ? ByteBuffer.allocateDirect(size)
      : ByteBuffer.allocate(size);
}
 
Example 18
Project: kafka-0.11.0.0-src-with-comment   File: MemoryRecordsBuilderTest.java   View Source Code Vote up 4 votes
@Test
public void convertToV1WithMixedV0AndV2Data() {
    ByteBuffer buffer = ByteBuffer.allocate(512);
    MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V0,
            compressionType, TimestampType.NO_TIMESTAMP_TYPE, 0L);
    builder.append(RecordBatch.NO_TIMESTAMP, "1".getBytes(), "a".getBytes());
    builder.close();

    builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V2, compressionType,
            TimestampType.CREATE_TIME, 1L);
    builder.append(11L, "2".getBytes(), "b".getBytes());
    builder.append(12L, "3".getBytes(), "c".getBytes());
    builder.close();

    buffer.flip();

    Records records = MemoryRecords.readableRecords(buffer).downConvert(RecordBatch.MAGIC_VALUE_V1, 0);

    List<? extends RecordBatch> batches = Utils.toList(records.batches().iterator());
    if (compressionType != CompressionType.NONE) {
        assertEquals(2, batches.size());
        assertEquals(RecordBatch.MAGIC_VALUE_V0, batches.get(0).magic());
        assertEquals(0, batches.get(0).baseOffset());
        assertEquals(RecordBatch.MAGIC_VALUE_V1, batches.get(1).magic());
        assertEquals(1, batches.get(1).baseOffset());
    } else {
        assertEquals(3, batches.size());
        assertEquals(RecordBatch.MAGIC_VALUE_V0, batches.get(0).magic());
        assertEquals(0, batches.get(0).baseOffset());
        assertEquals(RecordBatch.MAGIC_VALUE_V1, batches.get(1).magic());
        assertEquals(1, batches.get(1).baseOffset());
        assertEquals(RecordBatch.MAGIC_VALUE_V1, batches.get(2).magic());
        assertEquals(2, batches.get(2).baseOffset());
    }

    List<Record> logRecords = Utils.toList(records.records().iterator());
    assertEquals("1", utf8(logRecords.get(0).key()));
    assertEquals("2", utf8(logRecords.get(1).key()));
    assertEquals("3", utf8(logRecords.get(2).key()));

    records = MemoryRecords.readableRecords(buffer).downConvert(RecordBatch.MAGIC_VALUE_V1, 2L);

    batches = Utils.toList(records.batches().iterator());
    logRecords = Utils.toList(records.records().iterator());

    if (compressionType != CompressionType.NONE) {
        assertEquals(2, batches.size());
        assertEquals(RecordBatch.MAGIC_VALUE_V0, batches.get(0).magic());
        assertEquals(0, batches.get(0).baseOffset());
        assertEquals(RecordBatch.MAGIC_VALUE_V1, batches.get(1).magic());
        assertEquals(1, batches.get(1).baseOffset());
        assertEquals("1", utf8(logRecords.get(0).key()));
        assertEquals("2", utf8(logRecords.get(1).key()));
        assertEquals("3", utf8(logRecords.get(2).key()));
    } else {
        assertEquals(2, batches.size());
        assertEquals(RecordBatch.MAGIC_VALUE_V0, batches.get(0).magic());
        assertEquals(0, batches.get(0).baseOffset());
        assertEquals(RecordBatch.MAGIC_VALUE_V1, batches.get(1).magic());
        assertEquals(2, batches.get(1).baseOffset());
        assertEquals("1", utf8(logRecords.get(0).key()));
        assertEquals("3", utf8(logRecords.get(1).key()));
    }
}
 
Example 19
Project: boohee_v5.6   File: WebSocketServer.java   View Source Code Vote up 4 votes
public ByteBuffer createBuffer() {
    return ByteBuffer.allocate(WebSocketImpl.RCVBUF);
}
 
Example 20
Project: monarch   File: Buffers.java   View Source Code Vote up 4 votes
static ByteBuffer acquireBuffer(int size, DMStats stats, boolean send) {
  ByteBuffer result;
  if (TCPConduit.useDirectBuffers) {
    IdentityHashMap<BBSoftReference, BBSoftReference> alreadySeen = null; // keys are used like a
                                                                          // set
    BBSoftReference ref = (BBSoftReference) bufferQueue.poll();
    while (ref != null) {
      ByteBuffer bb = ref.getBB();
      if (bb == null) {
        // it was garbage collected
        int refSize = ref.consumeSize();
        if (refSize > 0) {
          if (ref.getSend()) { // fix bug 46773
            stats.incSenderBufferSize(-refSize, true);
          } else {
            stats.incReceiverBufferSize(-refSize, true);
          }
        }
      } else if (bb.capacity() >= size) {
        bb.rewind();
        bb.limit(size);
        return bb;
      } else {
        // wasn't big enough so put it back in the queue
        Assert.assertTrue(bufferQueue.offer(ref));
        if (alreadySeen == null) {
          alreadySeen = new IdentityHashMap<BBSoftReference, BBSoftReference>();
        }
        if (alreadySeen.put(ref, ref) != null) {
          // if it returns non-null then we have already seen this item
          // so we have worked all the way through the queue once.
          // So it is time to give up and allocate a new buffer.
          break;
        }
      }
      ref = (BBSoftReference) bufferQueue.poll();
    }
    result = ByteBuffer.allocateDirect(size);
  } else {
    // if we are using heap buffers then don't bother with keeping them around
    result = ByteBuffer.allocate(size);
  }
  if (send) {
    stats.incSenderBufferSize(size, TCPConduit.useDirectBuffers);
  } else {
    stats.incReceiverBufferSize(size, TCPConduit.useDirectBuffers);
  }
  return result;
}