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

The following examples show how to use org.jboss.netty.channel.ChannelHandlerContext#getChannel() . 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: FpmSessionHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
        throws Exception {
    SocketAddress socketAddress = ctx.getChannel().getRemoteAddress();

    if (!(socketAddress instanceof InetSocketAddress)) {
        throw new IllegalStateException("Address type is not InetSocketAddress");
    }

    us = FpmPeer.fromSocketAddress((InetSocketAddress) socketAddress);

    if (!fpmListener.peerConnected(us)) {
        log.error("Received new FPM connection while already connected");
        ctx.getChannel().close();
        return;
    }

    channel = ctx.getChannel();
    fpmManager.addSessionChannel(e.getChannel());
    fpmManager.processStaticRoutes(e.getChannel());
}
 
Example 2
Source File: ClientChannelHandler.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    super.channelConnected(ctx, e);

    state = State.CONNECTED;
    inetAddress = ((InetSocketAddress) e.getChannel().getRemoteAddress()).getAddress();
    channel = ctx.getChannel();
    log.info("Channel connected Ip:" + inetAddress.getHostAddress());
}
 
Example 3
Source File: NettyDispatcher.java    From ikasoa with MIT License 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	if (e.getMessage() instanceof TNettyMessage) {
		TNettyMessage message = (TNettyMessage) e.getMessage();
		message.setProcessStartTimeMillis(System.currentTimeMillis());
		checkResponseOrderingRequirements(ctx, message);
		TNettyTransport messageTransport = new TNettyTransport(ctx.getChannel(), message);
		TProtocol protocol = protocolFactory.getProtocol(messageTransport);
		processRequest(ctx, message, messageTransport, protocol, protocol);
	} else
		ctx.sendUpstream(e);
}
 
Example 4
Source File: RaopRtpTimingHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
@Override
public void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent evt) throws Exception {
	
	channelClosed(ctx, evt);

	/* create synchronization thread if it isn't already running */
	if (synchronizationThread == null) {
		synchronizationThread = new Thread(new TimingRequester(ctx.getChannel()));
		synchronizationThread.setDaemon(true);
		synchronizationThread.setName("Time Synchronizer");
	}
	
	super.channelOpen(ctx, evt);
}
 
Example 5
Source File: ManageSieveChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void logout(ChannelHandlerContext ctx) {
    // logout on error not sure if that is the best way to handle it
    attributes.remove(ctx.getChannel());
    // 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 6
Source File: ImapChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void channelBound(final ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    ImapSession imapsession = new NettyImapSession(ctx.getChannel(), context, enabledCipherSuites, compress, plainAuthDisallowed,
        SessionId.generate());
    attributes.set(ctx.getChannel(), imapsession);
    try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
        super.channelBound(ctx, e);
    }
}
 
Example 7
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 8
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 9
Source File: NetworkEventHandler.java    From android-netty with Apache License 2.0 5 votes vote down vote up
/** An exception is occurred! */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
	LogByCodeLab.w(String.format("%s.exceptionCaught() Exception: %s", NetworkEventHandler.class.getSimpleName(), LogByCodeLab.getStringFromThrowable(e.getCause())));
	super.exceptionCaught(ctx, e);
	
	if(ctx.getChannel() != null && ctx.getChannel().isOpen()) {
		ctx.getChannel().close();
	} else {
		mService.scheduleToReconnect();
	}
}
 
Example 10
Source File: TestShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
@Override
protected Shuffle getShuffle(final Configuration conf) {
  return new Shuffle(conf) {
    @Override
    protected void verifyRequest(String appid, ChannelHandlerContext ctx,
        HttpRequest request, HttpResponse response, URL requestUri)
        throws IOException {
      SocketChannel channel = (SocketChannel)(ctx.getChannel());
      socketKeepAlive = channel.getConfig().isKeepAlive();
    }
  };
}
 
Example 11
Source File: ProgrammableTSOServer.java    From phoenix-omid with Apache License 2.0 4 votes vote down vote up
/**
 * Handle received messages
 */
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Object msg = e.getMessage();
    if (msg instanceof TSOProto.Request) {
        TSOProto.Request request = (TSOProto.Request) msg;
        Channel channel = ctx.getChannel();
        if (request.hasHandshakeRequest()) {
            checkHandshake(ctx, request.getHandshakeRequest());
            return;
        }
        if (!handshakeCompleted(ctx)) {
            LOG.info("handshake not completed");
            channel.close();
        }

        Response resp = responseQueue.poll();
        if (request.hasTimestampRequest()) {
            if (resp == null || resp.type != ResponseType.TIMESTAMP) {
                throw new IllegalStateException("Expecting TS response to send but got " + resp);
            }
            TimestampResponse tsResp = (TimestampResponse) resp;
            sendTimestampResponse(tsResp.startTS, channel);
        } else if (request.hasCommitRequest()) {
            if (resp == null) {
                throw new IllegalStateException("Expecting COMMIT response to send but got null");
            }
            switch (resp.type) {
                case COMMIT:
                    CommitResponse commitResp = (CommitResponse) resp;
                    sendCommitResponse(commitResp.startTS, commitResp.commitTS, channel);
                    break;
                case ABORT:
                    AbortResponse abortResp = (AbortResponse) resp;
                    sendAbortResponse(abortResp.startTS, channel);
                    break;
                default:
                    throw new IllegalStateException("Expecting COMMIT response to send but got " + resp.type);
            }
        } else {
            LOG.error("Invalid request {}", request);
            ctx.getChannel().close();
        }
    } else {
        LOG.error("Unknown message type", msg);
    }
}
 
Example 12
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 13
Source File: OspfInterfaceImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Process the Ls Request message.
 *
 * @param ospfMessage OSPF message instance.
 * @param ctx         channel handler context instance.
 */
void processLsRequestMessage(OspfMessage ospfMessage, ChannelHandlerContext ctx) {
    log.debug("OspfChannelHandler::processLsRequestMessage...!!!");
    Channel channel = ctx.getChannel();
    LsRequest lsrPacket = (LsRequest) ospfMessage;
    OspfNbr nbr = neighbouringRouter(lsrPacket.routerId().toString());

    if (nbr.getState() == OspfNeighborState.EXCHANGE || nbr.getState() == OspfNeighborState.LOADING ||
            nbr.getState() == OspfNeighborState.FULL) {

        LsRequest reqMsg = (LsRequest) ospfMessage;
        if (reqMsg.getLinkStateRequests().isEmpty()) {
            log.debug("Received Link State Request Vector is Empty ");
            return;
        } else {
            //Send the LsUpdate back
            ListIterator<LsRequestPacket> listItr = reqMsg.getLinkStateRequests().listIterator();
            while (listItr.hasNext()) {
                LsUpdate lsupdate = new LsUpdate();
                lsupdate.setOspfVer(OspfUtil.OSPF_VERSION);
                lsupdate.setOspftype(OspfPacketType.LSUPDATE.value());
                lsupdate.setRouterId(ospfArea.routerId());
                lsupdate.setAreaId(ospfArea.areaId());
                lsupdate.setAuthType(OspfUtil.NOT_ASSIGNED);
                lsupdate.setAuthentication(OspfUtil.NOT_ASSIGNED);
                lsupdate.setOspfPacLength(OspfUtil.NOT_ASSIGNED); // to calculate packet length
                lsupdate.setChecksum(OspfUtil.NOT_ASSIGNED);

                //limit to mtu
                int currentLength = OspfUtil.OSPF_HEADER_LENGTH + OspfUtil.FOUR_BYTES;
                int maxSize = mtu() -
                        OspfUtil.LSA_HEADER_LENGTH; // subtract a normal IP header.
                int noLsa = 0;
                while (listItr.hasNext()) {
                    LsRequestPacket lsRequest = listItr.next();
                    // to verify length of the LSA
                    LsaWrapper wrapper = ospfArea.getLsa(lsRequest.lsType(), lsRequest.linkStateId(),
                                                         lsRequest.ownRouterId());
                    if (wrapper != null) {
                        OspfLsa ospflsa = wrapper.ospfLsa();
                        if ((currentLength + ((LsaWrapperImpl) wrapper).lsaHeader().lsPacketLen()) >= maxSize) {
                            listItr.previous();
                            break;
                        }
                        if (ospflsa != null) {
                            lsupdate.addLsa(ospflsa);
                            noLsa++;

                            currentLength = currentLength + ((LsaWrapperImpl) wrapper).lsaHeader().lsPacketLen();
                        } else {
                            nbr.badLSReq(channel);
                        }
                    }
                }
                lsupdate.setNumberOfLsa(noLsa);
                //set the destination
                if (state() == OspfInterfaceState.DR ||
                        state() == OspfInterfaceState.BDR ||
                        state() == OspfInterfaceState.POINT2POINT) {
                    lsupdate.setDestinationIp(OspfUtil.ALL_SPF_ROUTERS);
                } else if (state() == OspfInterfaceState.DROTHER) {
                    lsupdate.setDestinationIp(OspfUtil.ALL_DROUTERS);
                }
                byte[] messageToWrite = getMessage(lsupdate);
                ctx.getChannel().write(messageToWrite);
            }
        }
    }
}