Java Code Examples for java.nio.ByteBuffer#flip()
The following examples show how to use
java.nio.ByteBuffer#flip() .
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: ZipkinEmitterTest.java From cougar with Apache License 2.0 | 6 votes |
@Test public void emitAnnotation_OnShortOverload_ShouldEmitAnnotation() { short value = 327; ByteBuffer wrappedValue = ByteBuffer.allocate(Short.SIZE / 8).putShort(value); wrappedValue.flip(); BinaryAnnotation binaryAnnotation = new BinaryAnnotation(key, wrappedValue, AnnotationType.I16); binaryAnnotation.setHost(endpoint); List<Annotation> annotations = Collections.emptyList(); Span expectedSpan = new Span(traceId, spanName, spanId, annotations, Lists.newArrayList(binaryAnnotation)); expectedSpan.setParent_id(0); victim.emitAnnotation(zipkinData, key, value); verify(zipkinSpanCollector).collect(expectedSpan); }
Example 2
Source File: Client.java From coding-snippets with MIT License | 6 votes |
/** * 连接服务端 */ public void connect(String host, int port) throws IOException { try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(host, port))) { logger.info("Connected to server: %s", socketChannel); ByteBuffer buffer = ByteBuffer.allocate(8 * 1024 * 1024); try (FileChannel fileChannel = FileChannel.open(resultPath, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.READ)) { int total = 0; int n; while ((n = socketChannel.read(buffer)) != -1) { buffer.flip(); fileChannel.write(buffer); buffer.clear(); total += n; } logger.info("Result received. size = %d", total); } catch (IOException ex) { throw new RuntimeException(ex); } } }
Example 3
Source File: TextureUtils.java From OpenGL-Animation with The Unlicense | 6 votes |
protected static TextureData decodeTextureFile(MyFile file) { int width = 0; int height = 0; ByteBuffer buffer = null; try { InputStream in = file.getInputStream(); PNGDecoder decoder = new PNGDecoder(in); width = decoder.getWidth(); height = decoder.getHeight(); buffer = ByteBuffer.allocateDirect(4 * width * height); decoder.decode(buffer, width * 4, Format.BGRA); buffer.flip(); in.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Tried to load texture " + file.getName() + " , didn't work"); System.exit(-1); } return new TextureData(buffer, width, height); }
Example 4
Source File: ReadHandler.java From oxygen with Apache License 2.0 | 6 votes |
@Override public void completed(Integer result, ByteBuffer buffer) { if (result <= 0) { if (result == -1) { log.info("{} target closed", channelContext); } else { log.warn("{} read result {}", channelContext, result); } channelContext.close(); return; } buffer.flip(); channelContext.read(buffer); if (!channelContext.isClosed()) { buffer.clear(); channelContext.getChannel().read(buffer, buffer, this); } }
Example 5
Source File: TestMemoryManager.java From database with GNU General Public License v2.0 | 6 votes |
private String getString(final long saddr) { final StringBuffer sb = new StringBuffer(); final ByteBuffer[] bufs = manager.get(saddr); for (int i = 0; i < bufs.length; i++) { final byte[] data; if (bufs[i].isDirect()) { final ByteBuffer indbuf = ByteBuffer.allocate(bufs[i].remaining()); data = indbuf.array(); indbuf.put(bufs[i]); indbuf.flip(); } else { data = bufs[i].array(); } sb.append(new String(data)); } return sb.toString(); }
Example 6
Source File: ValuesTest.java From vespa with Apache License 2.0 | 6 votes |
@org.junit.Test public void testInt64Array() { int byteSize = 4 + 1 + 4 + 4 * 8; Values src = new Values(); long[] val = { 8, 16, 24, 32 }; src.add(new Int64Array(val)); checkSingleValue(src, Value.INT64_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT64_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asInt64Array(), val)); }
Example 7
Source File: OpentrackerLiveSync.java From bt with Apache License 2.0 | 5 votes |
void send() { ByteBuffer sendBuffer = ByteBuffer.allocate(HEADER_LENGTH); sendBuffer.put(id); sendBuffer.put(new byte[4]); sendBuffer.flip(); ByteBuffer[] buffers = new ByteBuffer[1 + PEERS_PER_PACKET]; buffers[0] = sendBuffer; try { while(running) { for(int i = 1;i<buffers.length;i++) { buffers[i] = toSend.take(); } channel.write(buffers); buffers[0].rewind(); } } catch (IOException | InterruptedException e) { running = false; e.printStackTrace(); } }
Example 8
Source File: EventSerializer.java From Flink-CEPplus with Apache License 2.0 | 5 votes |
private static ByteBuffer serializeCheckpointBarrier(CheckpointBarrier barrier) throws IOException { final CheckpointOptions checkpointOptions = barrier.getCheckpointOptions(); final CheckpointType checkpointType = checkpointOptions.getCheckpointType(); final byte[] locationBytes = checkpointOptions.getTargetLocation().isDefaultReference() ? null : checkpointOptions.getTargetLocation().getReferenceBytes(); final ByteBuffer buf = ByteBuffer.allocate(28 + (locationBytes == null ? 0 : locationBytes.length)); // we do not use checkpointType.ordinal() here to make the serialization robust // against changes in the enum (such as changes in the order of the values) final int typeInt; if (checkpointType == CheckpointType.CHECKPOINT) { typeInt = CHECKPOINT_TYPE_CHECKPOINT; } else if (checkpointType == CheckpointType.SAVEPOINT) { typeInt = CHECKPOINT_TYPE_SAVEPOINT; } else { throw new IOException("Unknown checkpoint type: " + checkpointType); } buf.putInt(CHECKPOINT_BARRIER_EVENT); buf.putLong(barrier.getId()); buf.putLong(barrier.getTimestamp()); buf.putInt(typeInt); if (locationBytes == null) { buf.putInt(-1); } else { buf.putInt(locationBytes.length); buf.put(locationBytes); } buf.flip(); return buf; }
Example 9
Source File: SendFailed.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
void doTest(int sendBufferSize, int recvBufferSize, boolean direct, int offset) throws IOException { debug("%n--- Testing with send size:[%d], recv size:[%d], offset:[%d] " + ", direct [%s]. ", sendBufferSize, recvBufferSize, offset, direct); try (SctpMultiChannel channel = SctpMultiChannel.open()) { MessageInfo messageInfo = MessageInfo.createOutgoing(remoteAddress, 0); ByteBuffer sendBuffer = filledBuffer(sendBufferSize, direct); debug("%nAttempting to send to %s. ", remoteAddress); int sent = channel.send(sendBuffer, messageInfo); sendBuffer.flip(); SendFailedNotificationHandler handler = new SendFailedNotificationHandler(); ByteBuffer recvBuffer = direct ? allocateDirect(recvBufferSize) : allocate((recvBufferSize)); channel.receive(recvBuffer, null, handler); // verify sent buffer received by send failed notification ByteBuffer buffer = handler.getSendFailedByteBuffer(); check(buffer.remaining() == sent); check(buffer.position() == 0); check(buffer.limit() == sent); assertSameContent(sendBuffer, handler.getSendFailedByteBuffer()); } }
Example 10
Source File: AbstractStreamingHashFunction.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * This is invoked for the last bytes of the input, which are not enough to fill a whole chunk. * The passed {@code ByteBuffer} is guaranteed to be non-empty. * * <p>This implementation simply pads with zeros and delegates to {@link #process(ByteBuffer)}. */ protected void processRemaining(ByteBuffer bb) { bb.position(bb.limit()); // move at the end bb.limit(chunkSize + 7); // get ready to pad with longs while (bb.position() < chunkSize) { bb.putLong(0); } bb.limit(chunkSize); bb.flip(); process(bb); }
Example 11
Source File: CubeHBaseEndpointRPC.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
private String getScanRequestString(GTScanRequest scanRequest) { int scanRequestBufferSize = BytesSerializer.SERIALIZE_BUFFER_SIZE; while (true) { try { ByteBuffer out = ByteBuffer.allocate(scanRequestBufferSize); GTInfo.serializer.serialize(scanRequest.getInfo(), out); BytesUtil.writeVInt(scanRequest.getGTScanRanges().size(), out); for (GTScanRange range : scanRequest.getGTScanRanges()) { serializeGTRecord(range.pkStart, out); serializeGTRecord(range.pkEnd, out); BytesUtil.writeVInt(range.fuzzyKeys.size(), out); for (GTRecord f : range.fuzzyKeys) { serializeGTRecord(f, out); } } ImmutableBitSet.serializer.serialize(scanRequest.getColumns(), out); BytesUtil.writeByteArray( GTUtil.serializeGTFilter(scanRequest.getFilterPushDown(), scanRequest.getInfo()), out); ImmutableBitSet.serializer.serialize(scanRequest.getAggrGroupBy(), out); ImmutableBitSet.serializer.serialize(scanRequest.getAggrMetrics(), out); BytesUtil.writeAsciiStringArray(scanRequest.getAggrMetricsFuncs(), out); BytesUtil.writeVInt(scanRequest.isAllowStorageAggregation() ? 1 : 0, out); BytesUtil.writeUTFString(scanRequest.getStorageLimitLevel().name(), out); BytesUtil.writeVInt(scanRequest.getStorageScanRowNumThreshold(), out); BytesUtil.writeVInt(scanRequest.getStoragePushDownLimit(), out); BytesUtil.writeUTFString(scanRequest.getStorageBehavior(), out); BytesUtil.writeBooleanArray(new boolean[]{storageContext.isExactAggregation()}, out); out.flip(); return Bytes.toStringBinary(out.array(), out.position(), out.limit()); } catch (BufferOverflowException boe) { logger.info("Buffer size {} cannot hold the scan request, resizing to 4 times", scanRequestBufferSize); scanRequestBufferSize *= 4; } } }
Example 12
Source File: ExternalEnv.java From p4ic4idea with Apache License 2.0 | 5 votes |
public byte[] marshal() { // FIXME: reimplement and refactor elsewhere properly when we're sure this is working -- HR. ByteBuffer byteBuf = ByteBuffer.allocate(10240); // FIXME!!!! -- HR. marshal(byteBuf); byteBuf.flip(); int envLength = byteBuf.limit(); byte[] envBytes = new byte[envLength]; byteBuf.get(envBytes); return envBytes; }
Example 13
Source File: SyncInfoValueControlTest.java From directory-ldap-api with Apache License 2.0 | 5 votes |
/** * Test the decoding of a SyncInfoValue control, refreshPresent choice, * no cookie, no refreshDone */ @Test public void testDecodeSyncInfoValueControlRefreshPresentNoCookieNoRefreshDone() throws Exception { ByteBuffer bb = ByteBuffer.allocate( 0x02 ); bb.put( new byte[] { ( byte ) 0xA2, 0x00 // syncInfoValue ::= CHOICE { } ); bb.flip(); SyncInfoValueFactory factory = ( SyncInfoValueFactory ) codec.getIntermediateResponseFactories(). get( SyncInfoValue.OID ); SyncInfoValue syncInfoValue = factory.newResponse(); factory.decodeValue( syncInfoValue, bb.array() ); assertEquals( SynchronizationInfoEnum.REFRESH_PRESENT, syncInfoValue.getSyncInfoValueType() ); assertEquals( "", Strings.utf8ToString( syncInfoValue.getCookie() ) ); assertTrue( syncInfoValue.isRefreshDone() ); // Check the revert encoding Asn1Buffer asn1Buffer = new Asn1Buffer(); factory.encodeValue( asn1Buffer, syncInfoValue ); assertArrayEquals( bb.array(), asn1Buffer.getBytes().array() ); }
Example 14
Source File: CommitLog.java From rocketmq with Apache License 2.0 | 4 votes |
private void resetByteBuffer(final ByteBuffer byteBuffer, final int limit) { byteBuffer.flip(); byteBuffer.limit(limit); }
Example 15
Source File: ExtendedResponseTest.java From directory-ldap-api with Apache License 2.0 | 4 votes |
/** * Test the decoding of an ExtendedResponse with no response */ @Test public void testDecodeExtendedResponseNoResponse() throws DecoderException, EncoderException { ByteBuffer stream = ByteBuffer.allocate( 0x1D ); stream.put( new byte[] { 0x30, 0x1B, // LDAPMessage ::= SEQUENCE { 0x02, 0x01, 0x01, // messageID MessageID // CHOICE { ..., extendedResp Response, ... 0x78, 0x16, // ExtendedResponse ::= [APPLICATION 24] SEQUENCE { // COMPONENTS OF LDAPResult, 0x0A, 0x01, 0x00, // LDAPResult ::= SEQUENCE { // resultCode ENUMERATED { // success (0), ... // }, 0x04, 0x00, // matchedDN LDAPDN, 0x04, 0x00, // errorMessage LDAPString, // referral [3] Referral OPTIONAL } // responseName [0] LDAPOID, ( byte ) 0x8A, 0x0D, // responseName [10] LDAPOID OPTIONAL, '1', '.', '3', '.', '6', '.', '1', '.', '5', '.', '5', '.', '2' } ); stream.flip(); // Allocate a LdapMessage Container LdapMessageContainer<ExtendedResponse> container = new LdapMessageContainer<>( codec ); // Decode the ExtendedRequest PDU Asn1Decoder.decode( stream, container ); // Check the decoded ExtendedResponse PDU ExtendedResponse extendedResponse = container.getMessage(); assertEquals( 1, extendedResponse.getMessageId() ); assertEquals( ResultCodeEnum.SUCCESS, extendedResponse.getLdapResult().getResultCode() ); assertEquals( Dn.EMPTY_DN, extendedResponse.getLdapResult().getMatchedDn() ); assertEquals( "", extendedResponse.getLdapResult().getDiagnosticMessage() ); assertEquals( "1.3.6.1.5.5.2", extendedResponse.getResponseName() ); // Check encode reverse Asn1Buffer buffer = new Asn1Buffer(); LdapEncoder.encodeMessage( buffer, codec, extendedResponse ); assertArrayEquals( stream.array(), buffer.getBytes().array() ); }
Example 16
Source File: AltsFraming.java From grpc-java with Apache License 2.0 | 4 votes |
/** * Reads bytes from input, parsing them into a frame. Returns false if and only if more data is * needed. To obtain a full frame this method must be called repeatedly until it returns true. */ public boolean readBytes(ByteBuffer input) throws GeneralSecurityException { Preconditions.checkNotNull(input); if (isComplete) { return true; } // Read enough bytes to determine the length while (buffer.position() < FRAME_LENGTH_HEADER_SIZE && input.hasRemaining()) { buffer.put(input.get()); } // If we have enough bytes to determine the length, read the length and ensure that our // internal buffer is large enough. if (buffer.position() == FRAME_LENGTH_HEADER_SIZE && input.hasRemaining()) { ByteBuffer bufferAlias = buffer.duplicate(); bufferAlias.flip(); bufferAlias.order(ByteOrder.LITTLE_ENDIAN); int dataLength = bufferAlias.getInt(); if (dataLength < FRAME_MESSAGE_TYPE_HEADER_SIZE || dataLength > MAX_DATA_LENGTH) { throw new IllegalArgumentException("Invalid frame length " + dataLength); } // Maybe resize the buffer int frameLength = dataLength + FRAME_LENGTH_HEADER_SIZE; if (buffer.capacity() < frameLength) { buffer = ByteBuffer.allocate(frameLength); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(dataLength); } buffer.limit(frameLength); } // TODO: Similarly extract and check message type. // Read the remaining data into the internal buffer. copy(buffer, input); if (!buffer.hasRemaining()) { buffer.flip(); isComplete = true; } return isComplete; }
Example 17
Source File: AMQDecoderTest.java From qpid-broker-j with Apache License 2.0 | 4 votes |
@Test public void testMultiplePartialFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException, IOException { ByteBuffer msgA = getHeartbeatBodyBuffer(); ByteBuffer msgB = getHeartbeatBodyBuffer(); ByteBuffer msgC = getHeartbeatBodyBuffer(); ByteBuffer sliceA = ByteBuffer.allocate(msgA.remaining() + msgB.remaining() / 2); sliceA.put(msgA); int limit = msgB.limit(); int pos = msgB.remaining() / 2; msgB.limit(pos); sliceA.put(msgB); sliceA.flip(); msgB.limit(limit); msgB.position(pos); ByteBuffer sliceB = ByteBuffer.allocate(msgB.remaining() + pos); sliceB.put(msgB); msgC.limit(pos); sliceB.put(msgC); sliceB.flip(); msgC.limit(limit); _decoder.decodeBuffer(sliceA); List<AMQDataBlock> frames = _methodProcessor.getProcessedMethods(); assertEquals((long) 1, (long) frames.size()); frames.clear(); _decoder.decodeBuffer(sliceB); assertEquals((long) 1, (long) frames.size()); frames.clear(); _decoder.decodeBuffer(msgC); assertEquals((long) 1, (long) frames.size()); for (AMQDataBlock frame : frames) { if (frame instanceof AMQFrame) { assertEquals((long) HeartbeatBody.FRAME.getBodyFrame().getFrameType(), (long) ((AMQFrame) frame).getBodyFrame().getFrameType()); } else { fail("decode was not a frame"); } } }
Example 18
Source File: CommitLog.java From DDMQ with Apache License 2.0 | 4 votes |
private void resetByteBuffer(final ByteBuffer byteBuffer, final int limit) { byteBuffer.flip(); byteBuffer.limit(limit); }
Example 19
Source File: WebSocket07FrameSinkChannel.java From lams with GNU General Public License v2.0 | 4 votes |
@Override protected SendFrameHeader createFrameHeader() { byte b0 = 0; //if writes are shutdown this is the final fragment if (isFinalFrameQueued()) { b0 |= 1 << 7; // set FIN } /* Known extensions (i.e. compression) should not modify RSV bit on continuation bit. */ byte opCode = opCode(); int rsv = opCode == WebSocket07Channel.OPCODE_CONT ? 0 : getRsv(); b0 |= (rsv & 7) << 4; b0 |= opCode & 0xf; final ByteBuffer header = ByteBuffer.allocate(14); byte maskKey = 0; if(masker != null) { maskKey |= 1 << 7; } long payloadSize = getBuffer().remaining(); if (payloadSize > 125 && opCode == WebSocket07Channel.OPCODE_PING) { throw WebSocketMessages.MESSAGES.invalidPayloadLengthForPing(payloadSize); } if (payloadSize <= 125) { header.put(b0); header.put((byte)((payloadSize | maskKey) & 0xFF)); } else if (payloadSize <= 0xFFFF) { header.put(b0); header.put((byte) ((126 | maskKey) & 0xFF)); header.put((byte) (payloadSize >>> 8 & 0xFF)); header.put((byte) (payloadSize & 0xFF)); } else { header.put(b0); header.put((byte) ((127 | maskKey) & 0xFF)); header.putLong(payloadSize); } if(masker != null) { int maskingKey = random.nextInt(); //generate a new key for this frame header.put((byte)((maskingKey >> 24) & 0xFF)); header.put((byte)((maskingKey >> 16) & 0xFF)); header.put((byte)((maskingKey >> 8) & 0xFF)); header.put((byte)((maskingKey & 0xFF))); masker.setMaskingKey(maskingKey); //do any required masking ByteBuffer buf = getBuffer(); masker.beforeWrite(buf, buf.position(), buf.remaining()); } header.flip(); return new SendFrameHeader(0, new ImmediatePooledByteBuffer(header)); }
Example 20
Source File: GelfUdpChunker.java From logback-gelf with GNU Lesser General Public License v2.1 | 3 votes |
private static ByteBuffer buildChunk(final byte[] messageId, final byte[] message, final byte chunkCount, final byte chunkNo, final int maxChunkPayloadSize) { final int chunkPayloadSize = Math.min(maxChunkPayloadSize, message.length - chunkNo * maxChunkPayloadSize); final ByteBuffer byteBuffer = ByteBuffer.allocate(HEADER_LENGTH + chunkPayloadSize); // Chunked GELF magic bytes 2 bytes byteBuffer.put(CHUNKED_GELF_HEADER); // Message ID 8 bytes byteBuffer.put(messageId); // Sequence number 1 byte byteBuffer.put(chunkNo); // Sequence count 1 byte byteBuffer.put(chunkCount); // message byteBuffer.put(message, chunkNo * maxChunkPayloadSize, chunkPayloadSize); byteBuffer.flip(); return byteBuffer; }