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. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: parallec   Source 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
Source Project: onos   Source 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
Source Project: onos   Source 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
Source Project: mt-flume   Source 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
Source Project: big-c   Source 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
Source Project: onos   Source 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
Source Project: onos   Source 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
Source Project: RDFS   Source 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
Source Project: pinpoint   Source 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
Source Project: dubbo-2.6.5   Source 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
Source Project: android-netty   Source 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
Source Project: whiteboard   Source 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
Source Project: Flink-CEPplus   Source 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
Source Project: parallec   Source 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
@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
Source Project: fqueue   Source 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
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
Source Project: fqueue   Source 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
Source Project: hadoop   Source 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
Source Project: onos   Source 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
Source Project: RDFS   Source 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
Source Project: DataLink   Source 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
Source Project: onos   Source 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
Source Project: jstorm   Source 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
Source Project: james-project   Source 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
Source Project: hadoop   Source 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
Source Project: usergrid   Source 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
Source Project: onos   Source 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
@Override
@LogMessageDoc(message="Disconnected controller {switch information}",
               explanation="The specified controller has disconnected.")
public void channelDisconnected(ChannelHandlerContext ctx,
                                ChannelStateEvent e) throws Exception {
    

}
 
Example 30
Source Project: dubbox   Source 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());
}