List of usage examples for java.nio ByteBuffer position
public final int position()
From source file:com.linkedin.databus.core.DbusEventV1.java
private static int serializeStringKeyEvent(byte[] key, ByteBuffer serializationBuffer, DbusEventInfo eventInfo) {/*from www . jav a 2 s .c o m*/ ByteBuffer valueBuffer = eventInfo.getValueByteBuffer(); int payloadLen = (valueBuffer == null) ? eventInfo.getValueLength() : valueBuffer.remaining(); int startPosition = serializationBuffer.position(); byte[] attributes = null; // Event without explicit opcode specified should always be considered UPSERT or existing code will break if (eventInfo.getOpCode() == DbusOpcode.DELETE) { if (serializationBuffer.order() == ByteOrder.BIG_ENDIAN) attributes = DeleteStringKeyAttributesBigEndian.clone(); else attributes = DeleteStringKeyAttributesLittleEndian.clone(); } else { if (serializationBuffer.order() == ByteOrder.BIG_ENDIAN) attributes = UpsertStringKeyAttributesBigEndian.clone(); else attributes = UpsertStringKeyAttributesLittleEndian.clone(); } if (eventInfo.isEnableTracing()) { setTraceFlag(attributes, serializationBuffer.order()); } if (eventInfo.isReplicated()) setExtReplicationFlag(attributes, serializationBuffer.order()); serializationBuffer.put(DbusEventFactory.DBUS_EVENT_V1).putInt(HeaderCrcDefault) .putInt(StringValueOffset(key.length) + payloadLen).put(attributes) .putLong(eventInfo.getSequenceId()).putShort(eventInfo.getpPartitionId()) .putShort(eventInfo.getlPartitionId()).putLong(eventInfo.getTimeStampInNanos()) .putShort(eventInfo.getSrcId()).put(eventInfo.getSchemaId(), 0, 16).putInt(HeaderCrcDefault) .putInt(key.length).put(key); if (valueBuffer != null) { // note. put will advance position. In the case of wrapped byte[] it is ok, in the case of // ByteBuffer this is actually a read only copy of the buffer passed in. serializationBuffer.put(valueBuffer); } int stopPosition = serializationBuffer.position(); long valueCrc = ByteBufferCRC32.getChecksum(serializationBuffer, startPosition + StringKeyOffset, key.length + payloadLen); Utils.putUnsignedInt(serializationBuffer, startPosition + ValueCrcOffset, valueCrc); if (eventInfo.isAutocommit()) { //TODO (DDSDBUS-61): Medium : can avoid new here DbusEventV1 e = new DbusEventV1(serializationBuffer, startPosition); e.applyCrc(); } serializationBuffer.position(stopPosition); return (stopPosition - startPosition); }
From source file:com.buaa.cfs.nfs3.OpenFileCtx.java
@VisibleForTesting public static void alterWriteRequest(WRITE3Request request, long cachedOffset) { long offset = request.getOffset(); int count = request.getCount(); long smallerCount = offset + count - cachedOffset; if (LOG.isDebugEnabled()) { LOG.debug(String.format(/* ww w . j a va2 s . c o m*/ "Got overwrite with appended data (%d-%d)," + " current offset %d," + " drop the overlapped section (%d-%d)" + " and append new data (%d-%d).", offset, (offset + count - 1), cachedOffset, offset, (cachedOffset - 1), cachedOffset, (offset + count - 1))); } ByteBuffer data = request.getData(); Preconditions.checkState(data.position() == 0, "The write request data has non-zero position"); data.position((int) (cachedOffset - offset)); Preconditions.checkState(data.limit() - data.position() == smallerCount, "The write request buffer has wrong limit/position regarding count"); request.setOffset(cachedOffset); request.setCount((int) smallerCount); }
From source file:net.phoenix.thrift.hello.ThreadedSelectorTest.java
@Test public void testByteBuffer() throws TException, IOException, InterruptedException { LOG.info("Client starting...."); String name = "World"; // TTransport transport = new TNonblockingSocket("localhost", 9804); TTransport transport = new TFramedTransport(new TSocket("localhost", 9804)); transport.open();/*w w w . j av a 2 s .c o m*/ // TTransport transport = new TTransport(socket); TProtocol protocol = new TBinaryProtocol(transport); HelloService.Client client = new HelloService.Client(protocol); try { Hello.HelloRequest.Builder request = Hello.HelloRequest.newBuilder(); request.setName(name); Hello.User.Builder user = Hello.User.newBuilder(); user.setName("hello"); user.setPassword("hello"); request.setUser(user.build()); ByteBuffer requestBuffer = ByteBuffer.wrap(request.build().toByteArray()); ByteBuffer buffer = client.hello(requestBuffer); Hello.HelloResponse response = Hello.HelloResponse .parseFrom(ArrayUtils.subarray(buffer.array(), buffer.position(), buffer.limit())); String message = response.getMessage(); assertEquals(message, "Hello " + name); // System.out.println(message); } finally { transport.close(); } }
From source file:byps.test.servlet.MyRemoteStreams.java
@Override public TreeMap<Integer, InputStream> getImages() throws RemoteException { if (log.isDebugEnabled()) log.debug("getImages("); Map<Integer, ByteBuffer> mapStreamBytes = this.mapStreamBytes; if (mapStreamBytes == null) return null; TreeMap<Integer, InputStream> map = new TreeMap<Integer, InputStream>(); for (Integer k : mapStreamBytes.keySet()) { ByteBuffer buf = mapStreamBytes.get(k); InputStream istrm = new ByteArrayInputStream(buf.array(), buf.position(), buf.remaining()); map.put(k, istrm);/*from www .j a v a 2 s . co m*/ } if (log.isDebugEnabled()) log.debug(")getImages=" + map); return map; }
From source file:net.sf.jinsim.UDPChannel.java
@Override protected synchronized int receive(ByteBuffer buffer) throws IOException { if (cacheBuffer.position() > 0 && cacheBuffer.hasRemaining()) { buffer.put(cacheBuffer);/*ww w . j a v a2 s.co m*/ return buffer.position(); } else { byte[] data = new byte[buffer.limit()]; cacheBuffer.clear(); SocketAddress address = datagramChannel.receive(cacheBuffer); int size = cacheBuffer.position(); if (address != null) { cacheBuffer.flip(); int remaining = cacheBuffer.remaining(); if (remaining > data.length) { remaining = data.length; } cacheBuffer.get(data, 0, remaining); buffer.put(data, 0, remaining); return data.length; } return size; } /* SocketAddress address = datagramChannel.receive(buffer); if (address != null) { System.out.println("has data: " + buffer.position()); return buffer.position(); } return 0; */ /* DatagramSocket socket = datagramChannel.socket(); receive(DatagramPacket p) */ }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java
private ByteBuffer fuse(List<byte[]> buffers, final int length) { //fuses the buffers into a single array of the target length final ByteBuffer bb = ByteBuffer.allocate(length); for (byte[] buffer : buffers) { if (buffer.length > length - bb.position()) { bb.put(buffer, 0, length - bb.position()); } else {/* w w w. java2 s . c om*/ bb.put(buffer); } } //important bb.flip(); return bb; }
From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java
@Test public void testWriteCompleteMessage() throws IOException { SocketChannel socket = mock(SocketChannel.class); ByteArrayOutputStream messageStream = new ByteArrayOutputStream(); String message = "hi\n"; when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() { @Override//from w w w . ja v a2 s .c o m public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0]; while (buffer.hasRemaining()) messageStream.write(buffer.get()); return buffer.position(); } }); INbContext nbContext = mock(INbContext.class); SelectionKey selectionKey = mock(SelectionKey.class); when(selectionKey.channel()).thenReturn(socket); when(selectionKey.isValid()).thenReturn(true); when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100)) .build(); List<String> callbackInvoked = new ArrayList<>(); Runnable callback = () -> callbackInvoked.add(""); Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage()); writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback, exceptionHandler); verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any()); writeTask.write(selectionKey, callback, exceptionHandler); verify(selectionKey, times(1)).interestOps(0); Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8)); Assert.assertEquals(1, callbackInvoked.size()); }
From source file:com.healthmarketscience.jackcess.impl.CompoundOleUtil.java
/** * Creates a nes CompoundContent for the given blob information. *//* www .jav a 2 s . c o m*/ public ContentImpl createCompoundPackageContent(OleBlobImpl blob, String prettyName, String className, String typeName, ByteBuffer blobBb, int dataBlockLen) { return new CompoundContentImpl(blob, prettyName, className, typeName, blobBb.position(), dataBlockLen); }
From source file:edu.tsinghua.lumaqq.qq.packets.PacketHelper.java
/** * ByteBuffer??InPacket?buf???limit/*from w w w .j ava 2s. c o m*/ * ????bufpositionlength? * * @param buf * @param length * @param debug * @return * @throws PacketParseException */ private OutPacket parseOut(ByteBuffer buf, int length, QQUser user) throws PacketParseException { int pos = buf.position(); try { OutPacket ret = parser.parseOutcoming(buf, length, user); return ret; } catch (PacketParseException e) { throw e; } finally { buf.position(pos + length); parser = null; } }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.unsafe.DeflateJsonQueryHandler.java
private ByteBuffer fuse(final int length) { //fuses the buffers into a single array of the target length final ByteBuffer bb = ByteBuffer.allocate(length); for (byte[] buffer : fBuffers) { if (buffer.length > length - bb.position()) { bb.put(buffer, 0, length - bb.position()); } else {//www . j a va 2 s.com bb.put(buffer); } } //important bb.flip(); fBuffers.clear(); return bb; }