Example usage for io.netty.buffer PooledByteBufAllocator DEFAULT

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

Introduction

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

Prototype

PooledByteBufAllocator DEFAULT

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

Click Source Link

Usage

From source file:org.opendaylight.sxp.core.messaging.MessageFactoryTest.java

License:Open Source License

@Test
public void testParseException0() throws Exception {
    byte[] msg = new byte[] { 0, 0 };
    ByteBuf message = PooledByteBufAllocator.DEFAULT.buffer(msg.length);
    message.writeBytes(msg);//from   w w  w .  j  a  v  a 2s . c o  m
    exception.expect(ErrorMessageException.class);
    MessageFactory.parse(Version.Version4, message);
}

From source file:org.opendaylight.sxp.core.messaging.MessageFactoryTest.java

License:Open Source License

@Test
public void testParseException1() throws Exception {
    byte[] msg = new byte[] { 0, 0, 0, 5, 0, 0, 0, 0 };
    ByteBuf message = PooledByteBufAllocator.DEFAULT.buffer(msg.length);
    message.writeBytes(msg);//w w w  .j  av  a  2s  .c o  m
    exception.expect(ErrorMessageException.class);
    MessageFactory.parse(Version.Version4, message);
}

From source file:org.opendaylight.sxp.core.service.BindingDispatcher.java

License:Open Source License

/**
 * @param deleteBindings Bindings that will be deleted
 * @param addBindings    Bindings that will be added
 * @param <T>            Any type extending SxpBindingFields
 * @return BiFunction used for export of bindings to Peers
 *///from w  w w.jav  a  2  s .  c  om
private <T extends SxpBindingFields> BiFunction<SxpConnection, SxpBindingFilter, ByteBuf> generatePart(
        List<T> deleteBindings, List<T> addBindings) {
    return (connection, bindingFilter) -> {
        try {
            return connection.getContext().executeUpdateMessageStrategy(connection, deleteBindings, addBindings,
                    bindingFilter);
        } catch (UpdateMessageCompositionException e) {
            LOG.error("{} Error creating update message {} {}", connection, deleteBindings, addBindings, e);
            return PooledByteBufAllocator.DEFAULT.buffer(0);
        }
    };
}

From source file:org.pidome.server.system.network.sockets.SocketBase.java

/**
 * Returns a default with minimal requirements set server bootstrap.
 * @param parents The parent worker controller amount.
 * @param childs The amount of childs per parent worker.
 * @return Server Bootstrap with a socket service channel.
 *//*from w  ww .  j  av  a  2  s .  co m*/
public final ServerBootstrap getSocketServerBootstrapContext(int parents, int childs) {
    if (workersGroup == null) {
        workersGroup = new NioEventLoopGroup();
    }
    return new ServerBootstrap().group(workersGroup)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.DEBUG));
}

From source file:org.proton.plug.context.AbstractProtonContextSender.java

License:Apache License

protected int performSend(ProtonJMessage serverMessage, Object context) {
    if (!creditsSemaphore.tryAcquire()) {
        try {/*w  w w  .j  a va  2s .c om*/
            creditsSemaphore.acquire();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // nothing to be done here.. we just keep going
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    //presettle means we can ack the message on the dealer side before we send it, i.e. for browsers
    boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;

    //we only need a tag if we are going to ack later
    byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

    ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
    try {
        serverMessage.encode(new NettyWritable(nettyBuffer));

        int size = nettyBuffer.writerIndex();

        synchronized (connection.getLock()) {
            final Delivery delivery;
            delivery = sender.delivery(tag, 0, tag.length);
            delivery.setContext(context);

            // this will avoid a copy.. patch provided by Norman using buffer.array()
            sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(),
                    nettyBuffer.readableBytes());

            if (preSettle) {
                delivery.settle();
            } else {
                sender.advance();
            }
        }

        connection.flush();

        return size;
    } finally {
        nettyBuffer.release();
    }
}

From source file:org.proton.plug.context.client.ProtonClientReceiverContext.java

License:Apache License

public void onMessage(Delivery delivery) throws ActiveMQAMQPException {
    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
    try {//  www.j a  va 2 s .  c o m
        synchronized (connection.getLock()) {
            readDelivery(receiver, buffer);
            MessageImpl clientMessage = decodeMessageImpl(buffer);

            // This second method could be better
            //            clientMessage.decode(buffer.nioBuffer());

            receiver.advance();
            delivery.disposition(Accepted.getInstance());
            queues.add(clientMessage);

        }
    } finally {
        buffer.release();
    }
}

From source file:org.proton.plug.context.ProtonTransactionHandler.java

License:Apache License

@Override
public void onMessage(Delivery delivery) throws ActiveMQAMQPException {
    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);

    final Receiver receiver;
    try {//from   ww w .j  a  v  a  2  s. co  m
        receiver = ((Receiver) delivery.getLink());

        if (!delivery.isReadable()) {
            return;
        }

        readDelivery(receiver, buffer);

        receiver.advance();

        MessageImpl msg = decodeMessageImpl(buffer);

        Object action = ((AmqpValue) msg.getBody()).getValue();

        if (action instanceof Declare) {
            Binary txID = sessionSPI.getCurrentTXID();
            Declared declared = new Declared();
            declared.setTxnId(txID);
            delivery.disposition(declared);
            delivery.settle();
        } else if (action instanceof Discharge) {
            Discharge discharge = (Discharge) action;
            if (discharge.getFail()) {
                try {
                    sessionSPI.rollbackCurrentTX();
                } catch (Exception e) {
                    throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage());
                }
            } else {
                try {
                    sessionSPI.commitCurrentTX();
                } catch (Exception e) {
                    throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCommittingCoordinator(e.getMessage());
                }
            }
            delivery.settle();
        }

    } catch (Exception e) {
        e.printStackTrace();
        Rejected rejected = new Rejected();
        ErrorCondition condition = new ErrorCondition();
        condition.setCondition(Symbol.valueOf("failed"));
        condition.setDescription(e.getMessage());
        rejected.setError(condition);
        delivery.disposition(rejected);
    } finally {
        buffer.release();
    }
}

From source file:org.proton.plug.context.server.ProtonServerReceiverContext.java

License:Apache License

public void onMessage(Delivery delivery) throws ActiveMQAMQPException {
    Receiver receiver;/*w  ww.j  a v  a 2  s  . co m*/
    try {
        receiver = ((Receiver) delivery.getLink());

        if (!delivery.isReadable()) {
            System.err.println("!!!!! Readable!!!!!!!");
            return;
        }

        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(10 * 1024);
        try {
            synchronized (connection.getLock()) {
                readDelivery(receiver, buffer);

                receiver.advance();

                sessionSPI.serverSend(receiver, delivery, address, delivery.getMessageFormat(), buffer);
                delivery.disposition(Accepted.getInstance());
                delivery.settle();

                if (receiver.getRemoteCredit() < numberOfCredits / 2) {
                    flow(numberOfCredits);
                }
            }
        } finally {
            buffer.release();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Rejected rejected = new Rejected();
        ErrorCondition condition = new ErrorCondition();
        condition.setCondition(Symbol.valueOf("failed"));
        condition.setDescription(e.getMessage());
        rejected.setError(condition);
        delivery.disposition(rejected);
    }
}

From source file:org.proton.plug.handler.impl.ProtonHandlerImpl.java

License:Apache License

@Override
public ByteBuf outputBuffer() {

    synchronized (lock) {
        int pending = transport.pending();

        if (pending < 0) {
            return null;//throw new IllegalStateException("xxx need to close the connection");
        }/*from w  ww.j a va  2  s . c om*/

        int size = pending - offset;

        if (size < 0) {
            throw new IllegalStateException("negative size: " + pending);
        }

        if (size == 0) {
            return null;
        }

        // For returning PooledBytes
        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer(size);
        ByteBuffer head = transport.head();
        head.position(offset);
        buffer.writeBytes(head);
        offset += size; // incrementing offset for future calls
        return buffer;
    }
}

From source file:org.proton.plug.test.minimalserver.MinimalServer.java

License:Apache License

public synchronized void start(String host, int port, final boolean sasl) throws Exception {
    this.host = host;
    this.port = port;
    this.sasl = sasl;

    if (channelClazz != null) {
        // Already started
        return;//from  w  w  w .j  ava 2 s . c o m
    }

    int threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    channelClazz = NioServerSocketChannel.class;
    eventLoopGroup = new NioEventLoopGroup(threadsToUse, new SimpleServerThreadFactory("simple-server", true,
            Thread.currentThread().getContextClassLoader()));

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("amqp-handler", new ProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    bootstrap.option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).
            //       childOption(ChannelOption.AUTO_READ, false).
            childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    SocketAddress address;
    address = new InetSocketAddress(host, port);
    Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel();
    serverChannelGroup.add(serverChannel);

}