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.apache.spark.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 . jav  a 2  s .  c  o  m*/
 */
@Override
public void doBootstrap(TransportClient client, Channel channel) {
    SparkSaslClient saslClient = new SparkSaslClient(appId, secretKeyHolder, conf.saslEncryption());
    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.authRTTimeoutMs());
            payload = saslClient.response(JavaUtils.bufferToArray(response));
        }

        client.setClientId(appId);

        if (conf.saslEncryption()) {
            if (!SparkSaslServer.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 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.apache.spark.network.shuffle.protocol.BlockTransferMessage.java

License:Apache License

/** Serializes the 'type' byte followed by the message itself. */
public ByteBuffer toByteBuffer() {
    // Allow room for encoded message, plus the type byte
    ByteBuf buf = Unpooled.buffer(encodedLength() + 1);
    buf.writeByte(type().id);/* ww  w .  ja  v a 2  s  .  co m*/
    encode(buf);
    assert buf.writableBytes() == 0 : "Writable bytes remain: " + buf.writableBytes();
    return buf.nioBuffer();
}

From source file:org.asterisque.netty.MessageDecoder.java

License:Apache License

public void decode(ChannelHandlerContext ctx, ByteBuf b, List<Object> out) throws CodecException {
    ByteBuffer buffer = b.nioBuffer();
    Optional<Message> msg = codec.decode(buffer);
    if (msg.isPresent()) {
        b.skipBytes(buffer.position());/*from   w w w  . j a  v a 2s .c  om*/
        out.add(msg.get());
    }
}

From source file:org.curioswitch.common.server.framework.redis.ProtobufRedisCodec.java

License:Open Source License

@Override
public ByteBuffer encodeKey(K key) {
    ByteBuf buf = Unpooled.buffer(estimateSize(key));
    encodeKey(key, buf);
    return buf.nioBuffer();
}

From source file:org.curioswitch.common.server.framework.redis.ProtobufRedisCodec.java

License:Open Source License

@Override
public ByteBuffer encodeValue(V value) {
    ByteBuf buf = Unpooled.buffer(estimateSize(value));
    encodeValue(value, buf);//from   w w  w.ja va 2  s  .  c om
    return buf.nioBuffer();
}

From source file:org.dcache.xrootd.stream.ChunkedFileChannelReadResponse.java

License:Open Source License

@Override
protected ByteBuf read(ByteBufAllocator alloc, long position, int length) throws IOException {
    ByteBuf chunk = alloc.ioBuffer(length);
    try {/*from   w  w w.j  av  a2 s. c o m*/
        chunk.writerIndex(length);
        ByteBuffer buffer = chunk.nioBuffer();
        while (length > 0) {
            /* use position independent thread safe call */
            int bytes = channel.read(buffer, position);
            if (bytes < 0) {
                break;
            }
            position += bytes;
            length -= bytes;
        }
        chunk.writerIndex(chunk.writerIndex() - length);
        return chunk;
    } catch (RuntimeException | IOException e) {
        ReferenceCountUtil.release(chunk);
        throw e;
    }
}

From source file:org.dcache.xrootd.stream.ChunkedFileChannelReadvResponse.java

License:Open Source License

@Override
protected ByteBuf read(ByteBufAllocator alloc, int fd, long position, int length)
        throws IOException, XrootdException {
    checkValidFileDescriptor(fd);/*from  ww  w .j  ava 2  s  . c  o  m*/

    FileChannel channel = channels.get(fd);

    ByteBuf chunk = alloc.ioBuffer(length);
    try {
        chunk.writerIndex(length);
        ByteBuffer buffer = chunk.nioBuffer();
        while (length > 0) {
            /* use position independent thread safe call */
            int bytes = channel.read(buffer, position);
            if (bytes < 0) {
                break;
            }
            position += bytes;
            length -= bytes;
        }
        chunk.writerIndex(chunk.writerIndex() - length);
        return chunk;
    } catch (RuntimeException | IOException e) {
        ReferenceCountUtil.release(chunk);
        throw e;
    }
}

From source file:org.dcache.xrootd.stream.ChunkedFileReadvResponse.java

License:Open Source License

@Override
protected ByteBuf read(ByteBufAllocator alloc, int fd, long position, int length)
        throws IOException, XrootdException {
    if (fd < 0 || fd >= files.size() || files.get(fd) == null) {
        throw new XrootdException(kXR_FileNotOpen, "Invalid file descriptor");
    }//w w w  . j  a v a 2 s. c  o  m

    FileChannel channel = files.get(fd).getChannel();

    ByteBuf chunk = alloc.ioBuffer(length);
    try {
        chunk.writerIndex(length);
        ByteBuffer buffer = chunk.nioBuffer();

        while (length > 0) {
            /* use position independent thread safe call */
            int bytes = channel.read(buffer, position);
            if (bytes < 0) {
                break;
            }
            position += bytes;
            length -= bytes;
        }
        chunk.writerIndex(chunk.writerIndex() - length);
        return chunk;
    } catch (RuntimeException | IOException e) {
        ReferenceCountUtil.release(chunk);
        throw e;
    }
}

From source file:org.dna.mqtt.moquette.parser.netty.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("decode invoked with buffer {}", in);
    }//  w  w  w.  j  a  v a2  s  . c  o m
    in.resetReaderIndex();
    int startPos = in.readerIndex();

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

    if (Utils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == AbstractMessage.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() == AbstractMessage.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 = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
    }

    message.setTopicName(topic);

    if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
            || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
        message.setMessageID(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

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

    out.add(message);
}

From source file:org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider.java

License:Open Source License

@Override
public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint,
        ByteString serverNonce) throws Exception {

    UserTokenPolicy tokenPolicy = Arrays.stream(endpoint.getUserIdentityTokens())
            .filter(t -> t.getTokenType() == UserTokenType.UserName).findFirst()
            .orElseThrow(() -> new Exception("no username token policy found"));

    String policyId = tokenPolicy.getPolicyId();

    SecurityPolicy securityPolicy = SecurityPolicy.None;

    String securityPolicyUri = tokenPolicy.getSecurityPolicyUri();
    try {/*from   w ww .  j  a v a  2  s  .  c o m*/
        if (securityPolicyUri != null && !securityPolicyUri.isEmpty()) {
            securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
        } else {
            securityPolicyUri = endpoint.getSecurityPolicyUri();
            securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
        }
    } catch (Throwable t) {
        logger.warn("Error parsing SecurityPolicy for uri={}, falling back to no security.", securityPolicyUri);
    }

    byte[] passwordBytes = password.getBytes("UTF-8");
    byte[] nonceBytes = Optional.ofNullable(serverNonce.bytes()).orElse(new byte[0]);

    ByteBuf buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

    if (securityPolicy == SecurityPolicy.None) {
        buffer.writeBytes(passwordBytes);
    } else {
        buffer.writeInt(passwordBytes.length + nonceBytes.length);
        buffer.writeBytes(passwordBytes);
        buffer.writeBytes(nonceBytes);

        ByteString bs = endpoint.getServerCertificate();
        X509Certificate certificate = CertificateUtil.decodeCertificate(bs.bytes());

        int plainTextBlockSize = getPlainTextBlockSize(certificate, securityPolicy);
        int cipherTextBlockSize = getCipherTextBlockSize(certificate, securityPolicy);
        int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize;
        Cipher cipher = getAndInitializeCipher(certificate, securityPolicy);

        ByteBuffer plainTextNioBuffer = buffer.nioBuffer();
        ByteBuffer cipherTextNioBuffer = Unpooled.buffer(cipherTextBlockSize * blockCount)
                .order(ByteOrder.LITTLE_ENDIAN).nioBuffer(0, cipherTextBlockSize * blockCount);

        for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
            int position = blockNumber * plainTextBlockSize;
            int limit = Math.min(buffer.readableBytes(), (blockNumber + 1) * plainTextBlockSize);
            plainTextNioBuffer.position(position).limit(limit);

            cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer);
        }

        cipherTextNioBuffer.flip();
        buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer);
    }

    byte[] bs = new byte[buffer.readableBytes()];
    buffer.readBytes(bs);

    // UA Part 4, Section 7.35.3 UserNameIdentityToken:
    // encryptionAlgorithm parameter is null if the password is not encrypted.
    String securityAlgorithmUri = securityPolicy.getAsymmetricEncryptionAlgorithm().getUri();
    String encryptionAlgorithm = securityAlgorithmUri.isEmpty() ? null : securityAlgorithmUri;

    UserNameIdentityToken token = new UserNameIdentityToken(policyId, username, ByteString.of(bs),
            encryptionAlgorithm);

    return new Tuple2<>(token, new SignatureData());
}