List of usage examples for io.netty.channel ChannelHandlerContext fireUserEventTriggered
@Override ChannelHandlerContext fireUserEventTriggered(Object evt);
From source file:io.grpc.alts.internal.TsiHandshakeHandler.java
License:Apache License
private void fireProtocolNegotiationEvent(ChannelHandlerContext ctx, TsiPeer peer, Object authContext, SecurityDetails details) {/* w w w. j a va 2 s . c om*/ checkState(pne != null, "negotiation not yet complete"); InternalProtocolNegotiators.negotiationLogger(ctx).log(ChannelLogLevel.INFO, "TsiHandshake finished"); ProtocolNegotiationEvent localPne = pne; Attributes.Builder attrs = InternalProtocolNegotiationEvent.getAttributes(localPne).toBuilder() .set(TSI_PEER_KEY, peer).set(AUTH_CONTEXT_KEY, authContext) .set(GrpcAttributes.ATTR_SECURITY_LEVEL, details.getSecurityLevel()); localPne = InternalProtocolNegotiationEvent.withAttributes(localPne, attrs.build()); localPne = InternalProtocolNegotiationEvent.withSecurity(localPne, details.getSecurity()); ctx.fireUserEventTriggered(localPne); }
From source file:io.hekate.network.netty.NettyClientHandshakeHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (trace) {/*from ww w .ja va 2 s.co m*/ log.trace("Received handshake response [from={}, message={}]", id, msg); } NetworkProtocol handshakeMsg = (NetworkProtocol) msg; if (handshakeMsg.type() == NetworkProtocol.Type.HANDSHAKE_REJECT) { HandshakeReject reject = (HandshakeReject) handshakeMsg; String reason = reject.reason(); if (debug) { log.debug("Server rejected connection [to={}, reason={}]", id, reason); } ctx.fireExceptionCaught(new ConnectException(reason)); } else { HandshakeAccept accept = (HandshakeAccept) handshakeMsg; // Unregister self from the pipeline (handshake is a one time event). ctx.pipeline().remove(this); // Fire handshake event. ctx.fireUserEventTriggered(new NettyClientHandshakeEvent(accept)); } }
From source file:io.lettuce.core.PlainChannelInitializer.java
License:Apache License
static void pingBeforeActivate(AsyncCommand<?, ?, ?> cmd, CompletableFuture<Boolean> initializedFuture, ChannelHandlerContext ctx, ClientResources clientResources, Duration timeout) throws Exception { ctx.fireUserEventTriggered(new PingBeforeActivate(cmd)); Runnable timeoutGuard = () -> { if (cmd.isDone() || initializedFuture.isDone()) { return; }// w ww . j av a 2s .c om initializedFuture.completeExceptionally(ExceptionFactory .createTimeoutException("Cannot initialize channel (PING before activate)", timeout)); }; Timeout timeoutHandle = clientResources.timer().newTimeout(t -> { if (clientResources.eventExecutorGroup().isShuttingDown()) { timeoutGuard.run(); return; } clientResources.eventExecutorGroup().submit(timeoutGuard); }, timeout.toNanos(), TimeUnit.NANOSECONDS); cmd.whenComplete((o, throwable) -> { timeoutHandle.cancel(); if (throwable == null) { ctx.fireChannelActive(); initializedFuture.complete(true); } else { initializedFuture.completeExceptionally(throwable); } }); }
From source file:io.liveoak.container.protocols.http.HttpResourceResponseEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, DefaultResourceResponse msg, List<Object> out) throws Exception { int responseStatusCode = 0; String responseMessage = null; HttpHeaders responseHeaders = new DefaultHttpHeaders(); boolean shouldEncodeState = false; boolean shouldCheckForHtmlApp = true; switch (msg.responseType()) { case CREATED: responseStatusCode = HttpResponseStatus.CREATED.code(); responseMessage = HttpResponseStatus.CREATED.reasonPhrase(); shouldEncodeState = true;/*from ww w. j av a 2s. co m*/ break; case READ: responseStatusCode = HttpResponseStatus.OK.code(); responseMessage = HttpResponseStatus.OK.reasonPhrase(); shouldEncodeState = true; break; case UPDATED: responseStatusCode = HttpResponseStatus.OK.code(); responseMessage = HttpResponseStatus.OK.reasonPhrase(); shouldEncodeState = true; break; case DELETED: responseStatusCode = HttpResponseStatus.OK.code(); responseMessage = HttpResponseStatus.OK.reasonPhrase(); shouldEncodeState = true; break; case ERROR: if (msg instanceof ResourceErrorResponse) { shouldEncodeState = true; shouldCheckForHtmlApp = false; switch (((DefaultResourceErrorResponse) msg).errorType()) { case NOT_AUTHORIZED: responseStatusCode = HttpResponseStatus.UNAUTHORIZED.code(); responseMessage = HttpResponseStatus.UNAUTHORIZED.reasonPhrase(); break; case FORBIDDEN: responseStatusCode = HttpResponseStatus.FORBIDDEN.code(); responseMessage = HttpResponseStatus.FORBIDDEN.reasonPhrase(); break; case NOT_ACCEPTABLE: responseStatusCode = HttpResponseStatus.NOT_ACCEPTABLE.code(); responseMessage = HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase(); break; case NO_SUCH_RESOURCE: responseStatusCode = HttpResponseStatus.NOT_FOUND.code(); responseMessage = HttpResponseStatus.NOT_FOUND.reasonPhrase(); break; case RESOURCE_ALREADY_EXISTS: responseStatusCode = HttpResponseStatus.NOT_ACCEPTABLE.code(); responseMessage = HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase(); break; case CREATE_NOT_SUPPORTED: responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code(); responseMessage = "Create not supported"; break; case READ_NOT_SUPPORTED: responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code(); responseMessage = "Read not supported"; break; case UPDATE_NOT_SUPPORTED: responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code(); responseMessage = "UpdateStep not supported"; break; case DELETE_NOT_SUPPORTED: responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code(); responseMessage = "Delete not supported"; break; case INTERNAL_ERROR: responseStatusCode = HttpResponseStatus.INTERNAL_SERVER_ERROR.code(); responseMessage = HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase(); break; } //TODO: add content values here to return proper error messages to the client // eg unique error id, short error message, link to page with more information, etc... //response.content().writeBytes(...) } break; case MOVED: if (msg instanceof ResourceMovedResponse) { ResourceMovedResponse resourceMovedResponse = (ResourceMovedResponse) msg; switch (resourceMovedResponse.movedType()) { case MOVED_PERMANENTLY: responseStatusCode = HttpResponseStatus.MOVED_PERMANENTLY.code(); responseMessage = HttpResponseStatus.MOVED_PERMANENTLY.reasonPhrase(); break; case MOVED_TEMPORARILY: responseStatusCode = HttpResponseStatus.FOUND.code(); responseMessage = HttpResponseStatus.FOUND.reasonPhrase(); break; } Integer maxAge = resourceMovedResponse.maxAge(); if (maxAge != null) { responseHeaders.add(HttpHeaders.Names.CACHE_CONTROL, "max-age=" + maxAge); } responseHeaders.add(HttpHeaders.Names.LOCATION, ((ResourceMovedResponse) msg).redirectURL()); } break; } DefaultHttpResponse response; HttpResponseStatus responseStatus; EncodingResult encodingResult = null; if (shouldEncodeState) { MediaTypeMatcher matcher = msg.inReplyTo().mediaTypeMatcher(); if (shouldCheckForHtmlApp) { Application app = msg.inReplyTo().requestContext().application(); if (app != null && app instanceof InternalApplication) { ResourcePath htmlAppPath = ((InternalApplication) app).htmlApplicationResourcePath(); if ((!(msg.resource() instanceof BinaryResource)) && (htmlAppPath != null)) { MediaType bestMatch = matcher.findBestMatch(this.codecManager.mediaTypes()); if (bestMatch == MediaType.HTML) { // HTML was requested and we have an HTML app ResourceRequest htmlAppRequest = new DefaultResourceRequest.Builder(RequestType.READ, htmlAppPath).mediaTypeMatcher(msg.inReplyTo().mediaTypeMatcher()) .requestAttributes(msg.inReplyTo().requestContext().requestAttributes()) .build(); ctx.channel().pipeline().fireChannelRead(htmlAppRequest); return; } } } } try { encodingResult = encodeState(msg.inReplyTo().requestContext(), matcher, msg); } catch (IncompatibleMediaTypeException e) { log.error("Incompatible media type", e); responseStatus = new HttpResponseStatus(HttpResponseStatus.NOT_ACCEPTABLE.code(), e.getMessage()); response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0); out.add(response); return; } catch (Throwable e) { log.error("Could not encode HTTP response", e); responseStatus = new HttpResponseStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase()); response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0); out.add(response); return; } } responseStatus = new HttpResponseStatus(responseStatusCode, responseMessage); if (encodingResult != null) { if (msg.resource() instanceof BinaryResource) { BinaryResource bin = (BinaryResource) msg.resource(); if (bin.contentLength() == 0) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0); } else { response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, responseStatus); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, bin.contentLength()); response.headers().add(HttpHeaders.Names.LOCATION, msg.resource().uri().toString()); response.headers().add(HttpHeaders.Names.CONTENT_TYPE, bin.mediaType()); final HttpResponse res = response; bin.readContent(msg.inReplyTo().requestContext(), new BinaryContentSink() { { ctx.write(res); } @Override public void close() { ctx.writeAndFlush(new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)); ctx.pipeline().fireUserEventTriggered(new RequestCompleteEvent(msg.requestId())); } @Override public void accept(ByteBuf byteBuf) { ctx.write(new DefaultHttpContent(byteBuf)); } }); return; } } else { ByteBuf content = encodingResult.encoded(); response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, content); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); if (msg.resource() != null) { response.headers().add(HttpHeaders.Names.LOCATION, msg.resource().uri().toString()); } else { response.headers().add(HttpHeaders.Names.LOCATION, msg.inReplyTo().resourcePath().toString()); } response.headers().add(HttpHeaders.Names.CONTENT_TYPE, encodingResult.mediaType()); } } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0); } response.headers().add(responseHeaders); out.add(response); ctx.fireUserEventTriggered(new RequestCompleteEvent(msg.requestId())); }
From source file:io.liveoak.container.ResourceStateHandler.java
License:Open Source License
/** * Encode (for some cheap value of 'encode') a resulting resource into a ResourceState. * * @param ctx//from ww w . j a va2 s . c o m * @param response The response to encode. * @throws Exception */ protected void encode(ChannelHandlerContext ctx, ResourceResponse response, ChannelPromise promise) { final ClientResourceResponse.ResponseType responseType = ClientResourceResponse.ResponseType.OK; if (response.resource() == null) { ctx.writeAndFlush(new ClientResourceResponseImpl(response.inReplyTo(), responseType, response.inReplyTo().resourcePath().toString(), null)); ctx.fireUserEventTriggered(new RequestCompleteEvent(response.requestId())); return; } final ResourceStateEncoder encoder = new ResourceStateEncoder(); RootEncodingDriver driver = new RootEncodingDriver(response.inReplyTo().requestContext(), encoder, response.resource(), () -> { ResourceState state = encoder.root(); response.setState(state); ctx.writeAndFlush(response, promise) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) .addListener(ChannelFutureListener.CLOSE_ON_FAILURE); }, t -> handleError(ctx, response.inReplyTo(), t)); try { driver.encode(); } catch (Throwable e) { handleError(ctx, response.inReplyTo(), e); } }
From source file:io.liveoak.container.ResourceStateHandler.java
License:Open Source License
private void handleError(ChannelHandlerContext ctx, ResourceRequest inReplyTo, Throwable e) { ErrorHandler.handleError(ctx, inReplyTo, e); ctx.fireUserEventTriggered(new RequestCompleteEvent(inReplyTo.requestId())); }
From source file:io.netty.handler.timeout.IdleStateActivityTracker.java
License:Apache License
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception { ctx.fireUserEventTriggered(evt); }
From source file:io.reactivex.netty.channel.ObservableConnection.java
License:Apache License
public ObservableConnection(final ChannelHandlerContext ctx, MetricEventsSubject<?> eventsSubject, ChannelMetricEventProvider metricEventProvider) { super(ctx, eventsSubject, metricEventProvider); this.eventsSubject = eventsSubject; this.metricEventProvider = metricEventProvider; inputSubject = PublishSubject.create(); ChannelHandlerContext firstContext = ctx.pipeline().firstContext(); firstContext.fireUserEventTriggered(new NewRxConnectionEvent(inputSubject)); }
From source file:io.urmia.proxy.HttpProxyFrontendHandler.java
License:Open Source License
private Channel openOutboundChannel(final ChannelHandlerContext ctx, String remoteHost, int remotePort, final int index) { log.info("proxy opening outbound channel to({}): {}:{}", index, remoteHost, remotePort); Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class) .handler(new HttpProxyBackendInitializer(ctx, index, directWriteBack)) .option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); Channel outboundChannel = f.channel(); f.addListener(new GenericFutureListener<ChannelFuture>() { @Override/*from ww w. j a va 2 s .c om*/ public void operationComplete(ChannelFuture futureC) throws Exception { if (futureC.isSuccess()) { futureC.channel().writeAndFlush(initHttpRequest) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture futureW) throws Exception { if (futureW.isSuccess()) onSuccessfulWrite(ctx, index); else { log.info("unable to write http request: {}", futureW.cause()); ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index)); } } }); } else { ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index)); } } }); return outboundChannel; }
From source file:io.vertx.core.net.impl.SslHandshakeCompletionHandler.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SniCompletionEvent) { // Shall we care ? SniCompletionEvent completion = (SniCompletionEvent) evt; Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR); val.set(completion.hostname()); } else if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent completion = (SslHandshakeCompletionEvent) evt; if (completion.isSuccess()) { ctx.pipeline().remove(this); handler.handle(Future.succeededFuture(ctx.channel())); } else {//from w w w. j a va 2 s . c om handler.handle(Future.failedFuture(completion.cause())); } } else { ctx.fireUserEventTriggered(evt); } }