Example usage for io.netty.buffer ByteBuf nioBuffer

List of usage examples for io.netty.buffer ByteBuf nioBuffer

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf nioBuffer.

Prototype

public abstract ByteBuffer nioBuffer();

Source Link

Document

Exposes this buffer's readable bytes as an NIO ByteBuffer .

Usage

From source file:org.hornetq.amqp.test.minimalserver.MinimalSessionSPI.java

License:Apache License

@Override
public void serverSend(Receiver receiver, Delivery delivery, String address, int messageFormat,
        ByteBuf buffer) {
    ProtonServerMessage serverMessage = new ProtonServerMessage();
    serverMessage.decode(buffer.nioBuffer());

    BlockingDeque<Object> queue = DumbServer.getQueue(address);
    queue.add(serverMessage);/*from   w  ww  .  j  a  va  2s  .c o m*/
}

From source file:org.jmqtt.core.codec.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    LOG.debug("decode invoked with buffer {}", in);
    in.resetReaderIndex();/*  w  w  w . ja va  2  s  .co m*/
    int startPos = in.readerIndex();

    //Common decoding part
    PublishPacket message = new PublishPacket();
    if (!decodeCommonHeader(message, in)) {
        LOG.debug("decode ask for more data after {}", in);
        in.resetReaderIndex();
        return;
    }

    if (MqttUtils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == QosType.MOST_ONE && message.isDupFlag()) {
            //bad protocol, if QoS=0 => DUP = 0
            throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
        }

        if (message.getQos() == QosType.RESERVED) {
            throw new CorruptedFrameException(
                    "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
        }
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = MqttUtils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters.
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containing wild card chars, topic: " + topic);
    }
    //check topic is at least one char [MQTT-4.7.3-1]
    if (topic.length() == 0) {
        throw new CorruptedFrameException("Received a PUBLISH with topic without any character");
    }

    message.setTopicName(topic);

    if (message.getQos() == QosType.LEAST_ONE || message.getQos() == QosType.EXACTLY_ONCE) {
        message.setPacketId(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

    //read the payload
    int payloadSize = remainingLength - (stopPos - startPos - 2)
            + (MqttUtils.numBytesToEncode(remainingLength) - 1);
    if (in.readableBytes() < payloadSize) {
        in.resetReaderIndex();
        return;
    }
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:org.kuali.test.proxyserver.TestProxyServer.java

License:Educational Community License

/**
 *
 * @param content/* w w  w .j a  v a 2 s .com*/
 * @return
 */
public static byte[] getHttpPostContent(ByteBuf content) {
    byte[] retval = null;
    if (content.isReadable()) {
        content.retain();
        ByteBuffer nioBuffer = content.nioBuffer();
        retval = new byte[nioBuffer.remaining()];
        nioBuffer.get(retval);
        content.release();
    }

    return retval;
}

From source file:org.msgpack.rpc.loop.netty.MessagePackDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> result) throws Exception {
    // TODO ???/*from   w w  w .ja v a2 s .  c om*/

    ByteBuffer buffer = msg.nioBuffer();
    if (!buffer.hasRemaining()) {
        return;
    }

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();

    Value v = messagePack.read(bytes, offset, length);
    result.add(v);
}

From source file:org.msgpack.rpc.loop.netty.MessagePackStreamDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> paramList) throws Exception {

    if (msg.isReadable()) {
        ByteBuffer buffer = msg.nioBuffer();
        Unpacker unpacker = msgpack.createBufferUnpacker(buffer);
        int lastPos = 0;
        try {/*w w w. j a v a 2  s. co  m*/
            while (buffer.position() < buffer.limit()) {
                Value v = unpacker.readValue();
                paramList.add(v);
                lastPos = buffer.position();
            }
            msg.skipBytes(lastPos);
        } catch (EOFException e) {
            msg.skipBytes(lastPos);
        }
    }
}

From source file:org.onosproject.openflow.controller.impl.OFMessageEncoder.java

License:Apache License

@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (!(msg instanceof List)) {
        return msg;
    }/*  w ww .  ja v a  2s  . c o m*/

    @SuppressWarnings("unchecked")
    List<OFMessage> msglist = (List<OFMessage>) msg;
    /* XXX S can't get length of OFMessage in loxigen's openflowj??
    int size = 0;
    for (OFMessage ofm : msglist) {
    size += ofm.getLengthU();
    }*/

    ByteBuf bb = Unpooled.buffer();

    for (OFMessage ofm : msglist) {
        if (ofm != null) {
            ofm.writeTo(bb);
        }
    }

    ChannelBuffer buf = ChannelBuffers.wrappedBuffer(bb.nioBuffer());

    return buf;
}

From source file:org.opendaylight.protocol.framework.SimpleByteToMessageDecoder.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
    out.add(new SimpleMessage(StandardCharsets.UTF_8.decode(in.nioBuffer()).toString()));
}

From source file:org.poweredrails.rails.net.packet.EncryptionHandler.java

License:MIT License

private ByteBuf update(ByteBuf msg, Cipher cipher) {
    ByteBuffer out = ByteBuffer.allocate(msg.readableBytes());

    try {//w w  w  .ja  v a 2s.c  om
        cipher.update(msg.nioBuffer(), out);
    } catch (ShortBufferException e) {
        throw new RuntimeException("Failed to update an encrpytion buffer!");
    }

    out.flip();
    return Unpooled.wrappedBuffer(out);
}

From source file:org.scache.network.sasl.SaslClientBootstrap.java

License:Apache License

/**
 * Performs SASL authentication by sending a token, and then proceeding with the SASL
 * challenge-response tokens until we either successfully authenticate or throw an exception
 * due to mismatch./*from   w  w  w . j av a 2s  .  com*/
 */
@Override
public void doBootstrap(TransportClient client, Channel channel) {
    ScacheSaslClient saslClient = new ScacheSaslClient(appId, secretKeyHolder, encrypt);
    try {
        byte[] payload = saslClient.firstToken();

        while (!saslClient.isComplete()) {
            SaslMessage msg = new SaslMessage(appId, payload);
            ByteBuf buf = Unpooled.buffer(msg.encodedLength() + (int) msg.body().size());
            msg.encode(buf);
            buf.writeBytes(msg.body().nioByteBuffer());

            ByteBuffer response = client.sendRpcSync(buf.nioBuffer(), conf.saslRTTimeoutMs());
            payload = saslClient.response(JavaUtils.bufferToArray(response));
        }

        client.setClientId(appId);

        if (encrypt) {
            if (!ScacheSaslServer.QOP_AUTH_CONF.equals(saslClient.getNegotiatedProperty(Sasl.QOP))) {
                throw new RuntimeException(
                        new SaslException("Encryption requests by negotiated non-encrypted connection."));
            }
            SaslEncryption.addToChannel(channel, saslClient, conf.maxSaslEncryptedBlockSize());
            saslClient = null;
            logger.debug("Channel {} configured for SASL encryption.", client);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } finally {
        if (saslClient != null) {
            try {
                // Once authentication is complete, the server will trust all remaining communication.
                saslClient.dispose();
            } catch (RuntimeException e) {
                logger.error("Error while disposing SASL client", e);
            }
        }
    }
}

From source file:org.sfs.io.AsyncFileWriterImpl.java

License:Apache License

private AsyncFileWriterImpl doWrite(Buffer buffer, long position, Handler<AsyncResult<Void>> handler) {
    Preconditions.checkNotNull(buffer, "buffer");
    Preconditions.checkArgument(position >= 0, "position must be >= 0");
    Handler<AsyncResult<Void>> wrapped = ar -> {
        if (ar.succeeded()) {
            if (handler != null) {
                handler.handle(ar);/*from  www. ja v a2  s .com*/
            }
        } else {
            if (handler != null) {
                handler.handle(ar);
            } else {
                handleException(ar.cause());
            }
        }
    };
    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        doWrite(buf.nioBuffers(), position, wrapped);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), wrapped);
    }
    return this;
}