Java Code Examples for org.jboss.netty.channel.ChannelHandlerContext#getAttachment()

The following examples show how to use org.jboss.netty.channel.ChannelHandlerContext#getAttachment() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpResponseFrameworkHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e.getMessage();
        HttpRequest request = (HttpRequest) ctx.getAttachment();

        LOG.debug("handler: {} is calling response-handler: {}", tag, responseHandler.getClass().getSimpleName());
        responseHandler.responseReceived(new HttpRequestFrameworkAdapter(request), new HttpResponseFrameworkAdapter(response));

        ctx.setAttachment(null);
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.writeRequested(ctx, e);
}
 
Example 2
Source File: NettyDispatcher.java    From ikasoa with MIT License 6 votes vote down vote up
private static DispatcherContext getDispatcherContext(ChannelHandlerContext ctx) {

			DispatcherContext dispatcherContext;
			Object attachment = ctx.getAttachment();

			if (ObjectUtil.isNull(attachment)) {
				// 如果没有上下文就创建一个
				dispatcherContext = new DispatcherContext();
				ctx.setAttachment(dispatcherContext);
			} else if (attachment instanceof DispatcherContext)
				dispatcherContext = (DispatcherContext) attachment;
			else
				throw new IllegalStateException(
						"NettyDispatcher handler context should be of type NettyDispatcher.DispatcherContext .");

			return dispatcherContext;
		}
 
Example 3
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
		throws Exception {
	Channel ch = e.getChannel();
	Throwable cause = e.getCause();

	if (log.isDebugEnabled())
		log.debug("I/O Exception during read or doConnect: ", cause);
	if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
		NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();

		if (future!= null){
			future.getAsyncHandler().onThrowable(cause);
		}
	}

	if (log.isDebugEnabled()){
		log.debug(e);
		log.debug(ch);
	}
}
 
Example 4
Source File: ImapRequestFrameDecoder.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized ChannelBuffer newCumulationBuffer(ChannelHandlerContext ctx, int minimumCapacity) {
    Map<String, Object> attachment = (Map<String, Object>) ctx.getAttachment();
    Object sizeAsObject = attachment.get(NEEDED_DATA);
    if (sizeAsObject != null) {
        @SuppressWarnings("unchecked")
        int size = (Integer) sizeAsObject;

        if (size > 0) {
            int sanitizedInMemorySizeLimit = Math.max(0, inMemorySizeLimit);
            int sanitizedSize = Math.min(sanitizedInMemorySizeLimit, size);

            return ChannelBuffers.dynamicBuffer(sanitizedSize, ctx.getChannel().getConfig().getBufferFactory());
        }
    }
    return super.newCumulationBuffer(ctx, minimumCapacity);
}
 
Example 5
Source File: BasicChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try (Closeable closeable = mdcContextFactory.from(protocol, ctx)) {
        ProtocolSession session = (ProtocolSession) ctx.getAttachment();
        LOGGER.info("Connection closed for {}", session.getRemoteAddress().getAddress().getHostAddress());
        cleanup(ctx);

        super.channelClosed(ctx, e);
    }
}
 
Example 6
Source File: BgpMessageDecoder.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
    log.debug("MESSAGE IS RECEIVED.");
    if (!channel.isConnected()) {
        log.info("Channel is not connected.");
        return null;
    }

    HexDump.dump(buffer);

    BgpMessageReader<BgpMessage> reader = BgpFactories.getGenericReader();
    List<BgpMessage> msgList = (List<BgpMessage>) ctx.getAttachment();

    if (msgList == null) {
        msgList = new LinkedList<>();
    }

    try {
        while (buffer.readableBytes() > 0) {
            buffer.markReaderIndex();
            BgpHeader bgpHeader = new BgpHeader();
            BgpMessage message = reader.readFrom(buffer, bgpHeader);
            msgList.add(message);
        }
        ctx.setAttachment(null);
        return msgList;
    } catch (Exception e) {
        log.debug("Bgp protocol message decode error");
        buffer.resetReaderIndex();
        buffer.discardReadBytes();
        ctx.setAttachment(msgList);
    }
    return null;
}
 
Example 7
Source File: PcepMessageDecoder.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer buffer) throws Exception {
    log.debug("Message received.");
    if (!channel.isConnected()) {
        log.info("Channel is not connected.");
        // In testing, I see decode being called AFTER decode last.
        // This check avoids that from reading corrupted frames
        return null;
    }

    HexDump.pcepHexDump(buffer);

    // Buffer can contain multiple messages, also may contain out of bound message.
    // Read the message one by one from buffer and parse it. If it encountered out of bound message,
    // then mark the reader index and again take the next chunk of messages from the channel
    // and parse again from the marked reader index.
    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    List<PcepMessage> msgList = (List<PcepMessage>) ctx.getAttachment();

    if (msgList == null) {
        msgList = new LinkedList<>();
    }

    try {
        while (buffer.readableBytes() > 0) {
            buffer.markReaderIndex();
            PcepMessage message = reader.readFrom(buffer);
            msgList.add(message);
        }
        ctx.setAttachment(null);
        return msgList;
    } catch (PcepOutOfBoundMessageException e) {
        log.debug("PCEP message decode error");
        buffer.resetReaderIndex();
        buffer.discardReadBytes();
        ctx.setAttachment(msgList);
    }
    return null;
}
 
Example 8
Source File: SMTPChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Cleanup temporary files
 */
@Override
protected void cleanup(ChannelHandlerContext ctx) {
    // Make sure we dispose everything on exit on session close
    SMTPSession smtpSession = (SMTPSession) ctx.getAttachment();

    if (smtpSession != null) {
        smtpSession.getAttachment(SMTPConstants.MAIL, State.Transaction).ifPresent(LifecycleUtil::dispose);
        smtpSession.getAttachment(SMTPConstants.DATA_MIMEMESSAGE_STREAMSOURCE, State.Transaction).ifPresent(LifecycleUtil::dispose);
    }

    super.cleanup(ctx);
}
 
Example 9
Source File: ImapChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
        imapCommandsMetric.increment();
        ImapSession session = (ImapSession) attributes.get(ctx.getChannel());
        ImapResponseComposer response = (ImapResponseComposer) ctx.getAttachment();
        ImapMessage message = (ImapMessage) e.getMessage();
        ChannelPipeline cp = ctx.getPipeline();

        try {
            if (cp.get(NettyConstants.EXECUTION_HANDLER) != null) {
                cp.addBefore(NettyConstants.EXECUTION_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
            } else {
                cp.addBefore(NettyConstants.CORE_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);

            }
            final ResponseEncoder responseEncoder = new ResponseEncoder(encoder, response);
            processor.process(message, responseEncoder, session);

            if (session.getState() == ImapSessionState.LOGOUT) {
                // Make sure we close the channel after all the buffers were flushed out
                Channel channel = ctx.getChannel();
                if (channel.isConnected()) {
                    channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
            final IOException failure = responseEncoder.getFailure();

            if (failure != null) {
                LOGGER.info(failure.getMessage());
                LOGGER.debug("Failed to write {}", message, failure);
                throw failure;
            }
        } finally {
            ctx.getPipeline().remove(NettyConstants.HEARTBEAT_HANDLER);
        }

        super.messageReceived(ctx, e);
    }
}
 
Example 10
Source File: BasicChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Cleanup the channel
 */
protected void cleanup(ChannelHandlerContext ctx) {
    ProtocolSession session = (ProtocolSession) ctx.getAttachment();
    if (session != null) {
        session.resetState();
        session = null;
    }
}
 
Example 11
Source File: NettyRpcServerHandler.java    From voyage with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
		throws Exception {
	RpcRequest request = (RpcRequest) ctx.getAttachment();
	if (e.getCause() instanceof ReadTimeoutException) {
		// The connection was OK but there was no traffic for last period.
		logger.warn("Disconnecting due to no inbound traffic");
	} else {
		logger.error("", e);
	}
	e.getChannel().close().awaitUninterruptibly();
}
 
Example 12
Source File: BasicChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Call the {@link LineHandler} 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    try (Closeable closeable = mdcContextFactory.from(protocol, ctx)) {
        ProtocolSession pSession = (ProtocolSession) ctx.getAttachment();
        LinkedList<LineHandler> lineHandlers = chain.getHandlers(LineHandler.class);
        LinkedList<ProtocolHandlerResultHandler> resultHandlers = chain.getHandlers(ProtocolHandlerResultHandler.class);


        if (lineHandlers.size() > 0) {

            ChannelBuffer buf = (ChannelBuffer) e.getMessage();
            LineHandler lHandler = (LineHandler) lineHandlers.getLast();
            long start = System.currentTimeMillis();
            Response response = lHandler.onLine(pSession, buf.toByteBuffer());
            long executionTime = System.currentTimeMillis() - start;

            for (ProtocolHandlerResultHandler resultHandler : resultHandlers) {
                response = resultHandler.onResponse(pSession, response, executionTime, lHandler);
            }
            if (response != null) {
                // TODO: This kind of sucks but I was able to come up with something more elegant here
                ((ProtocolSessionImpl) pSession).getProtocolTransport().writeResponse(response, pSession);
            }

        }

        super.messageReceived(ctx, e);
    }
}
 
Example 13
Source File: BasicChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try (Closeable closeable = mdcContextFactory.from(protocol, ctx)) {
        List<DisconnectHandler> connectHandlers = chain.getHandlers(DisconnectHandler.class);
        ProtocolSession session = (ProtocolSession) ctx.getAttachment();
        if (connectHandlers != null) {
            for (DisconnectHandler connectHandler : connectHandlers) {
                connectHandler.onDisconnect(session);
            }
        }
        super.channelDisconnected(ctx, e);
    }
}
 
Example 14
Source File: BasicChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Call the {@link ConnectHandler} instances which are stored in the {@link ProtocolHandlerChain}
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try (Closeable closeable = mdcContextFactory.from(protocol, ctx)) {
        List<ConnectHandler> connectHandlers = chain.getHandlers(ConnectHandler.class);
        List<ProtocolHandlerResultHandler> resultHandlers = chain.getHandlers(ProtocolHandlerResultHandler.class);
        ProtocolSession session = (ProtocolSession) ctx.getAttachment();
        LOGGER.info("Connection established from {}", session.getRemoteAddress().getAddress().getHostAddress());
        if (connectHandlers != null) {
            for (ConnectHandler cHandler : connectHandlers) {
                long start = System.currentTimeMillis();
                Response response = cHandler.onConnect(session);
                long executionTime = System.currentTimeMillis() - start;

                for (ProtocolHandlerResultHandler resultHandler : resultHandlers) {
                    resultHandler.onResponse(session, response, executionTime, cHandler);
                }
                if (response != null) {
                    // TODO: This kind of sucks but I was able to come up with something more elegant here
                    ((ProtocolSessionImpl) session).getProtocolTransport().writeResponse(response, session);
                }

            }
        }
        super.channelConnected(ctx, e);
    }
}
 
Example 15
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
	if (log.isDebugEnabled())
		log.debug("Channel closed: " + e.getState().toString());

	if (!isClose.get() && ctx.getAttachment() instanceof NettyResponseFuture<?>) {
		NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();

		if (future!= null && !future.isDone() && !future.isCancelled()){
			future.getAsyncHandler().onThrowable(new IOException("No response received. Connection timed out"));
		}
	}
	ctx.sendUpstream(e);
}
 
Example 16
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception {
	NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
	closeChannel(ctx);

	for (Entry<String,Channel> e: connectionsPool.entrySet()) {
		if (e.getValue().equals(ctx.getChannel())) {
			connectionsPool.remove(e.getKey());
			activeConnectionsCount.decrementAndGet();
			break;
		}
	}
	future.abort(new IOException("No response received. Connection timed out after " + config.getIdleConnectionTimeoutInMs()));
}
 
Example 17
Source File: ProgrammableTSOServer.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private boolean handshakeCompleted(ChannelHandlerContext ctx) {
    Object o = ctx.getAttachment();
    if (o instanceof TSOChannelContext) {
        TSOChannelContext tsoCtx = (TSOChannelContext) o;
        return tsoCtx.getHandshakeComplete();
    }
    return false;
}
 
Example 18
Source File: TSOChannelHandler.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private boolean handshakeCompleted(ChannelHandlerContext ctx) {

        Object o = ctx.getAttachment();
        if (o instanceof TSOChannelContext) {
            TSOChannelContext tsoCtx = (TSOChannelContext) o;
            return tsoCtx.getHandshakeComplete();
        }
        return false;

    }
 
Example 19
Source File: ImapChannelUpstreamHandler.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
        LOGGER.warn("Error while processing imap request", e.getCause());

        if (e.getCause() instanceof TooLongFrameException) {

            // Max line length exceeded
            // See RFC 2683 section 3.2.1
            //
            // "For its part, a server should allow for a command line of at
            // least
            // 8000 octets. This provides plenty of leeway for accepting
            // reasonable
            // length commands from clients. The server should send a BAD
            // response
            // to a command that does not end within the server's maximum
            // accepted
            // command length."
            //
            // See also JAMES-1190
            ImapResponseComposer composer = (ImapResponseComposer) ctx.getAttachment();
            composer.untaggedResponse(ImapConstants.BAD + " failed. Maximum command line length exceeded");

        } else {

            // logout on error not sure if that is the best way to handle it
            final ImapSession imapSession = (ImapSession) attributes.get(ctx.getChannel());
            if (imapSession != null) {
                imapSession.logout();
            }

            // Make sure we close the channel after all the buffers were flushed out
            Channel channel = ctx.getChannel();
            if (channel.isConnected()) {
                channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }

        }
    }
}
 
Example 20
Source File: HttpKeepAliveHandler.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) ctx.getAttachment();

    if (e.getMessage() instanceof HttpResponse) {

        HttpResponse response = (HttpResponse) e.getMessage();

        if (!response.isChunked()) {

            if (isKeepAliveSupported && isKeepAlive(request)) {

                LOG.debug("keep-alive IS implemented for this connection");

                // Add 'Content-Length' header only for a keep-alive connection.
                response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
                // Add keep alive header as per:
                // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
                response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

            } else {

                //not chunked and keep alive not supported, closing connection
                LOG.debug("keep-alive NOT implemented for this connection");
                e.getFuture().addListener(ChannelFutureListener.CLOSE);

            }

        } else {
            //response is chunked

            //don't send a content-length for chunked transfer-encoding
            response.removeHeader(CONTENT_LENGTH);

            //keep-alive explicitly off
            if (!isKeepAliveSupported || !isKeepAlive(request)) {
                response.removeHeader(CONNECTION);
                LOG.debug("keep-alive NOT implemented for this connection as it is explicitly turned off");
            } else {
                LOG.debug("keep-alive IMPLIED for this connection as it is chunked");
            }
        }
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("found chunk");
        if (((HttpChunk) e.getMessage()).isLast()) {

            if (!isKeepAliveSupported || !isKeepAlive(request)) {
                //keep alive explicitly off
                LOG.debug("reached the last chunk and keep alive is turned off so closing the connection");
                e.getFuture().addListener(ChannelFutureListener.CLOSE);
            }

        }
    } else {
        LOG.debug("found something else");
    }

    super.writeRequested(ctx, e);
}