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

The following are Jave code examples for showing how to use put() 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: directory-ldap-api   File: SyncDoneValueDecorator.java   View Source Code Vote up 6 votes
/**
 * Encode the SyncDoneValue control
 *
 * @param buffer The encoded sink
 * @return A ByteBuffer that contains the encoded PDU
 * @throws EncoderException If anything goes wrong while encoding.
 */
@Override
public ByteBuffer encode( ByteBuffer buffer ) throws EncoderException
{
    if ( buffer == null )
    {
        throw new EncoderException( I18n.err( I18n.ERR_04023 ) );
    }

    // Encode the SEQ
    buffer.put( UniversalTag.SEQUENCE.getValue() );
    buffer.put( TLV.getBytes( syncDoneValueLength ) );

    if ( getCookie() != null )
    {
        BerValue.encode( buffer, getCookie() );
    }

    if ( isRefreshDeletes() )
    {
        BerValue.encode( buffer, isRefreshDeletes() );
    }

    return buffer;
}
 
Example 2
Project: memory   File: BufferTest2.java   View Source Code Vote up 6 votes
@Test
public void testByteBufferPositionPreservation() {
  ByteBuffer bb = ByteBuffer.allocate(64).order(ByteOrder.nativeOrder());

  Byte b = 0;
  while (bb.hasRemaining()) {
    bb.put(b);
    b++;
  }
  bb.position(10);

  Buffer buffer = Buffer.wrap(bb);
  while (buffer.hasRemaining()) {
    assertEquals(bb.get(), buffer.getByte());
  }
}
 
Example 3
Project: directory-ldap-api   File: BasicControlDecorator.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public ByteBuffer encode( ByteBuffer buffer ) throws EncoderException
{
    if ( buffer == null )
    {
        throw new EncoderException( I18n.err( I18n.ERR_04023 ) );
    }

    if ( valueLength != 0 )
    {
        buffer.put( getValue() );
    }

    return buffer;
}
 
Example 4
Project: mycat-src-1.6.1-RELEASE   File: ErrorPacket.java   View Source Code Vote up 6 votes
public byte[] writeToBytes() {
	ByteBuffer buffer = ByteBuffer.allocate(calcPacketSize()+4);
	int size = calcPacketSize();
	BufferUtil.writeUB3(buffer, size);
	buffer.put(packetId);
	buffer.put(fieldCount);
	BufferUtil.writeUB2(buffer, errno);
	buffer.put(mark);
	buffer.put(sqlState);
	if (message != null) {
		buffer.put(message);
	}
	buffer.flip();
	byte[] data = new byte[buffer.limit()];
	buffer.get(data);

	return data;
}
 
Example 5
Project: Nukkit-Java9   File: QueryRegenerateEvent.java   View Source Code Vote up 6 votes
public byte[] getShortQuery() {
    ByteBuffer query = ByteBuffer.allocate(65536);
    query.put(this.serverName.getBytes(StandardCharsets.UTF_8));
    query.put((byte) 0x00);
    query.put(this.gameType.getBytes(StandardCharsets.UTF_8));
    query.put((byte) 0x00);
    query.put(this.map.getBytes(StandardCharsets.UTF_8));
    query.put((byte) 0x00);
    query.put(String.valueOf(this.numPlayers).getBytes(StandardCharsets.UTF_8));
    query.put((byte) 0x00);
    query.put(String.valueOf(this.maxPlayers).getBytes(StandardCharsets.UTF_8));
    query.put((byte) 0x00);
    query.put(Binary.writeLShort(this.port));
    query.put(this.ip.getBytes(StandardCharsets.UTF_8));
    query.put((byte) 0x00);
    return Arrays.copyOf(query.array(), query.position());
}
 
Example 6
Project: jdk8u-jdk   File: EngineWriter.java   View Source Code Vote up 5 votes
private HandshakeStatus getOutboundData(ByteBuffer dstBB) {

        Object msg = outboundList.removeFirst();
        assert(msg instanceof ByteBuffer);

        ByteBuffer bbIn = (ByteBuffer) msg;
        assert(dstBB.remaining() >= bbIn.remaining());

        dstBB.put(bbIn);

        /*
         * If we have more data in the queue, it's either
         * a finished message, or an indication that we need
         * to call wrap again.
         */
        if (hasOutboundDataInternal()) {
            msg = outboundList.getFirst();
            if (msg == HandshakeStatus.FINISHED) {
                outboundList.removeFirst();     // consume the message
                return HandshakeStatus.FINISHED;
            } else {
                return HandshakeStatus.NEED_WRAP;
            }
        } else {
            return null;
        }
    }
 
Example 7
Project: jdk8u-jdk   File: Encrypt.java   View Source Code Vote up 5 votes
private void combination_16(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocateDirect(0);
    emptyBuf.put(new byte[0]);
    c.updateAAD(emptyBuf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocateDirect(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer output = ByteBuffer.allocateDirect(
            c.getOutputSize(in.limit()));
    output.position(0);
    output.limit(c.getOutputSize(in.limit()));

    // process input text with an empty buffer
    c.update(in, output);
    ByteBuffer emptyBuf2 = ByteBuffer.allocate(0);
    emptyBuf2.put(new byte[0]);
    c.doFinal(emptyBuf2, output);
    int resultSize = output.position();
    byte[] result16 = new byte[resultSize];
    output.position(0);
    output.limit(resultSize);
    output.get(result16, 0, resultSize);
    results.add(result16);
}
 
Example 8
Project: openjdk-jdk10   File: DataSection.java   View Source Code Vote up 5 votes
@Override
protected void emit(ByteBuffer buffer, Patches patches) {
    int rest = getSize();
    while (rest > 8) {
        buffer.putLong(0L);
        rest -= 8;
    }
    while (rest > 0) {
        buffer.put((byte) 0);
        rest--;
    }
}
 
Example 9
Project: feeyo-redisproxy   File: Manage.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public static synchronized byte[] encodeObject(List<Object> lines) throws BufferOverflowException {
	// 粗略分配
	int bufferSize = getSize(lines);
	ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
	
	if (lines.size() > 0) {
		buffer.put((byte) '*');
		buffer.put(ProtoUtils.convertIntToByteArray(lines.size()));
		buffer.put("\r\n".getBytes());

		for (int i = 0; i < lines.size(); i++) {
			Object obj = lines.get(i);
			if (obj instanceof String) {
				byte[] lineBytes = String.valueOf(obj).getBytes();
				buffer.put((byte) '$');
				buffer.put(ProtoUtils.convertIntToByteArray(lineBytes.length));
				buffer.put("\r\n".getBytes());
				buffer.put(lineBytes);
				buffer.put("\r\n".getBytes());
				
			} else if (obj instanceof List) {
				buffer.put( encodeObject( (List<Object>) obj ) );
			}
		}

	} else {
		return "-ERR no data.\r\n".getBytes();
	}

	buffer.flip();
	byte[] data = new byte[buffer.remaining()];
	buffer.get(data);
	return data;
}
 
Example 10
Project: live_master   File: ContentDistributorIdBox.java   View Source Code Vote up 5 votes
@Override
protected void getContent(ByteBuffer byteBuffer) {
    writeVersionAndFlags(byteBuffer);
    IsoTypeWriter.writeIso639(byteBuffer, language);
    byteBuffer.put(Utf8.convert(contentDistributorId));
    byteBuffer.put((byte) 0);

}
 
Example 11
Project: directory-ldap-api   File: ExtendedResponseTest.java   View Source Code Vote up 5 votes
/**
 * Test the decoding of an empty ExtendedResponse
 */
@Test
public void testDecodeExtendedResponseEmpty()
{
    Asn1Decoder ldapDecoder = new Asn1Decoder();

    ByteBuffer stream = ByteBuffer.allocate( 0x07 );

    stream.put( new byte[]
        { 0x30, 0x05, // LDAPMessage ::= SEQUENCE {
            0x02,
            0x01,
            0x01, // messageID MessageID
            // CHOICE { ..., extendedResp Response, ...
            0x78,
            0x00 // ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
    } );

    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<ExtendedResponseDecorator<?>> container =
        new LdapMessageContainer<ExtendedResponseDecorator<?>>( codec );

    // Decode a DelRequest PDU
    try
    {
        ldapDecoder.decode( stream, container );
        fail( "We should never reach this point !!!" );
    }
    catch ( DecoderException de )
    {
        assertTrue( true );
    }
}
 
Example 12
Project: lams   File: Masker.java   View Source Code Vote up 5 votes
private void mask(ByteBuffer buf, int position, int length) {
    int limit = position + length;
    for (int i = position ; i < limit; ++i) {
        buf.put(i, (byte) (buf.get(i) ^ maskingKey[m++]));
        m %= 4;
    }
}
 
Example 13
Project: mi-firma-android   File: XfrBlock.java   View Source Code Vote up 5 votes
XfrBlock(final byte insCount, final byte[] apdu, final byte[] typeXfr){
	this.instructionCount = insCount;
	final ByteBuffer commandBuffer = ByteBuffer.allocate(UsbCommand.USB_HEADER_BASE_SIZE + apdu.length);
	final byte DEFAULT_BLOCKING_WAIT = (byte) 0x01;
	commandBuffer.put((byte) 0x6F);
	commandBuffer.put(HexUtils.intToByteArray(apdu.length));
	commandBuffer.put(new byte[]{(byte) 0x00, this.instructionCount, DEFAULT_BLOCKING_WAIT});
	commandBuffer.put(typeXfr);
	commandBuffer.put(apdu);
	this.command = commandBuffer.array();
}
 
Example 14
Project: directory-ldap-api   File: EntryChangeControlTest.java   View Source Code Vote up 5 votes
/**
 * Test the decoding of a EntryChangeControl
 */
@Test
public void testDecodeEntryChangeControlSuccess() throws Exception
{
    ByteBuffer bb = ByteBuffer.allocate( 0x0D );
    bb.put( new byte[]
        {
            0x30, 0x0B, // EntryChangeNotification ::= SEQUENCE {
            0x0A,
            0x01,
            0x08, //     changeType ENUMERATED {
                  //         modDN (8)
                  //     }
            0x04,
            0x03,
            'a',
            '=',
            'b', //     previousDN LDAPDN OPTIONAL, -- modifyDN ops. only
            0x02,
            0x01,
            0x10 //     changeNumber INTEGER OPTIONAL } -- if supported
    } );
    bb.flip();

    EntryChangeDecorator decorator = new EntryChangeDecorator( codec );

    EntryChange entryChange = ( EntryChange ) decorator.decode( bb.array() );

    assertEquals( ChangeType.MODDN, entryChange.getChangeType() );
    assertEquals( "a=b", entryChange.getPreviousDn().toString() );
    assertEquals( 16, entryChange.getChangeNumber() );
}
 
Example 15
Project: dble   File: BufferPerformanceMain.java   View Source Code Vote up 5 votes
public void putAllocateDirect() {
    ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
    byte[] b = new byte[1024];

    int count = 1000000;
    System.currentTimeMillis();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        buffer.position(0);
        buffer.put(b);
    }
    long t2 = System.currentTimeMillis();
    System.out.println("take time:" + (t2 - t1) + " ms.(Put:allocateDirect)");
}
 
Example 16
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MessageEncodeDecodeTest.java   View Source Code Vote up 5 votes
@Test
public void testEncodeDecodeSingle() throws Exception {
    Message message = new Message("topic", "body".getBytes());
    message.setFlag(12);
    message.putUserProperty("key", "value");
    byte[] bytes = MessageDecoder.encodeMessage(message);
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);
    buffer.flip();
    Message newMessage = MessageDecoder.decodeMessage(buffer);

    assertTrue(message.getFlag() == newMessage.getFlag());
    assertTrue(newMessage.getProperty("key").equals(newMessage.getProperty("key")));
    assertTrue(Arrays.equals(newMessage.getBody(), message.getBody()));
}
 
Example 17
Project: mycat-src-1.6.1-RELEASE   File: BufferUtil.java   View Source Code Vote up 4 votes
public static final void writeUB4(ByteBuffer buffer, long l) {
    buffer.put((byte) (l & 0xff));
    buffer.put((byte) (l >>> 8));
    buffer.put((byte) (l >>> 16));
    buffer.put((byte) (l >>> 24));
}
 
Example 18
Project: Cybernet-VPN   File: LogItem.java   View Source Code Vote up 4 votes
public byte[] getMarschaledBytes() throws UnsupportedEncodingException, BufferOverflowException {
    ByteBuffer bb = ByteBuffer.allocate(16384);
    bb.put((byte) 0x0);               //version
    bb.putLong(logtime);              //8
    bb.putInt(mVerbosityLevel);      //4
    bb.putInt(mLevel.getInt());
    bb.putInt(mRessourceId);
    if (mMessage == null || mMessage.length() == 0) {
        bb.putInt(0);
    } else {
        marschalString(mMessage, bb);
    }
    if (mArgs == null || mArgs.length == 0) {
        bb.putInt(0);
    } else {
        bb.putInt(mArgs.length);
        for (Object o : mArgs) {
            if (o instanceof String) {
                bb.putChar('s');
                marschalString((String) o, bb);
            } else if (o instanceof Integer) {
                bb.putChar('i');
                bb.putInt((Integer) o);
            } else if (o instanceof Float) {
                bb.putChar('f');
                bb.putFloat((Float) o);
            } else if (o instanceof Double) {
                bb.putChar('d');
                bb.putDouble((Double) o);
            } else if (o instanceof Long) {
                bb.putChar('l');
                bb.putLong((Long) o);
            } else if (o == null) {
                bb.putChar('0');
            } else {
                VpnStatus.logDebug("Unknown object for LogItem marschaling " + o);
                bb.putChar('s');
                marschalString(o.toString(), bb);
            }
        }
    }
    int pos = bb.position();
    bb.rewind();
    return Arrays.copyOf(bb.array(), pos);
}
 
Example 19
Project: CodeBroker   File: DefaultSFSDataSerializer.java   View Source Code Vote up 4 votes
private ByteBuffer binEncode_DOUBLE(ByteBuffer buffer, Double value) {
    ByteBuffer buf = ByteBuffer.allocate(9);
    buf.put((byte) DataType.DOUBLE.typeID);
    buf.putDouble(value.doubleValue());
    return this.addData(buffer, buf.array());
}
 
Example 20
Project: openjdk-jdk10   File: Receive.java   View Source Code Vote up 4 votes
@Override
public void run() {
    try {
        SctpChannel sc = ssc.accept();

        /* send a small message */
        MessageInfo info = MessageInfo.createOutgoing(null, 0)
                .payloadProtocolID(PPID);
        ByteBuffer buf = ByteBuffer.allocateDirect(Util.SMALL_BUFFER);
        buf.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buf.flip();

        debug("sending small message: " + buf);
        sc.send(buf, info);

        /* send a large message */
        buf = ByteBuffer.allocateDirect(Util.LARGE_BUFFER);
        buf.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buf.flip();

        debug("sending large message: " + buf);
        sc.send(buf, info);
        sc.shutdown();
        debug("shutdown");
        ReceiveNotificationHandler handler =
            new ReceiveNotificationHandler(sc);
        sc.receive(buf, null, handler);
        sc.close();

        /* accept another socket for the TEST 6 */
        sc = ssc.accept();
        ssc.close();

        clientFinishedLatch.await(10L, TimeUnit.SECONDS);
        serverFinishedLatch.countDown();
        sc.close();
    } catch (IOException ioe) {
        unexpected(ioe);
    } catch (InterruptedException ie) {
        unexpected(ie);
    }
}