List of usage examples for io.netty.channel ChannelHandlerContext fireExceptionCaught
@Override ChannelHandlerContext fireExceptionCaught(Throwable cause);
From source file:net.tomp2p.message.TestMessage.java
License:Apache License
/** * Mock Nettys ChannelHandlerContext with the minimal functions. * /*from w w w . java 2 s . co m*/ * @param buf * The buffer to use for decoding * @param m2 * The message reference to store the result * @return The mocked ChannelHandlerContext */ @SuppressWarnings("unchecked") private ChannelHandlerContext mockChannelHandlerContext(final AlternativeCompositeByteBuf buf, final AtomicReference<Message> m2) { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); ByteBufAllocator alloc = mock(ByteBufAllocator.class); when(ctx.alloc()).thenReturn(alloc); when(alloc.ioBuffer()).thenReturn(buf); DatagramChannel dc = mock(DatagramChannel.class); when(ctx.channel()).thenReturn(dc); when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(null); Attribute<InetSocketAddress> attr = mock(Attribute.class); when(ctx.attr(any(AttributeKey.class))).thenReturn(attr); when(ctx.fireChannelRead(any())).then(new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); m2.set((Message) args[0]); return null; } }); when(ctx.fireExceptionCaught(any(Throwable.class))).then(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); for (Object obj : args) { if (obj instanceof Throwable) { ((Throwable) obj).printStackTrace(); } else { System.err.println("Err: " + obj); } } return null; } }); return ctx; }
From source file:nettyprivateprotocolclientdemo.HeartBeatReqHandler.java
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (heartBeat != null) { heartBeat.cancel(true);//from w ww . j av a 2 s .c om heartBeat = null; } ctx.fireExceptionCaught(cause); }
From source file:nettyprivateprotocolserverdemo.LoginAuthRespHandler.java
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { nodeCheck.remove(ctx.channel().remoteAddress().toString()); ctx.close();//w w w .j a va 2s . c om ctx.fireExceptionCaught(cause); }
From source file:nikoladasm.aspark.server.ServerHandler.java
License:Open Source License
private boolean WebSocketHandshake(HttpMethod method, String path, FullHttpRequest req, ChannelHandlerContext ctx) { if (method.equals(GET)) { final WebSocketHandler wsHandler = webSockets.handler(path); if (wsHandler == null) return false; Channel channel = ctx.channel(); final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(channel.pipeline(), req, path), null, true); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel); } else {//from w w w . j av a2 s . co m final ChannelFuture handshakeFuture = handshaker.handshake(channel, req); handshakeFuture.addListener((future) -> { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { channel.attr(WEBSOCKET_HANDLER_ATTR_KEY).set(wsHandler); channel.attr(HANDSHAKER_ATTR_KEY).set(handshaker); WebSocketContextImpl wsContext = new WebSocketContextImpl(channel); channel.attr(WEBSOCKET_CONTEXT_ATTR_KEY).set(wsContext); wsHandler.onConnect(wsContext); } }); } return true; } return false; }
From source file:org.apache.tinkerpop.gremlin.driver.handler.WebSocketClientHandler.java
License:Apache License
@Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { if (!handshakeFuture.isDone()) handshakeFuture.setFailure(cause); // let the GremlinResponseHandler take care of exception logging, channel closing, and cleanup ctx.fireExceptionCaught(cause); }
From source file:org.artJava.protocol.server.handlers.HeartBeatRespHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); cause.printStackTrace();/*from w w w.j a v a 2s . c o m*/ ctx.close(); ctx.fireExceptionCaught(cause); }
From source file:org.asynchttpclient.netty.handler.AsyncHttpClientHandler.java
License:Open Source License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { Throwable cause = getCause(e); if (cause instanceof PrematureChannelClosureException || cause instanceof ClosedChannelException) return;// w w w . j a va 2 s . c o m Channel channel = ctx.channel(); NettyResponseFuture<?> future = null; logger.debug("Unexpected I/O exception on channel {}", channel, cause); try { Object attribute = Channels.getAttribute(channel); if (attribute instanceof StreamedResponsePublisher) { ctx.fireExceptionCaught(e); // setting `attribute` to be the underlying future so that the // retry logic can kick-in attribute = ((StreamedResponsePublisher) attribute).future(); } if (attribute instanceof NettyResponseFuture<?>) { future = (NettyResponseFuture<?>) attribute; future.attachChannel(null, false); future.touch(); if (cause instanceof IOException) { // FIXME why drop the original exception and throw a new one? if (hasIOExceptionFilters) { if (!requestSender.applyIoExceptionFiltersAndReplayRequest(future, ChannelClosedException.INSTANCE, channel)) { // Close the channel so the recovering can occurs. Channels.silentlyCloseChannel(channel); } return; } } if (StackTraceInspector.recoverOnReadOrWriteException(cause)) { logger.debug("Trying to recover from dead Channel: {}", channel); future.pendingException = cause; return; } } else if (attribute instanceof Callback) { future = Callback.class.cast(attribute).future(); } } catch (Throwable t) { cause = t; } if (future != null) try { logger.debug("Was unable to recover Future: {}", future); requestSender.abort(channel, future, cause); handleException(future, e); } catch (Throwable t) { logger.error(t.getMessage(), t); } channelManager.closeChannel(channel); // FIXME not really sure // ctx.fireChannelRead(e); Channels.silentlyCloseChannel(channel); }
From source file:org.ballerinalang.test.util.websocket.server.WebSocketHeadersHandler.java
License:Open Source License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { log.error("Exception Caught: " + cause.getMessage()); ctx.pipeline().remove(this); ctx.fireExceptionCaught(cause); }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerAsymmetricHandler.java
License:Open Source License
private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId, OpenSecureChannelRequest request) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try {//from ww w. j av a2 s . c o m OpenSecureChannelResponse response = openSecureChannel(ctx, request); binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, response); checkMessageSize(messageBuffer); chunkEncoder.encodeAsymmetric(secureChannel, requestId, messageBuffer, MessageType.OpenSecureChannel, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding OpenSecureChannelResponse: {}", ex.getMessage(), ex); ctx.fireExceptionCaught(ex); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { if (!symmetricHandlerAdded) { UascServerSymmetricHandler symmetricHandler = new UascServerSymmetricHandler( stackServer, serializationQueue, secureChannel); ctx.pipeline().addBefore(ctx.name(), null, symmetricHandler); symmetricHandlerAdded = true; } CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); logger.debug("Sent OpenSecureChannelResponse."); } }); } catch (UaException e) { logger.error("Error installing security token: {}", e.getStatusCode(), e); ctx.close(); } catch (UaSerializationException e) { ctx.fireExceptionCaught(e); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerSymmetricHandler.java
License:Open Source License
private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3); // Skip messageType char chunkType = (char) buffer.readByte(); if (chunkType == 'A') { chunkBuffers.forEach(ByteBuf::release); chunkBuffers.clear();//from www . ja v a 2 s . co m } else { buffer.skipBytes(4); // Skip messageSize long secureChannelId = buffer.readUnsignedIntLE(); if (secureChannelId != secureChannel.getChannelId()) { throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid, "invalid secure channel id: " + secureChannelId); } int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (maxChunkCount > 0 && chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } if (chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { try { validateChunkHeaders(buffersToDecode); } catch (UaException e) { logger.error("Error validating chunk headers: {}", e.getMessage(), e); buffersToDecode.forEach(ReferenceCountUtil::safeRelease); ctx.fireExceptionCaught(e); return; } chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode, new ChunkDecoder.Callback() { @Override public void onDecodingError(UaException ex) { logger.error("Error decoding symmetric message: {}", ex.getMessage(), ex); ctx.close(); } @Override public void onMessageAborted(MessageAbortedException ex) { logger.warn("Received message abort chunk; error={}, reason={}", ex.getStatusCode(), ex.getMessage()); } @Override public void onMessageDecoded(ByteBuf message, long requestId) { UaRequestMessage request = (UaRequestMessage) binaryDecoder.setBuffer(message) .readMessage(null); stackServer.getConfig().getExecutor().execute(() -> { try { String endpointUrl = ctx.channel().attr(UascServerHelloHandler.ENDPOINT_URL_KEY) .get(); EndpointDescription endpoint = ctx.channel() .attr(UascServerAsymmetricHandler.ENDPOINT_KEY).get(); String path = EndpointUtil.getPath(endpointUrl); InetSocketAddress remoteSocketAddress = (InetSocketAddress) ctx.channel() .remoteAddress(); ServiceRequest serviceRequest = new ServiceRequest(stackServer, request, endpoint, secureChannel.getChannelId(), remoteSocketAddress.getAddress(), secureChannel.getRemoteCertificateBytes()); serviceRequest.getFuture().whenComplete((response, fault) -> { if (response != null) { sendServiceResponse(ctx, requestId, request, response); } else { UInteger requestHandle = request.getRequestHeader().getRequestHandle(); sendServiceFault(ctx, requestId, requestHandle, fault); } }); stackServer.onServiceRequest(path, serviceRequest); } catch (Throwable t) { logger.error("Error decoding UaRequestMessage", t); sendServiceFault(ctx, requestId, uint(0), t); } finally { message.release(); buffersToDecode.clear(); } }); } }); }); } } }