Java Code Examples for org.jboss.netty.channel.ChannelHandlerContext

The following examples show how to use org.jboss.netty.channel.ChannelHandlerContext. These examples are extracted from open source projects.
Example 1
Project: parallec   File: UdpWorker.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {

    if (!hasCaughtException) {
        hasCaughtException = true;

        String errMsg = e.getCause().toString();
        logger.debug("UDP Handler exceptionCaught: {} . ", errMsg);
        e.getChannel().close();

        int statusCodeInt = 1;
        String statusCode = statusCodeInt + " FAILURE";

        udpWorker.onComplete(udpWorker.responseSb.toString(), true,
                errMsg, errMsg, statusCode, statusCodeInt);
    }
}
 
Example 2
Project: onos   File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses BGP UPDATE Attribute Type LOCAL_PREF.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param attrTypeCode the attribute type code
 * @param attrLen the attribute length (in octets)
 * @param attrFlags the attribute flags
 * @param message the message to parse
 * @return the parsed LOCAL_PREF value
 * @throws BgpMessage.BgpParseException
 */
private static long parseAttributeTypeLocalPref(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message)
    throws BgpMessage.BgpParseException {

    // Check the Attribute Length
    if (attrLen != BgpConstants.Update.LocalPref.LENGTH) {
        // ERROR: Attribute Length Error
        actionsBgpUpdateAttributeLengthError(
            bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
        String errorMsg = "Attribute Length Error";
        throw new BgpMessage.BgpParseException(errorMsg);
    }

    long localPref = message.readUnsignedInt();
    return localPref;
}
 
Example 3
Project: onos   File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Attribute Length Error: send NOTIFICATION and close the channel.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param attrTypeCode the attribute type code
 * @param attrLen the attribute length (in octets)
 * @param attrFlags the attribute flags
 * @param message the message with the data
 */
private static void actionsBgpUpdateAttributeLengthError(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message) {
    log.debug("BGP RX UPDATE Error from {}: Attribute Length Error",
              bgpSession.remoteInfo().address());

    //
    // ERROR: Attribute Length Error
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.ATTRIBUTE_LENGTH_ERROR;
    ChannelBuffer data =
        prepareBgpUpdateNotificationDataPayload(attrTypeCode, attrLen,
                                                attrFlags, message);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 4
Project: mt-flume   File: SyslogUDPSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent mEvent) {
  try {
    syslogUtils.setEventSize(maxsize);
    Event e = syslogUtils.extractEvent((ChannelBuffer)mEvent.getMessage());
    if (e == null) {
      return;
    }
    getChannelProcessor().processEvent(e);
    counterGroup.incrementAndGet("events.success");
  } catch (ChannelException ex) {
    counterGroup.incrementAndGet("events.dropped");
    logger.error("Error writting to channel", ex);
    return;
  }
}
 
Example 5
Project: big-c   File: RpcProgram.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  RpcInfo info = (RpcInfo) e.getMessage();
  RpcCall call = (RpcCall) info.header();
  
  SocketAddress remoteAddress = info.remoteAddress();
  if (LOG.isTraceEnabled()) {
    LOG.trace(program + " procedure #" + call.getProcedure());
  }
  
  if (this.progNumber != call.getProgram()) {
    LOG.warn("Invalid RPC call program " + call.getProgram());
    sendAcceptedReply(call, remoteAddress, AcceptState.PROG_UNAVAIL, ctx);
    return;
  }

  int ver = call.getVersion();
  if (ver < lowProgVersion || ver > highProgVersion) {
    LOG.warn("Invalid RPC call version " + ver);
    sendAcceptedReply(call, remoteAddress, AcceptState.PROG_MISMATCH, ctx);
    return;
  }
  
  handleInternal(ctx, info);
}
 
Example 6
Project: onos   File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Missing Well-known Attribute Error: send NOTIFICATION and close the
 * channel.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param missingAttrTypeCode the missing attribute type code
 */
private static void actionsBgpUpdateMissingWellKnownAttribute(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int missingAttrTypeCode) {
    log.debug("BGP RX UPDATE Error from {}: Missing Well-known Attribute: {}",
              bgpSession.remoteInfo().address(), missingAttrTypeCode);

    //
    // ERROR: Missing Well-known Attribute
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.MISSING_WELL_KNOWN_ATTRIBUTE;
    ChannelBuffer data = ChannelBuffers.buffer(1);
    data.writeByte(missingAttrTypeCode);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 7
Project: onos   File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Attribute Flags Error: send NOTIFICATION and close the channel.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param attrTypeCode the attribute type code
 * @param attrLen the attribute length (in octets)
 * @param attrFlags the attribute flags
 * @param message the message with the data
 */
private static void actionsBgpUpdateAttributeFlagsError(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message) {
    log.debug("BGP RX UPDATE Error from {}: Attribute Flags Error",
              bgpSession.remoteInfo().address());

    //
    // ERROR: Attribute Flags Error
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.ATTRIBUTE_FLAGS_ERROR;
    ChannelBuffer data =
        prepareBgpUpdateNotificationDataPayload(attrTypeCode, attrLen,
                                                attrFlags, message);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 8
Project: RDFS   File: ShuffleHandler.java    License: 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 (cause instanceof TooLongFrameException) {
    sendError(ctx, BAD_REQUEST);
    return;
  }

  LOG.error("Shuffle error: ", cause);
  shuffleMetrics.failedOutput();
  if (ch.isConnected()) {
    LOG.error("Shuffle error " + e);
    sendError(ctx, INTERNAL_SERVER_ERROR);
  }
}
 
Example 9
Project: pinpoint   File: DefaultPinpointClientHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    final Channel channel = e.getChannel();

    logger.debug("{} channelOpen() started. channel:{}", objectUniqName, channel);

    this.channel = channel;
}
 
Example 10
Project: dubbo-2.6.5   File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    try {
        handler.received(channel, e.getMessage());
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 11
Project: android-netty   File: FrameDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

	Object m = e.getMessage();
	if (!(m instanceof ChannelBuffer)) {
		ctx.sendUpstream(e);
		return;
	}

	ChannelBuffer input = (ChannelBuffer) m;
	if (!input.readable()) {
		return;
	}

	if (cumulation == null) {
		try {
			// the cumulation buffer is not created yet so just pass the
			// input to callDecode(...) method
			callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
		} finally {
			updateCumulation(ctx, input);
		}
	} else {
		input = appendToCumulation(input);
		try {
			callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
		} finally {
			updateCumulation(ctx, input);
		}
	}
}
 
Example 12
Project: whiteboard   File: MyClientHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception
{
	Log.i(TAG, "����˶Ͽ�����");
	if (mConnectStateListener != null)
	{
		mConnectStateListener.channelClosed();
	}
}
 
Example 13
Project: Flink-CEPplus   File: NetworkFailureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelClosed(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	Channel targetChannel = sourceToTargetChannels.get(event.getChannel());
	if (targetChannel == null) {
		return;
	}
	closeOnFlush(targetChannel);
	sourceToTargetChannels.remove(event.getChannel());
	onClose.accept(this);
}
 
Example 14
Project: parallec   File: TcpWorker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Why not use channelClosed: if fail to establish a channel 
 * (e.g. connection refused). will also call channelClosed. 
 *
 * @param ctx the ctx
 * @param e the e
 * @throws Exception the exception
 */
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)
        throws Exception {
    logger.debug("channel is closed. ");
    
    int statusCodeInt = 0;
    String statusCode = statusCodeInt + " SUCCESSFUL";
    
    tcpWorker.onComplete(tcpWorker.responseSb.toString(), false, 
            null, null, statusCode, statusCodeInt);

}
 
Example 15
Project: Android-Airplay-Server   File: RaopRtspChallengeResponseHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	final HttpRequest req = (HttpRequest)evt.getMessage();

	synchronized(this) {
		if (req.containsHeader(HeaderChallenge)) {
			/* The challenge is sent without padding! */
			final byte[] challenge = Base64.decodeUnpadded(req.getHeader(HeaderChallenge));

			/* Verify that we got 16 bytes */
			if (challenge.length != 16)
				throw new ProtocolException("Invalid Apple-Challenge header, " + challenge.length + " instead of 16 bytes");

			/* Remember challenge and local address.
			 * Both are required to compute the response
			 */
			m_challenge = challenge;
			m_localAddress = ((InetSocketAddress)ctx.getChannel().getLocalAddress()).getAddress();
		}
		else {
			/* Forget last challenge */
			m_challenge = null;
			m_localAddress = null;
		}
	}

	super.messageReceived(ctx, evt);
}
 
Example 16
Project: fqueue   File: AbstractCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return runtime statistics
 * 
 * @param arg
 *            additional arguments to the stats command
 * @return the full command response
 */
public final Map<String, Set<String>> stat(String arg, ChannelHandlerContext channelHandlerContext) {
	Map<String, Set<String>> result = new HashMap<String, Set<String>>();
	// stats we know
	multiSet(result, "version", MemCacheDaemon.memcachedVersion);
	multiSet(result, "cmd_get", java.lang.String.valueOf(getGetCmds()));
	multiSet(result, "cmd_set", java.lang.String.valueOf(getSetCmds()));
	multiSet(result, "get_hits", java.lang.String.valueOf(getGetHits()));
	multiSet(result, "get_misses", java.lang.String.valueOf(getGetMisses()));
	multiSet(result, "time", java.lang.String.valueOf(java.lang.String.valueOf(Now())));
	multiSet(result, "uptime", java.lang.String.valueOf(Now() - this.started.longValue()));
	multiSet(result, "curr_items", java.lang.String.valueOf(this.getCurrentItems()));
	multiSet(result, "total_items", java.lang.String.valueOf(this.getCurrentItems()));
	multiSet(result, "limit_maxbytes", java.lang.String.valueOf(this.getLimitMaxBytes()));
	multiSet(result, "current_bytes", java.lang.String.valueOf(this.getCurrentBytes()));
	multiSet(result, "bytes", java.lang.String.valueOf(this.getCurrentBytes()));
	multiSet(result, "free_bytes", java.lang.String.valueOf(Runtime.getRuntime().freeMemory()));

	// Not really the same thing precisely, but meaningful nonetheless.
	// potentially this should be renamed
	multiSet(result, "pid", java.lang.String.valueOf(Thread.currentThread().getId()));

	// stuff we know nothing about; gets faked only because some clients
	// expect this
	multiSet(result, "rusage_user", String.valueOf(TimeUnit.NANOSECONDS.toSeconds(getJVMCpuTime())));
	multiSet(result, "rusage_system", "0.0");
	multiSet(result, "connection_structures", "0");
	multiSet(result, "curr_connections", String.valueOf(StatsCounter.curr_conns.longValue()));
	multiSet(result, "total_connections", String.valueOf(StatsCounter.total_conns.longValue()));

	// TODO we could collect these stats
	multiSet(result, "bytes_read", String.valueOf(StatsCounter.bytes_read.longValue()));
	multiSet(result, "bytes_written", String.valueOf(StatsCounter.bytes_written.longValue()));
	multiSet(result, "system_load", String.valueOf(getJVMLoad()));
	multiSet(result, "threads", String.valueOf(getAllthreadsCount()));
	return result;
}
 
Example 17
Project: chuidiang-ejemplos   File: MessageDecoder.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Object decode(ChannelHandlerContext ctx, Channel channel,
		ChannelBuffer buffer) throws Exception {

   System.out.println(ctx.canHandleUpstream());
		List<List<Byte>> objectsDecoded = new LinkedList<>();
		
		int initialIndex = buffer.readerIndex();
		int readableBytes = buffer.readableBytes();
		List<Byte> bytes = new LinkedList<>();

		for (int i = initialIndex; i < initialIndex + readableBytes; i++) {
			if (buffer.getByte(i) == 0) {
				buffer.readerIndex(i + 1);
				objectsDecoded.add(bytes);
				bytes = new LinkedList<>();
			} else {
				bytes.add(buffer.getByte(i));
			}
		}
		
		if (objectsDecoded.size()>0){
			return objectsDecoded;
		}
		
		return null;
	
}
 
Example 18
Project: fqueue   File: MemcachedCommandHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void handleStats(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command,
		int cmdKeysSize, Channel channel) {
	String option = "";
	if (cmdKeysSize > 0) {
		option = command.keys.get(0);
	}
	Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withStatResponse(cache.stat(
			option, channelHandlerContext)), channel.getRemoteAddress());
}
 
Example 19
Project: hadoop   File: RegistrationClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
  ChannelBuffer buf = (ChannelBuffer) e.getMessage(); // Read reply
  if (!validMessageLength(buf.readableBytes())) {
    e.getChannel().close();
    return;
  }

  // handling fragment header for TCP, 4 bytes.
  byte[] fragmentHeader = Arrays.copyOfRange(buf.array(), 0, 4);
  int fragmentSize = XDR.fragmentSize(fragmentHeader);
  boolean isLast = XDR.isLastFragment(fragmentHeader);
  assert (fragmentSize == 28 && isLast == true);

  XDR xdr = new XDR();
  xdr.writeFixedOpaque(Arrays.copyOfRange(buf.array(), 4,
      buf.readableBytes()));

  RpcReply reply = RpcReply.read(xdr);
  if (reply.getState() == RpcReply.ReplyState.MSG_ACCEPTED) {
    RpcAcceptedReply acceptedReply = (RpcAcceptedReply) reply;
    handle(acceptedReply, xdr);
  } else {
    RpcDeniedReply deniedReply = (RpcDeniedReply) reply;
    handle(deniedReply);
  }
  e.getChannel().close(); // shutdown now that request is complete
}
 
Example 20
Project: onos   File: PcepMessageDecoder.java    License: 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 21
Project: RDFS   File: ShuffleHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(
      ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 22
Project: DataLink   File: SessionHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handleGroupCoordinatorRequest(ChannelHandlerContext ctx, Request request) {
    ResponseHeader responseHeader = new ResponseHeader(request.getHeader().correlationId());

    Node activeNode = coordinator.getActiveGroupCoordinator();
    if (activeNode == null) {
        logger.trace("Coordinator不存在");
        sendResponse(ctx,
                new Response(responseHeader, new GroupCoordinatorResponse(Errors.GROUP_COORDINATOR_NOT_AVAILABLE.code(), Node.noNode())));
    } else {
        logger.trace("Coordinator存在,当前Coordinator是:{}", activeNode.toString());
        sendResponse(ctx,
                new Response(responseHeader, new GroupCoordinatorResponse(Errors.NONE.code(), activeNode)));
    }
}
 
Example 23
Project: onos   File: TestBgpPeerFrameDecoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes BGP OPEN message.
 *
 * @param ctx the Channel Handler Context.
 * @param message the message to process.
 */
private void processBgpOpen(ChannelHandlerContext ctx,
                            ChannelBuffer message) {
    int minLength =
        BgpConstants.BGP_OPEN_MIN_LENGTH - BgpConstants.BGP_HEADER_LENGTH;
    if (message.readableBytes() < minLength) {
        // ERROR: Bad Message Length. Close the channel.
        ctx.getChannel().close();
        return;
    }

    //
    // Parse the OPEN message
    //
    remoteInfo.setBgpVersion(message.readUnsignedByte());
    remoteInfo.setAsNumber(message.readUnsignedShort());
    remoteInfo.setHoldtime(message.readUnsignedShort());
    remoteInfo.setBgpId(Ip4Address.valueOf((int) message.readUnsignedInt()));
    // Optional Parameters
    int optParamLen = message.readUnsignedByte();
    if (message.readableBytes() < optParamLen) {
        // ERROR: Bad Message Length. Close the channel.
        ctx.getChannel().close();
        return;
    }
    message.readBytes(optParamLen);             // NOTE: data ignored

    // BGP OPEN message successfully received
    receivedOpenMessageLatch.countDown();
}
 
Example 24
Project: jstorm   File: StormServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    // removeFailureCounter(e.getChannel());
    if (e.getChannel() != null) {
        LOG.info("Channel occur exception {}, cause={}", e.getChannel().getRemoteAddress(), e.getCause());
    }

    server.closeChannel(e.getChannel());
}
 
Example 25
Project: james-project   File: BasicChannelUpstreamHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected ProtocolSession createSession(ChannelHandlerContext ctx) throws Exception {
    SSLEngine engine = null;
    if (secure != null) {
        engine = secure.getContext().createSSLEngine();
        String[] enabledCipherSuites = secure.getEnabledCipherSuites();
        if (enabledCipherSuites != null && enabledCipherSuites.length > 0) {
            engine.setEnabledCipherSuites(enabledCipherSuites);
        }
    }
    
    return protocol.newSession(new NettyProtocolTransport(ctx.getChannel(), engine));
}
 
Example 26
Project: hadoop   File: RpcUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
    ChannelBuffer buf) {

  if (buf.readableBytes() < 4)
    return null;

  buf.markReaderIndex();

  byte[] fragmentHeader = new byte[4];
  buf.readBytes(fragmentHeader);
  int length = XDR.fragmentSize(fragmentHeader);
  boolean isLast = XDR.isLastFragment(fragmentHeader);

  if (buf.readableBytes() < length) {
    buf.resetReaderIndex();
    return null;
  }

  ChannelBuffer newFragment = buf.readSlice(length);
  if (currentFrame == null) {
    currentFrame = newFragment;
  } else {
    currentFrame = ChannelBuffers.wrappedBuffer(currentFrame, newFragment);
  }

  if (isLast) {
    ChannelBuffer completeFrame = currentFrame;
    currentFrame = null;
    return completeFrame;
  } else {
    return null;
  }
}
 
Example 27
Project: usergrid   File: WebSocketChannelHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelDisconnected( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception {
    super.channelDisconnected( ctx, e );
    if ( websocket ) {
        logger.info( "Websocket disconnected" );
    }
}
 
Example 28
Project: onos   File: OspfMessageEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) {

    byte[] byteMsg = (byte[]) msg;
    log.debug("Encoding ospfMessage of length {}", byteMsg.length);
    ChannelBuffer channelBuffer = ChannelBuffers.buffer(byteMsg.length);
    channelBuffer.writeBytes(byteMsg);

    return channelBuffer;
}
 
Example 29
Project: FlowSpaceFirewall   File: OFControllerChannelHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@LogMessageDoc(message="Disconnected controller {switch information}",
               explanation="The specified controller has disconnected.")
public void channelDisconnected(ChannelHandlerContext ctx,
                                ChannelStateEvent e) throws Exception {
    

}
 
Example 30
Project: dubbox   File: NettyCodecAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
    com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer =
        com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
    NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ch);
    }
    return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
 
Example 31
Project: big-c   File: RpcProgramPortmap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {

  RpcInfo info = (RpcInfo) e.getMessage();
  RpcCall rpcCall = (RpcCall) info.header();
  final int portmapProc = rpcCall.getProcedure();
  int xid = rpcCall.getXid();
  XDR in = new XDR(info.data().toByteBuffer().asReadOnlyBuffer(),
      XDR.State.READING);
  XDR out = new XDR();

  if (portmapProc == PMAPPROC_NULL) {
    out = nullOp(xid, in, out);
  } else if (portmapProc == PMAPPROC_SET) {
    out = set(xid, in, out);
  } else if (portmapProc == PMAPPROC_UNSET) {
    out = unset(xid, in, out);
  } else if (portmapProc == PMAPPROC_DUMP) {
    out = dump(xid, in, out);
  } else if (portmapProc == PMAPPROC_GETPORT) {
    out = getport(xid, in, out);
  } else if (portmapProc == PMAPPROC_GETVERSADDR) {
    out = getport(xid, in, out);
  } else {
    LOG.info("PortmapHandler unknown rpc procedure=" + portmapProc);
    RpcAcceptedReply reply = RpcAcceptedReply.getInstance(xid,
        RpcAcceptedReply.AcceptState.PROC_UNAVAIL, new VerifierNone());
    reply.write(out);
  }

  ChannelBuffer buf = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
      .buffer());
  RpcResponse rsp = new RpcResponse(buf, info.remoteAddress());
  RpcUtil.sendRpcResponse(ctx, rsp);
}
 
Example 32
Project: tez   File: ShuffleHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
    String user, String mapId, int reduce, MapOutputInfo mapOutputInfo)
    throws IOException {
  final TezIndexRecord info = mapOutputInfo.indexRecord;
  final ShuffleHeader header =
    new ShuffleHeader(mapId, info.getPartLength(), info.getRawLength(), reduce);
  final DataOutputBuffer dob = new DataOutputBuffer();
  header.write(dob);
  ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  final File spillfile =
      new File(mapOutputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillfile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillfile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  final DefaultFileRegion partition =
      new DefaultFileRegion(spill.getChannel(), info.getStartOffset(), info.getPartLength());
  writeFuture = ch.write(partition);
  writeFuture.addListener(new ChannelFutureListener() {
    // TODO error handling; distinguish IO/connection failures,
    //      attribute to appropriate spill output
    @Override
    public void operationComplete(ChannelFuture future) {
      partition.releaseExternalResources();
    }
  });
  return writeFuture;
}
 
Example 33
Project: onos   File: TestBgpPeerChannelHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx,
                             ChannelStateEvent channelEvent) {
    this.savedCtx = ctx;
    // Prepare and transmit BGP OPEN message
    ChannelBuffer message = BgpOpen.prepareBgpOpen(localInfo);
    ctx.getChannel().write(message);

    // Prepare and transmit BGP KEEPALIVE message
    message = BgpKeepalive.prepareBgpKeepalive();
    ctx.getChannel().write(message);
}
 
Example 34
Project: james-project   File: ImapChannelUpstreamHandler.java    License: 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 35
Project: parallec   File: TcpWorker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    //add \n to the end
    tcpWorker.responseSb.append(e.getMessage().toString()+"\n");
    logger.debug("DONE." + ++msgRecvCount);
    logger.debug("MSG_RECEIVED_AT_TCP_CLIENT: {}", e.getMessage().toString());
}
 
Example 36
Project: onos   File: BgpChannelHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {

    log.error("[exceptionCaught]: " + e.toString());

    if (e.getCause() instanceof ClosedChannelException) {
        bgpController.activeSessionExceptionAdd(peerAddr, e.getCause().toString());
        log.debug("Channel for bgp {} already closed", getPeerInfoString());
    } else if (e.getCause() instanceof IOException) {
        log.error("Disconnecting peer {} due to IO Error: {}", getPeerInfoString(), e.getCause().getMessage());
        bgpController.closedSessionExceptionAdd(peerAddr, e.getCause().toString());
        if (log.isDebugEnabled()) {
            // still print stack trace if debug is enabled
            log.debug("StackTrace for previous Exception: ", e.getCause());
        }
        stopSessionTimers();
        ctx.getChannel().close();
    } else if (e.getCause() instanceof BgpParseException) {
        byte[] data = new byte[] {};
        BgpParseException errMsg = (BgpParseException) e.getCause();
        byte errorCode = errMsg.getErrorCode();
        byte errorSubCode = errMsg.getErrorSubCode();
        bgpController.activeSessionExceptionAdd(peerAddr, e.getCause().toString());
        ChannelBuffer tempCb = errMsg.getData();
        if (tempCb != null) {
            int dataLength = tempCb.readableBytes();
            data = new byte[dataLength];
            tempCb.readBytes(data, 0, dataLength);
        }
        sendNotification(errorCode, errorSubCode, data);
    } else if (e.getCause() instanceof RejectedExecutionException) {
        log.warn("Could not process message: queue full");
        bgpController.activeSessionExceptionAdd(peerAddr, e.getCause().toString());
    } else {
        stopSessionTimers();
        log.error("Error while processing message from peer " + getPeerInfoString() + "state " + this.state);
        bgpController.closedSessionExceptionAdd(peerAddr, e.getCause().toString());
        ctx.getChannel().close();
    }
}
 
Example 37
Project: anima   File: NettyHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    NettyChannel channel = NettyChannel.getOrAddChannel(conf,ctx.getChannel(), handler);
    try {
    	InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
    	String key = address.getAddress().getHostAddress() + ":" + address.getPort();
        channels.remove(key);
        handler.disconnected(channel);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 38
Project: onos   File: OspfInterfaceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests processDdMessage() method.
 */
@Test
public void testProcessDdMessage() throws Exception {
    ospfInterface.setOspfArea(ospfArea);
    ospfInterface.setIpAddress(Ip4Address.valueOf("11.11.11.11"));
    ospfInterface.setInterfaceType(2);
    ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
    ospfInterface.setHelloIntervalTime(10);
    ospfInterface.setRouterDeadIntervalTime(10);
    ospfArea.setAreaId(Ip4Address.valueOf("12.12.12.12"));
    channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class);
    OspfMessage message;
    ddPacket = new DdPacket();
    ddPacket.setSourceIp(Ip4Address.valueOf("1.1.1.1"));
    ddPacket.setOspfVer(2);
    ddPacket.setAreaId(Ip4Address.valueOf("12.12.12.12"));
    ddPacket.setRouterId(Ip4Address.valueOf("2.2.2.2"));
    ddPacket.setIsOpaqueCapable(true);
    ddPacket.setIsMore(1);
    ddPacket.setIsInitialize(1);
    ddPacket.setIsMaster(1);
    ddPacket.setSequenceNo(123);
    message = ddPacket;
    ospfNbrHashMap = new HashMap();
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.10.10.10"),
                              Ip4Address.valueOf("2.2.2.2"), 2,
                              topologyForDeviceAndLink);
    ospfNbr.setLastDdPacket(createDdPacket());
    ospfNbr.setNeighborId(Ip4Address.valueOf("2.2.2.2"));
    ospfNbr.setState(OspfNeighborState.EXSTART);
    ospfNbr.setRouterPriority(0);
    ospfNbr.setNeighborDr(Ip4Address.valueOf("13.13.13.13"));
    ospfNbr.setDdSeqNum(123);
    ospfInterface.addNeighbouringRouter(ospfNbr);
    channelHandlerContext = null;
    channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class);
    ospfInterface.processDdMessage(message, channelHandlerContext);
    assertThat(ospfInterfaceChannelHandler, is(notNullValue()));
}
 
Example 39
Project: onos   File: BgpUpdate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Invalid ORIGIN Attribute Error: send NOTIFICATION and close the channel.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param attrTypeCode the attribute type code
 * @param attrLen the attribute length (in octets)
 * @param attrFlags the attribute flags
 * @param message the message with the data
 * @param origin the ORIGIN attribute value
 */
private static void actionsBgpUpdateInvalidOriginAttribute(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message,
                            short origin) {
    log.debug("BGP RX UPDATE Error from {}: Invalid ORIGIN Attribute",
              bgpSession.remoteInfo().address());

    //
    // ERROR: Invalid ORIGIN Attribute
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.INVALID_ORIGIN_ATTRIBUTE;
    ChannelBuffer data =
        prepareBgpUpdateNotificationDataPayload(attrTypeCode, attrLen,
                                                attrFlags, message);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 40
Project: dubbox-hystrix   File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    try {
        if (channel != null) {
            channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()), channel);
        }
        handler.connected(channel);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}