Java Code Examples for java.nio.ByteBuffer

The following are top voted examples for showing how to use java.nio.ByteBuffer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: monarch   File: HydraLineMapper.java   Source Code and License 8 votes vote down vote up
private String getDiskStoreIdFromInitFile(File dir, String fileName)
    throws FileNotFoundException, IOException {
  FileInputStream fis = new FileInputStream(new File(dir, fileName));
  try {
    byte[] bytes = new byte[1 + 8 + 8];
    fis.read(bytes);
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    // Skip the record type.
    buffer.get();
    long least = buffer.getLong();
    long most = buffer.getLong();
    UUID id = new UUID(most, least);
    return id.toString();
  } finally {
    fis.close();
  }
}
 
Example 2
Project: java-tutorial   File: FileChannelTest.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) {
    Path file = Paths.get(System.getProperty("user.home") + "/test/myfile.txt");

    try (SeekableByteChannel sbc = Files.newByteChannel(file)) { // |\longremark{newByteChannel默认返回只读的Channel}|
        ByteBuffer buf = ByteBuffer.allocate(10); // |\longremark{allocate创建一个指定字节的ByteBuffer,本例中,sbc这个Channel每次读取10个字节}|

        String encoding = System.getProperty("file.encoding"); // |\longremark{获得当前系统文件编码方式,以便读取文件字节后解码}|
        while (sbc.read(buf) > 0) { // |\longremark{从通道读数据到缓冲区}|
            buf.flip(); // |\longremark{切换缓冲区为读模式}|
            System.out.print(Charset.forName(encoding).decode(buf));
            buf.clear(); // |\longremark{清空缓冲区,准备写入下一轮数据}|
        }
    } catch (IOException x) {
        System.out.println("caught exception: " + x);
    }
}
 
Example 3
Project: OpenJSharp   File: AnnotationParser.java   Source Code and License 6 votes vote down vote up
private static Object parseCharArray(int length,
                              ByteBuffer buf, ConstantPool constPool) {
    char[] result = new char[length];
    boolean typeMismatch = false;
    byte tag = 0;

    for (int i = 0; i < length; i++) {
        tag = buf.get();
        if (tag == 'C') {
            int index = buf.getShort() & 0xFFFF;
            result[i] = (char) constPool.getIntAt(index);
        } else {
            skipMemberValue(tag, buf);
            typeMismatch = true;
        }
    }
    return typeMismatch ? exceptionProxy(tag) : result;
}
 
Example 4
Project: apkfile   File: PackageChunk.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(ByteBuffer buffer) {
    super.init(buffer);
    for (Chunk chunk : getChunks().values()) {
        if (chunk instanceof TypeChunk) {
            TypeChunk typeChunk = (TypeChunk) chunk;
            types.put(typeChunk.getId(), typeChunk);
        } else if (chunk instanceof TypeSpecChunk) {
            TypeSpecChunk typeSpecChunk = (TypeSpecChunk) chunk;
            typeSpecs.put(typeSpecChunk.getId(), typeSpecChunk);
        } else if (chunk instanceof StringPoolChunk) {
            continue;
        } else if (chunk instanceof LibraryChunk) {
            LibraryChunk libraryChunk = (LibraryChunk) chunk;
            libraries.add(libraryChunk);
        } else {
            throw new IllegalStateException(String.format("PackageChunk contains an unexpected chunk: %s", chunk.getClass()));
        }
    }
}
 
Example 5
Project: AI-Powered-Intelligent-Banking-Platform   File: EncodedAudioRecorder.java   Source Code and License 6 votes vote down vote up
/**
 * Save the encoded (output) buffer into the complete encoded recording.
 * TODO: copy directly (without the intermediate byte array)
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void dequeueOutputBuffer(MediaCodec codec, ByteBuffer[] outputBuffers, int index, MediaCodec.BufferInfo info) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        ByteBuffer buffer = outputBuffers[index];
        Log.i("size/remaining: " + info.size + "/" + buffer.remaining());
        if (info.size <= buffer.remaining()) {
            final byte[] bufferCopied = new byte[info.size];
            buffer.get(bufferCopied); // TODO: catch BufferUnderflow
            // TODO: do we need to clear?
            // on N5: always size == remaining(), clearing is not needed
            // on SGS2: remaining decreases until it becomes less than size, which results in BufferUnderflow
            // (but SGS2 records only zeros anyway)
            //buffer.clear();
            codec.releaseOutputBuffer(index, false);
            addEncoded(bufferCopied);
            if (Log.DEBUG) {
                AudioUtils.showSomeBytes("out", bufferCopied);
            }
        } else {
            Log.e("size > remaining");
            codec.releaseOutputBuffer(index, false);
        }
    }
}
 
Example 6
Project: libRtmp   File: NReader.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    ByteBuffer buffer = ByteBuffer.allocate(Options.getInstance().bufferSize);
    while (running) {
        try {
            selector.select();
            Set selectedKeys = selector.selectedKeys();
            for (Object selectedKey : selectedKeys) {
                SelectionKey key = (SelectionKey) selectedKey;
                SocketChannel channel = (SocketChannel) key.channel();
                channel.read(buffer);


                //TODO
            }
        } catch (IOException e) {
            Lg.e(Error.READER, e);
        }
    }
}
 
Example 7
Project: GitHub   File: GifBytesTestUtil.java   Source Code and License 6 votes vote down vote up
public static void writeImageDescriptor(ByteBuffer out, int imageLeft, int imageTop,
    int imageWidth, int imageHeight, boolean hasLct, int numColors) {
  verifyRemaining(out, IMAGE_DESCRIPTOR_LENGTH);
  verifyShortValues(imageLeft, imageTop, imageWidth, imageHeight);

  final byte packed;
  if (hasLct) {
    int size = log2(numColors) - 1;
    packed = (byte) (0x80 | size);
  } else {
    packed = 0x00;
  }

  // Image separator
  out.put((byte) 0x2C);
  out.putShort((short) imageLeft).putShort((short) imageTop).putShort((short) imageWidth)
      .putShort((short) imageHeight).put(packed);
}
 
Example 8
Project: dble   File: FastByteOperations.java   Source Code and License 6 votes vote down vote up
public int compare(ByteBuffer buffer1, byte[] buffer2, int offset2, int length2) {
    Object obj1;
    long offset1;
    if (buffer1.hasArray()) {
        obj1 = buffer1.array();
        offset1 = BYTE_ARRAY_BASE_OFFSET + buffer1.arrayOffset();
    } else {
        obj1 = null;
        offset1 = THE_UNSAFE.getLong(buffer1, DIRECT_BUFFER_ADDRESS_OFFSET);
    }
    int length1;
    {
        int position = buffer1.position();
        int limit = buffer1.limit();
        length1 = limit - position;
        offset1 += position;
    }
    return compareTo(obj1, offset1, length1, buffer2, BYTE_ARRAY_BASE_OFFSET + offset2, length2);
}
 
Example 9
Project: MetadataEditor   File: OggVorbisTagWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Calculate checkSum over the Page
 *
 * @param page
 */
private void calculateChecksumOverPage(ByteBuffer page)
{           
    //CRC should be zero before calculating it
    page.putInt(OggPageHeader.FIELD_PAGE_CHECKSUM_POS, 0);

    //Compute CRC over the  page  //TODO shouldnt really use array();
    byte[] crc = OggCRCFactory.computeCRC(page.array());
    for (int i = 0; i < crc.length; i++)
    {
        page.put(OggPageHeader.FIELD_PAGE_CHECKSUM_POS + i, crc[i]);
    }

    //Rewind to start of Page
    page.rewind();
}
 
Example 10
Project: s-store   File: TestStoredProcedureInvocation.java   Source Code and License 6 votes vote down vote up
/**
 * testGetParameterSet
 */
public void testGetParameterSet() throws Exception {
    StoredProcedureInvocation invocation = new StoredProcedureInvocation(CLIENT_HANDLE,
                                                                         TARGET_PROCEDURE,
                                                                         PARAMS);
    byte[] invocation_bytes = FastSerializer.serialize(invocation);
    assertNotNull(invocation_bytes);
    
    ByteBuffer buffer = ByteBuffer.wrap(invocation_bytes);
    ByteBuffer paramsBuffer = StoredProcedureInvocation.getParameterSet(buffer);
    assertNotNull(paramsBuffer);
    
    ParameterSet cloneParams = new ParameterSet();
    FastDeserializer fds = new FastDeserializer(paramsBuffer);
    cloneParams.readExternal(fds);
    
    assertEquals(PARAMS.length, cloneParams.size());
    for (int i = 0; i < PARAMS.length; i++) {
        assertEquals(PARAMS[i], cloneParams.toArray()[i]);
    } 
}
 
Example 11
Project: lams   File: ByteBufferIndexInput.java   Source Code and License 6 votes vote down vote up
/** Returns a sliced view from a set of already-existing buffers: 
 *  the last buffer's limit() will be correct, but
 *  you must deal with offset separately (the first buffer will not be adjusted) */
private ByteBuffer[] buildSlice(ByteBuffer[] buffers, long offset, long length) {
  final long sliceEnd = offset + length;
  
  final int startIndex = (int) (offset >>> chunkSizePower);
  final int endIndex = (int) (sliceEnd >>> chunkSizePower);

  // we always allocate one more slice, the last one may be a 0 byte one
  final ByteBuffer slices[] = new ByteBuffer[endIndex - startIndex + 1];
  
  for (int i = 0; i < slices.length; i++) {
    slices[i] = buffers[startIndex + i].duplicate();
  }

  // set the last buffer's limit for the sliced view.
  slices[slices.length - 1].limit((int) (sliceEnd & chunkSizeMask));
  
  return slices;
}
 
Example 12
Project: openjdk-jdk10   File: ZipPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
    in.transformAndCopy((resource) -> {
        ResourcePoolEntry res = resource;
        if (resource.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)
                && predicate.test(resource.path())) {
            byte[] compressed;
            compressed = compress(resource.contentBytes());
            res = ResourcePoolManager.newCompressedResource(resource,
                    ByteBuffer.wrap(compressed), getName(), null,
                    ((ResourcePoolImpl)in).getStringTable(), in.byteOrder());
        }
        return res;
    }, out);

    return out.build();
}
 
Example 13
Project: kafka-0.11.0.0-src-with-comment   File: KafkaLZ4Test.java   Source Code and License 6 votes vote down vote up
@Test
public void testArrayBackedBufferSlice() throws IOException {
    byte[] compressed = compressedBytes();

    int sliceOffset = 12;

    ByteBuffer buffer = ByteBuffer.allocate(compressed.length + sliceOffset + 123);
    buffer.position(sliceOffset);
    buffer.put(compressed).flip();
    buffer.position(sliceOffset);

    ByteBuffer slice = buffer.slice();
    testDecompression(slice);

    int offset = 42;
    buffer = ByteBuffer.allocate(compressed.length + sliceOffset + offset);
    buffer.position(sliceOffset + offset);
    buffer.put(compressed).flip();
    buffer.position(sliceOffset);

    slice = buffer.slice();
    slice.position(offset);
    testDecompression(slice);
}
 
Example 14
Project: libRtmp   File: FlvPackerHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 生成flv medadata 数据
 * @param width 视频宽度
 * @param height 视频高度
 * @param fps 视频帧率
 * @param audioRate 音频采样率
 * @param audioSize 音频大小
 * @param isStereo 音频是否为立体声
 * @return byte数组
 */
public static byte[] writeFlvMetaData(int width, int height, int fps, int audioRate, int audioSize, boolean isStereo) {
    AmfString metaDataHeader = new AmfString("onMetaData", false);
    AmfMap amfMap = new AmfMap();
    amfMap.setProperty("width", width);
    amfMap.setProperty("height", height);
    amfMap.setProperty("framerate", fps);
    amfMap.setProperty("videocodecid", FlvVideoCodecID.AVC);
    amfMap.setProperty("audiosamplerate", audioRate);
    amfMap.setProperty("audiosamplesize", audioSize);
    if(isStereo) {
        amfMap.setProperty("stereo", true);
    } else {
        amfMap.setProperty("stereo", false);
    }
    amfMap.setProperty("audiocodecid", FlvAudio.AAC);

    int size = amfMap.getSize() + metaDataHeader.getSize();
    ByteBuffer amfBuffer = ByteBuffer.allocate(size);
    amfBuffer.put(metaDataHeader.getBytes());
    amfBuffer.put(amfMap.getBytes());
    return amfBuffer.array();
}
 
Example 15
Project: lazycat   File: WsWebSocketContainer.java   Source Code and License 6 votes vote down vote up
private static void addHeader(ByteBuffer result, String key, List<String> values) {
	StringBuilder sb = new StringBuilder();

	Iterator<String> iter = values.iterator();
	if (!iter.hasNext()) {
		return;
	}
	sb.append(iter.next());
	while (iter.hasNext()) {
		sb.append(',');
		sb.append(iter.next());
	}

	result.put(key.getBytes(StandardCharsets.ISO_8859_1));
	result.put(": ".getBytes(StandardCharsets.ISO_8859_1));
	result.put(sb.toString().getBytes(StandardCharsets.ISO_8859_1));
	result.put(crlf);
}
 
Example 16
Project: directory-ldap-api   File: CertGenerationRequestDecorator.java   Source Code and License 6 votes vote down vote up
/**
 * Encodes the CertGenerationRequest extended operation.
 * 
 * @return A ByteBuffer that contains the encoded PDU
 * @throws org.apache.directory.api.asn1.EncoderException If anything goes wrong.
 */
/* no qualifier */ByteBuffer encodeInternal() throws EncoderException
{
    // Allocate the bytes buffer.
    ByteBuffer bb = ByteBuffer.allocate( computeLengthInternal() );

    bb.put( UniversalTag.SEQUENCE.getValue() );
    bb.put( TLV.getBytes( requestLength ) );

    BerValue.encode( bb, certGenerationRequest.getTargetDN() );
    BerValue.encode( bb, certGenerationRequest.getIssuerDN() );
    BerValue.encode( bb, certGenerationRequest.getSubjectDN() );
    BerValue.encode( bb, certGenerationRequest.getKeyAlgorithm() );

    return bb;
}
 
Example 17
Project: dble   File: ByteBufferUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Compare two ByteBuffer at specified offsets for length.
 * Compares the non equal bytes as unsigned.
 *
 * @param bytes1  First byte buffer to compare.
 * @param offset1 Position to start the comparison at in the first array.
 * @param bytes2  Second byte buffer to compare.
 * @param offset2 Position to start the comparison at in the second array.
 * @param length  How many bytes to compare?
 * @return -1 if byte1 is less than byte2, 1 if byte2 is less than byte1 or 0 if equal.
 */
public static int compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length) {
    if (bytes1 == null) {
        return bytes2 == null ? 0 : -1;
    }
    if (bytes2 == null) {
        return 1;
    }

    assert bytes1.limit() >= offset1 + length : "The first byte array isn't long enough for the specified offset and length.";
    assert bytes2.limit() >= offset2 + length : "The second byte array isn't long enough for the specified offset and length.";
    for (int i = 0; i < length; i++) {
        byte byte1 = bytes1.get(offset1 + i);
        byte byte2 = bytes2.get(offset2 + i);
        // compare non-equal bytes as unsigned
        if (byte1 != byte2) {
            return (byte1 & 0xFF) < (byte2 & 0xFF) ? -1 : 1;
        }
    }
    return 0;
}
 
Example 18
Project: FApkSigner   File: RandomAccessFileDataSource.java   Source Code and License 5 votes vote down vote up
@Override
public ByteBuffer getByteBuffer(long offset, int size) throws IOException {
    if (size < 0) {
        throw new IndexOutOfBoundsException("size: " + size);
    }
    ByteBuffer result = ByteBuffer.allocate(size);
    copyTo(offset, size, result);
    result.flip();
    return result;
}
 
Example 19
Project: fresco_floodlight   File: LLDPOrganizationalTLV.java   Source Code and License 5 votes vote down vote up
@Override
public byte[] serialize() {
    int valueLength = OUI_LENGTH + SUBTYPE_LENGTH + infoString.length;
    value = new byte[valueLength];
    ByteBuffer bb = ByteBuffer.wrap(value);
    bb.put(oui);
    bb.put(subType);
    bb.put(infoString);
    return super.serialize();
}
 
Example 20
Project: jdk8u-jdk   File: WindowsAsynchronousFileChannelImpl.java   Source Code and License 5 votes vote down vote up
ReadTask(ByteBuffer dst,
         int pos,
         int rem,
         long position,
         PendingFuture<Integer,A> result)
{
    this.dst = dst;
    this.pos = pos;
    this.rem = rem;
    this.position = position;
    this.result = result;
}
 
Example 21
Project: hadoop   File: TestAuxServices.java   Source Code and License 5 votes vote down vote up
@Override
public void initializeApplication(ApplicationInitializationContext context) {
  ByteBuffer data = context.getApplicationDataForService();
  assertEquals(idef, data.getChar());
  assertEquals(expected_appId, data.getInt());
  assertEquals(expected_appId, context.getApplicationId().getId());
}
 
Example 22
Project: NoRiskNoFun   File: SessionImplTests.java   Source Code and License 5 votes vote down vote up
@Test(expected = IOException.class)
public void doWriteToSocketDoesNotCatchExceptionFromSocket() throws IOException {

    // given
    when(socketMock.write(ArgumentMatchers.any(ByteBuffer.class))).thenThrow(IOException.class);
    SessionImpl target = new SessionImpl(selectorMock);
    target.write("Hello World!".getBytes());

    // when/then
    target.doWriteToSocket(socketMock);
}
 
Example 23
Project: multiple-dimension-spread   File: OptimizeDoubleColumnBinaryMaker.java   Source Code and License 5 votes vote down vote up
@Override
public void create( final int[] dicIndexArray , final byte[] buffer , final int start , final int length ) throws IOException{
  ByteBuffer wrapBuffer = ByteBuffer.wrap( buffer , start , length );
  for( int index : dicIndexArray ){
    wrapBuffer.putShort( (short)index );
  }
}
 
Example 24
Project: lams   File: SpdyClientProvider.java   Source Code and License 5 votes vote down vote up
private ChannelListener<StreamConnection> createOpenListener(final ClientCallback<ClientConnection> listener, final URI uri, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
    return new ChannelListener<StreamConnection>() {
        @Override
        public void handleEvent(StreamConnection connection) {
            handleConnected(connection, listener, uri, ssl, bufferPool, options);
        }
    };
}
 
Example 25
Project: lams   File: FlexBase64.java   Source Code and License 5 votes vote down vote up
private static ByteBuffer decode(ByteBuffer source) throws IOException {
    int len = source.remaining();
    int remainder = len % 4;
    int size = ((len / 4) + (remainder == 0 ? 0 : 4 - remainder)) * 3;
    ByteBuffer buffer = ByteBuffer.allocate(size);
    createDecoder().decode(source, buffer);
    buffer.flip();
    return buffer;
}
 
Example 26
Project: state-channels   File: BlocksController.java   Source Code and License 5 votes vote down vote up
@PostMapping
@SuppressWarnings("all")
public Mono<ResponseEntity<Object>> save(@RequestHeader("X-Block-Id") String blockId, @RequestBody Flux<ByteBuffer> blockFlux) {
    log.info("Block {}", blockId);
    return logsStorage.streamBlock(blockId, blockFlux)
        .map(res -> {
            if (res.getHttpCode() >= 200 && res.getHttpCode() < 300) {
                return noContent();
            } else {
                return status(res.getHttpCode());
            }
        })
        .map(r -> r.build())
        .onErrorResume(t -> Mono.just(status(INTERNAL_SERVER_ERROR).build()));
}
 
Example 27
Project: Quavo   File: ByteBufferUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Gets a unsigned smart from the buffer.
 * 
 * @param buffer The buffer.
 * @return The value.
 */
public static int getUnsignedSmart(ByteBuffer buf) {
	int peek = buf.get(buf.position()) & 0xFF;
	if (peek < 128)
		return buf.get() & 0xFF;
	else
		return (buf.getShort() & 0xFFFF) - 32768;
}
 
Example 28
Project: onekey-proxy-android   File: DnsHeader.java   Source Code and License 5 votes vote down vote up
public static DnsHeader FromBytes(ByteBuffer buffer) {
 DnsHeader header=new DnsHeader(buffer.array(),buffer.arrayOffset()+buffer.position());
 header.ID=buffer.getShort();
 header.Flags=DnsFlags.Parse(buffer.getShort());
 header.QuestionCount=buffer.getShort();
 header.ResourceCount=buffer.getShort();
 header.AResourceCount=buffer.getShort();
 header.EResourceCount=buffer.getShort();
 return header;
}
 
Example 29
Project: sstore-soft   File: SnapshotUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Create a digest for a snapshot containing the time of the snapshot and the list of tables included.
 * The first item in the comma separated list is the time in milliseconds as a string.
 * @param snapshotTime
 * @param path
 * @param nonce
 * @param tables
 * @throws IOException
 */
public static void
    recordSnapshotTableList(
        long snapshotTime,
        String path,
        String nonce,
        List<Table> tables) throws IOException {
    final File f = new File(path, constructDigestFilenameForNonce(nonce));
    if (f.exists()) {
        if (!f.delete()) {
            throw new IOException("Unable to write table list file " + f);
        }
    }
    FileOutputStream fos = new FileOutputStream(f);
    StringWriter sw = new StringWriter();
    sw.append(Long.toString(snapshotTime));
    if (!tables.isEmpty()) {
        sw.append(',');
    }
    for (int ii = 0; ii < tables.size(); ii++) {
        sw.append(tables.get(ii).getTypeName());
        if (!(ii == (tables.size() - 1))) {
            sw.append(',');
        } else {
            sw.append('\n');
        }
    }

    final byte tableListBytes[] = sw.getBuffer().toString().getBytes("UTF-8");
    final CRC32 crc = new CRC32();
    crc.update(tableListBytes);
    ByteBuffer fileBuffer = ByteBuffer.allocate(tableListBytes.length + 4);
    fileBuffer.putInt((int)crc.getValue());
    fileBuffer.put(tableListBytes);
    fileBuffer.flip();
    fos.getChannel().write(fileBuffer);
    fos.getFD().sync();
}
 
Example 30
Project: jdk8u-jdk   File: X11KSC5601_OLD.java   Source Code and License 5 votes vote down vote up
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();

    try {
        while (sp < sl) {
            char c = sa[sp];
            if (c <= '\u007f')
                return CoderResult.unmappableForLength(1);
            int ncode = encodeDouble(c);
            if (ncode != 0 && c != '\u0000' ) {
                da[dp++] = (byte) ((ncode  >> 8) & 0x7f);
                da[dp++] = (byte) (ncode & 0x7f);
                sp++;
                continue;
            }
            return CoderResult.unmappableForLength(1);
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 31
Project: jdk8u-jdk   File: SingleByte.java   Source Code and License 5 votes vote down vote up
private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();

    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();

    CoderResult cr = CoderResult.UNDERFLOW;
    if ((dl - dp) < (sl - sp)) {
        sl = sp + (dl - dp);
        cr = CoderResult.OVERFLOW;
    }

    while (sp < sl) {
        char c = sa[sp];
        int b = encode(c);
        if (b == UNMAPPABLE_ENCODING) {
            if (Character.isSurrogate(c)) {
                if (sgp == null)
                    sgp = new Surrogate.Parser();
                if (sgp.parse(c, sa, sp, sl) < 0)
                    return withResult(sgp.error(), src, sp, dst, dp);
                return withResult(sgp.unmappableResult(), src, sp, dst, dp);
            }
            return withResult(CoderResult.unmappableForLength(1),
                       src, sp, dst, dp);
        }
        da[dp++] = (byte)b;
        sp++;
    }
    return withResult(cr, src, sp, dst, dp);
}
 
Example 32
Project: dubbo2   File: ByteBufferBackedChannelBuffer.java   Source Code and License 5 votes vote down vote up
public ByteBufferBackedChannelBuffer(ByteBuffer buffer) {
    if (buffer == null) {
        throw new NullPointerException("buffer");
    }

    this.buffer = buffer.slice();
    capacity = buffer.remaining();
    writerIndex(capacity);
}
 
Example 33
Project: playTorrent   File: BitEncoder.java   Source Code and License 5 votes vote down vote up
private void encodeByte(@NonNull OutputStream out, @NonNull ByteBuffer buffer) throws IOException {
    byte[] bytes = buffer.array();
    if (bytes.length == 0) {
        throw new IOException("Input bytes is empty");
    }

    String encodeBytes = String.format(Locale.getDefault(), "%d:", bytes.length);
    out.write(encodeBytes.getBytes("UTF-8"));
    out.write(bytes);
}
 
Example 34
Project: burstcoin   File: Attachment.java   Source Code and License 5 votes vote down vote up
@Override
void putMyBytes(ByteBuffer buffer) {
	buffer.putLong(this.amountNQT);
	buffer.putInt(this.deadline);
	buffer.put(Escrow.decisionToByte(this.deadlineAction));
	buffer.put(this.requiredSigners);
	byte totalSigners = (byte) this.signers.size();
	buffer.put(totalSigners);
	for(Long id : this.signers) {
		buffer.putLong(id);
	}
}
 
Example 35
Project: hadoop   File: TestCryptoStreams.java   Source Code and License 5 votes vote down vote up
@Override
public int read(ByteBuffer buf) throws IOException {
  checkStream();
  if (pos < length) {
    int n = (int) Math.min(buf.remaining(), length - pos);
    if (n > 0) {
      buf.put(data, pos, n);
    }
    pos += n;
    return n;
  }
  return -1;
}
 
Example 36
Project: OpenJSharp   File: DatagramChannelImpl.java   Source Code and License 5 votes vote down vote up
public long read(ByteBuffer[] dsts, int offset, int length)
    throws IOException
{
    if ((offset < 0) || (length < 0) || (offset > dsts.length - length))
        throw new IndexOutOfBoundsException();
    synchronized (readLock) {
        synchronized (stateLock) {
            ensureOpen();
            if (!isConnected())
                throw new NotYetConnectedException();
        }
        long n = 0;
        try {
            begin();
            if (!isOpen())
                return 0;
            readerThread = NativeThread.current();
            do {
                n = IOUtil.read(fd, dsts, offset, length, nd);
            } while ((n == IOStatus.INTERRUPTED) && isOpen());
            return IOStatus.normalize(n);
        } finally {
            readerThread = 0;
            end((n > 0) || (n == IOStatus.UNAVAILABLE));
            assert IOStatus.check(n);
        }
    }
}
 
Example 37
Project: sstable-adaptor   File: Murmur3Partitioner.java   Source Code and License 5 votes vote down vote up
private LongToken getToken(ByteBuffer key, long[] hash)
{
    if (key.remaining() == 0)
        return MINIMUM;

    return new LongToken(normalize(hash[0]));
}
 
Example 38
Project: ditb   File: TestThriftServer.java   Source Code and License 5 votes vote down vote up
/**
 * Appends the value to a cell and checks that the cell value is updated properly.
 *
 * @throws Exception
 */
public static void doTestAppend() throws Exception {
  ThriftServerRunner.HBaseHandler handler =
    new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration(),
      UserProvider.instantiate(UTIL.getConfiguration()));
  handler.createTable(tableAname, getColumnDescriptors());
  try {
    List<Mutation> mutations = new ArrayList<Mutation>(1);
    mutations.add(new Mutation(false, columnAname, valueAname, true));
    handler.mutateRow(tableAname, rowAname, mutations, null);

    List<ByteBuffer> columnList = new ArrayList<ByteBuffer>();
    columnList.add(columnAname);
    List<ByteBuffer> valueList = new ArrayList<ByteBuffer>();
    valueList.add(valueBname);

    TAppend append = new TAppend(tableAname, rowAname, columnList, valueList);
    handler.append(append);

    TRowResult rowResult = handler.getRow(tableAname, rowAname, null).get(0);
    assertEquals(rowAname, rowResult.row);
    assertArrayEquals(Bytes.add(valueAname.array(), valueBname.array()),
      rowResult.columns.get(columnAname).value.array());
  } finally {
    handler.disableTable(tableAname);
    handler.deleteTable(tableAname);
  }
}
 
Example 39
Project: Hotspot-master-devp   File: URLEncodedUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 *
 * @param content     the portion to decode
 * @param charset     the charset to use
 * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return encoded string
 */
private static String urldecode(
        final String content,
        final Charset charset,
        final boolean plusAsBlank) {
    if (content == null) {
        return null;
    }
    ByteBuffer bb = ByteBuffer.allocate(content.length());
    CharBuffer cb = CharBuffer.wrap(content);
    while (cb.hasRemaining()) {
        char c = cb.get();
        if (c == '%' && cb.remaining() >= 2) {
            char uc = cb.get();
            char lc = cb.get();
            int u = Character.digit(uc, 16);
            int l = Character.digit(lc, 16);
            if (u != -1 && l != -1) {
                bb.put((byte) ((u << 4) + l));
            } else {
                bb.put((byte) '%');
                bb.put((byte) uc);
                bb.put((byte) lc);
            }
        } else if (plusAsBlank && c == '+') {
            bb.put((byte) ' ');
        } else {
            bb.put((byte) c);
        }
    }
    bb.flip();
    return charset.decode(bb).toString();
}
 
Example 40
Project: heifreader   File: ItemPropertiesBox.java   Source Code and License 5 votes vote down vote up
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
    initContainer(dataSource, contentSize, boxParser);
    for (AbstractBox box : this.getBoxes(AbstractBox.class)) {
        box.parseDetails();
    }
}
 
Example 41
Project: PaoMovie   File: MagicTenderFilter.java   Source Code and License 5 votes vote down vote up
public void onInitialized(){
	super.onInitialized();
    runOnDraw(new Runnable(){
	    public void run(){
	    	GLES20.glGenTextures(1, mToneCurveTexture, 0);
		    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mToneCurveTexture[0]);
		    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
	                GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
	        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
	                GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
	        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
	                GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
	        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
	                GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);					
	        byte[] arrayOfByte = new byte[1024];
	        int[] arrayOfInt1 = { 10, 12, 14, 15, 17, 19, 21, 22, 24, 26, 28, 29, 31, 33, 35, 38, 40, 41, 43, 45, 47, 48, 50, 52, 53, 55, 57, 58, 60, 61, 63, 65, 66, 68, 69, 71, 72, 74, 75, 77, 79, 80, 81, 83, 84, 86, 87, 89, 92, 93, 94, 96, 97, 99, 100, 101, 103, 104, 105, 107, 108, 109, 110, 112, 113, 114, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 158, 159, 160, 161, 162, 163, 164, 165, 166, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 175, 176, 177, 178, 179, 179, 180, 181, 182, 182, 183, 184, 184, 185, 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, 195, 195, 196, 196, 197, 198, 198, 199, 200, 200, 201, 201, 202, 202, 203, 204, 204, 205, 205, 206, 206, 207, 207, 208, 209, 209, 210, 210, 211, 211, 212, 212, 213, 213, 214, 214, 215, 215, 216, 216, 216, 217, 217, 218, 218, 219, 219, 219, 220, 220, 221, 221, 222, 222, 223, 223, 224, 224, 224, 225, 225, 226, 226, 227, 227, 227, 228, 228, 229, 229, 230, 230, 230, 231, 231, 232, 232, 232, 233, 233, 234, 234, 234, 234, 235, 235, 236, 236, 236, 237, 237, 238, 238, 238, 239, 239, 240, 240, 240, 241, 241, 242, 242 };
	        int[] arrayOfInt2 = { 10, 12, 14, 15, 17, 19, 19, 21, 22, 24, 26, 28, 29, 31, 33, 35, 36, 36, 38, 40, 41, 43, 45, 47, 48, 50, 52, 52, 53, 55, 57, 58, 60, 61, 63, 65, 66, 68, 69, 69, 71, 72, 74, 75, 77, 79, 80, 81, 83, 84, 86, 86, 87, 89, 90, 92, 93, 94, 96, 97, 99, 100, 101, 103, 103, 104, 105, 107, 108, 109, 110, 112, 113, 114, 116, 117, 118, 119, 120, 122, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 158, 159, 160, 161, 162, 163, 164, 165, 166, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 175, 176, 177, 178, 179, 179, 180, 181, 182, 182, 183, 184, 184, 185, 186, 187, 187, 188, 189, 190, 191, 191, 192, 193, 193, 194, 195, 195, 196, 196, 197, 198, 198, 199, 200, 200, 201, 201, 202, 202, 204, 204, 205, 205, 206, 206, 207, 207, 208, 209, 209, 210, 210, 211, 211, 212, 213, 213, 214, 214, 215, 215, 216, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 222, 223, 223, 224, 224, 224, 225, 226, 226, 227, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 232, 233, 233, 234, 234, 234, 235, 236, 236, 236, 237, 237, 238, 238, 238, 239, 239, 240, 240, 241, 241, 242, 242 };
	        int[] arrayOfInt3 = { 10, 12, 12, 14, 15, 15, 17, 17, 19, 21, 21, 22, 24, 24, 26, 28, 28, 29, 31, 31, 33, 33, 35, 36, 36, 38, 40, 40, 41, 43, 43, 45, 47, 47, 48, 50, 52, 52, 53, 55, 55, 57, 58, 58, 60, 61, 63, 63, 65, 66, 68, 68, 69, 71, 71, 72, 74, 75, 77, 77, 79, 80, 81, 81, 83, 84, 86, 87, 87, 89, 90, 92, 93, 94, 94, 96, 97, 99, 100, 101, 103, 103, 104, 105, 107, 108, 109, 110, 112, 113, 113, 114, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 127, 129, 130, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 154, 155, 156, 157, 158, 158, 159, 160, 161, 162, 163, 164, 165, 166, 166, 167, 169, 170, 171, 171, 172, 173, 174, 175, 175, 176, 178, 179, 179, 180, 181, 182, 182, 183, 184, 185, 186, 187, 187, 188, 189, 190, 191, 191, 192, 193, 193, 195, 195, 196, 196, 197, 198, 199, 200, 200, 201, 201, 202, 203, 204, 204, 205, 206, 206, 207, 207, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 222, 222, 223, 223, 224, 224, 225, 225, 226, 227, 227, 227, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 238, 238, 238, 239, 240, 240, 240, 241, 242, 242 };
	        int[] arrayOfInt4 = { 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 27, 27, 28, 28, 28, 28, 29, 29, 30, 29, 31, 31, 31, 31, 32, 32, 33, 33, 34, 34, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 40, 41, 42, 42, 43, 43, 44, 44, 45, 45, 45, 46, 47, 47, 48, 48, 49, 50, 51, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 63, 63, 64, 65, 66, 67, 68, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 93, 94, 95, 96, 97, 98, 100, 101, 103, 104, 105, 107, 108, 110, 111, 113, 115, 116, 118, 119, 120, 122, 123, 125, 127, 128, 130, 132, 134, 135, 137, 139, 141, 143, 144, 146, 148, 150, 152, 154, 156, 158, 160, 163, 165, 167, 169, 171, 173, 175, 178, 180, 182, 185, 187, 189, 192, 194, 197, 199, 201, 204, 206, 209, 211, 214, 216, 219, 221, 224, 226, 229, 232, 234, 236, 239, 241, 245, 247, 250, 252, 255 };
	        for (int i = 0; i < 256; i++){
	          arrayOfByte[(i * 4)] = ((byte)arrayOfInt1[i]);
	          arrayOfByte[(1 + i * 4)] = ((byte)arrayOfInt2[i]);
	          arrayOfByte[(2 + i * 4)] = ((byte)arrayOfInt3[i]);
	          arrayOfByte[(3 + i * 4)] = ((byte)arrayOfInt4[i]);
	        }
	        GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, 256, 1, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ByteBuffer.wrap(arrayOfByte));
	        mMaskGrey1TextureId = OpenGLUtils.loadTexture(mContext, "filter/bluevintage_mask1.jpg");
	    }
    });
}
 
Example 42
Project: OpenPad-for-Android   File: TextManager.java   Source Code and License 5 votes vote down vote up
/**
 * 파일의 인코딩 포멧 형식을 판단합니다.
 * @param _buffer 입력된 텍스트
 * @return char형 Buffer를 반환합니다.
 */
private CharBuffer formatDetector(final ByteBuffer _buffer) {
    CharBuffer charBuffer = null;
    try {
        CharsetDecoder decoder = Charset.forName(Constant.ENCODE_TYPE_UTF8_STR).newDecoder();
        charBuffer = decoder.decode(_buffer);
    } catch (CharacterCodingException cce) {
        Log.e("TextManager(format-)", cce.getMessage());
        return null;
    }
    return charBuffer;
}
 
Example 43
Project: dubbox-hystrix   File: ByteBufferBackedChannelBuffer.java   Source Code and License 5 votes vote down vote up
public ByteBufferBackedChannelBuffer(ByteBuffer buffer) {
    if (buffer == null) {
        throw new NullPointerException("buffer");
    }

    this.buffer = buffer.slice();
    capacity = buffer.remaining();
    writerIndex(capacity);
}
 
Example 44
Project: athena   File: EncapSecurityPayload.java   Source Code and License 5 votes vote down vote up
@Override
public IPacket deserialize(byte[] data, int offset, int length) {
    final ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
    this.securityParamIndex = bb.getInt();
    this.sequence = bb.getInt();

    this.payload = new Data();
    this.payload.deserialize(data, bb.position(),
                             bb.limit() - bb.position());
    this.payload.setParent(this);

    return this;
}
 
Example 45
Project: live_master   File: SampleGroupDescriptionBox.java   Source Code and License 5 votes vote down vote up
@Override
protected void getContent(ByteBuffer byteBuffer) {
    writeVersionAndFlags(byteBuffer);
    byteBuffer.put(groupingType.getBytes());
    if (this.getVersion() == 1) {
        IsoTypeWriter.writeUInt32(byteBuffer, defaultLength);
    }
    IsoTypeWriter.writeUInt32(byteBuffer, this.groupEntries.size());
    for (GroupEntry entry : groupEntries) {
        if (this.getVersion() == 1 && defaultLength == 0) {
            IsoTypeWriter.writeUInt32(byteBuffer, entry.get().limit());
        }
        byteBuffer.put(entry.get());
    }
}
 
Example 46
Project: amazon-kinesis-video-streams-parser-library   File: MkvStreamReaderCallback.java   Source Code and License 5 votes vote down vote up
CurrentMkvDataElementInfo(EBMLElementMetaData elementMetadata,
        long dataSize,
        List<EBMLElementMetaData> elementPath,
        ByteBuffer idAndSizeRawBytes) {
    this.elementMetadata = elementMetadata;
    this.dataSize = dataSize;
    this.elementPath = elementPath;
    //Copy the id and size raw bytes since these will be retained.
    this.idAndSizeRawBytes.put(idAndSizeRawBytes);
    this.idAndSizeRawBytes.flip();
    idAndSizeRawBytes.rewind();
}
 
Example 47
Project: hadoop-oss   File: Server.java   Source Code and License 5 votes vote down vote up
/**
 * This is a wrapper around {@link ReadableByteChannel#read(ByteBuffer)}.
 * If the amount of data is large, it writes to channel in smaller chunks. 
 * This is to avoid jdk from creating many direct buffers as the size of 
 * ByteBuffer increases. There should not be any performance degredation.
 * 
 * @see ReadableByteChannel#read(ByteBuffer)
 */
private int channelRead(ReadableByteChannel channel, 
                        ByteBuffer buffer) throws IOException {
  
  int count = (buffer.remaining() <= NIO_BUFFER_LIMIT) ?
              channel.read(buffer) : channelIO(channel, null, buffer);
  if (count > 0) {
    rpcMetrics.incrReceivedBytes(count);
  }
  return count;
}
 
Example 48
Project: mycat-src-1.6.1-RELEASE   File: BufferPerformanceMain.java   Source Code and License 5 votes vote down vote up
public void getAllocate() {
    ByteBuffer buffer = ByteBuffer.allocate(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.get(b);
    }
    long t2 = System.currentTimeMillis();
    System.out.println("take time:" + (t2 - t1) + " ms.(Get:allocate)");
}
 
Example 49
Project: openjdk-jdk10   File: Http2TestServerConnection.java   Source Code and License 5 votes vote down vote up
private void writeFrame(Http2Frame frame) throws IOException {
    ByteBufferReference[] refs = new FramesEncoder().encodeFrame(frame);
    //System.err.println("TestServer: Writing frame " + frame.toString());
    int c = 0;
    for (ByteBufferReference ref : refs) {
        ByteBuffer buf = ref.get();
        byte[] ba = buf.array();
        int start = buf.arrayOffset() + buf.position();
        c += buf.remaining();
        os.write(ba, start, buf.remaining());
    }
    os.flush();
    //System.err.printf("TestServer: wrote %d bytes\n", c);
}
 
Example 50
Project: openjdk-jdk10   File: ScriptObjectMirror.java   Source Code and License 5 votes vote down vote up
/**
 * Nashorn extension: setIndexedPropertiesToExternalArrayData.
 * set indexed properties be exposed from a given nio ByteBuffer.
 *
 * @param buf external buffer - should be a nio ByteBuffer
 */
public void setIndexedPropertiesToExternalArrayData(final ByteBuffer buf) {
    inGlobal(new Callable<Void>() {
        @Override public Void call() {
            sobj.setArray(ArrayData.allocate(buf));
            return null;
        }
    });
}
 
Example 51
Project: openjdk-jdk10   File: TrueTypeFont.java   Source Code and License 5 votes vote down vote up
@Override
protected byte[] getTableBytes(int tag) {
    ByteBuffer buffer = getTableBuffer(tag);
    if (buffer == null) {
        return null;
    } else if (buffer.hasArray()) {
        try {
            return buffer.array();
        } catch (Exception re) {
        }
    }
    byte []data = new byte[getTableSize(tag)];
    buffer.get(data);
    return data;
}
 
Example 52
Project: smb-nio   File: SeekableSMBByteChannel.java   Source Code and License 5 votes vote down vote up
/**
 * Writes the content of the provided {@link ByteBuffer} into the {@link SmbRandomAccessFile} handled by the current
 * instance of {@link SeekableSMBByteChannel}. The {@link ByteBuffer} is read from its current position to it end.
 *
 * @param src {@link ByteBuffer} from which to read the data.
 * @return Number of bytes that were written.
 * @throws IOException If something goes wrong while writing to the file.
 */
@Override
public synchronized int write(ByteBuffer src) throws IOException {
    if (!this.open) throw new ClosedChannelException();
    final int len = src.limit() - src.position();
    final byte[] buffer = new byte[len];
    src.get(buffer);
    this.random.write(buffer);
    return len;
}
 
Example 53
Project: BIMplatform   File: ReadWriteVirtualObject.java   Source Code and License 5 votes vote down vote up
protected ByteBuffer ensureCapacity(ByteBuffer buffer, int sizeToAdd) {
	int currentPos = buffer.position();
	if (buffer.capacity() < currentPos + sizeToAdd) {
		int newSize = Math.max(currentPos + sizeToAdd, buffer.capacity() * 2);
		ByteBuffer newBuffer = ByteBuffer.allocate(newSize);
		buffer.position(0);
		buffer.get(newBuffer.array(), 0, currentPos);
		buffer = newBuffer;
		buffer.position(currentPos);
	}
	return buffer;
}
 
Example 54
Project: chromium-net-for-android   File: UploadDataProviders.java   Source Code and License 5 votes vote down vote up
@Override
public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer) {
    if (!byteBuffer.hasRemaining()) {
        throw new IllegalStateException("Cronet passed a buffer with no bytes remaining");
    }
    if (byteBuffer.remaining() >= mUploadBuffer.remaining()) {
        byteBuffer.put(mUploadBuffer);
    } else {
        int oldLimit = mUploadBuffer.limit();
        mUploadBuffer.limit(mUploadBuffer.position() + byteBuffer.remaining());
        byteBuffer.put(mUploadBuffer);
        mUploadBuffer.limit(oldLimit);
    }
    uploadDataSink.onReadSucceeded(false);
}
 
Example 55
Project: Exoplayer2Radio   File: AudioTrack.java   Source Code and License 5 votes vote down vote up
private static int getFramesPerEncodedSample(@C.Encoding int encoding, ByteBuffer buffer) {
  if (encoding == C.ENCODING_DTS || encoding == C.ENCODING_DTS_HD) {
    return DtsUtil.parseDtsAudioSampleCount(buffer);
  } else if (encoding == C.ENCODING_AC3) {
    return Ac3Util.getAc3SyncframeAudioSampleCount();
  } else if (encoding == C.ENCODING_E_AC3) {
    return Ac3Util.parseEAc3SyncframeAudioSampleCount(buffer);
  } else {
    throw new IllegalStateException("Unexpected audio encoding: " + encoding);
  }
}
 
Example 56
Project: mysql-protocol   File: BufferUtils.java   Source Code and License 5 votes vote down vote up
public static final void writeWithLength(ByteBuffer buffer, byte[] src,
                                         byte nullValue) {
    if (src == null) {
        buffer.put(nullValue);
    } else {
        writeWithLength(buffer, src);
    }
}
 
Example 57
Project: tapir   File: ByteBufferUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkGetIPv4String() throws UnknownHostException {
    String ip = "127.0.0.1";

    InetAddress addr = InetAddress.getByName(ip);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.put(addr.getAddress());
    buffer.flip();

    assertEquals(ip, ByteBufferUtil.getIPv4String(buffer));
}
 
Example 58
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: AppendCallbackTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAppendMessageBatchEndOfFile() throws Exception{
    List<Message>  messages = new ArrayList<>();
    String topic = "test-topic";
    int queue= 0;
    for (int i = 0; i < 10; i++) {
        Message msg = new Message();
        msg.setBody("body".getBytes());
        msg.setTopic(topic);
        msg.setTags("abc");
        messages.add(msg);
    }
    MessageExtBatch messageExtBatch = new MessageExtBatch();
    messageExtBatch.setTopic(topic);
    messageExtBatch.setQueueId(queue);
    messageExtBatch.setBornTimestamp(System.currentTimeMillis());
    messageExtBatch.setBornHost(new InetSocketAddress("127.0.0.1",123));
    messageExtBatch.setStoreHost(new InetSocketAddress("127.0.0.1",124));
    messageExtBatch.setBody(MessageDecoder.encodeMessages(messages));

    messageExtBatch.setEncodedBuff(batchEncoder.encode(messageExtBatch));
    ByteBuffer buff = ByteBuffer.allocate(1024 * 10);
    //encounter end of file when append half of the data
    AppendMessageResult result = callback.doAppend(0, buff, 1000, messageExtBatch);
    assertEquals(AppendMessageStatus.END_OF_FILE, result.getStatus());
    assertEquals(0, result.getWroteOffset());
    assertEquals(0, result.getLogicsOffset());
    assertEquals(1000, result.getWroteBytes());
    assertEquals(8, buff.position()); //write blank size and magic value

    assertTrue(result.getMsgId().length() > 0); //should have already constructed some message ids
}
 
Example 59
Project: memory   File: BufferInvariantsTest.java   Source Code and License 5 votes vote down vote up
static void printbb(ByteBuffer bb) {
  println("pos: " + bb.position() + ", lim: " + bb.limit() + ", cap: " + bb.capacity());
  int rem = bb.remaining();
  int pos = bb.position();
  int i;
  for (i = 0; i < (rem-1); i++) {
    print(bb.get(i+ pos) + ", ");
  }
  println(bb.get(i + pos) + "\n");
}
 
Example 60
Project: kafka-0.11.0.0-src-with-comment   File: StickyAssignor.java   Source Code and License 5 votes vote down vote up
private static List<TopicPartition> deserializeTopicPartitionAssignment(ByteBuffer buffer) {
    Struct struct = STICKY_ASSIGNOR_USER_DATA.read(buffer);
    List<TopicPartition> partitions = new ArrayList<>();
    for (Object structObj : struct.getArray(TOPIC_PARTITIONS_KEY_NAME)) {
        Struct assignment = (Struct) structObj;
        String topic = assignment.getString(TOPIC_KEY_NAME);
        for (Object partitionObj : assignment.getArray(PARTITIONS_KEY_NAME)) {
            Integer partition = (Integer) partitionObj;
            partitions.add(new TopicPartition(topic, partition));
        }
    }
    return partitions;
}