List of usage examples for io.netty.buffer UnpooledByteBufAllocator DEFAULT
UnpooledByteBufAllocator DEFAULT
To view the source code for io.netty.buffer UnpooledByteBufAllocator DEFAULT.
Click Source Link
From source file:com.tesora.dve.db.mysql.portal.MySqlPortal.java
License:Open Source License
public MySqlPortal(Properties props) throws PEException { // This is the port the Portal is going to listen on - // default to Mysql's port int port = Singletons.require(HostService.class).getPortalPort(props); Singletons.replace(MySqlPortalService.class, this); InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory()); int max_concurrent = KnownVariables.MAX_CONCURRENT.getValue(null).intValue(); //TODO: parse/plan is on this pool, which is probably ok, especially with blocking calls to catalog. Check for responses that can be done by backend netty threads and avoid two context shifts. clientExecutorService = new PEThreadPoolExecutor(max_concurrent, max_concurrent, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), //The thread count limits concurrency here. Using a bounded queue here would block netty threads (very bad), so this pool could be overrun by 'bad' clients that pipeline. -sgossard new PEDefaultThreadFactory("msp-client")); clientExecutorService.allowCoreThreadTimeOut(true); bossGroup = new NioEventLoopGroup(1, new PEDefaultThreadFactory("msp-boss")); //fixes the number of Netty NIO threads to the number of available CPUs. workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new PEDefaultThreadFactory("netty-worker")); ServerBootstrap b = new ServerBootstrap(); try {// w w w .ja v a 2s. c o m b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if (PACKET_LOGGER) ch.pipeline().addFirst(new LoggingHandler(LogLevel.INFO)); ch.pipeline() .addLast(MSPProtocolDecoder.class.getSimpleName(), new MSPProtocolDecoder( MSPProtocolDecoder.MyDecoderState.READ_CLIENT_AUTH)) .addLast(new MSPAuthenticateHandlerV10()) .addLast(MSPCommandHandler.class.getSimpleName(), new MSPCommandHandler(clientExecutorService)) .addLast(ConnectionHandlerAdapter.getInstance()); } }) .childOption(ChannelOption.ALLOCATOR, USE_POOLED_BUFFERS ? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .bind(port).sync(); logger.info("DVE Server bound to port " + port); } catch (Exception e) { throw new PEException("Failed to bind DVE server to port " + port + " - " + e.getMessage(), e); } }
From source file:com.tesora.dve.tools.libmy.AsyncExample.java
License:Open Source License
public static void main(String[] args) throws Exception { final String mysqlHost = "localhost"; final int mysqlPort = 3307; final String username = "root"; final String password = "password"; final boolean isClearText = true; final InetSocketAddress serverAddress = new InetSocketAddress(mysqlHost, mysqlPort); final MyBackendDecoder.CharsetDecodeHelper charsetHelper = constructCharsetDecodeHelper(); final SimpleCredentials cred = constructCredentials(username, password, isClearText); final JavaCharsetCatalog javaCharsetCatalog = constructJavaCharsetCatalog(); final MysqlClientAuthenticationHandler authHandler = new MysqlClientAuthenticationHandler(cred, ClientCapabilities.DEFAULT_PSITE_CAPABILITIES, javaCharsetCatalog, new AtomicReference<Charset>()); final NioEventLoopGroup connectionEventGroup = new NioEventLoopGroup(1); final Bootstrap mysqlBootstrap = new Bootstrap(); mysqlBootstrap // .group(inboundChannel.eventLoop()) .channel(NioSocketChannel.class).group(connectionEventGroup) .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) .handler(new ChannelInitializer<Channel>() { @Override/*from www.j a v a2 s .co m*/ protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(authHandler).addLast(MyBackendDecoder.class.getSimpleName(), new MyBackendDecoder(charsetHelper)).addLast(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { System.out.println("WRITE:" + msg); super.write(ctx, msg, promise); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof MyFieldPktResponse) { final MyFieldPktResponse myFieldPktResponse = (MyFieldPktResponse) msg; System.out.println("COLUMN: " + myFieldPktResponse.getOrig_column() + "," + myFieldPktResponse.getColumn_type()); } else if (msg instanceof MyTextResultRow) { final StringBuilder builder = new StringBuilder(); builder.append("ROW:"); final MyTextResultRow textRow = (MyTextResultRow) msg; for (int i = 0; i < textRow.size(); i++) { builder.append('\t'); builder.append(textRow.getString(i)); } System.out.println(builder.toString()); } super.channelRead(ctx, msg); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); System.out.println("CLOSE. "); } }); } }); final ChannelFuture connectFut = mysqlBootstrap.connect(serverAddress); connectFut.sync(); System.out.println("Waiting to finish authenticate handshake"); authHandler.assertAuthenticated();//don't write a request until you know the login is complete. System.out.println("Connected, and authenticated, getting channel to write requests"); final Channel chan = connectFut.channel(); System.out.println("Sending two pipelined requests without blocking for first response."); chan.write(MSPComQueryRequestMessage.newMessage("show databases", CharsetUtil.UTF_8)); chan.write( MSPComQueryRequestMessage.newMessage("select * from information_schema.tables", CharsetUtil.UTF_8)); chan.flush();//NOTE: nothing is sent until this is called. Use writeAndFlush if you want it to go out immediately. System.out.println("Sleeping 5 sec so all results come back"); //normally you would sync to responses here. TimeUnit.SECONDS.sleep(5); System.out.println("Closing socket."); chan.writeAndFlush(MSPComQuitRequestMessage.newMessage());//send friendly hangup message. Probably correct to also wait for server close or an OK packet. chan.close(); chan.closeFuture().sync(); System.out.println("Exiting."); System.exit(0); }
From source file:com.turo.pushy.apns.server.ParsingMockApnsServerListenerAdapterTest.java
License:Open Source License
@Test public void testHandlePushNotificationAccepted() { final TestParsingMockApnsServerListener listener = new TestParsingMockApnsServerListener(); {//from w w w . j a va2 s. c o m final String token = "test-token"; final Http2Headers headers = new DefaultHttp2Headers().path(APNS_PATH_PREFIX + token); listener.handlePushNotificationAccepted(headers, null); assertEquals(token, listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String topic = "test-topic"; final Http2Headers headers = new DefaultHttp2Headers().add(APNS_TOPIC_HEADER, topic); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertEquals(topic, listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final DeliveryPriority priority = DeliveryPriority.CONSERVE_POWER; final Http2Headers headers = new DefaultHttp2Headers().addInt(APNS_PRIORITY_HEADER, priority.getCode()); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertEquals(priority, listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final Date expiration = new Date(1_000_000_000); final Http2Headers headers = new DefaultHttp2Headers().addInt(APNS_EXPIRATION_HEADER, (int) (expiration.getTime() / 1000)); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertEquals(expiration, listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String collapseId = "collapse-id"; final Http2Headers headers = new DefaultHttp2Headers().add(APNS_COLLAPSE_ID_HEADER, collapseId); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertEquals(collapseId, listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String payload = "A test payload!"; final Http2Headers headers = new DefaultHttp2Headers(); final ByteBuf payloadBuffer = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, payload); try { listener.handlePushNotificationAccepted(headers, payloadBuffer); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertEquals(payload, listener.mostRecentPushNotification.getPayload()); } finally { payloadBuffer.release(); } } }
From source file:com.turo.pushy.apns.server.ValidatingPushNotificationHandlerTest.java
License:Open Source License
@Before public void setUp() throws Exception { this.headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).authority(getClass().getName()) .path(APNS_PATH_PREFIX + TOKEN); this.headers.add(APNS_TOPIC_HEADER, TOPIC); this.addAcceptableCredentialsToHeaders(this.headers); this.payload = UnpooledByteBufAllocator.DEFAULT.buffer(); this.payload.writeBytes("{}".getBytes(StandardCharsets.UTF_8)); }
From source file:com.turo.pushy.apns.server.ValidatingPushNotificationHandlerTest.java
License:Open Source License
@Test public void testHandleNotificationWithEmptyPayload() { final ByteBuf emptyPayload = UnpooledByteBufAllocator.DEFAULT.buffer(); try {/* w w w. j ava2 s. c o m*/ this.testWithExpectedRejection( "Push notifications with a device token for the wrong topic should be rejected.", this.getHandler(DEVICE_TOKENS_BY_TOPIC, Collections.<String, Date>emptyMap()), this.headers, emptyPayload, RejectionReason.PAYLOAD_EMPTY); } finally { emptyPayload.release(); } }
From source file:com.turo.pushy.apns.server.ValidatingPushNotificationHandlerTest.java
License:Open Source License
@Test public void testHandleNotificationWithOversizedPayload() { final int size = 4096 * 2; final ByteBuf largePayload = UnpooledByteBufAllocator.DEFAULT.buffer(size); try {/* www . ja v a 2s.co m*/ final byte[] payloadBytes = new byte[size]; new Random().nextBytes(payloadBytes); largePayload.writeBytes(payloadBytes); this.testWithExpectedRejection( "Push notifications with a device token for the wrong topic should be rejected.", this.getHandler(DEVICE_TOKENS_BY_TOPIC, Collections.<String, Date>emptyMap()), this.headers, largePayload, RejectionReason.PAYLOAD_TOO_LARGE); } finally { largePayload.release(); } }
From source file:com.uber.tchannel.tracing.TracingPropagationTest.java
License:Open Source License
private static TraceResponse callDownstreamThrift(String remainingEncodings) throws Exception { ThriftRequest<Example> request = new ThriftRequest.Builder<Example>("tchannel-name", "Behavior::trace") .setTimeout(1, TimeUnit.MINUTES).setBody(new Example(remainingEncodings, 0)).build(); TFuture<ThriftResponse<Example>> responsePromise = subChannel.send(request, tchannel.getHost(), tchannel.getListeningPort()); ThriftResponse<Example> thriftResponse = responsePromise.get(); assertNull(thriftResponse.getError()); String json = thriftResponse.getBody(Example.class).getAString(); thriftResponse.release();/*from www . j av a2s . c o m*/ ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(json.length()); byteBuf.writeBytes(json.getBytes()); TraceResponse response = new JSONSerializer().decodeBody(byteBuf, TraceResponse.class); byteBuf.release(); return response; }
From source file:com.uber.tchannel.tracing.TracingPropagationTest.java
License:Open Source License
private static TraceResponse callDownstreamThriftAsync(String remainingEncodings) throws Exception { ThriftRequest<Example> request = new ThriftRequest.Builder<Example>("tchannel-name", "Behavior::asynctrace") .setTimeout(1, TimeUnit.MINUTES).setBody(new Example(remainingEncodings, 0)).build(); TFuture<ThriftResponse<Example>> responsePromise = subChannel.send(request, tchannel.getHost(), tchannel.getListeningPort()); ThriftResponse<Example> thriftResponse = responsePromise.get(); assertNull(thriftResponse.getError()); String json = thriftResponse.getBody(Example.class).getAString(); thriftResponse.release();/* w w w .j av a2s. c o m*/ ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(json.length()); byteBuf.writeBytes(json.getBytes()); TraceResponse response = new JSONSerializer().decodeBody(byteBuf, TraceResponse.class); byteBuf.release(); return response; }
From source file:com.xx_dev.apn.proxy.ApnProxyServer.java
License:Apache License
public void start() { int bossThreadCount = ApnProxyConfig.getConfig().getBossThreadCount(); int workerThreadCount = ApnProxyConfig.getConfig().getWorkerThreadCount(); int port = ApnProxyConfig.getConfig().getPort(); LoggerUtil.info(logger, "ApnProxy Server Listen on: " + port); ServerBootstrap serverBootStrap = new ServerBootstrap(); serverBootStrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); bossGroup = new NioEventLoopGroup(bossThreadCount); workerGroup = new NioEventLoopGroup(workerThreadCount); try {//from ww w . jav a2s . co m serverBootStrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port) .childHandler(new ApnProxyServerChannelInitializer()); serverBootStrap.bind().sync().channel().closeFuture().sync(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { logger.error("showdown the server"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.xx_dev.apn.proxy.expriment.HttpServer.java
License:Apache License
public static void main(String[] args) { ServerBootstrap serverBootStrap = new ServerBootstrap(); serverBootStrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); try {// ww w.jav a2s . c o m serverBootStrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup(2)) .channel(NioServerSocketChannel.class).localAddress(5000) .childHandler(new HttpServerChannelInitializer()); serverBootStrap.bind().sync().channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { } }