List of usage examples for io.netty.channel ChannelHandlerContext attr
@Deprecated @Override <T> Attribute<T> attr(AttributeKey<T> key);
From source file:net.pms.network.RequestHandlerV2.java
License:Open Source License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof TooLongFrameException) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return;//from w w w .j a v a 2 s. c om } if (cause != null) { if (cause.getClass().equals(IOException.class)) { LOGGER.debug("Connection error: " + cause); StartStopListenerDelegate startStopListenerDelegate = ctx.attr(startStop).get(); if (startStopListenerDelegate != null) { LOGGER.debug("Premature end, stopping..."); startStopListenerDelegate.stop(); } } else if (!cause.getClass().equals(ClosedChannelException.class)) { LOGGER.debug("Caught exception: " + cause); } } if (ctx.channel().isActive()) { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } ctx.close(); }
From source file:net.tomp2p.message.TestMessage.java
License:Apache License
/** * Mock Nettys ChannelHandlerContext with the minimal functions. * /*www. j a v a 2s .c o 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:nz.co.fortytwo.signalk.server.CamelNettyHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send greeting for a new connection. ctx.write(Util.getWelcomeMsg().toString() + "\r\n"); ctx.flush();//www . ja v a 2 s . c o m String session = UUID.randomUUID().toString(); String localAddress = ctx.channel().localAddress().toString(); String remoteAddress = ctx.channel().remoteAddress().toString(); SubscriptionManagerFactory.getInstance().add(session, session, outputType, localAddress, remoteAddress); contextList.put(session, ctx); //make up headers ctx.attr(msgHeaders).set(getHeaders(ctx)); }
From source file:nz.co.fortytwo.signalk.server.CamelNettyHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { if (logger.isDebugEnabled()) logger.debug("Request:" + request); Exchange ex = new DefaultExchange(CamelContextFactory.getInstance()); ex.getIn().setBody(request);/* ww w .j a va 2s .c om*/ ex.getIn().getHeaders().putAll(ctx.attr(msgHeaders).get()); producer.asyncSend(producer.getDefaultEndpoint(), ex); }
From source file:org.apache.camel.component.netty4.http.handlers.HttpServerMultiplexChannelHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // store request, as this channel handler is created per pipeline HttpRequest request = (HttpRequest) msg; LOG.debug("Message received: {}", request); HttpServerChannelHandler handler = getHandler(request); if (handler != null) { Attribute<HttpServerChannelHandler> attr = ctx.attr(SERVER_HANDLER_KEY); // store handler as attachment attr.set(handler);/*from w ww . ja va2 s . c o m*/ if (msg instanceof HttpContent) { // need to hold the reference of content HttpContent httpContent = (HttpContent) msg; httpContent.content().retain(); } handler.channelRead(ctx, request); } else { // this resource is not found, so send empty response back HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); response.headers().set(Exchange.CONTENT_TYPE, "text/plain"); response.headers().set(Exchange.CONTENT_LENGTH, 0); ctx.writeAndFlush(response); ctx.close(); } }
From source file:org.apache.camel.component.netty4.http.handlers.HttpServerMultiplexChannelHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Attribute<HttpServerChannelHandler> attr = ctx.attr(SERVER_HANDLER_KEY); HttpServerChannelHandler handler = attr.get(); if (handler != null) { handler.exceptionCaught(ctx, cause); } else {//from w ww. ja v a 2 s . co m if (cause instanceof ClosedChannelException) { // The channel is closed so we do nothing here LOG.debug("Channel already closed. Ignoring this exception."); return; } else { // we cannot throw the exception here LOG.warn( "HttpServerChannelHandler is not found as attachment to handle exception, send 404 back to the client.", cause); // Now we just send 404 back to the client HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); response.headers().set(Exchange.CONTENT_TYPE, "text/plain"); response.headers().set(Exchange.CONTENT_LENGTH, 0); ctx.writeAndFlush(response); ctx.close(); } } }
From source file:org.apache.giraph.comm.netty.handler.AuthorizeServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("messageReceived: Got " + msg.getClass()); }// w ww . j a va 2s . co m // Authorize: client is allowed to doRequest() if and only if the client // has successfully authenticated with this server. SaslNettyServer saslNettyServer = ctx.attr(NettyServer.CHANNEL_SASL_NETTY_SERVERS).get(); if (saslNettyServer == null) { LOG.warn("messageReceived: This client is *NOT* authorized to perform " + "this action since there's no saslNettyServer to " + "authenticate the client: " + "refusing to perform requested action: " + msg); return; } if (!saslNettyServer.isComplete()) { LOG.warn("messageReceived: This client is *NOT* authorized to perform " + "this action because SASL authentication did not complete: " + "refusing to perform requested action: " + msg); // Return now *WITHOUT* sending upstream here, since client // not authorized. return; } if (LOG.isDebugEnabled()) { LOG.debug("messageReceived: authenticated client: " + saslNettyServer.getUserName() + " is authorized to do request " + "on server."); } // We call fireChannelRead since the client is allowed to perform this // request. The client's request will now proceed to the next // pipeline component, namely, RequestServerHandler. ctx.fireChannelRead(msg); }
From source file:org.apache.giraph.comm.netty.handler.SaslClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { WritableRequest decodedMessage = decode(ctx, msg); // Generate SASL response to server using Channel-local SASL client. SaslNettyClient saslNettyClient = ctx.attr(NettyClient.SASL).get(); if (saslNettyClient == null) { throw new Exception( "handleUpstream: saslNettyClient was unexpectedly " + "null for channel: " + ctx.channel()); }/*from w w w . java 2 s . c o m*/ if (decodedMessage.getClass() == SaslCompleteRequest.class) { if (LOG.isDebugEnabled()) { LOG.debug("handleUpstream: Server has sent us the SaslComplete " + "message. Allowing normal work to proceed."); } synchronized (saslNettyClient.getAuthenticated()) { saslNettyClient.getAuthenticated().notify(); } if (!saslNettyClient.isComplete()) { LOG.error("handleUpstream: Server returned a Sasl-complete message, " + "but as far as we can tell, we are not authenticated yet."); throw new Exception("handleUpstream: Server returned a " + "Sasl-complete message, but as far as " + "we can tell, we are not authenticated yet."); } // Remove SaslClientHandler and replace LengthFieldBasedFrameDecoder // from client pipeline. ctx.pipeline().remove(this); ctx.pipeline().replace("length-field-based-frame-decoder", "fixed-length-frame-decoder", new FixedLengthFrameDecoder(RequestServerHandler.RESPONSE_BYTES)); return; } SaslTokenMessageRequest serverToken = (SaslTokenMessageRequest) decodedMessage; if (LOG.isDebugEnabled()) { LOG.debug( "handleUpstream: Responding to server's token of length: " + serverToken.getSaslToken().length); } // Generate SASL response (but we only actually send the response if it's // non-null. byte[] responseToServer = saslNettyClient.saslResponse(serverToken); if (responseToServer == null) { // If we generate a null response, then authentication has completed (if // not, warn), and return without sending a response back to the server. if (LOG.isDebugEnabled()) { LOG.debug( "handleUpstream: Response to server is null: " + "authentication should now be complete."); } if (!saslNettyClient.isComplete()) { LOG.warn("handleUpstream: Generated a null response, " + "but authentication is not complete."); } return; } else { if (LOG.isDebugEnabled()) { LOG.debug("handleUpstream: Response to server token has length:" + responseToServer.length); } } // Construct a message containing the SASL response and send it to the // server. SaslTokenMessageRequest saslResponse = new SaslTokenMessageRequest(responseToServer); ctx.channel().writeAndFlush(saslResponse); }
From source file:org.apache.giraph.comm.netty.handler.SaslServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("messageReceived: Got " + msg.getClass()); }/*from ww w . j av a2s . c o m*/ WritableRequest writableRequest = (WritableRequest) msg; // Simulate a closed connection on the first request (if desired) // TODO: Move out into a separate, dedicated handler. if (closeFirstRequest && !ALREADY_CLOSED_FIRST_REQUEST) { LOG.info("messageReceived: Simulating closing channel on first " + "request " + writableRequest.getRequestId() + " from " + writableRequest.getClientId()); setAlreadyClosedFirstRequest(); ctx.close(); return; } if (writableRequest.getType() == RequestType.SASL_TOKEN_MESSAGE_REQUEST) { // initialize server-side SASL functionality, if we haven't yet // (in which case we are looking at the first SASL message from the // client). SaslNettyServer saslNettyServer = ctx.attr(NettyServer.CHANNEL_SASL_NETTY_SERVERS).get(); if (saslNettyServer == null) { if (LOG.isDebugEnabled()) { LOG.debug("No saslNettyServer for " + ctx.channel() + " yet; creating now, with secret manager: " + secretManager); } try { saslNettyServer = new SaslNettyServer(secretManager, AuthMethod.SIMPLE); } catch (IOException ioe) { //TODO: throw new RuntimeException(ioe); } ctx.attr(NettyServer.CHANNEL_SASL_NETTY_SERVERS).set(saslNettyServer); } else { if (LOG.isDebugEnabled()) { LOG.debug("Found existing saslNettyServer on server:" + ctx.channel().localAddress() + " for client " + ctx.channel().remoteAddress()); } } ((SaslTokenMessageRequest) writableRequest).processToken(saslNettyServer); // Send response to client. ctx.write(writableRequest); if (saslNettyServer.isComplete()) { // If authentication of client is complete, we will also send a // SASL-Complete message to the client. if (LOG.isDebugEnabled()) { LOG.debug("SASL authentication is complete for client with " + "username: " + saslNettyServer.getUserName()); } SaslCompleteRequest saslComplete = new SaslCompleteRequest(); ctx.write(saslComplete); if (LOG.isDebugEnabled()) { LOG.debug( "Removing SaslServerHandler from pipeline since SASL " + "authentication is complete."); } ctx.pipeline().remove(this); } ctx.flush(); // do not send upstream to other handlers: no further action needs to be // done for SASL_TOKEN_MESSAGE_REQUEST requests. return; } else { // Client should not be sending other-than-SASL messages before // SaslServerHandler has removed itself from the pipeline. Such non-SASL // requests will be denied by the Authorize channel handler (the next // handler upstream in the server pipeline) if SASL authentication has // not completed. LOG.warn("Sending upstream an unexpected non-SASL message : " + writableRequest); ctx.fireChannelRead(msg); } }
From source file:org.apache.tinkerpop.gremlin.server.handler.SaslAuthenticationHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof RequestMessage) { final RequestMessage requestMessage = (RequestMessage) msg; final Attribute<Authenticator.SaslNegotiator> negotiator = ctx.attr(StateKey.NEGOTIATOR); final Attribute<RequestMessage> request = ctx.attr(StateKey.REQUEST_MESSAGE); if (negotiator.get() == null) { // First time through so save the request and send an AUTHENTICATE challenge with no data negotiator.set(authenticator.newSaslNegotiator(getRemoteInetAddress(ctx))); request.set(requestMessage); final ResponseMessage authenticate = ResponseMessage.build(requestMessage) .code(ResponseStatusCode.AUTHENTICATE).create(); ctx.writeAndFlush(authenticate); } else {//from www. j a v a2 s . c o m if (requestMessage.getOp().equals(Tokens.OPS_AUTHENTICATION) && requestMessage.getArgs().containsKey(Tokens.ARGS_SASL)) { final Object saslObject = requestMessage.getArgs().get(Tokens.ARGS_SASL); final byte[] saslResponse; if (saslObject instanceof byte[]) { saslResponse = (byte[]) saslObject; } else if (saslObject instanceof String) { saslResponse = BASE64_DECODER.decode((String) saslObject); } else { final ResponseMessage error = ResponseMessage.build(request.get()) .statusMessage("Incorrect type for : " + Tokens.ARGS_SASL + " - byte[] or base64 encoded String is expected") .code(ResponseStatusCode.REQUEST_ERROR_MALFORMED_REQUEST).create(); ctx.writeAndFlush(error); return; } try { final byte[] saslMessage = negotiator.get().evaluateResponse(saslResponse); if (negotiator.get().isComplete()) { // todo: do something with this user final AuthenticatedUser user = negotiator.get().getAuthenticatedUser(); // If we have got here we are authenticated so remove the handler and pass // the original message down the pipeline for processing ctx.pipeline().remove(this); final RequestMessage original = request.get(); ctx.fireChannelRead(original); } else { // not done here - send back the sasl message for next challenge. note that we send back // the base64 encoded sasl as well as the byte array. the byte array will eventually be // phased out, but is present now for backward compatibility in 3.2.x final Map<String, Object> metadata = new HashMap<>(); metadata.put(Tokens.ARGS_SASL, BASE64_ENCODER.encodeToString(saslMessage)); final ResponseMessage authenticate = ResponseMessage.build(requestMessage) .statusAttributes(metadata).code(ResponseStatusCode.AUTHENTICATE) .result(saslMessage).create(); ctx.writeAndFlush(authenticate); } } catch (AuthenticationException ae) { final ResponseMessage error = ResponseMessage.build(request.get()) .statusMessage(ae.getMessage()).code(ResponseStatusCode.UNAUTHORIZED).create(); ctx.writeAndFlush(error); } } else { final ResponseMessage error = ResponseMessage.build(requestMessage) .statusMessage("Failed to authenticate").code(ResponseStatusCode.UNAUTHORIZED).create(); ctx.writeAndFlush(error); } } } else { logger.warn("{} only processes RequestMessage instances - received {} - channel closing", this.getClass().getSimpleName(), msg.getClass()); ctx.close(); } }