List of usage examples for io.netty.buffer ByteBuf slice
public abstract ByteBuf slice();
From source file:io.grpc.alts.internal.ByteBufTestUtils.java
License:Apache License
/** Fragment byte buffer into multiple pieces. */ public static List<ByteBuf> fragmentByteBuf(ByteBuf in, int num, RegisterRef ref) { ByteBuf buf = in.slice(); Preconditions.checkArgument(num > 0); List<ByteBuf> fragmentedBufs = new ArrayList<>(num); int fragmentSize = buf.readableBytes() / num; while (buf.isReadable()) { int readBytes = num == 0 ? buf.readableBytes() : fragmentSize; ByteBuf tmpBuf = getDirectBuffer(readBytes, ref); tmpBuf.writeBytes(buf, readBytes); fragmentedBufs.add(tmpBuf);//from w ww . j av a 2s .c o m num--; } return fragmentedBufs; }
From source file:io.grpc.alts.internal.TsiTest.java
License:Apache License
/** Test corrupted counter. */ public static void corruptedCounterTest(Handshakers handshakers, RegisterRef ref) throws GeneralSecurityException { performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); String message = "hello world"; ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); final List<ByteBuf> protectOut = new ArrayList<>(); List<Object> unprotectOut = new ArrayList<>(); sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() { @Override/* ww w. ja v a 2s . co m*/ public void accept(ByteBuf buf) { protectOut.add(buf); } }, alloc); assertThat(protectOut.size()).isEqualTo(1); ByteBuf protect = ref.register(protectOut.get(0)); // Unprotect once to increase receiver counter. receiver.unprotect(protect.slice(), unprotectOut, alloc); assertThat(unprotectOut.size()).isEqualTo(1); ref.register((ByteBuf) unprotectOut.get(0)); try { receiver.unprotect(protect, unprotectOut, alloc); fail("Exception expected"); } catch (AEADBadTagException ex) { assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); } sender.destroy(); receiver.destroy(); }
From source file:io.grpc.alts.internal.TsiTest.java
License:Apache License
/** Test reflected ciphertext. */ public static void reflectedCiphertextTest(Handshakers handshakers, RegisterRef ref) throws GeneralSecurityException { performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); String message = "hello world"; ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); final List<ByteBuf> protectOut = new ArrayList<>(); List<Object> unprotectOut = new ArrayList<>(); sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() { @Override//from w ww. ja v a2 s . com public void accept(ByteBuf buf) { protectOut.add(buf); } }, alloc); assertThat(protectOut.size()).isEqualTo(1); ByteBuf protect = ref.register(protectOut.get(0)); try { sender.unprotect(protect.slice(), unprotectOut, alloc); fail("Exception expected"); } catch (AEADBadTagException ex) { assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); } sender.destroy(); receiver.destroy(); }
From source file:k4unl.minecraft.Hydraulicraft.network.PacketPipeline.java
License:LGPL
@Override protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception { ByteBuf payload = msg.payload(); byte discriminator = payload.readByte(); Class<? extends AbstractPacket> clazz = packets.get(discriminator); if (clazz == null) { throw new NullPointerException("No packet registered for discriminator: " + discriminator); }//ww w. j a v a2 s.com AbstractPacket pkt = clazz.newInstance(); pkt.decodeInto(ctx, payload.slice()); EntityPlayer player; switch (FMLCommonHandler.instance().getEffectiveSide()) { case CLIENT: player = getClientPlayer(); pkt.handleClientSide(player); break; case SERVER: INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get(); player = ((NetHandlerPlayServer) netHandler).playerEntity; pkt.handleServerSide(player); break; default: } out.add(pkt); }
From source file:net.dries007.races.network.PacketPipeline.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception { ByteBuf payload = msg.payload(); byte discriminator = payload.readByte(); Class<? extends AbstractPacket> clazz = this.packets.get(discriminator); if (clazz == null) { throw new NullPointerException("No packet registered for discriminator: " + discriminator); }/* ww w .ja va2 s . com*/ AbstractPacket pkt = clazz.newInstance(); pkt.decodeInto(ctx, payload.slice()); EntityPlayer player; switch (FMLCommonHandler.instance().getEffectiveSide()) { case CLIENT: player = this.getClientPlayer(); pkt.handleClientSide(player); break; case SERVER: INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get(); player = ((NetHandlerPlayServer) netHandler).playerEntity; pkt.handleServerSide(player); break; default: } out.add(pkt); }
From source file:nova.core.wrapper.mc.forge.v17.network.discriminator.NovaPacket.java
License:Open Source License
@Override public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) { data = buffer.slice(); }
From source file:nova.core.wrapper.mc.forge.v17.network.discriminator.PacketPlayerItem.java
License:Open Source License
@Override public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) { slotId = buffer.readInt(); data = buffer.slice(); }
From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java
License:Apache License
/** * In a loop create/write/delete the ledger with same ledgerId through * the functionality of Advanced Ledger which accepts ledgerId as input. * * @throws Exception// w w w . j ava 2 s . c om */ @Test public void testLedgerCreateAdvWithLedgerIdInLoop() throws Exception { int ledgerCount = 40; long maxId = 9999999999L; if (baseConf.getLedgerManagerFactoryClass().equals(LongHierarchicalLedgerManagerFactory.class)) { // since LongHierarchicalLedgerManager supports ledgerIds of decimal length upto 19 digits but other // LedgerManagers only upto 10 decimals maxId = Long.MAX_VALUE; } rng.longs(ledgerCount, 0, maxId) // generate a stream of ledger ids .mapToObj(ledgerId -> { // create a ledger for each ledger id LOG.info("Creating adv ledger with id {}", ledgerId); return bkc.newCreateLedgerOp().withEnsembleSize(1).withWriteQuorumSize(1).withAckQuorumSize(1) .withDigestType(org.apache.bookkeeper.client.api.DigestType.CRC32) .withPassword(ledgerPassword).makeAdv().withLedgerId(ledgerId).execute() .thenApply(writer -> { // Add entries to ledger when created LOG.info("Writing stream of {} entries to {}", numEntriesToWrite, ledgerId); List<ByteBuf> entries = rng.ints(numEntriesToWrite, 0, maxInt).mapToObj(i -> { ByteBuf entry = Unpooled.buffer(4); entry.retain(); entry.writeInt(i); return entry; }).collect(Collectors.toList()); CompletableFuture<?> lastRequest = null; int i = 0; for (ByteBuf entry : entries) { long entryId = i++; LOG.info("Writing {}:{} as {}", ledgerId, entryId, entry.slice().readInt()); lastRequest = writer.writeAsync(entryId, entry); } lastRequest.join(); return Pair.of(writer, entries); }); }).parallel().map(CompletableFuture::join) // wait for all creations and adds in parallel .forEach(e -> { // check that each set of adds succeeded try { WriteAdvHandle handle = e.getLeft(); List<ByteBuf> entries = e.getRight(); // Read and verify LOG.info("Read entries for ledger: {}", handle.getId()); readEntries(handle, entries); entries.forEach(ByteBuf::release); handle.close(); bkc.deleteLedger(handle.getId()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); Assert.fail("Test interrupted"); } catch (Exception ex) { LOG.info("Readback failed with exception", ex); Assert.fail("Readback failed " + ex.getMessage()); } }); }
From source file:org.apache.bookkeeper.statelib.impl.mvcc.MVCCRecordCoder.java
License:Apache License
@Override public MVCCRecord decode(ByteBuf data) { ByteBuf copy = data.slice(); int metaLen = copy.readInt(); ByteBuffer metaBuf = copy.slice(copy.readerIndex(), metaLen).nioBuffer(); KeyMeta meta;//from www .j a v a2s . c om try { meta = KeyMeta.parseFrom(metaBuf); } catch (InvalidProtocolBufferException e) { throw new StateStoreRuntimeException("Failed to deserialize key metadata", e); } copy.skipBytes(metaLen); int valLen = copy.readInt(); ByteBuf valBuf = copy.retainedSlice(copy.readerIndex(), valLen); MVCCRecord record = MVCCRecord.newRecord(); record.setCreateRev(meta.getCreateRevision()); record.setModRev(meta.getModRevision()); record.setVersion(meta.getVersion()); record.setValue(valBuf, meta.getValueType()); return record; }
From source file:org.apache.distributedlog.io.TestCompressionCodec.java
License:Apache License
private void testCompressionCodec2(CompressionCodec codec) throws Exception { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer(32, 4 * 1024 * 1024); for (int i = 0; i < 100; i++) { ByteBuffer record = ByteBuffer.wrap(("record-" + i).getBytes(UTF_8)); buffer.writeInt(record.remaining()); buffer.writeBytes(record);//w w w . j ava 2s . c o m } byte[] uncompressedData = new byte[buffer.readableBytes()]; buffer.slice().readBytes(uncompressedData); ByteBuf compressedBuf = codec.compress(buffer, 0); byte[] compressedData = new byte[compressedBuf.readableBytes()]; compressedBuf.slice().readBytes(compressedData); ByteBuf decompressedBuf = codec.decompress(compressedBuf, uncompressedData.length); byte[] decompressedData = new byte[decompressedBuf.readableBytes()]; decompressedBuf.slice().readBytes(decompressedData); buffer.release(); compressedBuf.release(); decompressedBuf.release(); }