List of usage examples for io.netty.buffer PooledByteBufAllocator DEFAULT
PooledByteBufAllocator DEFAULT
To view the source code for io.netty.buffer PooledByteBufAllocator DEFAULT.
Click Source Link
From source file:org.eclipse.milo.opcua.stack.client.UaTcpStackClient.java
License:Open Source License
public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client, Optional<ClientSecureChannel> existingChannel) { CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override/*w w w .j a v a 2 s . c om*/ protected void initChannel(SocketChannel channel) throws Exception { UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client, existingChannel, handshake); channel.pipeline().addLast(acknowledgeHandler); } }); try { URI uri = new URI(client.getEndpointUrl()).parseServerAuthority(); bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> { if (!f.isSuccess()) { handshake.completeExceptionally(f.cause()); } }); } catch (Throwable e) { UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, e); handshake.completeExceptionally(failure); } return handshake; }
From source file:org.eclipse.milo.opcua.stack.server.transport.ServerChannelManager.java
License:Open Source License
private static CompletableFuture<Channel> bootstrap(UaStackServer stackServer, InetSocketAddress bindAddress, TransportProfile transportProfile) { ChannelInitializer<SocketChannel> initializer; if (transportProfile == TransportProfile.TCP_UASC_UABINARY) { initializer = new OpcServerTcpChannelInitializer(stackServer); } else {/*from w w w .j ava2s . c o m*/ initializer = new OpcServerHttpChannelInitializer(stackServer); } ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(Stack.sharedEventLoop()).handler(new LoggingHandler(ServerChannelManager.class)) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true).childHandler(initializer); CompletableFuture<Channel> channelFuture = new CompletableFuture<>(); bootstrap.bind(bindAddress).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { Channel channel = future.channel(); channelFuture.complete(channel); } else { channelFuture.completeExceptionally(future.cause()); } }); return channelFuture; }
From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java
License:Open Source License
protected ServerBootstrap getBootstrap(MessageInput input) { final LinkedHashMap<String, Callable<? extends ChannelHandler>> parentHandlers = getChannelHandlers(input); final LinkedHashMap<String, Callable<? extends ChannelHandler>> childHandlers = getChildChannelHandlers( input);/*from www . java 2 s . co m*/ childEventLoopGroup = eventLoopGroupFactory.create(workerThreads, localRegistry, "workers"); return new ServerBootstrap().group(parentEventLoopGroup, childEventLoopGroup) .channelFactory(new ServerSocketChannelFactory(nettyTransportConfiguration.getType())) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(8192)) .option(ChannelOption.SO_RCVBUF, getRecvBufferSize()) .childOption(ChannelOption.SO_RCVBUF, getRecvBufferSize()) .childOption(ChannelOption.SO_KEEPALIVE, tcpKeepalive) .handler(getChannelInitializer(parentHandlers)).childHandler(getChannelInitializer(childHandlers)); }
From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingServer.java
License:Apache License
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyServerConfig.getServerWorkerThreads(), new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override/*from w ww .jav a 2s . co m*/ public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = this.serverBootstrap .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) .childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(defaultEventExecutorGroup, HANDSHAKE_HANDLER_NAME, new HandshakeHandler(TlsSystemConfig.tlsMode)) .addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(), new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Throwable e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
From source file:org.hornetq.amqp.dealer.protonimpl.AbstractProtonSender.java
License:Apache License
protected int performSend(ProtonJMessage serverMessage, Object context) { if (!creditsSemaphore.tryAcquire()) { try {// w ww . j ava 2 s. co m 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.getTrio().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.hornetq.amqp.dealer.protonimpl.client.ProtonClientReceiver.java
License:Apache License
public void onMessage(Delivery delivery) throws HornetQAMQPException { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); try {/*from w w w. ja v a 2 s . c o m*/ synchronized (connection.getTrio().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.hornetq.amqp.dealer.protonimpl.server.ProtonServerReceiver.java
License:Apache License
public void onMessage(Delivery delivery) throws HornetQAMQPException { Receiver receiver;/*w w w. j a v a 2s . co m*/ try { receiver = ((Receiver) delivery.getLink()); if (!delivery.isReadable()) { return; } ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(10 * 1024); try { synchronized (connection.getTrio().getLock()) { readDelivery(receiver, buffer); sessionSPI.serverSend(receiver, delivery, address, delivery.getMessageFormat(), buffer); receiver.advance(); 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.hornetq.amqp.dealer.protonimpl.TransactionHandler.java
License:Apache License
@Override public void onMessage(Delivery delivery) throws HornetQAMQPException { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); final Receiver receiver; try {/*from www . ja v a 2s . c om*/ 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 HornetQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage()); } } else { try { sessionSPI.commitCurrentTX(); } catch (Exception e) { throw HornetQAMQPProtocolMessageBundle.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.hornetq.amqp.test.SimpleTest.java
License:Apache License
@Test public void testMeasureMessageImpl() { long time = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { if (i % 10000 == 0) { System.out.println("Decoded " + i); }/*from www. j av a 2s . c o m*/ ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024 * 1024); MessageImpl message = (MessageImpl) Message.Factory.create(); message.setBody(new Data(new Binary(new byte[5]))); Properties props = new Properties(); props.setMessageId("Some String"); props.setAbsoluteExpiryTime(new Date(System.currentTimeMillis())); message.setProperties(props); message.encode(new NettyWritable(buf)); MessageImpl readMessage = (MessageImpl) Message.Factory.create(); readMessage.decode(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes()); buf.release(); } long total = System.currentTimeMillis() - time; System.out.println("Took " + total); }
From source file:org.ireland.jnetty.HttpHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpMessage message) throws Exception { if (message instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) message; if (is100ContinueExpected(request)) { send100Continue(ctx);// ww w. j av a 2 s.c o m } //TODO: UnpooledHeapByteBuf ? ??,? ( + ? ??) ? FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), OK, PooledByteBufAllocator.DEFAULT.directBuffer(0)); handle(ctx, request, response); // flush(ctx, request,response); need flush?? } }