Example usage for io.netty.buffer Unpooled wrappedBuffer

List of usage examples for io.netty.buffer Unpooled wrappedBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled wrappedBuffer.

Prototype

public static ByteBuf wrappedBuffer(ByteBuffer... buffers) 

Source Link

Document

Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them.

Usage

From source file:alluxio.grpc.WriteRequestMarshaller.java

License:Apache License

@Override
protected ByteBuf[] serialize(WriteRequest message) throws IOException {
    if (message.hasCommand()) {
        byte[] command = new byte[message.getSerializedSize()];
        CodedOutputStream stream = CodedOutputStream.newInstance(command);
        message.writeTo(stream);/*from   ww w  .  ja  v  a  2  s.c o m*/
        return new ByteBuf[] { Unpooled.wrappedBuffer(command) };
    }
    DataBuffer chunkBuffer = pollBuffer(message);
    if (chunkBuffer == null) {
        if (!message.hasChunk() || !message.getChunk().hasData()) {
            // nothing to serialize
            return new ByteBuf[0];
        }
        // attempts to fallback to read chunk from message
        chunkBuffer = new NettyDataBuffer(
                Unpooled.wrappedBuffer(message.getChunk().getData().asReadOnlyByteBuffer()));
    }
    int headerSize = message.getSerializedSize() - chunkBuffer.readableBytes();
    byte[] header = new byte[headerSize];
    CodedOutputStream stream = CodedOutputStream.newInstance(header);
    stream.writeTag(WriteRequest.CHUNK_FIELD_NUMBER, WireFormat.WIRETYPE_LENGTH_DELIMITED);
    stream.writeUInt32NoTag(message.getChunk().getSerializedSize());
    stream.writeTag(Chunk.DATA_FIELD_NUMBER, WireFormat.WIRETYPE_LENGTH_DELIMITED);
    stream.writeUInt32NoTag(chunkBuffer.readableBytes());
    return new ByteBuf[] { Unpooled.wrappedBuffer(header), (ByteBuf) chunkBuffer.getNettyOutput() };
}

From source file:alluxio.network.protocol.databuffer.DataByteBuffer.java

License:Apache License

@Override
public Object getNettyOutput() {
    return Unpooled.wrappedBuffer(mBuffer);
}

From source file:alluxio.network.protocol.databuffer.NioDataBuffer.java

License:Apache License

@Override
public void readBytes(OutputStream outputStream, int length) throws IOException {
    Unpooled.wrappedBuffer(mBuffer).readBytes(outputStream, length).release();
}

From source file:alluxio.worker.block.io.LocalFileBlockWriterTest.java

License:Apache License

@Test
public void appendByteBuf() throws Exception {
    ByteBuf buffer = Unpooled.wrappedBuffer(BufferUtils.getIncreasingByteBuffer(TEST_BLOCK_SIZE));
    buffer.markReaderIndex();//  www  .j a  v a 2  s  .c o m
    Assert.assertEquals(TEST_BLOCK_SIZE, mWriter.append(buffer));
    buffer.resetReaderIndex();
    Assert.assertEquals(TEST_BLOCK_SIZE, mWriter.append(buffer));
    mWriter.close();
    Assert.assertEquals(2 * TEST_BLOCK_SIZE, new File(mTestFilePath).length());
    ByteBuffer result = ByteBuffer.wrap(Files.readAllBytes(Paths.get(mTestFilePath)));
    result.position(0).limit(TEST_BLOCK_SIZE);
    BufferUtils.equalIncreasingByteBuffer(0, TEST_BLOCK_SIZE, result.slice());
    result.position(TEST_BLOCK_SIZE).limit(TEST_BLOCK_SIZE * 2);
    BufferUtils.equalIncreasingByteBuffer(0, TEST_BLOCK_SIZE, result.slice());
}

From source file:appeng.fmp.CableBusPart.java

License:Open Source License

@Override
public void readDesc(final MCDataInput packet) {
    final int len = packet.readInt();
    final byte[] data = packet.readByteArray(len);

    try {// ww  w .ja v  a  2s .c  o m
        if (len > 0) {
            final ByteBuf byteBuffer = Unpooled.wrappedBuffer(data);
            this.getCableBus().readFromStream(byteBuffer);
        }
    } catch (final IOException e) {
        AELog.error(e);
    }
}

From source file:at.yawk.accordion.compression.SnappyCompressor.java

License:Mozilla Public License

@Override
public ByteBuf encode(ByteBuf raw) {
    try {/*from   ww w.j  a va  2  s.  co  m*/
        return Unpooled.wrappedBuffer(Snappy.compress(toArray(raw)));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:at.yawk.accordion.compression.SnappyCompressor.java

License:Mozilla Public License

@Override
public ByteBuf decode(ByteBuf compressed) {
    try {/*from  ww  w  . jav  a 2s . c  o  m*/
        return Unpooled.wrappedBuffer(Snappy.uncompress(toArray(compressed)));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:at.yawk.accordion.minecraft.AccordionBukkit.java

License:Mozilla Public License

public static AccordionApi createApi(Plugin plugin) {
    try {//from www.j a  va 2  s.c om
        AccordionApi api = new AccordionApi().mcPort(Bukkit.getPort())
                // use plugin logger
                .logger(plugin.getLogger()).listenAddress(InetAddress.getByName(Bukkit.getIp()))
                // do not listen on bukkit
                .listen(false).tier(AccordionApi.DEFAULT_TIER_BUKKIT);
        // auto start on first tick (bukkit load complete)
        plugin.getServer().getScheduler().runTask(plugin, api::tryAutoStart);
        // peer discovery
        plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin,
                AccordionApi.PEER_DISCOVERY_PLUGIN_CHANNEL, (channel, player, data) -> {
                    if (!api.isAutomaticDiscovery()) {
                        return;
                    }

                    // new nodes received
                    ByteBuf wrapped = Unpooled.wrappedBuffer(data);
                    api.getLocalNode().loadEncodedNodes(wrapped);
                });
        return api;
    } catch (UnknownHostException e) {
        throw new IllegalStateException("Invalid bukkit IP", e);
    }
}

From source file:at.yawk.dbus.protocol.DbusConnector.java

/**
 * Connect to the dbus server at the given {@link SocketAddress}.
 *///from w w w  .j a v a  2 s  .  c  o  m
public DbusChannel connect(SocketAddress address) throws Exception {
    Bootstrap localBootstrap = bootstrap.clone();
    if (address instanceof DomainSocketAddress) {
        localBootstrap.group(new EpollEventLoopGroup());
        localBootstrap.channel(EpollDomainSocketChannel.class);
    } else {
        localBootstrap.group(new NioEventLoopGroup());
        localBootstrap.channel(NioSocketChannel.class);
    }

    Channel channel = localBootstrap.connect(address).sync().channel();

    AuthClient authClient = new AuthClient();
    if (LoggingInboundAdapter.isEnabled()) {
        channel.pipeline().addLast(new LoggingInboundAdapter());
    }

    channel.pipeline().addLast("auth", authClient);
    channel.config().setAutoRead(true);
    log.trace("Pipeline is now {}", channel.pipeline());

    // I really don't get why dbus does this
    channel.write(Unpooled.wrappedBuffer(new byte[] { 0 }));

    if (authMechanism == null) {
        authMechanism = new ExternalAuthMechanism();
    }
    CompletionStage<?> completionPromise = authClient.startAuth(channel, authMechanism);

    SwappableMessageConsumer swappableConsumer = new SwappableMessageConsumer(initialConsumer);
    completionPromise.toCompletableFuture().thenRun(() -> {
        channel.pipeline().replace("auth", "main", new DbusMainProtocol(swappableConsumer));
        log.trace("Pipeline is now {}", channel.pipeline());
    }).get();

    DbusChannelImpl dbusChannel = new DbusChannelImpl(channel, swappableConsumer);

    dbusChannel.write(MessageFactory.methodCall("/", "org.freedesktop.DBus", "org.freedesktop.DBus", "Hello"));

    return dbusChannel;
}

From source file:at.yawk.votifier.VoteDecrypter.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int readable = in.readableBytes();
    if (readable < MESSAGE_SIZE) {
        // the message must be exactly 256 bytes long
        return;//  www  .  j av a2 s .co  m
    }

    byte[] encrypted = new byte[MESSAGE_SIZE];
    in.readBytes(encrypted);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encrypted);
    out.add(Unpooled.wrappedBuffer(decrypted));
}