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

The following examples show how to use org.jboss.netty.channel.ChannelHandlerContext#setAttachment() . 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: TSOChannelHandler.java    From phoenix-omid with Apache License 2.0 6 votes vote down vote up
private void checkHandshake(final ChannelHandlerContext ctx, TSOProto.HandshakeRequest request) {

        TSOProto.HandshakeResponse.Builder response = TSOProto.HandshakeResponse.newBuilder();
        if (request.hasClientCapabilities()) {

            response.setClientCompatible(true)
                    .setServerCapabilities(TSOProto.Capabilities.newBuilder().build());
            TSOChannelContext tsoCtx = new TSOChannelContext();
            tsoCtx.setHandshakeComplete();
            ctx.setAttachment(tsoCtx);
        } else {
            response.setClientCompatible(false);
        }
        response.setLowLatency(config.getLowLatency());
        ctx.getChannel().write(TSOProto.Response.newBuilder().setHandshakeResponse(response.build()).build());

    }
 
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: 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 4
Source File: ManageSieveChannelUpstreamHandler.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try (Closeable closeable = ManageSieveMDCContext.from(ctx, attributes)) {
        InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
        logger.info("Connection established from {}", address.getAddress().getHostAddress());

        Session session = new SettableSession();
        if (sslServer) {
            session.setSslEnabled(true);
        }
        attributes.set(ctx.getChannel(), session);
        ctx.setAttachment(new ChannelManageSieveResponseWriter(ctx.getChannel()));
        super.channelBound(ctx, e);
        ((ChannelManageSieveResponseWriter) ctx.getAttachment()).write(manageSieveProcessor.getAdvertisedCapabilities());
    }
}
 
Example 5
Source File: NettyRpcServerHandler.java    From voyage with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	Object msg = e.getMessage();
	if (!(msg instanceof RpcRequest)) {
		logger.error("not RpcRequest received!");
		return;
	}
	RpcRequest request = (RpcRequest) msg;
	ctx.setAttachment(request);

	RpcResponse response = new RpcResponse(request.getRequestID());
	try {
		Object result = handle(request);
		response.setResult(result);
	} catch (Throwable t) {
		logger.error("handle rpc request fail! request:"+request, t);
		response.setException(t);
	}
	e.getChannel().write(response);
}
 
Example 6
Source File: ImapChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
        InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
        LOGGER.info("Connection established from {}", address.getAddress().getHostAddress());
        imapConnectionsMetric.increment();

        ImapResponseComposer response = new ImapResponseComposerImpl(new ChannelImapResponseWriter(ctx.getChannel()));
        ctx.setAttachment(response);

        // write hello to client
        response.untagged().message("OK").message(hello).end();
        super.channelConnected(ctx, e);
    }
}
 
Example 7
Source File: OpInsert.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public OpReply doOp( MongoChannelHandler handler, ChannelHandlerContext ctx, MessageEvent messageEvent ) {

    ApplicationInfo application = SubjectUtils.getApplication( Identifier.from( getDatabaseName() ) );

    if ( application == null ) {
        ctx.setAttachment( new IllegalArgumentException(
                String.format( "Could not find application with name '%s' ", getDatabaseName() ) ) );
        return null;
    }


    EntityManager em = handler.getEmf().getEntityManager( application.getId() );


    for ( BSONObject document : documents ) {
        try {
            //special case to serialize mongo ObjectId if required
            Object id = document.get( "_id" );

            if ( id instanceof ObjectId ) {
                document.put( "_id", ( ( ObjectId ) id ).toStringMongod() );
            }

            em.create( getCollectionName(), document.toMap() );
        }
        catch ( Exception e ) {
            logger.error( "Unable to insert mongo document {}", document, e );
            ctx.setAttachment( e );
        }
    }

    //insert never returns a response in mongo
    return null;
}
 
Example 8
Source File: HttpResponseFrameworkHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    LOG.debug("attaching message: {}", e.getMessage().getClass().getSimpleName());
    if (e.getMessage() instanceof HttpRequest) {
        ctx.setAttachment(e.getMessage());
    }
    super.messageReceived(ctx, e);
}
 
Example 9
Source File: HttpKeepAliveHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest && isKeepAliveSupported) {
        ctx.setAttachment(e.getMessage());
    }
    super.messageReceived(ctx, e);
}
 
Example 10
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 11
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 12
Source File: BasicChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try (Closeable closeable = mdcContextFactory.from(protocol, ctx)) {
        ctx.setAttachment(createSession(ctx));
        super.channelBound(ctx, e);
    }
}
 
Example 13
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
private void closeChannel(ChannelHandlerContext ctx) {
	// Catch any unexpected exception when marking the channel.
	ctx.setAttachment(new DiscardEvent());
	try{
		ctx.getChannel().setReadable(false);
	} catch (Exception ex){
		if (log.isTraceEnabled()){
			log.trace(ex);
		}
	}
}
 
Example 14
Source File: ProgrammableTSOServer.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private void checkHandshake(final ChannelHandlerContext ctx, TSOProto.HandshakeRequest request) {
    TSOProto.HandshakeResponse.Builder response = TSOProto.HandshakeResponse.newBuilder();
    if (request.hasClientCapabilities()) {

        response.setClientCompatible(true).setServerCapabilities(TSOProto.Capabilities.newBuilder().build());
        TSOChannelContext tsoCtx = new TSOChannelContext();
        tsoCtx.setHandshakeComplete();
        ctx.setAttachment(tsoCtx);
    } else {
        response.setClientCompatible(false);
    }
    ctx.getChannel().write(TSOProto.Response.newBuilder().setHandshakeResponse(response.build()).build());
}
 
Example 15
Source File: ImapRequestFrameDecoder.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    ctx.setAttachment(new HashMap<String, Object>());
    super.channelOpen(ctx, e);
}
 
Example 16
Source File: OpUpdate.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public OpReply doOp( MongoChannelHandler handler, ChannelHandlerContext ctx, MessageEvent messageEvent ) {

    ApplicationInfo application = SubjectUtils.getApplication( Identifier.from( getDatabaseName() ) );

    if ( application == null ) {
        ctx.setAttachment( new IllegalArgumentException(
                String.format( "Could not find application with name '%s' ", getDatabaseName() ) ) );
        return null;
    }

    EntityManager em = handler.getEmf().getEntityManager( application.getId() );

    Results results = null;
    Query q = MongoQueryParser.toNativeQuery( selector, 1000 );

    if ( q == null ) {
        ctx.setAttachment( new IllegalArgumentException( "Could not parse query" ) );
        return null;
    }

    try {
        do {
            if ( results != null ) {
                q.setCursor( results.getCursor() );
            }

            results = em.searchCollection( em.getApplicationRef(), getCollectionName(), q );

            // apply the update

            for ( Entity entity : results.getEntities() ) {
                em.updateProperties( entity, update.toMap() );
            }
        }
        while ( results != null && results.getCursor() != null );
    }
    catch ( Exception e ) {
        logger.error( "Unable to perform update with query {} and update {}",
                new Object[] { selector, update, e } );
        ctx.setAttachment( e );
    }

    return null;
}
 
Example 17
Source File: OpDelete.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public OpReply doOp( MongoChannelHandler handler, ChannelHandlerContext ctx, MessageEvent messageEvent ) {

    // perform the query
    Query query = MongoQueryParser.toNativeQuery( selector, 0 );

    // TODO TN set an error
    if ( query == null ) {
        return null;
    }

    query.setResultsLevel( Level.IDS );
    query.setLimit( BATCH_SIZE );

    ApplicationInfo application = SubjectUtils.getApplication( Identifier.from( getDatabaseName() ) );

    if ( application == null ) {
        ctx.setAttachment( new IllegalArgumentException(
                String.format( "Could not find application with name '%s' ", getDatabaseName() ) ) );
        return null;
    }

    // delete every result

    EntityManager em = handler.getEmf().getEntityManager( application.getId() );

    Results results = null;

    do {

        try {

            if ( results != null ) {
                query.setCursor( results.getCursor() );
            }

            results = em.searchCollection( em.getApplicationRef(), getCollectionName(), query );

            // now loop through all the ids and delete them
            for ( UUID id : results.getIds() ) {
                em.delete( new SimpleEntityRef( query.getEntityType(), id ) );
            }
        }
        catch ( Exception ex ) {
            logger.error( "Unable to delete object", ex );
            ctx.setAttachment( ex );
        }
    }
    while ( results.getCursor() != null );

    // return nothing on delete, like insert

    return null;
}