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:deathcap.wsmc.web.WebSocketHandler.java

License:Apache License

@Override
protected void messageReceived(final ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception { // channelRead
    if (firstMessage) {
        firstMessage = false;//from   w  w w  . j  ava2  s  .c  o m
        this.webThread.getChannelGroup().add(ctx.channel());
    }

    MinecraftThread minecraft = minecraftThreads.get(ctx.channel().remoteAddress().toString());
    if (minecraft == null) {
        this.setupInitialConnection(ctx, msg);
        return;
    }

    final ByteBuf buf = msg.content();

    if (verbose)
        logger.info("ws received " + buf.readableBytes() + " bytes: " + HexDumper.hexByteBuf(buf));

    byte bytes[] = new byte[buf.readableBytes()];
    buf.readBytes(bytes);

    // read packet id type for filtering
    int id = DefinedPacket.readVarInt(Unpooled.copiedBuffer(bytes)); // TODO: avoid copying (but need to reply with id in buffer)

    if (!this.filter.isAllowed(id)) {
        logger.info("FILTERED PACKET: " + id);
        return;
    }

    final ByteBuf reply = Unpooled.wrappedBuffer(bytes).retain();
    if (verbose)
        logger.info(
                "id " + id + " stripped " + reply.readableBytes() + " reply=" + HexDumper.hexByteBuf(reply));

    final MinecraftThread mc = minecraft;
    // forward MC to WS
    try {
        final ChannelFuture f = mc.clientHandler.minecraftClientHandler.ctx.writeAndFlush(reply);

        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                try {
                    assert f == channelFuture;
                    if (verbose)
                        logger.info("forwarded WS -> MC, " + reply.readableBytes() + " bytes");
                    reply.release();
                } catch (RejectedExecutionException ex) {
                    // TODO
                }
            }
        });
    } catch (RejectedExecutionException ex) {
        //TODO mc.clientHandler.minecraftClientHandler.close(ctx, )
    }

}

From source file:dimos.playing.WebSocketClient.java

License:Apache License

public static void configure(URI uri, int port /*, String host, String scheme*/) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   ww  w . j ava2s.  co m
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();

        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                        WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }

}

From source file:discord4j.gateway.payload.JacksonPayloadWriter.java

License:Open Source License

@Override
public Mono<ByteBuf> write(GatewayPayload<?> payload) {
    return Mono.create(sink -> {
        try {//  ww  w .j  a  v a 2 s .c om
            sink.success(Unpooled.wrappedBuffer(mapper.writeValueAsBytes(payload)));
        } catch (JsonProcessingException e) {
            sink.error(Exceptions.propagate(e));
        }
    });
}

From source file:discord4j.gateway.ZlibDecompressor.java

License:Open Source License

public Flux<ByteBuf> completeMessages(Flux<ByteBuf> payloads) {
    return payloads.windowUntil(windowPredicate).flatMap(Flux::collectList).map(list -> {
        ByteBuf buf = Unpooled.wrappedBuffer(list.toArray(new ByteBuf[0]));
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);//from   www . j a  v  a 2s . c o m

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (InflaterOutputStream inflater = new InflaterOutputStream(out, context)) {
            inflater.write(bytes);
            return Unpooled.wrappedBuffer(out.toByteArray());
        } catch (IOException e) {
            throw Exceptions.propagate(e);
        }
    });
}

From source file:discord4j.voice.VoiceGatewayClient.java

License:Open Source License

private Mono<Void> handle(WebsocketInbound in, WebsocketOutbound out) {
    Mono<Void> inboundThen = in.aggregateFrames().receiveFrames().map(WebSocketFrame::content)
            .flatMap(buf -> Mono.fromCallable(() -> mapper.readValue((InputStream) new ByteBufInputStream(buf),
                    VoiceGatewayPayload.class)))
            .doOnNext(gatewayFSM::onEvent).then();

    Mono<Void> outboundThen = out.options(NettyPipeline.SendOptions::flushOnEach)
            .sendObject(sender.flatMap(payload -> Mono.fromCallable(
                    () -> new TextWebSocketFrame(Unpooled.wrappedBuffer(mapper.writeValueAsBytes(payload))))))
            .then();//from  w w  w  .  ja  v  a  2 s .  c o m

    return Mono.zip(inboundThen, outboundThen).then();
}

From source file:discord4j.voice.VoiceSendTask.java

License:Open Source License

private void run() {
    if (provider.provide()) {
        if (!speaking) {
            changeSpeaking(true);/*from w w  w  .  j  a  v  a 2  s .  c om*/
        }

        byte[] b = new byte[provider.getBuffer().limit()];
        provider.getBuffer().get(b);
        provider.getBuffer().clear();
        ByteBuf packet = Unpooled.wrappedBuffer(transformer.nextSend(b));

        client.voiceSocket.send(packet);
    } else if (speaking) {
        changeSpeaking(false);
    }
}

From source file:divconq.api.internal.UploadStream.java

License:Open Source License

@Override
public ByteBuf getChunk(int length) throws IOException {
    if (this.in == null || length == 0)
        return Unpooled.EMPTY_BUFFER;

    // indicate that we are keeping busy and not hung
    this.ops.touch();

    //System.out.println("Get last activity after touch: " + this.ops.getLastActivity());

    int read = 0;

    ByteBuffer byteBuffer = ByteBuffer.allocate(length);

    while (read < length) {
        int readnow = this.in.read(byteBuffer);

        if (readnow == -1) {
            this.in.close();
            this.in = null;
            break;
        } else {/*from  ww w.j a  v a2  s. c om*/
            read += readnow;
        }
    }

    if (read == 0)
        return Unpooled.EMPTY_BUFFER;

    byteBuffer.flip();
    ByteBuf buffer = Unpooled.wrappedBuffer(byteBuffer);
    buffer.readerIndex(0);
    buffer.writerIndex(read);
    return buffer;
}

From source file:dorkbox.network.connection.KryoExtra.java

License:Apache License

/**
 * This is NOT ENCRYPTED (and is only done on the loopback connection!)
 *//*from  w  ww.  j ava  2  s . c om*/
public Object readCompressed(final Connection_ connection, final ByteBuf buffer, int length)
        throws IOException {
    // required by RMI and some serializers to determine which connection wrote (or has info about) this object
    this.rmiSupport = connection.rmiSupport();

    ////////////////
    // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it!
    ////////////////

    ByteBuf inputBuf = buffer;

    // get the decompressed length (at the beginning of the array)
    final int uncompressedLength = OptimizeUtilsByteBuf.readInt(buffer, true);
    final int lengthLength = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-5 bytes for the decompressed size

    // have to adjust for uncompressed length
    length = length - lengthLength;

    ///////// decompress data -- as it's ALWAYS compressed

    // NOTE: compression and encryption MUST work with byte[] because they use JNI!
    // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use
    // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it...
    // see:   https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf

    byte[] inputArray;
    int inputOffset;

    // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because
    // the buffer might be a slice of other buffer or a pooled buffer:
    //noinspection Duplicates
    if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0)
            && inputBuf.array().length == inputBuf.capacity()) {

        // we can use it...
        inputArray = inputBuf.array();
        inputArrayLength = -1; // this is so we don't REUSE this array accidentally!
        inputOffset = inputBuf.arrayOffset() + lengthLength;
    } else {
        // we can NOT use it.
        if (length > inputArrayLength) {
            inputArrayLength = length;
            inputArray = new byte[length];
            this.inputArray = inputArray;
        } else {
            inputArray = this.inputArray;
        }

        inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length);
        inputOffset = 0;
    }

    // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index.
    buffer.readerIndex(buffer.readerIndex() + length);

    ///////// decompress data -- as it's ALWAYS compressed

    byte[] decompressOutputArray = this.decompressOutput;
    if (uncompressedLength > decompressOutputLength) {
        decompressOutputLength = uncompressedLength;
        decompressOutputArray = new byte[uncompressedLength];
        this.decompressOutput = decompressOutputArray;

        decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo
    }
    inputBuf = decompressBuf;

    // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor)
    decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength);

    inputBuf.setIndex(0, uncompressedLength);

    // read the object from the buffer.
    reader.setBuffer(inputBuf);

    return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer
}

From source file:dorkbox.network.connection.KryoExtra.java

License:Apache License

public Object readCrypto(final Connection_ connection, final ByteBuf buffer, int length) throws IOException {
    // required by RMI and some serializers to determine which connection wrote (or has info about) this object
    this.rmiSupport = connection.rmiSupport();

    ////////////////
    // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it!
    ////////////////

    ByteBuf inputBuf = buffer;//  www  . j ava2 s.co m

    final long gcmIVCounter = OptimizeUtilsByteBuf.readLong(buffer, true);
    int lengthLength = OptimizeUtilsByteArray.longLength(gcmIVCounter, true);

    // have to adjust for the gcmIVCounter
    length = length - lengthLength;

    /////////// decrypting data

    // NOTE: compression and encryption MUST work with byte[] because they use JNI!
    // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use
    // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it...
    // see:   https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf

    byte[] inputArray;
    int inputOffset;

    // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because
    // the buffer might be a slice of other buffer or a pooled buffer:
    //noinspection Duplicates
    if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0)
            && inputBuf.array().length == inputBuf.capacity()) {

        // we can use it...
        inputArray = inputBuf.array();
        inputArrayLength = -1; // this is so we don't REUSE this array accidentally!
        inputOffset = inputBuf.arrayOffset() + lengthLength;
    } else {
        // we can NOT use it.
        if (length > inputArrayLength) {
            inputArrayLength = length;
            inputArray = new byte[length];
            this.inputArray = inputArray;
        } else {
            inputArray = this.inputArray;
        }

        inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length);
        inputOffset = 0;
    }

    // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index.
    buffer.readerIndex(buffer.readerIndex() + length);

    // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time
    final ParametersWithIV cryptoParameters = connection.getCryptoParameters();
    BigEndian.Long_.toBytes(gcmIVCounter, cryptoParameters.getIV(), 4); // put our counter into the IV

    final GCMBlockCipher aes = this.aesEngine;
    aes.reset();
    aes.init(false, cryptoParameters);

    int cryptoSize = length - 16; // from:  aes.getOutputSize(length);

    // lazy initialize the decrypt output buffer
    byte[] decryptOutputArray;
    if (cryptoSize > decryptOutputLength) {
        decryptOutputLength = cryptoSize;
        decryptOutputArray = new byte[cryptoSize];
        this.decryptOutput = decryptOutputArray;

        decryptBuf = Unpooled.wrappedBuffer(decryptOutputArray);
    } else {
        decryptOutputArray = this.decryptOutput;
    }

    int decryptedLength = aes.processBytes(inputArray, inputOffset, length, decryptOutputArray, 0);

    try {
        // authentication tag for GCM
        decryptedLength += aes.doFinal(decryptOutputArray, decryptedLength);
    } catch (Exception e) {
        throw new IOException("Unable to AES decrypt the data", e);
    }

    ///////// decompress data -- as it's ALWAYS compressed

    // get the decompressed length (at the beginning of the array)
    inputArray = decryptOutputArray;
    final int uncompressedLength = OptimizeUtilsByteArray.readInt(inputArray, true);
    inputOffset = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-4 bytes for the decompressed size

    byte[] decompressOutputArray = this.decompressOutput;
    if (uncompressedLength > decompressOutputLength) {
        decompressOutputLength = uncompressedLength;
        decompressOutputArray = new byte[uncompressedLength];
        this.decompressOutput = decompressOutputArray;

        decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo
    }
    inputBuf = decompressBuf;

    // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor
    decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength);

    inputBuf.setIndex(0, uncompressedLength);

    // read the object from the buffer.
    reader.setBuffer(inputBuf);

    return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer
}

From source file:dorkbox.network.serialization.Serialization.java

License:Apache License

/**
 * NOTE: When this fails, the CLIENT will just time out. We DO NOT want to send an error message to the client
 *   (it should check for updates or something else). We do not want to give "rogue" clients knowledge of the
 *   server, thus preventing them from trying to probe the server data structures.
 *
 * @return true if kryo registration is required for all classes sent over the wire
 */// ww  w .  j  a v a 2s  . c  om
@SuppressWarnings("Duplicates")
@Override
public boolean verifyKryoRegistration(byte[] otherRegistrationData) {
    // verify the registration IDs if necessary with our own. The CLIENT does not verify anything, only the server!
    byte[] kryoRegistrationDetails = savedRegistrationDetails;
    boolean equals = java.util.Arrays.equals(kryoRegistrationDetails, otherRegistrationData);
    if (equals) {
        return true;
    }

    // now we need to figure out WHAT was screwed up so we know what to fix
    KryoExtra kryo = takeKryo();

    ByteBuf byteBuf = Unpooled.wrappedBuffer(otherRegistrationData);

    try {
        kryo.setRegistrationRequired(false);
        @SuppressWarnings("unchecked")
        Object[][] classRegistrations = (Object[][]) kryo.readCompressed(byteBuf, otherRegistrationData.length);

        int lengthOrg = mergedRegistrations.length;
        int lengthNew = classRegistrations.length;
        int index = 0;

        // list all of the registrations that are mis-matched between the server/client
        for (; index < lengthOrg; index++) {
            final ClassRegistration classOrg = mergedRegistrations[index];

            if (index >= lengthNew) {
                logger.error("Missing client registration for {} -> {}", classOrg.id, classOrg.clazz.getName());
            } else {
                Object[] classNew = classRegistrations[index];
                int idNew = (Integer) classNew[0];
                String nameNew = (String) classNew[1];
                String serializerNew = (String) classNew[2];

                int idOrg = classOrg.id;
                String nameOrg = classOrg.clazz.getName();
                String serializerOrg = classOrg.serializer.getClass().getName();

                if (idNew != idOrg || !nameOrg.equals(nameNew)
                        || !serializerNew.equalsIgnoreCase(serializerOrg)) {
                    logger.error("Registration {} Client -> {} ({})", idNew, nameNew, serializerNew);
                    logger.error("Registration {} Server -> {} ({})", idOrg, nameOrg, serializerOrg);
                }
            }
        }

        // list all of the registrations that are missing on the server
        if (index < lengthNew) {
            for (; index < lengthNew; index++) {
                Object[] holderClass = classRegistrations[index];
                int id = (Integer) holderClass[0];
                String name = (String) holderClass[1];
                String serializer = (String) holderClass[2];

                logger.error("Missing server registration : {} -> {} ({})", id, name, serializer);
            }
        }
    } catch (Exception e) {
        logger.error("Error [{}] during registration validation", e.getMessage());

    } finally {
        if (registrationRequired) {
            kryo.setRegistrationRequired(true);
        }

        returnKryo(kryo);
        byteBuf.release();
    }

    return false;
}