List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:org.neo4j.bolt.v1.transport.socket.SocketTransportHandlerTest.java
License:Open Source License
@Test public void logsAndClosesConnectionOnUnexpectedExceptions() throws Throwable { // Given/* www . j a v a 2 s.c o m*/ Session session = mock(Session.class); Channel ch = mock(Channel.class); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()).thenReturn(ch); when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); AssertableLogProvider logging = new AssertableLogProvider(); SocketTransportHandler handler = new SocketTransportHandler(protocolChooser(session), logging); // And Given a session has been established handler.channelRead(ctx, handshake()); // When Throwable cause = new Throwable("Oh no!"); handler.exceptionCaught(ctx, cause); // Then verify(session).close(); logging.assertExactly(inLog(SocketTransportHandler.class) .error(equalTo("Fatal error occurred when handling a client connection: Oh no!"), is(cause))); }
From source file:org.neo4j.ndp.transport.socket.ChunkedOutputTest.java
License:Open Source License
@Before public void setup() { ChannelHandlerContext ch = mock(ChannelHandlerContext.class); when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(ch.writeAndFlush(any())).thenAnswer(new Answer<Object>() { @Override//from w w w . ja va 2 s . c o m public Object answer(InvocationOnMock invocation) throws Throwable { ByteBuf byteBuf = (ByteBuf) invocation.getArguments()[0]; writtenData.limit(writtenData.position() + byteBuf.readableBytes()); byteBuf.readBytes(writtenData); return null; } }); out.setTargetChannel(ch); }
From source file:org.neo4j.ndp.transport.socket.SocketTransportHandler.java
License:Open Source License
private void chooseProtocolVersion(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { switch (protocolChooser.handleVersionHandshakeChunk(buffer)) { case PROTOCOL_CHOSEN: protocol = protocolChooser.chosenProtocol(); ctx.writeAndFlush(ctx.alloc().buffer(4).writeInt(protocol.version())); // If there is more data pending, the client optimistically sent this in its initial payload. It really // shouldn't be doing that since it can't know which versions we support, but here we are anyway. // Emulate a second call to channelRead, the remaining data in the buffer will be forwarded to the newly // selected protocol. if (buffer.readableBytes() > 0) { channelRead(ctx, buffer);//from w w w.j av a2 s . c o m } return; case NO_APPLICABLE_PROTOCOL: ctx.writeAndFlush(wrappedBuffer(new byte[] { 0, 0, 0, 0 })).sync().channel().close(); return; case PARTIAL_HANDSHAKE: return; } }
From source file:org.nosceon.titanite.body.AbstractRawBodyParser.java
License:Apache License
@Override public final void initialize(ChannelHandlerContext ctx, HttpRequest request) { this.content = ctx.alloc().compositeBuffer(); }
From source file:org.opencloudb.net.mysql.FrontendAuthenticator.java
License:Open Source License
protected void success(ChannelHandlerContext ctx, AuthPacket auth) { ConnectionInfo conInf = NettyUtil.getConnectionInfo(ctx); conInf.setUser(auth.user);/* w w w .ja va 2 s.c o m*/ conInf.setSchema(auth.database); conInf.setCharsetIndex(auth.charsetIndex); // conInf.setHandler(new FrontendCommandHandler(source)); if (LOGGER.isInfoEnabled()) { StringBuilder s = new StringBuilder(); s.append(ctx.channel()).append('\'').append(auth.user).append("' login success"); byte[] extra = auth.extra; if (extra != null && extra.length > 0) { s.append(",extra:").append(new String(extra)); } LOGGER.info(s.toString()); } ctx.writeAndFlush(ctx.alloc().ioBuffer(AUTH_OK.length).writeBytes(AUTH_OK)); FrontSession session = new FrontSession(ctx, MycatSystem.getInstance().getPrivileges().isReadOnly(conInf.getUser()), conInf); NettyUtil.removeConnectionInfo(ctx); NettyUtil.updateFrontSession(ctx, session); // to query hanlder NettyUtil.setConnectionHandler(ctx, FrontendCommandHandler.INSTANCE); ctx.read(); }
From source file:org.opencloudb.net.mysql.MySQLBackendAuthenticator.java
License:Open Source License
private void authenticate(ChannelHandlerContext ctx, BackMysqlConnection con) { AuthPacket packet = new AuthPacket(); packet.packetId = 1;/* ww w . j a v a 2s . c o m*/ packet.clientFlags = clientFlags; packet.maxPacketSize = 1024 * 1024 * 16; packet.charsetIndex = 0; packet.user = con.getUser(); try { packet.password = passwd(con.getPassword(), con.getHandshake()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } packet.database = con.getSchema(); ByteBuf buf = ctx.alloc().ioBuffer(128, 1024); packet.write(buf); ctx.writeAndFlush(buf); }
From source file:org.opencloudb.net.mysql.MySQLBackendAuthenticator.java
License:Open Source License
private void auth323(ChannelHandlerContext ctx, BackMysqlConnection con, byte packetId) { // ??323???/* w w w. j a va2s .c o m*/ Reply323Packet r323 = new Reply323Packet(); r323.packetId = ++packetId; String pass = con.getPassword(); if (pass != null && pass.length() > 0) { byte[] seed = con.getHandshake().seed; r323.seed = SecurityUtil.scramble323(pass, new String(seed)).getBytes(); } ByteBuf buffer = ctx.alloc().ioBuffer(128, 512); r323.write(buffer); ctx.writeAndFlush(buffer); }
From source file:org.ow2.petals.bc.gateway.commons.handlers.AuthenticatorSSLHandler.java
License:Open Source License
private void setUpSslHandlers(final ChannelHandlerContext ctx, final AbstractDomain domain, final @Nullable String certificate, final @Nullable String key, final @Nullable String passphrase, final @Nullable String remoteCertificate) throws SSLException { // TODO could we use certificate only for auth and not encryption? // TODO support openssl final SslHandler sslHandler; if (pdOrAuth.isB() && certificate != null && key != null) { // server side ssl, do not forget startTls so that our accept can be sent after the handler is added final ServiceUnitDataHandler handler = domain.getSUHandler(); final SslContextBuilder builder = SslContextBuilder .forServer(ServiceUnitUtil.getFile(handler.getInstallRoot(), certificate), ServiceUnitUtil.getFile(handler.getInstallRoot(), key), passphrase) .sslProvider(SslProvider.JDK).ciphers(null, IdentityCipherSuiteFilter.INSTANCE) .sessionCacheSize(0).sessionTimeout(0); if (remoteCertificate != null) { builder.trustManager(ServiceUnitUtil.getFile(handler.getInstallRoot(), remoteCertificate)) .clientAuth(ClientAuth.REQUIRE); }/* www . j a va2s.co m*/ // until https://github.com/netty/netty/issues/5170 is accepted // we need to create the handler by hand sslHandler = new SslHandler(builder.build().newEngine(ctx.alloc()), true); } else if (pdOrAuth.isA() && remoteCertificate != null) { // client side final String installRoot = domain.getSUHandler().getInstallRoot(); final SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(ServiceUnitUtil.getFile(installRoot, remoteCertificate)) .ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0); if (certificate != null && key != null) { builder.keyManager(ServiceUnitUtil.getFile(installRoot, certificate), ServiceUnitUtil.getFile(installRoot, key), passphrase); } sslHandler = builder.build().newHandler(ctx.alloc()); } else { sslHandler = null; } // For a server, it contains the transporter name and the consumer domain name (it was updated in channelRead0) // For a client, it contains the provider domain name (it was set by the component) final String logName = logger.getName(); // let's replace the debug logger with something specific to this consumer ctx.pipeline().replace(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.LOG_DEBUG_HANDLER, new LoggingHandler(logName, LogLevel.TRACE)); ctx.pipeline().replace(HandlerConstants.LOG_ERRORS_HANDLER, HandlerConstants.LOG_ERRORS_HANDLER, new LastLoggingHandler(logName + ".errors")); if (sslHandler != null) { // if there is a sslHandler, then we can only add the domain handler after the handshake is finished // if not we risk sending things too early in it sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() { @Override public void operationComplete(final @Nullable Future<Channel> future) throws Exception { assert future != null; if (!future.isSuccess()) { authenticationFuture.setFailure(future.cause()); } else { // I must keep the handler here until now in case there is an exception so that I can log it ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER, dhb.build(domain)); authenticationFuture.setSuccess(ctx.channel()); } } }); ctx.pipeline().addAfter(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.SSL_HANDLER, sslHandler); } if (pdOrAuth.isB()) { if (logger.isLoggable(Level.FINE)) { logger.fine("Sending an Accept (" + ctx.channel().remoteAddress() + ")"); } // this must be sent after the ssh handler is replaced (when using ssl) so that we are ready to receive ssl data right away // but this must be sent before the domain handler is replaced (when not using ssl), because it will send // data and it must arrive AFTER our Accept ctx.writeAndFlush(new AuthAccept()); } // else it is done in the FutureListener if (sslHandler == null) { ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER, dhb.build(domain)); authenticationFuture.setSuccess(ctx.channel()); } }
From source file:org.pidome.server.system.network.http.Http2ClientHandler.java
@Override public void writeResponse(ChannelHandlerContext ctx, HttpResponseStatus status, byte[] buf, String fileType, String streamId, boolean cache) { String plainIp = HttpRequestHandler.getPlainIp(ctx.channel().localAddress()); ByteBuf content = ctx.alloc().buffer(buf.length); content.writeBytes(buf);/*ww w . j a va 2 s . c o m*/ FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content); HttpUtil.setContentLength(response, response.content().readableBytes()); streamId(response, streamId); response.headers().set(HttpHeaderNames.CONTENT_TYPE, fileType); response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpRequestHandler.getContentTypeHeader(fileType)); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "https://" + plainIp + ((port != 80) ? ":" + port : "")); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 HTTP2"); if (cache == true) { DateTime dt = new DateTime(); HttpHeaderDateFormat dateFormat = HttpHeaderDateFormat.get(); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=3153600"); response.headers().set(HttpHeaderNames.EXPIRES, dateFormat.format(dt.plusMonths(12).toDate())); } else { response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, must-revalidate"); response.headers().set(HttpHeaderNames.EXPIRES, "Sat, 26 Jul 1997 05:00:00 GMT"); } ctx.writeAndFlush(response); }
From source file:org.pidome.server.system.network.http.HttpClientHandler.java
License:Apache License
/** * Writes the response to the output/*from w w w. java 2 s. c o m*/ * @param ctx The channel context * @param status The response status * @param buf The buffer containing the data to send. * @param fileType The file type. * @param streamId The Stream id (only used in http2) * @param cache (if cache headers should be send). */ @Override public final void writeResponse(ChannelHandlerContext ctx, HttpResponseStatus status, byte[] buf, String fileType, String streamId, boolean cache) { ByteBuf content = ctx.alloc().buffer(buf.length); content.writeBytes(buf); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content); HttpUtil.setContentLength(response, response.content().readableBytes()); // In case of SPDY protocol used. if (spdyId != null) { response.headers().set(SPDY_STREAM_ID, spdyId); response.headers().set(SPDY_STREAM_PRIO, 0); response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 SPDY"); } else { response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 HTTP1.1"); } response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpRequestHandler.getContentTypeHeader(fileType)); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "http" + ((ssl == true) ? "s" : "") + "://" + plainIp + ((port != 80) ? ":" + port : "")); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); if (cache == true) { DateTime dt = new DateTime(); HttpHeaderDateFormat dateFormat = HttpHeaderDateFormat.get(); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=3153600"); response.headers().set(HttpHeaderNames.EXPIRES, dateFormat.format(dt.plusMonths(12).toDate())); } else { response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, must-revalidate"); response.headers().set(HttpHeaderNames.EXPIRES, "Sat, 26 Jul 1997 05:00:00 GMT"); } if (keepAlive) { // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } else { // If keep-alive is off, close the connection once the content is fully written. ctx.write(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }