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

The following are Jave code examples for showing how to use wrap() 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: OpenJSharp   File: Base64.java   View Source Code Vote up 6 votes
/**
 * Decodes all bytes from the input byte buffer using the {@link Base64}
 * encoding scheme, writing the results into a newly-allocated ByteBuffer.
 *
 * <p> Upon return, the source buffer's position will be updated to
 * its limit; its limit will not have been changed. The returned
 * output buffer's position will be zero and its limit will be the
 * number of resulting decoded bytes
 *
 * <p> {@code IllegalArgumentException} is thrown if the input buffer
 * is not in valid Base64 encoding scheme. The position of the input
 * buffer will not be advanced in this case.
 *
 * @param   buffer
 *          the ByteBuffer to decode
 *
 * @return  A newly-allocated byte buffer containing the decoded bytes
 *
 * @throws  IllegalArgumentException
 *          if {@code src} is not in valid Base64 scheme.
 */
public ByteBuffer decode(ByteBuffer buffer) {
    int pos0 = buffer.position();
    try {
        byte[] src;
        int sp, sl;
        if (buffer.hasArray()) {
            src = buffer.array();
            sp = buffer.arrayOffset() + buffer.position();
            sl = buffer.arrayOffset() + buffer.limit();
            buffer.position(buffer.limit());
        } else {
            src = new byte[buffer.remaining()];
            buffer.get(src);
            sp = 0;
            sl = src.length;
        }
        byte[] dst = new byte[outLength(src, sp, sl)];
        return ByteBuffer.wrap(dst, 0, decode0(src, sp, sl, dst));
    } catch (IllegalArgumentException iae) {
        buffer.position(pos0);
        throw iae;
    }
}
 
Example 2
Project: openjdk-jdk10   File: BufferOverflowUnderflowTest.java   View Source Code Vote up 6 votes
private void checkBufferOverflowOnWrap(SSLEngine engine)
        throws SSLException {
    String mode = engine.getUseClientMode() ? "client"
            : "server";
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing SSLEngine buffer overflow"
            + " on wrap by " + mode);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    //Making net buffer size less than required by 1 byte.
    ByteBuffer net = ByteBuffer
            .allocate(engine.getSession().getPacketBufferSize() - 1);
    SSLEngineResult r = engine.wrap(app, net);
    checkResult(r, SSLEngineResult.Status.BUFFER_OVERFLOW);
    System.out.println("Passed");
}
 
Example 3
Project: rmq4note   File: RemotingCommandTest.java   View Source Code Vote up 6 votes
@Test
public void testEncodeAndDecode_FilledBody() {
    System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, "2333");

    int code = 103; //org.apache.rocketmq.common.protocol.RequestCode.REGISTER_BROKER
    CommandCustomHeader header = new SampleCommandCustomHeader();
    RemotingCommand cmd = RemotingCommand.createRequestCommand(code, header);
    cmd.setBody(new byte[] { 0, 1, 2, 3, 4});

    ByteBuffer buffer = cmd.encode();

    //Simulate buffer being read in NettyDecoder
    buffer.getInt();
    byte[] bytes = new byte[buffer.limit() - 4];
    buffer.get(bytes, 0, buffer.limit() - 4);
    buffer = ByteBuffer.wrap(bytes);

    RemotingCommand decodedCommand = RemotingCommand.decode(buffer);

    assertThat(decodedCommand.getSerializeTypeCurrentRPC()).isEqualTo(SerializeType.JSON);
    assertThat(decodedCommand.getBody()).isEqualTo(new byte[]{ 0, 1, 2, 3, 4});
}
 
Example 4
Project: athena   File: LldpLinkProviderTest.java   View Source Code Vote up 6 votes
@Override
public InboundPacket inPacket() {
    ONOSLLDP lldp = ONOSLLDP.onosLLDP(deviceService.getDevice(DID1).id().toString(),
                                      device.chassisId(),
                                      (int) pd1.number().toLong());

    Ethernet ethPacket = new Ethernet();
    ethPacket.setEtherType(Ethernet.TYPE_LLDP);
    ethPacket.setDestinationMACAddress(ONOSLLDP.LLDP_NICIRA);
    ethPacket.setPayload(lldp);
    ethPacket.setPad(true);

    ethPacket.setSourceMACAddress("DE:AD:BE:EF:BA:11");

    ConnectPoint cp = new ConnectPoint(device.id(), pd3.number());

    return new DefaultInboundPacket(cp, ethPacket,
                                    ByteBuffer.wrap(ethPacket.serialize()));

}
 
Example 5
Project: kafka-0.11.0.0-src-with-comment   File: SegmentedCacheFunctionTest.java   View Source Code Vote up 5 votes
@Test
public void cacheKey() throws Exception {
    final long segmentId = TIMESTAMP / SEGMENT_INTERVAL;

    final Bytes actualCacheKey = cacheFunction.cacheKey(THE_KEY);
    final ByteBuffer buffer = ByteBuffer.wrap(actualCacheKey.get());

    assertThat(buffer.getLong(), equalTo(segmentId));

    byte[] actualKey = new byte[buffer.remaining()];
    buffer.get(actualKey);
    assertThat(Bytes.wrap(actualKey), equalTo(THE_KEY));
}
 
Example 6
Project: aliyun-maxcompute-data-collectors   File: AvroUtil.java   View Source Code Vote up 5 votes
/**
 * Convert a Sqoop's Java representation to Avro representation.
 */
public static Object toAvro(Object o, boolean bigDecimalFormatString) {
  if (o instanceof BigDecimal) {
    if (bigDecimalFormatString) {
      // Returns a string representation of this without an exponent field.
      return ((BigDecimal) o).toPlainString();
    } else {
      return o.toString();
    }
  } else if (o instanceof Date) {
    return ((Date) o).getTime();
  } else if (o instanceof Time) {
    return ((Time) o).getTime();
  } else if (o instanceof Timestamp) {
    return ((Timestamp) o).getTime();
  } else if (o instanceof BytesWritable) {
    BytesWritable bw = (BytesWritable) o;
    return ByteBuffer.wrap(bw.getBytes(), 0, bw.getLength());
  } else if (o instanceof BlobRef) {
    BlobRef br = (BlobRef) o;
    // If blob data is stored in an external .lob file, save the ref file
    // as Avro bytes. If materialized inline, save blob data as Avro bytes.
    byte[] bytes = br.isExternal() ? br.toString().getBytes() : br.getData();
    return ByteBuffer.wrap(bytes);
  } else if (o instanceof ClobRef) {
    throw new UnsupportedOperationException("ClobRef not supported");
  }
  // primitive types (Integer, etc) are left unchanged
  return o;
}
 
Example 7
Project: openjdk-jdk10   File: EncapsInputStream.java   View Source Code Vote up 5 votes
public EncapsInputStream(org.omg.CORBA.ORB orb, byte[] buf,
                         int size, boolean littleEndian,
                         GIOPVersion version) {
    super(orb, ByteBuffer.wrap(buf), size, littleEndian,
          version, Message.CDR_ENC_VERSION,
          BufferManagerFactory.newBufferManagerRead(
                                  BufferManagerFactory.GROW,
                                  Message.CDR_ENC_VERSION,
                                  (ORB)orb));

    wrapper = ORBUtilSystemException.get( (ORB)orb,
        CORBALogDomains.RPC_ENCODING ) ;

    performORBVersionSpecificInit();
}
 
Example 8
Project: openjdk-jdk10   File: ChecksumBase.java   View Source Code Vote up 5 votes
private static void testLittleEndianWrappedByteBufferOffset(Checksum checksum, long expected) {
    byte[] unaligned_bytes_123456789 = new byte[BYTES_123456789.length + 64];
    for (int i = 0; i < unaligned_bytes_123456789.length - BYTES_123456789.length; i++) {
        checksum.reset();
        System.arraycopy(BYTES_123456789, 0, unaligned_bytes_123456789, i, BYTES_123456789.length);
        ByteBuffer bb = ByteBuffer.wrap(unaligned_bytes_123456789);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.position(i);
        bb.limit(i + BYTES_123456789.length);
        checksum.update(bb);
        checkChecksumOffset(checksum, expected, i);
    }
}
 
Example 9
Project: sstore-soft   File: TestStoredProcedureInvocation.java   View Source Code Vote up 5 votes
/**
 * testProcedureId
 */
public void testProcedureId() throws Exception {
    Procedure catalog_proc = this.getProcedure(TARGET_PROCEDURE);
    StoredProcedureInvocation invocation = new StoredProcedureInvocation(CLIENT_HANDLE, "@DatabaseDump", PARAMS);
    invocation.setProcedureId(catalog_proc.getId());
    byte[] invocation_bytes = FastSerializer.serialize(invocation);
    assertNotNull(invocation_bytes);
    
    ByteBuffer buffer = ByteBuffer.wrap(invocation_bytes);
    assertEquals(catalog_proc.getId(), StoredProcedureInvocation.getProcedureId(buffer));
}
 
Example 10
Project: directory-ldap-api   File: PasswordModifyRequestDecoder.java   View Source Code Vote up 5 votes
/**
 * Decode a PDU which must contain a PwdModifyRequest extended operation.
 * Note that the stream of bytes much contain a full PDU, not a partial one.
 * 
 * @param stream The bytes to be decoded
 * @return a PwdModifyRequest object
 * @throws org.apache.directory.api.asn1.DecoderException If the decoding failed
 */
public PasswordModifyRequest decode( byte[] stream ) throws DecoderException
{
    ByteBuffer bb = ByteBuffer.wrap( stream );
    PasswordModifyRequestContainer container = new PasswordModifyRequestContainer();
    DECODER.decode( bb, container );
    PasswordModifyRequestDecorator passwordModifyRequest = container.getPwdModifyRequest();

    // Clean the container for the next decoding
    container.clean();

    return passwordModifyRequest;
}
 
Example 11
Project: ApkMultiChannelPlugin   File: ByteArrayDataSink.java   View Source Code Vote up 5 votes
@Override
public ByteBuffer getByteBuffer(long offset, int size) throws IOException {
    checkChunkValid(offset, size);
    // checkChunkValid combined with the way instances of this class are constructed ensures
    // that mSliceOffset + offset does not overflow.
    return ByteBuffer.wrap(mArray, (int) (mSliceOffset + offset), size);
}
 
Example 12
Project: ddpush   File: ClientStatMachine.java   View Source Code Vote up 5 votes
private void gen0x11Message(ClientMessage cm, ArrayList<ServerMessage> smList) throws Exception{
	if(message0x11 == 0){
		return;
	}
	byte[] data = new byte[Constant.SERVER_MESSAGE_MIN_LENGTH+8];//13 bytes
	ByteBuffer bb = ByteBuffer.wrap(data);
	bb.put((byte)1);//version
	bb.put(cm.getData()[1]);//app id
	bb.put((byte)ClientStatMachine.CMD_0x11);//cmd
	bb.putShort((short)8);//length 8
	bb.putLong(message0x11);
	bb.flip();
	ServerMessage sm = new ServerMessage(cm.getSocketAddress(), data);
	smList.add(sm);
}
 
Example 13
Project: fuck_zookeeper   File: Util.java   View Source Code Vote up 5 votes
/**
 * Verifies that the file is a valid snapshot. Snapshot may be invalid if 
 * it's incomplete as in a situation when the server dies while in the process
 * of storing a snapshot. Any file that is not a snapshot is also 
 * an invalid snapshot. 
 * 
 * @param f file to verify
 * @return true if the snapshot is valid
 * @throws IOException
 */
public static boolean isValidSnapshot(File f) throws IOException {
    if (f==null || Util.getZxidFromName(f.getName(), "snapshot") == -1)
        return false;

    // Check for a valid snapshot
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    try {
        // including the header and the last / bytes
        // the snapshot should be atleast 10 bytes
        if (raf.length() < 10) {
            return false;
        }
        raf.seek(raf.length() - 5);
        byte bytes[] = new byte[5];
        int readlen = 0;
        int l;
        while(readlen < 5 &&
              (l = raf.read(bytes, readlen, bytes.length - readlen)) >= 0) {
            readlen += l;
        }
        if (readlen != bytes.length) {
            LOG.info("Invalid snapshot " + f
                    + " too short, len = " + readlen);
            return false;
        }
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        int len = bb.getInt();
        byte b = bb.get();
        if (len != 1 || b != '/') {
            LOG.info("Invalid snapshot " + f + " len = " + len
                    + " byte = " + (b & 0xff));
            return false;
        }
    } finally {
        raf.close();
    }

    return true;
}
 
Example 14
Project: dble   File: FileSystemRepository.java   View Source Code Vote up 5 votes
private void write(CoordinatorLogEntry coordinatorLogEntry,
                   boolean flushImmediately) throws IOException {
    String str = Serializer.toJson(coordinatorLogEntry);
    byte[] buffer = str.getBytes();
    ByteBuffer buff = ByteBuffer.wrap(buffer);
    writeToFile(buff, flushImmediately);
}
 
Example 15
Project: multiple-dimension-spread   File: OptimizeLongColumnBinaryMaker.java   View Source Code Vote up 5 votes
@Override
public void create( final List<PrimitiveObject> objList , final byte[] buffer , final int start , final int length ) throws IOException{
  ByteBuffer wrapBuffer = ByteBuffer.wrap( buffer , start , length );
  for( PrimitiveObject obj : objList ){
    wrapBuffer.putInt( (int)( obj.getLong() - min ) );
  }
}
 
Example 16
Project: ditb   File: TRegionInfo.java   View Source Code Vote up 4 votes
public TRegionInfo setEndKey(byte[] endKey) {
  this.endKey = endKey == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(endKey, endKey.length));
  return this;
}
 
Example 17
Project: ditb   File: Hbase.java   View Source Code Vote up 4 votes
/**
 * name of table
 */
public getRows_args setTableName(byte[] tableName) {
  this.tableName = tableName == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(tableName, tableName.length));
  return this;
}
 
Example 18
Project: Responder-Android   File: FramedataImpl1.java   View Source Code Vote up 4 votes
public FramedataImpl1( Opcode op ) {
	this.optcode = op;
	unmaskedpayload = ByteBuffer.wrap( emptyarray );
}
 
Example 19
Project: multiple-dimension-spread   File: BlockIndexNode.java   View Source Code Vote up 4 votes
public int toBinary( final byte[] buffer , final int start ) throws IOException{
  if( isDisable ){
    return start;
  }
  int offset = start;
  ByteBuffer wrapBuffer = ByteBuffer.wrap( buffer );
  if( blockIndex == null ){
    wrapBuffer.putInt( offset , 0 );
    offset += Integer.BYTES;
  }
  else{
    wrapBuffer.putInt( offset , 1 );
    offset += Integer.BYTES;
    byte[] rangeClassNameBytes = RangeBlockIndexNameShortCut.getShortCutName( blockIndex.getClass().getName() ).getBytes( "UTF-8" );
    wrapBuffer.putInt( offset , rangeClassNameBytes.length );
    offset += Integer.BYTES;
    wrapBuffer.position( offset );
    wrapBuffer.put( rangeClassNameBytes );
    offset += rangeClassNameBytes.length;
    byte[] indexBinary = blockIndex.toBinary();
    wrapBuffer.putInt( offset , indexBinary.length );
    offset += Integer.BYTES;
    wrapBuffer.position( offset );
    wrapBuffer.put( indexBinary );
    offset += indexBinary.length;
  }
  int childCountOffset = offset;
  int childCount = 0;
  offset += Integer.BYTES;
  for( Map.Entry<String,BlockIndexNode> entry : childContainer.entrySet() ){
    byte[] childKeyNameBytes = entry.getKey().getBytes( "UTF-8" );
    int childBinaryLengthOffset = offset;
    offset += Integer.BYTES;
    int childKeyNameLengthOffset = offset;
    offset += Integer.BYTES;
    int childKeyNameOffset = offset;
    offset += childKeyNameBytes.length;
    int childEndOffset = entry.getValue().toBinary( buffer , offset );
    if( childEndOffset == offset ){
      offset = childBinaryLengthOffset;
    }
    else{
      wrapBuffer.putInt( childBinaryLengthOffset , childEndOffset - offset );
      wrapBuffer.putInt( childKeyNameLengthOffset , childKeyNameBytes.length );
      wrapBuffer.position( childKeyNameOffset );
      wrapBuffer.put( childKeyNameBytes );
      childCount++;
      offset = childEndOffset;
    }
  }
  wrapBuffer.putInt( childCountOffset , childCount );
  return offset;
}
 
Example 20
Project: javaide   File: Dex.java   View Source Code Vote up 2 votes
/**
 * Creates a new dex that reads from {@code data}. It is an error to modify
 * {@code data} after using it to create a dex buffer.
 */
public Dex(byte[] data) throws IOException {
    this(ByteBuffer.wrap(data));
}