Example usage for io.netty.buffer ByteBufAllocator DEFAULT

List of usage examples for io.netty.buffer ByteBufAllocator DEFAULT

Introduction

In this page you can find the example usage for io.netty.buffer ByteBufAllocator DEFAULT.

Prototype

ByteBufAllocator DEFAULT

To view the source code for io.netty.buffer ByteBufAllocator DEFAULT.

Click Source Link

Usage

From source file:org.apache.activemq.artemis.core.protocol.mqtt.MQTTConnectionManager.java

License:Apache License

/**
 * Handles the connect packet.  See spec for details on each of parameters.
 *///from ww w  . java 2 s .  co m
synchronized void connect(String cId, String username, byte[] passwordInBytes, boolean will, byte[] willMessage,
        String willTopic, boolean willRetain, int willQosLevel, boolean cleanSession) throws Exception {
    String clientId = validateClientId(cId, cleanSession);
    if (clientId == null) {
        session.getProtocolHandler().sendConnack(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED);
        session.getProtocolHandler().disconnect(true);
        return;
    }

    session.setSessionState(getSessionState(clientId));
    String password = passwordInBytes == null ? null : new String(passwordInBytes, CharsetUtil.UTF_8);
    session.getConnection().setClientID(clientId);
    ServerSessionImpl serverSession = createServerSession(username, password);
    serverSession.start();

    session.setServerSession(serverSession);
    session.setIsClean(cleanSession);

    if (will) {
        isWill = true;
        this.willMessage = ByteBufAllocator.DEFAULT.buffer(willMessage.length);
        this.willMessage.writeBytes(willMessage);
        this.willQoSLevel = willQosLevel;
        this.willRetain = willRetain;
        this.willTopic = willTopic;
    }

    session.getConnection().setConnected(true);
    session.start();
    session.getProtocolHandler().sendConnack(MqttConnectReturnCode.CONNECTION_ACCEPTED);
}

From source file:org.apache.activemq.artemis.core.protocol.mqtt.MQTTPublishManager.java

License:Apache License

private void sendServerMessage(int messageId, ICoreMessage message, int deliveryCount, int qos) {
    String address = MQTTUtil.convertCoreAddressFilterToMQTT(
            message.getAddress() == null ? "" : message.getAddress().toString(),
            session.getWildcardConfiguration());
    boolean isRetain = message.getBooleanProperty(MQTT_MESSAGE_RETAIN_KEY);

    ByteBuf payload;//ww  w  .  j a  v  a2 s .  com
    switch (message.getType()) {
    case Message.TEXT_TYPE:
        try {
            SimpleString text = message.getDataBuffer().readNullableSimpleString();
            byte[] stringPayload = text.toString().getBytes("UTF-8");
            payload = ByteBufAllocator.DEFAULT.buffer(stringPayload.length);
            payload.writeBytes(stringPayload);
            break;
        } catch (UnsupportedEncodingException e) {
            log.warn("Unable to send message: " + message.getMessageID() + " Cause: " + e.getMessage(), e);
        }
    default:
        ActiveMQBuffer bodyBuffer = message.getDataBuffer();
        payload = ByteBufAllocator.DEFAULT.buffer(bodyBuffer.writerIndex());
        payload.writeBytes(bodyBuffer.byteBuf());
        break;
    }
    session.getProtocolHandler().send(messageId, address, qos, isRetain, payload, deliveryCount);
}

From source file:org.apache.activemq.artemis.utils.SimpleStringTest.java

License:Apache License

@Test
public void testOutOfBoundsThrownOnMalformedString() {
    ByteBuf byteBuffer = ByteBufAllocator.DEFAULT.buffer(5);
    byteBuffer.writeInt(100);/*from w w  w .j  a  v a 2s .c o m*/

    Exception e = null;
    try {
        SimpleString.readSimpleString(byteBuffer);
    } catch (IndexOutOfBoundsException iob) {
        e = iob;
    }
    assertTrue(e instanceof IndexOutOfBoundsException);
}

From source file:org.apache.bookkeeper.proto.ProtocolBenchmark.java

License:Apache License

@Benchmark
public void testAddEntryV2() throws Exception {
    ByteBufList list = ByteBufList.get(entry.retainedSlice());
    BookieProtocol.AddRequest req = BookieProtocol.AddRequest.create(BookieProtocol.CURRENT_PROTOCOL_VERSION,
            ledgerId, entryId, flags, masterKey, list);
    Object res = this.reqEnDeV2.encode(req, ByteBufAllocator.DEFAULT);
    ReferenceCountUtil.release(res);//from   w  ww  .  j  a v  a 2 s  . c o  m
    ReferenceCountUtil.release(list);
}

From source file:org.apache.bookkeeper.proto.ProtocolBenchmark.java

License:Apache License

@Benchmark
public void testAddEntryV3() throws Exception {
    // Build the request and calculate the total size to be included in the packet.
    BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE)
            .setOperation(OperationType.ADD_ENTRY).setTxnId(0L);

    ByteBuf toSend = entry.slice();//from www  . j a  v a 2 s  .c  om
    byte[] toSendArray = new byte[toSend.readableBytes()];
    toSend.getBytes(toSend.readerIndex(), toSendArray);
    AddRequest.Builder addBuilder = AddRequest.newBuilder().setLedgerId(ledgerId).setEntryId(entryId)
            .setMasterKey(ByteString.copyFrom(masterKey)).setBody(ByteString.copyFrom(toSendArray))
            .setFlag(AddRequest.Flag.RECOVERY_ADD);

    Request request = Request.newBuilder().setHeader(headerBuilder).setAddRequest(addBuilder).build();

    Object res = this.reqEnDeV3.encode(request, ByteBufAllocator.DEFAULT);
    ReferenceCountUtil.release(res);
}

From source file:org.apache.bookkeeper.proto.ProtocolBenchmark.java

License:Apache License

@Benchmark
public void testAddEntryV3WithMdc() throws Exception {
    MDC.put("parent_id", "LetsPutSomeLongParentRequestIdHere");
    MDC.put("request_id", "LetsPutSomeLongRequestIdHere");
    // Build the request and calculate the total size to be included in the packet.
    BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE)
            .setOperation(OperationType.ADD_ENTRY).setTxnId(0L);

    ByteBuf toSend = entry.slice();//from  w  ww  . ja  va2  s.c om
    byte[] toSendArray = new byte[toSend.readableBytes()];
    toSend.getBytes(toSend.readerIndex(), toSendArray);
    AddRequest.Builder addBuilder = AddRequest.newBuilder().setLedgerId(ledgerId).setEntryId(entryId)
            .setMasterKey(ByteString.copyFrom(masterKey)).setBody(ByteString.copyFrom(toSendArray))
            .setFlag(AddRequest.Flag.RECOVERY_ADD);

    Request request = PerChannelBookieClient.appendRequestContext(Request.newBuilder()).setHeader(headerBuilder)
            .setAddRequest(addBuilder).build();

    Object res = this.reqEnDeV3.encode(request, ByteBufAllocator.DEFAULT);
    ReferenceCountUtil.release(res);
    MDC.clear();
}

From source file:org.apache.bookkeeper.proto.ProtocolBenchmark.java

License:Apache License

@Benchmark
public void testAddEntryV3WithExtraContextDataNoMdc() throws Exception {
    // Build the request and calculate the total size to be included in the packet.
    BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE)
            .setOperation(OperationType.ADD_ENTRY).setTxnId(0L);

    ByteBuf toSend = entry.slice();//from  w  w  w .  ja v  a 2s.  c om
    byte[] toSendArray = new byte[toSend.readableBytes()];
    toSend.getBytes(toSend.readerIndex(), toSendArray);
    AddRequest.Builder addBuilder = AddRequest.newBuilder().setLedgerId(ledgerId).setEntryId(entryId)
            .setMasterKey(ByteString.copyFrom(masterKey)).setBody(ByteString.copyFrom(toSendArray))
            .setFlag(AddRequest.Flag.RECOVERY_ADD);

    Request request = appendRequestContextNoMdc(Request.newBuilder()).setHeader(headerBuilder)
            .setAddRequest(addBuilder).build();

    Object res = this.reqEnDeV3.encode(request, ByteBufAllocator.DEFAULT);
    ReferenceCountUtil.release(res);
}

From source file:org.apache.camel.component.netty4.NettyConverter.java

License:Apache License

@Converter
public static ByteBuf toByteBuffer(byte[] bytes, Exchange exchange) {
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(bytes.length);
    buf.writeBytes(bytes);/*from w  w w  .ja va2 s.  co m*/
    return buf;
}

From source file:org.apache.carbondata.spark.dictionary.client.SecureDictionaryClientHandler.java

License:Apache License

/**
 * client send request to server/*from ww w.j  a v a2 s .com*/
 *
 * @param key DictionaryMessage
 * @return DictionaryMessage
 */
public DictionaryMessage getDictionary(DictionaryMessage key, TransportClient client) {
    DictionaryMessage dictionaryMessage;
    ByteBuffer resp = null;
    try {

        ByteBuf buffer = ByteBufAllocator.DEFAULT.heapBuffer();
        key.writeData(buffer);
        resp = client.sendRpcSync(buffer.nioBuffer(), 100000);
    } catch (Exception e) {
        LOGGER.error("Error while send request to server ", e);
    }
    try {
        if (resp == null) {
            StringBuilder message = new StringBuilder();
            message.append("DictionaryMessage { ColumnName: ").append(key.getColumnName())
                    .append(", DictionaryValue: ").append(key.getDictionaryValue()).append(", type: ")
                    .append(key.getType()).append(" }");
            throw new RuntimeException("Request timed out for key : " + message);
        }
        DictionaryMessage newKey = new DictionaryMessage();
        ByteBuf data = Unpooled.wrappedBuffer(resp);
        newKey.readFullLength(data);
        data.release();
        return newKey;
    } catch (Exception e) {
        LOGGER.error(e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.carbondata.spark.dictionary.server.SecureDictionaryServerHandler.java

License:Apache License

@Override
public void receive(TransportClient transportClient, ByteBuffer byteBuffer,
        RpcResponseCallback rpcResponseCallback) {
    try {//from w ww  .j av  a2s  . c o m
        ByteBuf data = Unpooled.wrappedBuffer(byteBuffer);
        DictionaryMessage key = new DictionaryMessage();
        key.readFullLength(data);
        data.release();
        int outPut = processMessage(key);
        key.setDictionaryValue(outPut);
        // Send back the response
        ByteBuf buff = ByteBufAllocator.DEFAULT.buffer();
        key.writeData(buff);
        rpcResponseCallback.onSuccess(buff.nioBuffer());
    } catch (Exception e) {
        LOGGER.error(e);
    }
}