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

The following examples show how to use java.nio.ByteBuffer#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProxiedAuthzControlTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Test encoding of a ProxiedAuthzControl.
 */
@Test
public void testEncodeProxiedAnonymousAuthzControl() throws DecoderException
{
    ByteBuffer bb = ByteBuffer.allocate( 0x00 );
    bb.put( new byte[]
        {
            // ProxiedAuthzNotification ::= anonymous
        } );

    bb.flip();

    ProxiedAuthzFactory factory = ( ProxiedAuthzFactory ) codec.getRequestControlFactories().
        get( ProxiedAuthz.OID );
    ProxiedAuthz control = factory.newControl();
    factory.decodeValue( control, bb.array() );


    // test reverse encoding
    Asn1Buffer buffer = new Asn1Buffer();

    factory.encodeValue( buffer, control );

    assertArrayEquals( bb.array(), buffer.getBytes().array() );
}
 
Example 2
Source File: NotFilter.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Encode the NotFilter message to a PDU. 
 * <br>
 * NotFilter :
 * <pre> 
 * 0xA2 LL filter.encode()
 * </pre>
 * 
 * @param buffer The buffer where to put the PDU
 * @return The PDU.
 */
@Override
public ByteBuffer encode( ByteBuffer buffer ) throws EncoderException
{
    if ( buffer == null )
    {
        throw new EncoderException( I18n.err( I18n.ERR_08000_CANNOT_PUT_A_PDU_IN_NULL_BUFFER ) );
    }

    try
    {
        // The NotFilter Tag
        buffer.put( ( byte ) LdapCodecConstants.NOT_FILTER_TAG );
        buffer.put( TLV.getBytes( filtersLength ) );
    }
    catch ( BufferOverflowException boe )
    {
        throw new EncoderException( I18n.err( I18n.ERR_08212_PDU_BUFFER_TOO_SMALL ), boe );
    }

    super.encode( buffer );

    return buffer;
}
 
Example 3
Source File: SetDevicePropValueCommand.java    From remoteyourcam-usb with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeData(ByteBuffer b) {
    // header
    b.putInt(12 + PtpConstants.getDatatypeSize(datatype));
    b.putShort((short) Type.Data);
    b.putShort((short) Operation.SetDevicePropValue);
    b.putInt(camera.currentTransactionId());
    // specific block
    if (datatype == Datatype.int8 || datatype == Datatype.uint8) {
        b.put((byte) value);
    } else if (datatype == Datatype.int16 || datatype == Datatype.uint16) {
        b.putShort((short) value);
    } else if (datatype == Datatype.int32 || datatype == Datatype.uint32) {
        b.putInt(value);
    } else {
        throw new UnsupportedOperationException();
    }
}
 
Example 4
Source File: CharsetConverter.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Add the remaining bytes from the split UTF8 word to the start of the buffer
 *
 * @param buffer to be converted
 * @return new buffer with the remainder.
 */
private ByteBuffer addRemainder(ByteBuffer buffer) {
	ByteBuffer combined;
	if (remainder != null) {
		remainder.clear();
		int last = remainder.remaining();
		combined = ByteBuffer.allocate(last + buffer.remaining());
		combined.put(remainder);
		combined.put(buffer);
		remainder = null;
		combined.rewind();
		return combined;
	} else {
		return buffer;
	}
}
 
Example 5
Source File: SaslInputStream.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public int read(ByteBuffer dst) throws IOException {
  int bytesRead = 0;
  if (dst.hasArray()) {
    bytesRead = read(dst.array(), dst.arrayOffset() + dst.position(),
        dst.remaining());
    if (bytesRead > -1) {
      dst.position(dst.position() + bytesRead);
    }
  } else {
    byte[] buf = new byte[dst.remaining()];
    bytesRead = read(buf);
    if (bytesRead > -1) {
      dst.put(buf, 0, bytesRead);
    }
  }
  return bytesRead;
}
 
Example 6
Source File: ModBitSet.java    From macrobase with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new byte array containing all the bits in this bit set.
 *
 * <p>More precisely, if
 * <br>{@code byte[] bytes = s.toByteArray();}
 * <br>then {@code bytes.length == (s.length()+7)/8} and
 * <br>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
 * <br>for all {@code n < 8 * bytes.length}.
 *
 * @return a byte array containing a little-endian representation
 *         of all the bits in this bit set
 * @since 1.7
 */
public byte[] toByteArray() {
    int n = wordsInUse;
    if (n == 0)
        return new byte[0];
    int len = 8 * (n-1);
    for (long x = words[n - 1]; x != 0; x >>>= 8)
        len++;
    byte[] bytes = new byte[len];
    ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
    for (int i = 0; i < n - 1; i++)
        bb.putLong(words[i]);
    for (long x = words[n - 1]; x != 0; x >>>= 8)
        bb.put((byte) (x & 0xff));
    return bytes;
}
 
Example 7
Source File: UsbIpDevicePacket.java    From USBIPServerForAndroid with GNU General Public License v3.0 5 votes vote down vote up
public byte[] serialize() {
	byte[] internalData = serializeInternal();
	
	ByteBuffer bb = ByteBuffer.allocate(20 + internalData.length);
	
	bb.putInt(command);
	bb.putInt(seqNum);
	bb.putInt(devId);
	bb.putInt(direction);
	bb.putInt(ep);
	
	bb.put(internalData);
	
	return bb.array();
}
 
Example 8
Source File: BeFrameParserTest.java    From pgadba with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
public void parseNetworkPayload(String packetName, byte[] packet) {
  BeFrameParser instance = new BeFrameParser();

  ByteBuffer bb = ByteBuffer.allocate(1024);
  bb.put(packet);
  BeFrame sp = instance.parseBeFrame(bb, 0, packet.length);

  assertNotNull(sp, packetName + " could not be parsed");
}
 
Example 9
Source File: SameBuffer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void doTestWithSeparatedBuffer(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare AAD byte buffers to test
    byte[] AAD = Helper.generateBytes(AADLength);
    ByteBuffer AAD_Buf = ByteBuffer.allocate(AADLength);
    AAD_Buf.put(AAD, 0, AAD.length);
    AAD_Buf.flip();

    // prepare text byte buffer to encrypt/decrypt
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset;
    byte[] inputText = Helper.generateBytes(outputBufSize);
    ByteBuffer plainTextBB = ByteBuffer.allocateDirect(inputText.length);
    plainTextBB.put(inputText);
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength);

    // do test
    runGCMWithSeparateBuffers(Cipher.ENCRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength + tagLength);
    runGCMWithSeparateBuffers(Cipher.DECRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength + tagLength, params);
}
 
Example 10
Source File: ConsumerLog.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public AppendMessageResult<Void> doAppend(long baseOffset, ByteBuffer targetBuffer, int freeSpace, MessageLogIndex message) {
    workingBuffer.clear();

    final long wroteOffset = baseOffset + targetBuffer.position();
    workingBuffer.flip();
    workingBuffer.limit(CONSUMER_LOG_UNIT_BYTES);
    workingBuffer.putLong(message.getTimestamp());
    workingBuffer.putLong(message.getWroteOffset());
    workingBuffer.putInt(message.getWroteBytes());
    workingBuffer.putShort(message.getHeaderSize());
    targetBuffer.put(workingBuffer.array(), 0, CONSUMER_LOG_UNIT_BYTES);
    return new AppendMessageResult<>(AppendMessageStatus.SUCCESS, wroteOffset, CONSUMER_LOG_UNIT_BYTES);
}
 
Example 11
Source File: IPv6TunnelPacketTest.java    From JavaLinuxNet with Apache License 2.0 5 votes vote down vote up
@Test
public void testIPv6TunnelPacket() {
    ByteBuffer rawData = ByteBuffer.allocate(ipv6Tunnel_1.length);
    rawData.put(ipv6Tunnel_1);
    rawData.flip();
    IpPacket packet = IPFactory.processRawPacket(rawData, (byte) rawData.limit());
    Assert.assertNotNull(packet);
    logger.info("IPv6Tunnel packet: {}", packet.toString());
    IPv6TunnelPacket ipv6 = (IPv6TunnelPacket) packet;
    ByteBuffer payload = ipv6.getPayLoad();
    Assert.assertNotNull(ipv6.getHeader());
    Assert.assertEquals(0, ipv6.getHeaderSize());
    Assert.assertEquals(84, ipv6.getPayLoadSize());
}
 
Example 12
Source File: GenreBox.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
@Override
protected void getContent(ByteBuffer byteBuffer) {
    writeVersionAndFlags(byteBuffer);
    IsoTypeWriter.writeIso639(byteBuffer, language);
    byteBuffer.put(Utf8.convert(genre));
    byteBuffer.put((byte) 0);
}
 
Example 13
Source File: NativeArrayBuffer.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static ByteBuffer cloneBuffer(final ByteBuffer original, final int begin, final int end) {
    final ByteBuffer clone = ByteBuffer.allocateDirect(original.capacity());
    original.rewind();//copy from the beginning
    clone.put(original);
    original.rewind();
    clone.flip();
    clone.position(begin);
    clone.limit(end);
    return clone.slice();
}
 
Example 14
Source File: FormatWAV.java    From Android-Audio-Recorder with Apache License 2.0 5 votes vote down vote up
void write(String str, ByteOrder order) {
    try {
        byte[] cc = str.getBytes("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate(cc.length);
        bb.order(order);
        bb.put(cc);
        bb.flip();

        outFile.write(bb.array());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: FixedLenDimEnc.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Object value, ByteBuffer out) {
    byte[] buf = currentBuf();
    String str = value == null ? null : value.toString();
    encode(str, buf, 0);
    out.put(buf);
}
 
Example 16
Source File: DBCS_IBM_EBCDIC_Encoder.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) {
    int mark = src.position();
    int outputSize = 0;             // size of output
    int spaceNeeded;

    try {
        while (src.hasRemaining()) {
            int index;
            int theBytes;
            char c = src.get();
            if (Surrogate.is(c)) {
                if (sgp.parse(c, src) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }
            if (c >= '\uFFFE')
                return CoderResult.unmappableForLength(1);

            index = index1[((c & mask1) >> shift)]
                            + (c & mask2);
            if (index < 15000)
                theBytes = (int)(index2.charAt(index));
            else
                theBytes = (int)(index2a.charAt(index-15000));
            b1 = (byte)((theBytes & 0x0000ff00)>>8);
            b2 = (byte)(theBytes & 0x000000ff);

            if (b1== 0x00 && b2 == 0x00
                && c != '\u0000') {
                    return CoderResult.unmappableForLength(1);
            }

            if (currentState == DBCS && b1 == 0x00) {
                if (dst.remaining() < 1)
                    return CoderResult.OVERFLOW;
                currentState = SBCS;
                dst.put(SI);
            } else if (currentState == SBCS && b1 != 0x00) {
                if (dst.remaining() < 1)
                    return CoderResult.OVERFLOW;
                currentState = DBCS;
                dst.put(SO);
            }

            if (currentState == DBCS)
                spaceNeeded = 2;
            else
                spaceNeeded = 1;

            if (dst.remaining() < spaceNeeded)
                return CoderResult.OVERFLOW;

            if (currentState == SBCS)
                dst.put(b2);
            else {
                dst.put(b1);
                dst.put(b2);
            }
            mark++;
         }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(mark);
    }
}
 
Example 17
Source File: DBCS_IBM_ASCII_Encoder.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) {
    int mark = src.position();
    int outputSize = 0;             // size of output

    try {
        while (src.hasRemaining()) {
            int index;
            int theBytes;
            char c = src.get();
            if (Surrogate.is(c)) {
                if (sgp.parse(c, src) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }
            if (c >= '\uFFFE')
                return CoderResult.unmappableForLength(1);

            index = index1[((c & mask1) >> shift)]
                            + (c & mask2);
            if (index < 15000)
                theBytes = (int)(index2.charAt(index));
            else
                theBytes = (int)(index2a.charAt(index-15000));
            b1 = (byte)((theBytes & 0x0000ff00)>>8);
            b2 = (byte)(theBytes & 0x000000ff);

            if (b1 == 0x00 && b2 == 0x00
                && c != '\u0000') {
                    return CoderResult.unmappableForLength(1);
            }

            if (b1 == 0) {
                if (dst.remaining() < 1)
                    return CoderResult.OVERFLOW;
                dst.put((byte) b2);
            } else {
                if (dst.remaining() < 2)
                    return CoderResult.OVERFLOW;
                dst.put((byte) b1);
                dst.put((byte) b2);
            }
            mark++;
         }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(mark);
    }
}
 
Example 18
Source File: ISCII91.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private CoderResult encodeBufferLoop(CharBuffer src,
                                     ByteBuffer dst)
{
    int mark = src.position();

    try {
        char inputChar;
        while (src.hasRemaining()) {
            int index = Integer.MIN_VALUE;
            inputChar = src.get();

            if (inputChar >= 0x0000 && inputChar <= 0x007f) {
                if (dst.remaining() < 1)
                    return CoderResult.OVERFLOW;
                dst.put((byte) inputChar);
                mark++;
                continue;
            }

            // if inputChar == ZWJ replace it with halant
            // if inputChar == ZWNJ replace it with Nukta

            if (inputChar == 0x200c) {
                inputChar = HALANT_CHAR;
            }
            else if (inputChar == 0x200d) {
                inputChar = NUKTA_CHAR;
            }

            if (inputChar >= 0x0900 && inputChar <= 0x097f) {
                index = ((int)(inputChar) - 0x0900)*2;
            }

            if (Character.isSurrogate(inputChar)) {
                if (sgp.parse(inputChar, src) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }

            if (index == Integer.MIN_VALUE ||
                encoderMappingTable[index] == NO_CHAR) {
                return CoderResult.unmappableForLength(1);
            } else {
                if(encoderMappingTable[index + 1] == NO_CHAR) {
                    if(dst.remaining() < 1)
                        return CoderResult.OVERFLOW;
                    dst.put(encoderMappingTable[index]);
                } else {
                    if(dst.remaining() < 2)
                        return CoderResult.OVERFLOW;
                    dst.put(encoderMappingTable[index]);
                    dst.put(encoderMappingTable[index + 1]);
                }
            }
            mark++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(mark);
    }
}
 
Example 19
Source File: ModelLoadAndSaveSTL.java    From Robot-Overlord-App with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void save(OutputStream outputStream, Model model) throws Exception {
	byte[] info = new byte[80];
	for(int k=0;k<80;++k) info[k]=' ';
    info[0]='M';
    info[1]='C';
    info[2]='R';
    info[4]='D';
    info[5]='R';
    outputStream.write(info);

    int numTriangles = model.vertexArray.size()/3;
	ByteBuffer dataBuffer = ByteBuffer.allocate(4);
    dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
    dataBuffer.putInt(numTriangles);
    outputStream.write(dataBuffer.array());

    dataBuffer = ByteBuffer.allocate(74);
    dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
    
    Iterator<Float> vi = model.vertexArray.iterator();
    Iterator<Float> ni = model.normalArray.iterator();
    
    int i;
    for(i=0;i<numTriangles;++i) {
    	dataBuffer.rewind();
    	dataBuffer.putFloat(ni.next().floatValue());
    	dataBuffer.putFloat(ni.next().floatValue());
    	dataBuffer.putFloat(ni.next().floatValue());

    	dataBuffer.putFloat(ni.next().floatValue());
    	dataBuffer.putFloat(ni.next().floatValue());
    	dataBuffer.putFloat(ni.next().floatValue());

    	dataBuffer.putFloat(ni.next().floatValue());
    	dataBuffer.putFloat(ni.next().floatValue());
    	dataBuffer.putFloat(ni.next().floatValue());

    	dataBuffer.putFloat(vi.next().floatValue());
    	dataBuffer.putFloat(vi.next().floatValue());
    	dataBuffer.putFloat(vi.next().floatValue());

    	dataBuffer.putFloat(vi.next().floatValue());
    	dataBuffer.putFloat(vi.next().floatValue());
    	dataBuffer.putFloat(vi.next().floatValue());

    	dataBuffer.putFloat(vi.next().floatValue());
    	dataBuffer.putFloat(vi.next().floatValue());
    	dataBuffer.putFloat(vi.next().floatValue());
    	
    	dataBuffer.put((byte)0);
    	dataBuffer.put((byte)0);
    	outputStream.write(dataBuffer.array());
    }
}
 
Example 20
Source File: PNGDecoder.java    From opsu-dance with GNU General Public License v3.0 4 votes vote down vote up
private void copy(ByteBuffer buffer, byte[] curLine) {
    buffer.put(curLine, 1, curLine.length-1);
}