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

The following are Jave code examples for showing how to use putShort() 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: samples-cognitive-services-android   File: AudioConverter.java   View Source Code Vote up 6 votes
public static ByteBuffer convert(byte[] audioData,
                                 @IntRange(from = 0) int read,
                                 @NonNull String requestId) {
    String builder = PATH.getValue() + ": " + AUDIO.getValue() + CRLF.getValue() +
            X_REQUEST_ID.getValue() + ": " + requestId + CRLF.getValue() +
            X_TIMESTAMP.getValue() + ": " + CurrentTime.newTime() + CRLF.getValue() +
            CONTENT_TYPE.getValue() + ": " + AUDIO_WAV.getValue() + CRLF.getValue() + CRLF.getValue();

    byte[] header = builder.getBytes(UTF_8);

    ByteBuffer byteBuffer = ByteBuffer.allocate(2 + header.length + read);
    byteBuffer.putShort(toShort(header.length));
    byteBuffer.put(header);
    if (read > 0) byteBuffer.put(audioData, 0, read);

    return byteBuffer;
}
 
Example 2
Project: athena   File: IGMPMembership.java   View Source Code Vote up 6 votes
/**
 * Serialize this Membership Report.
 *
 * @param bb the ByteBuffer to write into, positioned at the next spot to be written to.
 * @return serialized IGMP message.
 */
@Override
public byte[] serialize(ByteBuffer bb) {

    bb.put(recordType);
    bb.put(auxDataLength);      // reserved
    bb.putShort((short) sources.size());
    bb.put(gaddr.toOctets());
    for (IpAddress ipaddr : sources) {
        bb.put(ipaddr.toOctets());
    }

    if (auxDataLength > 0) {
        bb.put(auxData);
    }

    return bb.array();
}
 
Example 3
Project: BiglyBT   File: ProxyLoginHandler.java   View Source Code Vote up 6 votes
private ByteBuffer[] createSocks4aMessage() {
  ByteBuffer handshake = ByteBuffer.allocate( 256 + mapped_ip.length() );   //TODO convert to direct?

  handshake.put( (byte)4 ); // socks 4(a)
  handshake.put( (byte)1 ); // command = CONNECT
  handshake.putShort( (short)remote_address.getPort() ); // port
  handshake.put( (byte)0 );
  handshake.put( (byte)0 );
  handshake.put( (byte)0 );
  handshake.put( (byte)1 ); // indicates socks 4a

  if( socks_user.length() > 0 ) {
    handshake.put( socks_user.getBytes() );
  }

  handshake.put( (byte)0 );
  handshake.put( mapped_ip.getBytes() );
  handshake.put( (byte)0 );

  handshake.flip();

  return new ByteBuffer[] { handshake, ByteBuffer.allocate( 8 ) };   //TODO convert to direct?
}
 
Example 4
Project: ddpush   File: ClientStatMachine.java   View Source Code Vote up 6 votes
private void push0x20() throws Exception{
	if(has0x20Message() == false){
		return;
	}
	if((this.lastAddr == null || (System.currentTimeMillis() - this.lastTick)>1000*PUSH_IM_AFTER_ACTIVE_SECOND) && this.getMessengerTask() == null ){
		return;
	}
	byte[] data = new byte[Constant.SERVER_MESSAGE_MIN_LENGTH+message0x20Len];
	ByteBuffer bb = ByteBuffer.wrap(data);
	bb.put((byte)1);//version
	bb.put((byte)0);//app id, 0 here
	bb.put((byte)ClientStatMachine.CMD_0x20);//cmd
	bb.putShort((short)message0x20Len);
	bb.put(this.message0x20);
	bb.flip();
	ServerMessage sm = new ServerMessage(this.lastAddr, data);
	if(this.lastAddr != null && (System.currentTimeMillis() - this.lastTick)<1000*PUSH_IM_AFTER_ACTIVE_SECOND){
		IMServer.getInstance().pushInstanceMessage(sm);
	}
	if(this.getMessengerTask() != null){
		try{this.getMessengerTask().pushInstanceMessage(sm);}catch(Exception e){};
	}
}
 
Example 5
Project: libRtmp   File: FlvPackerHelper.java   View Source Code Vote up 6 votes
/**
 * 第一个视频Tag,需要写入AVC视频流的configuretion信息,这个信息根据pps、sps生成
 * 8 bit configuration version ------ 版本号
 * 8 bit AVC Profile Indication ------- sps[1]
 * 8 bit Profile Compatibility ------- sps[2]
 * 8 bit AVC Level Compatibility ------- sps[3]
 * 6 bit Reserved ------- 111111
 * 2 bit Length Size Minus One ------- NAL Unit Length长度为-1,一般为3
 * 3 bit Reserved ------- 111
 * 5 bit Num of Sequence Parameter Sets ------- sps个数,一般为1
 * ? bit Sequence Parameter Set NAL Units ------- (sps_size + sps)的数组
 * 8 bit Num of Picture Parameter Sets ------- pps个数,一般为1
 * ? bit Picture Parameter Set NAL Units ------- (pps_size + pps)的数组
 * @param sps
 * @param pps
 * @return
 */
public static void writeFirstVideoTag(ByteBuffer buffer, byte[] sps, byte[] pps) {
    //写入Flv Video Header
    writeVideoHeader(buffer, FlvVideoFrameType.KeyFrame, FlvVideoCodecID.AVC, FlvVideoAVCPacketType.SequenceHeader);

    buffer.put((byte)0x01);
    buffer.put(sps[1]);
    buffer.put(sps[2]);
    buffer.put(sps[3]);
    buffer.put((byte)0xff);

    buffer.put((byte)0xe1);
    buffer.putShort((short)sps.length);
    buffer.put(sps);

    buffer.put((byte)0x01);
    buffer.putShort((short)pps.length);
    buffer.put(pps);
}
 
Example 6
Project: AndResM   File: TypeChunk.java   View Source Code Vote up 6 votes
@Override
public final byte[] toByteArray(boolean shrink) {
  ByteBuffer buffer = ByteBuffer.allocate(size());
  buffer.order(ByteOrder.LITTLE_ENDIAN);
  buffer.putShort((short) headerSize());
  buffer.putShort((short) flags());
  buffer.putInt(keyIndex());
  if (isComplex()) {
    buffer.putInt(parentEntry());
    buffer.putInt(values().size());
    for (Map.Entry<Integer, ResourceValue> entry : values().entrySet()) {
      buffer.putInt(entry.getKey());
      buffer.put(entry.getValue().toByteArray(shrink));
    }
  } else {
    ResourceValue value = value();
    Preconditions.checkNotNull(value, "A non-complex TypeChunk entry must have a value.");
    buffer.put(value.toByteArray());
  }
  return buffer.array();
}
 
Example 7
Project: samples-cognitive-services-android   File: AudioConverter.java   View Source Code Vote up 5 votes
public static ByteBuffer convert(@NonNull String requestId) {
    String builder = PATH.getValue() + ": " + AUDIO.getValue() + CRLF.getValue() +
            X_REQUEST_ID.getValue() + ": " + requestId + CRLF.getValue() +
            X_TIMESTAMP.getValue() + ": " + CurrentTime.newTime() + CRLF.getValue() +
            CONTENT_TYPE.getValue() + ": " + AUDIO_WAV.getValue() + CRLF.getValue() + CRLF.getValue();

    byte[] header = builder.getBytes(UTF_8);

    ByteBuffer byteBuffer = ByteBuffer.allocate(2 + header.length);
    byteBuffer.putShort(toShort(header.length));
    byteBuffer.put(header);

    return byteBuffer;
}
 
Example 8
Project: script-wars   File: ConnectionUtil.java   View Source Code Vote up 5 votes
public static ByteBuffer stringToBuffer(String message) {
	byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
	ByteBuffer result = ByteBuffer.allocate(bytes.length + Short.BYTES);
	result.putShort((short) bytes.length);
	result.put(bytes);
	result.flip();
	
	return result;
}
 
Example 9
Project: Virtual-Hosts   File: Packet.java   View Source Code Vote up 5 votes
public void fillHeader(ByteBuffer buffer)
{
    buffer.put((byte) (this.version << 4 | this.IHL));
    buffer.put((byte) this.typeOfService);
    buffer.putShort((short) this.totalLength);

    buffer.putInt(this.identificationAndFlagsAndFragmentOffset);

    buffer.put((byte) this.TTL);
    buffer.put((byte) this.protocol.getNumber());
    buffer.putShort((short) this.headerChecksum);

    buffer.put(this.sourceAddress.getAddress());
    buffer.put(this.destinationAddress.getAddress());
}
 
Example 10
Project: drc-sim-client   File: CommandPacket.java   View Source Code Vote up 5 votes
public static byte[] create_joystick(short left_x, short left_y, short right_x, short right_y) {
    ByteBuffer buffer = ByteBuffer.allocate(12);
    buffer.putShort(0, Constants.COMMAND_INPUT_JOYSTICK); // type
    buffer.putShort(2, (short) 8); // payload_size
    buffer.putShort(4, left_x);
    buffer.putShort(6, left_y);
    buffer.putShort(8, right_x);
    buffer.putShort(10, right_y);
    return buffer.array();
}
 
Example 11
Project: fresco_floodlight   File: LLDPTLV.java   View Source Code Vote up 5 votes
public byte[] serialize() {
    // type = 7 bits
    // info string length 9 bits, each value == byte
    // info string
    short scratch = (short) (((0x7f & this.type) << 9) | (0x1ff & this.length));
    byte[] data = new byte[2+this.length];
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb.putShort(scratch);
    if (this.value != null)
        bb.put(this.value);
    return data;
}
 
Example 12
Project: x7   File: MessageUtil.java   View Source Code Vote up 5 votes
public static void writeMap(ByteBuffer buffer, Map<Integer,Integer> map) {
	if (map==null || map.isEmpty()){
		buffer.putShort((byte)0);
		return;
	}
	short size = (short) map.size();
	buffer.putShort(size);
	for (Integer key : map.keySet()){
		buffer.putInt(key);
		buffer.putInt(map.get(key));
	}
}
 
Example 13
Project: OpenJSharp   File: DflCache.java   View Source Code Vote up 5 votes
private static SeekableByteChannel createNoClose(Path p)
        throws IOException {
    SeekableByteChannel newChan = Files.newByteChannel(
            p, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING,
                StandardOpenOption.WRITE);
    ByteBuffer buffer = ByteBuffer.allocate(6);
    buffer.putShort((short)KRB5_RV_VNO);
    buffer.order(ByteOrder.nativeOrder());
    buffer.putInt(KerberosTime.getDefaultSkew());
    buffer.flip();
    newChan.write(buffer);
    return newChan;
}
 
Example 14
Project: ddpush   File: ClientStatMachine.java   View Source Code Vote up 5 votes
private void gen0x00Message(ClientMessage cm, ArrayList<ServerMessage> smList) throws Exception{
	byte[] data = new byte[Constant.SERVER_MESSAGE_MIN_LENGTH];//5 bytes
	ByteBuffer bb = ByteBuffer.wrap(data);
	bb.put((byte)1);//version
	bb.put(cm.getData()[1]);//app id
	bb.put((byte)ClientStatMachine.CMD_0x00);//cmd
	bb.putShort((short)0);//length 0
	bb.flip();
	ServerMessage sm = new ServerMessage(cm.getSocketAddress(), data);
	smList.add(sm);
}
 
Example 15
Project: fresco_floodlight   File: Ethernet.java   View Source Code Vote up 5 votes
public byte[] serialize() {
    byte[] payloadData = null;
    if (payload != null) {
        payload.setParent(this);
        payloadData = payload.serialize();
    }
    int length = 14 + ((vlanID == VLAN_UNTAGGED) ? 0 : 4) +
                      ((payloadData == null) ? 0 : payloadData.length);
    if (pad && length < 60) {
        length = 60;
    }
    byte[] data = new byte[length];
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb.put(destinationMACAddress.getBytes());
    bb.put(sourceMACAddress.getBytes());
    if (vlanID != VLAN_UNTAGGED) {
        bb.putShort((short) EthType.VLAN_FRAME.getValue());
        bb.putShort((short) ((priorityCode << 13) | (vlanID & 0x0fff)));
    }
    bb.putShort((short) etherType.getValue());
    if (payloadData != null)
        bb.put(payloadData);
    if (pad) {
        Arrays.fill(data, bb.position(), data.length, (byte)0x0);
    }
    return data;
}
 
Example 16
Project: sstable-adaptor   File: CounterContext.java   View Source Code Vote up 5 votes
/**
 * Remove all the local of a context (but keep global).
 *
 * @param context a counter context
 * @return a version of {@code context} where no shards are local.
 */
public ByteBuffer clearAllLocal(ByteBuffer context)
{
    int count = Math.abs(context.getShort(context.position()));
    if (count == 0)
        return context; // no local or global shards present.

    List<Short> globalShardIndexes = new ArrayList<>(count);
    for (int i = 0; i < count; i++)
    {
        short elt = context.getShort(context.position() + HEADER_SIZE_LENGTH + i * HEADER_ELT_LENGTH);
        if (elt < 0)
            globalShardIndexes.add(elt);
    }

    if (count == globalShardIndexes.size())
        return context; // no local shards detected.

    // allocate a smaller BB for the cleared context - with no local header elts.
    ByteBuffer cleared = ByteBuffer.allocate(context.remaining() - (count - globalShardIndexes.size()) * HEADER_ELT_LENGTH);

    cleared.putShort(cleared.position(), (short) globalShardIndexes.size());
    for (int i = 0; i < globalShardIndexes.size(); i++)
        cleared.putShort(cleared.position() + HEADER_SIZE_LENGTH + i * HEADER_ELT_LENGTH, globalShardIndexes.get(i));

    int origHeaderLength = headerLength(context);
    ByteBufferUtil.arrayCopy(context,
                             context.position() + origHeaderLength,
                             cleared,
                             cleared.position() + headerLength(cleared),
                             context.remaining() - origHeaderLength);

    return cleared;
}
 
Example 17
Project: sstable-adaptor   File: CounterContext.java   View Source Code Vote up 5 votes
/**
 * Allocate a new context big enough for globalCount + localCount + remoteCount elements
 * and return the initial corresponding ContextState.
 */
public static ContextState allocate(int globalCount, int localCount, int remoteCount)
{
    int headerLength = HEADER_SIZE_LENGTH + (globalCount + localCount) * HEADER_ELT_LENGTH;
    int bodyLength = (globalCount + localCount + remoteCount) * STEP_LENGTH;

    ByteBuffer buffer = ByteBuffer.allocate(headerLength + bodyLength);
    buffer.putShort(buffer.position(), (short) (globalCount + localCount));

    return ContextState.wrap(buffer);
}
 
Example 18
Project: OpenGL-Bullet-engine   File: TextureLoader.java   View Source Code Vote up 4 votes
public static ByteBuffer imgToBuff(BufferedImage image){
	
	int[] pixels=new int[image.getWidth()*image.getHeight()];
	image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
	ByteBuffer buffer=BufferUtils.createByteBuffer(image.getWidth()*image.getHeight()*image.getColorModel().getPixelSize()/8);
	
	for(int y=0;y<image.getHeight();y++){
		for(int x=0;x<image.getWidth();x++){
			int pixel=pixels[y*image.getWidth()+x];
			switch(image.getType()){
			case TYPE_3BYTE_BGR:
			case TYPE_INT_RGB:{
				buffer.put((byte)(pixel>>16&0xFF)); // Red component
				buffer.put((byte)(pixel>>8&0xFF)); // Green component
				buffer.put((byte)(pixel&0xFF)); // Blue component
			}
			break;
			case TYPE_4BYTE_ABGR:
			case TYPE_INT_ARGB:{
				buffer.put((byte)(pixel>>16&0xFF)); // Red component
				buffer.put((byte)(pixel>>8&0xFF)); // Green component
				buffer.put((byte)(pixel&0xFF)); // Blue component
				buffer.put((byte)(pixel>>24&0xFF)); // Alpha component. Only for RGBA
			}
			break;
			case TYPE_BYTE_GRAY:{
				buffer.put((byte)pixel);
			}
			break;
			case TYPE_USHORT_GRAY:{
				buffer.putShort((short)pixel);
			}
			break;
			default:
				LogUtil.printlnEr(image.getType());
				throw new IllegalStateException("Unknown type image format: "+image.getColorModel().toString());
			}
		}
	}
	
	buffer.flip();
	return buffer;
}
 
Example 19
Project: GitHub   File: DefaultImageHeaderParserTest.java   View Source Code Vote up 4 votes
private static ByteBuffer getExifMagicNumber() {
  ByteBuffer jpegHeaderBytes = ByteBuffer.allocate(2);
  jpegHeaderBytes.putShort((short) DefaultImageHeaderParser.EXIF_MAGIC_NUMBER);
  jpegHeaderBytes.position(0);
  return jpegHeaderBytes;
}
 
Example 20
Project: CodeBroker   File: DefaultSFSDataSerializer.java   View Source Code Vote up 4 votes
public byte[] object2binary(IObject object) {
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CHUNK_SIZE);
    buffer.put((byte) DataType.OBJECT.typeID);
    buffer.putShort((short) object.size());
    return this.obj2bin(object, buffer);
}