List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.tesora.dve.db.mysql.portal.protocol.StreamValve.java
License:Open Source License
public static FlowControl wrap(final ChannelHandlerContext ctx) { final ChannelPipeline pipeline = ctx.pipeline(); return new FlowControl() { @Override/*from w w w . j av a2s . c o m*/ public void pauseSourceStreams() { StreamValve valve = locateValve(pipeline); valve.pause(pipeline); } @Override public void resumeSourceStreams() { StreamValve valve = locateValve(pipeline); valve.resume(pipeline); } }; }
From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java
License:Open Source License
private void resumeInput(ChannelHandlerContext ctx) { if (paused) { //make sure we don't recurse infinitely. paused = false;/* w w w.j av a2 s . c o m*/ ctx.channel().config().setAutoRead(true); ctx.pipeline().fireChannelRead(Unpooled.EMPTY_BUFFER); //this flushes any partial packets held upstream (may cause recursion). } }
From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java
License:Open Source License
private void sendResponseAndRemove(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); try {//from www . j a va2 s . com pauseInput(ctx);//stop incoming packets so we don't process the next request, we'll resume in the removal callback. MyMessage response; if (encounteredError == null) response = createLoadDataEOFMsg(myLoadDataInfileContext); else response = new MyErrorResponse(new PEException(encounteredError)); pipeline.writeAndFlush(response); pipeline.remove(this); } catch (Exception e) { ctx.channel().close(); } }
From source file:com.tongtech.tis.fsc.file.HttpStaticFileServerHandler.java
License:Apache License
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { URI requri = new URI(request.uri()); System.out.println("uri download: " + requri.getPath()); if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w ww.ja v a 2 s . com return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { logger.info("file is modified."); SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.topsec.bdc.platform.api.test.file.FileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { RandomAccessFile raf = null;// w w w .java2 s . c o m long length = -1; try { raf = new RandomAccessFile(msg, "r"); length = raf.length(); } catch (Exception e) { ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n'); return; } finally { if (length < 0 && raf != null) { raf.close(); } } ctx.write("OK: " + raf.length() + '\n'); if (ctx.pipeline().get(SslHandler.class) == null) { // SSL not enabled - can use zero-copy file transfer. ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length)); } else { // SSL enabled - cannot use zero-copy file transfer. ctx.write(new ChunkedFile(raf)); } ctx.writeAndFlush("\n"); }
From source file:com.topsec.bdc.platform.api.test.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w ww. j av a 2 s . c o m return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.turo.pushy.apns.BenchmarkApnsServer.java
License:Open Source License
public BenchmarkApnsServer(final InputStream certificateChainInputStream, final InputStream privateKeyPkcs8InputStream, final NioEventLoopGroup eventLoopGroup) throws SSLException { final SslContext sslContext; {//w ww . j a va2 s . com final SslProvider sslProvider; if (OpenSsl.isAvailable()) { if (OpenSsl.isAlpnSupported()) { sslProvider = SslProvider.OPENSSL; } else { sslProvider = SslProvider.JDK; } } else { sslProvider = SslProvider.JDK; } sslContext = SslContextBuilder.forServer(certificateChainInputStream, privateKeyPkcs8InputStream, null) .sslProvider(sslProvider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .clientAuth(ClientAuth.OPTIONAL) .applicationProtocolConfig( new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)) .build(); } this.bootstrap = new ServerBootstrap(); this.bootstrap.group(eventLoopGroup); this.bootstrap.channel(NioServerSocketChannel.class); this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); channel.pipeline().addLast(sslHandler); channel.pipeline() .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { context.pipeline().addLast( new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder() .initialSettings(new Http2Settings() .maxConcurrentStreams(MAX_CONCURRENT_STREAMS)) .build()); BenchmarkApnsServer.this.allChannels.add(context.channel()); } else { throw new IllegalStateException("Unexpected protocol: " + protocol); } } }); } }); }
From source file:com.turo.pushy.apns.MockApnsServer.java
License:Open Source License
protected MockApnsServer(final SslContext sslContext, final EventLoopGroup eventLoopGroup) { this.bootstrap = new ServerBootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else {/*from w w w .j a v a 2s . c o m*/ this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.bootstrap.channel(SocketChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group())); this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); channel.pipeline().addLast(sslHandler); channel.pipeline() .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { AbstractMockApnsServerHandler.AbstractMockApnsServerHandlerBuilder handlerBuilder; try { final SSLSession sslSession = sslHandler.engine().getSession(); // This will throw an exception if the peer hasn't authenticated (i.e. we're expecting // token authentication). final String principalName = sslSession.getPeerPrincipal().getName(); final Pattern pattern = Pattern.compile(".*UID=([^,]+).*"); final Matcher matcher = pattern.matcher(principalName); final String baseTopic; if (matcher.matches()) { baseTopic = matcher.group(1); } else { throw new IllegalArgumentException( "Client certificate does not specify a base topic."); } final TlsAuthenticationMockApnsServerHandler.TlsAuthenticationMockApnsServerHandlerBuilder tlsAuthenticationHandlerBuilder = new TlsAuthenticationMockApnsServerHandler.TlsAuthenticationMockApnsServerHandlerBuilder(); tlsAuthenticationHandlerBuilder.baseTopic(baseTopic); handlerBuilder = tlsAuthenticationHandlerBuilder; } catch (final SSLPeerUnverifiedException e) { // No need for alarm; this is an expected case final TokenAuthenticationMockApnsServerHandler.TokenAuthenticationMockApnsServerHandlerBuilder tokenAuthenticationHandlerBuilder = new TokenAuthenticationMockApnsServerHandler.TokenAuthenticationMockApnsServerHandlerBuilder(); tokenAuthenticationHandlerBuilder.verificationKeysByKeyId( MockApnsServer.this.verificationKeysByKeyId); tokenAuthenticationHandlerBuilder.topicsByVerificationKey( MockApnsServer.this.topicsByVerificationKey); tokenAuthenticationHandlerBuilder.emulateExpiredFirstToken( MockApnsServer.this.emulateExpiredFirstToken); handlerBuilder = tokenAuthenticationHandlerBuilder; } context.pipeline().addLast(handlerBuilder .initialSettings(new Http2Settings().maxConcurrentStreams(8)) .emulateInternalErrors(MockApnsServer.this.emulateInternalErrors) .deviceTokenExpirationsByTopic( MockApnsServer.this.deviceTokenExpirationsByTopic) .build()); MockApnsServer.this.allChannels.add(context.channel()); } else { throw new IllegalStateException("Unexpected protocol: " + protocol); } } }); } }); }
From source file:com.uber.tchannel.channels.PeerManager.java
License:Open Source License
public void add(ChannelHandlerContext ctx) { // Direction only matters for the init path when the // init handler hasn't been removed Connection.Direction direction = Connection.Direction.OUT; if (ctx.pipeline().names().contains("InitRequestHandler")) { direction = Connection.Direction.IN; }//from w w w .j a v a 2s .co m if (direction == Connection.Direction.IN) { return; } Channel channel = ctx.channel(); SocketAddress address = channel.remoteAddress(); Peer peer = findOrNewPeer(address); peer.handleActiveOutConnection(ctx); }
From source file:com.uber.tchannel.handlers.InitRequestHandler.java
License:Open Source License
@Override public void messageReceived(ChannelHandlerContext ctx, ByteBuf buf) throws Exception { Frame frame = MessageCodec.decode(MessageCodec.decode(buf)); switch (frame.getType()) { case InitRequest: InitRequestFrame initRequestFrameMessage = (InitRequestFrame) frame; if (initRequestFrameMessage.getVersion() == InitFrame.DEFAULT_VERSION) { InitResponseFrame initResponseFrame = new InitResponseFrame(initRequestFrameMessage.getId(), InitFrame.DEFAULT_VERSION); initResponseFrame.setHostPort(this.peerManager.getHostPort()); // TODO: figure out what to put here initResponseFrame.setProcessName("java-process"); MessageCodec.write(ctx, initResponseFrame); ctx.pipeline().remove(this); peerManager.setIdentified(ctx.channel(), initRequestFrameMessage.getHeaders()); } else {/*from ww w. j ava 2 s . c o m*/ sendError(ErrorType.FatalProtocolError, String.format("Expected Protocol version: %d, got version: %d", InitFrame.DEFAULT_VERSION, initRequestFrameMessage.getVersion()), frame.getId(), ctx); } break; default: sendError(ErrorType.FatalProtocolError, "The first frame should be an Init Request", frame.getId(), ctx); break; } }