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

The following are top voted examples for showing how to use org.jboss.netty.channel.MessageEvent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: voyage   File: NettyRpcServerHandler.java   View source code 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 2
Project: fuck_zookeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 3
Project: HiBangClient   File: SMsgManage.java   View source code 6 votes vote down vote up
public static void messageReceived(MessageEvent e) {
	String msgName = e.getMessage().getClass().getName();
	if (msgName.equals(SLoginMsg.class.getName())) {
		sendToLogin(e);
	} else if (msgName.equals(SRecommendListMsg.class.getName())) {
		sendToRecommend(e);
	} else if (msgName.equals(SHelpMeMsg.class.getName())) {
		sendToHelpMeMsg(e);
	} else if (msgName.equals(SMeHelpMsg.class.getName())) {
		sendToMeHelpMsg(e);
	} else if (msgName.equals(SFriendList.class.getName())) {
		sendToFriend(e);
	} else if (msgName.equals(SChatMessage.class.getName())) {
		sendToChat(e);
	} else if (msgName.equals(SSelectReqMsg.class.getName())) {
		sendToQuery(e);
	} else if (msgName.equals(SRegisterMsg.class.getName())) {
		sendToRegister(e);
	} else if (msgName.equals(SPhotoRequestMsg.class.getName())) {
		sendToPhoto(e);
	} else if (msgName.equals(SUserInfoRequest.class.getName())) {
		sendToInformation(e);
	} else if(msgName.equals(SOrderMsg.class.getName())) {
		sendToInformation1(e);
	} 
}
 
Example 4
Project: HiBangClient   File: SMsgManage.java   View source code 6 votes vote down vote up
private static void sendToInformation1(MessageEvent e) {
	SOrderMsg msg = (SOrderMsg) e.getMessage();
	if (isCurrUI(Config.TAG_InformationActivity)) {
		sOrderMsgListener.onSOrderMsgReceived(msg);
	} else {
		Intent intent = new Intent(currContext, InformationActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("TAG", Config.TAG_SOrderMsg);
		bundle.putSerializable("SOrderMsg", msg);
		intent.putExtras(bundle);
		String content = "";
		String title  = msg.getReqDetail();
			if(msg.getOrderType() == OrderMsgType.REQUEST) {
				content = "嗨,有人帮助你啦,快来看吧!";
			} else {
				if(msg.isbOrdered()) {
					content = "嗨,你们已经正在交易中了";
				}
			}
		myNotifi(1000,intent, title, content);
	}
}
 
Example 5
Project: HiBangClient   File: SMsgManage.java   View source code 6 votes vote down vote up
public static void sendToHelpMeMsg(MessageEvent e) {
		SHelpMeMsg msg = (SHelpMeMsg) e.getMessage();
		synchronized (String.class) {
		if(DataHiBang.sHelpMeMsgList.size()>=10) {
			DataHiBang.sHelpMeMsgList.remove(0);
		}
		DataHiBang.sHelpMeMsgList.add(msg);
		}
		if (isCurrUI(Config.TAG_MessageActivity)) {
			sHelpMeMsgListener.onHelpMeMsgReveived(msg);
		} else {
//			Intent intent = new Intent(currContext, MessageActivity.class);
			myMainTabListener.onMsgReveived(msg);
			Intent intent = new Intent(currContext, InformationActivity.class);
			Bundle bundle = new Bundle();
			bundle.putInt("TAG", Config.TAG_HelpMeMessage);
			MySHelpMeMsg helpMeMsg = new MySHelpMeMsg(msg);
			bundle.putSerializable("helpMeMessage", helpMeMsg);
			
			intent.putExtras(bundle);
			myNotifi(1002,intent, msg.getHelpName(), msg.getReqItem());
		}
	}
 
Example 6
Project: HiBangClient   File: SMsgManage.java   View source code 6 votes vote down vote up
public static void sendToChat(MessageEvent e) {
	SChatMessage msg = (SChatMessage) e.getMessage();
	if (msg.getSenderID() == chattingUserId) {
		DBManage.addSChatMsg(msg, false);
		myChattingListener.onMsgReceived(msg);
	} else {
		DBManage.addSChatMsg(msg, true);
		Intent intent = new Intent(currContext, ChatActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("friendId", msg.getSenderID());
		bundle.putString("friendName", msg.getReceiverName());
		intent.putExtras(bundle);
		String title = "嗨帮-聊天消息 (共1条未读)";
		myNotifi(1003,intent,title,msg.getChatContent());
		
		// sChatMessageListener.onMsgReveived(msg);
	}
}
 
Example 7
Project: HiBangClient   File: SMsgManage.java   View source code 6 votes vote down vote up
public static void sendToRecommend(MessageEvent e) {
		SRecommendListMsg msg = (SRecommendListMsg) e.getMessage();
//		DBManage.addRequirement(msg.getRecommendList(), true);
		synchronized (String.class) {
			if(DataHiBang.sRecommMsgList.size()>25) {
				int n = DataHiBang.sRecommMsgList.size() - 25;
				for(int i=0;i<n;i++) {
					DataHiBang.sRecommMsgList.remove(i);
				}
			}
			DataHiBang.sRecommMsgList.addAll(msg.getRecommendList());
		}
		
		if (isCurrUI(Config.TAG_RecommendActivity)) {
			sRlMsgListener.onMsgReveived(msg);
		} else {
			Intent intent = new Intent(currContext, MainTabActivity.class);
			myNotifi(1004,intent, "快来帮助别人吧······", msg.getRecommendList().get(0).getReqDetail());
		}
	}
 
Example 8
Project: https-github.com-apache-zookeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 9
Project: NioSmtpClient   File: ChunkingExtension.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  if (e.getMessage() instanceof ChannelBuffer) {
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();

    int bytesToRead = Math.min(currentChunkSize - bytesRead, buffer.readableBytes());
    buffer.readBytes(getMailEnvelope().getMessageOutputStream(), bytesToRead);
    bytesRead += bytesToRead;

    if (bytesRead == currentChunkSize) {
      stopCapturingData();
    }

    return;
  }

  super.messageReceived(ctx, e);
}
 
Example 10
Project: hadoop   File: RpcProgram.java   View source code 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 11
Project: hadoop   File: RpcUtil.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  ChannelBuffer buf = (ChannelBuffer) e.getMessage();
  ByteBuffer b = buf.toByteBuffer().asReadOnlyBuffer();
  XDR in = new XDR(b, XDR.State.READING);

  RpcInfo info = null;
  try {
    RpcCall callHeader = RpcCall.read(in);
    ChannelBuffer dataBuffer = ChannelBuffers.wrappedBuffer(in.buffer()
        .slice());
    info = new RpcInfo(callHeader, dataBuffer, ctx, e.getChannel(),
        e.getRemoteAddress());
  } catch (Exception exc) {
    LOG.info("Malformed RPC request from " + e.getRemoteAddress());
  }

  if (info != null) {
    Channels.fireMessageReceived(ctx, info);
  }
}
 
Example 12
Project: athena   File: OFChannelHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
    if (e.getMessage() instanceof List) {
        @SuppressWarnings("unchecked")
        List<OFMessage> msglist = (List<OFMessage>) e.getMessage();


        for (OFMessage ofm : msglist) {
            // Do the actual packet processing
            state.processOFMessage(this, ofm);
        }
    } else {
        state.processOFMessage(this, (OFMessage) e.getMessage());
    }
}
 
Example 13
Project: ZooKeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 14
Project: iTAP-controller   File: AbstractRPCChannelHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx,
                            MessageEvent e) throws Exception {
    Object message = e.getMessage();
    if (message instanceof SyncMessage) {
        handleSyncMessage((SyncMessage)message, ctx.getChannel());
    } else if (message instanceof List) {
        for (Object i : (List<?>)message) {
            if (i instanceof SyncMessage) {
                try {
                    handleSyncMessage((SyncMessage)i,
                                         ctx.getChannel());
                } catch (Exception ex) {
                    Channels.fireExceptionCaught(ctx, ex);
                }
            }
        }
    } else {
        handleUnknownMessage(ctx, message);
    }
}
 
Example 15
Project: iTAP-controller   File: OFChannelHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	if (e.getMessage() instanceof List) {
		@SuppressWarnings("unchecked")
		List<OFMessage> msglist = (List<OFMessage>)e.getMessage();
		for (OFMessage ofm : msglist) {
			try {
				// Do the actual packet processing
				state.processOFMessage(ofm);
			}
			catch (Exception ex) {
				// We are the last handler in the stream, so run the
				// exception through the channel again by passing in
				// ctx.getChannel().
				Channels.fireExceptionCaught(ctx.getChannel(), ex);
			}
		}
	}
	else {
		Channels.fireExceptionCaught(ctx.getChannel(),
				new AssertionError("Message received from channel is not a list"));
	}
}
 
Example 16
Project: CacheStore   File: EchoClientHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    lock.lock();
    try {
        // construct response
        if( e.getMessage() instanceof Request) {
            Request req = (Request) e.getMessage();
            resp =req;
            logger.info("receive "+ req.toString() +" from "+e.getRemoteAddress().toString() );
        }
        else {
            logger.info( e.getMessage().getClass().getName()+" len " + e.getMessage().toString().length()
                    +" "+ e.getChannel().getRemoteAddress().toString() );
            resp = null;
        }
        //throw new RuntimeException( e.getMessage().getClass().getName()+" is not supported");
    } finally {
        cleanUp();
        lock.unlock();
    }
    // Server is supposed to send nothing.  Therefore, do nothing.
}
 
Example 17
Project: CacheStore   File: InvokerServerHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Request req =  (Request) e.getMessage();
    logger.info("receive " + req.toString()+" from "+e.getRemoteAddress().toString());
    // it might need to create a different copy
    Header header = new Header( req.getHeader().getName(), req.getHeader().getVersion(), req.getHeader().getRelease(),
          req.getHeader().getNodeId());
    Response response = null;
    try {
      Invoker invoker = (Invoker) serializer.toObject( req.getPayload() );
      response = invoke( invoker );
    } catch (Exception ex) {
      logger.error(ex.getMessage(), ex);
      response = new Response( ex.getMessage(), true);
    } finally {
       byte[] payload = serializer.toBytes( response);
       Request request = new Request(header, payload ,  Request.RequestType.Response  );
       ctx.getChannel().write(request);
    }
}
 
Example 18
Project: aliyun-oss-hadoop-fs   File: RpcProgram.java   View source code 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 19
Project: aliyun-oss-hadoop-fs   File: RpcUtil.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  ChannelBuffer buf = (ChannelBuffer) e.getMessage();
  ByteBuffer b = buf.toByteBuffer().asReadOnlyBuffer();
  XDR in = new XDR(b, XDR.State.READING);

  RpcInfo info = null;
  try {
    RpcCall callHeader = RpcCall.read(in);
    ChannelBuffer dataBuffer = ChannelBuffers.wrappedBuffer(in.buffer()
        .slice());
    info = new RpcInfo(callHeader, dataBuffer, ctx, e.getChannel(),
        e.getRemoteAddress());
  } catch (Exception exc) {
    LOG.info("Malformed RPC request from " + e.getRemoteAddress());
  }

  if (info != null) {
    Channels.fireMessageReceived(ctx, info);
  }
}
 
Example 20
Project: Camel   File: NettyEndpoint.java   View source code 6 votes vote down vote up
protected void updateMessageHeader(Message in, ChannelHandlerContext ctx, MessageEvent messageEvent) {
    in.setHeader(NettyConstants.NETTY_CHANNEL_HANDLER_CONTEXT, ctx);
    in.setHeader(NettyConstants.NETTY_MESSAGE_EVENT, messageEvent);
    in.setHeader(NettyConstants.NETTY_REMOTE_ADDRESS, messageEvent.getRemoteAddress());
    in.setHeader(NettyConstants.NETTY_LOCAL_ADDRESS, messageEvent.getChannel().getLocalAddress());

    if (configuration.isSsl()) {
        // setup the SslSession header
        SSLSession sslSession = getSSLSession(ctx);
        in.setHeader(NettyConstants.NETTY_SSL_SESSION, sslSession);

        // enrich headers with details from the client certificate if option is enabled
        if (configuration.isSslClientCertHeaders()) {
            enrichWithClientCertInformation(sslSession, in);
        }
    }
}
 
Example 21
Project: StreamProcessingInfrastructure   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 22
Project: bigstreams   File: ServerUtil.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	super.messageReceived(ctx, e);

	System.out.println("-------- Server  Channel messageRecieved "
			+ System.currentTimeMillis());

	if (induceError.get()) {
		System.out
				.println("Inducing Error in Server messageReceived method");
		throw new IOException("Induced error ");
	}

	MessageEventBag bag = new MessageEventBag();
	bag.setBytes(e);
	bagList.add(bag);

	ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
	buffer.writeInt(200);

	ChannelFuture future = e.getChannel().write(buffer);

	future.addListener(ChannelFutureListener.CLOSE);

}
 
Example 23
Project: Camel   File: HttpServerMultiplexChannelHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    // store request, as this channel handler is created per pipeline
    HttpRequest request = (HttpRequest) messageEvent.getMessage();

    LOG.debug("Message received: {}", request);

    HttpServerChannelHandler handler = getHandler(request);
    if (handler != null) {
        // store handler as attachment
        ctx.setAttachment(handler);
        handler.messageReceived(ctx, messageEvent);
    } else {
        // this resource is not found, so send empty response back
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        // close the channel after send error message
        messageEvent.getChannel().close();
    }
}
 
Example 24
Project: bigstreams   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 25
Project: QoS-floodlight   File: AbstractRPCChannelHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx,
                            MessageEvent e) throws Exception {
    Object message = e.getMessage();
    if (message instanceof SyncMessage) {
        handleSyncMessage((SyncMessage)message, ctx.getChannel());
    } else if (message instanceof List) {
        for (Object i : (List<?>)message) {
            if (i instanceof SyncMessage) {
                try {
                    handleSyncMessage((SyncMessage)i,
                                         ctx.getChannel());
                } catch (Exception ex) {
                    Channels.fireExceptionCaught(ctx, ex);
                }
            }
        }
    } else {
        handleUnknownMessage(ctx, message);
    }
}
 
Example 26
Project: nfs-rpc   File: NettyProtocolDecoder.java   View source code 6 votes vote down vote up
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;
  }

  ChannelBuffer cumulation = cumulation(ctx);
  if (cumulation.readable()) {
    cumulation.discardReadBytes();
    cumulation.writeBytes(input);
    callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress());
  } else {
    callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
    if (input.readable()) {
      cumulation.writeBytes(input);
    }
  }
}
 
Example 27
Project: nfs-rpc   File: NettyClientHandler.java   View source code 6 votes vote down vote up
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  if (e.getMessage() instanceof List) {
    @SuppressWarnings("unchecked")
    List<ResponseWrapper> responses = (List<ResponseWrapper>) e.getMessage();
    if (isDebugEnabled) {
      // for performance trace
      LOGGER.debug("receive response list from server: " + ctx.getChannel().getRemoteAddress() + ",list size is:" + responses.size());
    }
    client.putResponses(responses);
  } else if (e.getMessage() instanceof ResponseWrapper) {
    ResponseWrapper response = (ResponseWrapper) e.getMessage();
    if (isDebugEnabled) {
      // for performance trace
      LOGGER
          .debug("receive response list from server: " + ctx.getChannel().getRemoteAddress() + ",request is:" + response.getRequestId());
    }
    client.putResponse(response);
  } else {
    LOGGER.error("receive message error,only support List || ResponseWrapper");
    throw new Exception("receive message error,only support List || ResponseWrapper");
  }
}
 
Example 28
Project: big-c   File: RpcUtil.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  ChannelBuffer buf = (ChannelBuffer) e.getMessage();
  ByteBuffer b = buf.toByteBuffer().asReadOnlyBuffer();
  XDR in = new XDR(b, XDR.State.READING);

  RpcInfo info = null;
  try {
    RpcCall callHeader = RpcCall.read(in);
    ChannelBuffer dataBuffer = ChannelBuffers.wrappedBuffer(in.buffer()
        .slice());
    info = new RpcInfo(callHeader, dataBuffer, ctx, e.getChannel(),
        e.getRemoteAddress());
  } catch (Exception exc) {
    LOG.info("Malformed RPC request from " + e.getRemoteAddress());
  }

  if (info != null) {
    Channels.fireMessageReceived(ctx, info);
  }
}
 
Example 29
Project: incubator-omid   File: TSOClientRaw.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    LOG.info("Message received", e);
    if (e.getMessage() instanceof Response) {
        Response resp = (Response) e.getMessage();
        try {
            SettableFuture<Response> future = responseQueue.take();
            future.set(resp);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            LOG.warn("Interrupted in handler", ie);
        }
    } else {
        LOG.warn("Received unknown message", e.getMessage());
    }
}
 
Example 30
Project: Camel   File: ClientChannelHandler.java   View source code 6 votes vote down vote up
/**
 * Gets the Camel {@link Message} to use as the message to be set on the current {@link Exchange} when
 * we have received a reply message.
 * <p/>
 *
 * @param exchange      the current exchange
 * @param messageEvent  the incoming event which has the response message from Netty.
 * @return the Camel {@link Message} to set on the current {@link Exchange} as the response message.
 * @throws Exception is thrown if error getting the response message
 */
protected Message getResponseMessage(Exchange exchange, MessageEvent messageEvent) throws Exception {
    Object body = messageEvent.getMessage();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Channel: {} received body: {}", new Object[]{messageEvent.getChannel(), body});
    }

    // if textline enabled then covert to a String which must be used for textline
    if (producer.getConfiguration().isTextline()) {
        body = producer.getContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);
    }

    // set the result on either IN or OUT on the original exchange depending on its pattern
    if (ExchangeHelper.isOutCapable(exchange)) {
        NettyPayloadHelper.setOut(exchange, body);
        return exchange.getOut();
    } else {
        NettyPayloadHelper.setIn(exchange, body);
        return exchange.getIn();
    }
}
 
Example 31
Project: zookeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 32
Project: opentsdb-flume   File: OpenTSDBSource.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  LineBasedFrameDecoder.LineEvent line = (LineBasedFrameDecoder.LineEvent) e.getMessage();
  if (line == null) {
    return;
  }
  if (isEvent(line)) {
    try {
      queue.offer(line.getBody());
    } catch (ChannelException ex) {
      logger.error("Error putting event to queue, event dropped", ex);
    }
  } else {
    signalWaiters();
    e.getChannel().write("ok\n");
    if (logger.isDebugEnabled()) {
      logger.debug("Waking up flusher");
    }
  }
}
 
Example 33
Project: opentsdb-flume   File: LegacyHttpSource.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  try {
    final HttpRequest req = (HttpRequest) e.getMessage();
    if (req.getMethod().equals(HttpMethod.POST)) {
      doPost(ctx, e, req);
    } else if (req.getMethod().equals(HttpMethod.GET)) {
      doGet(ctx, e, req);
    } else {
      writeResponseAndClose(e, new DefaultHttpResponse(
              HttpVersion.HTTP_1_1,
              HttpResponseStatus.BAD_REQUEST));
    }
  } catch (Exception ex) {
    if (logger.isDebugEnabled())
      logger.debug("Failed to process message", ex);
    HttpResponse response = new DefaultHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.INTERNAL_SERVER_ERROR);
    response.setContent(
            ChannelBuffers.copiedBuffer(ex.getMessage().getBytes()));
    writeResponseAndClose(e, response);
  }
}
 
Example 34
Project: opentsdb-flume   File: LegacyHttpSource.java   View source code 6 votes vote down vote up
private void doPost(ChannelHandlerContext ctx, MessageEvent e, HttpRequest req)
        throws IOException {

  final QueryStringDecoder decoded = new QueryStringDecoder(req.getUri());
  if (!decoded.getPath().equalsIgnoreCase("/write")) {
    writeResponseAndClose(e,
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
    return;
  }

  try {
    metricParser.parse(req);
  } catch (IllegalArgumentException iae) {
    logger.warn("Metric parser failed: " + iae.getMessage());
  }

  HttpResponse response = new DefaultHttpResponse(
          HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.setContent(ChannelBuffers.copiedBuffer(
          ("Seen events").getBytes()
  ));
  writeResponseAndClose(e, response);
}
 
Example 35
Project: Android-Airplay-Server   File: RaopAudioHandler.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception {
	
	/* Get audio channel from the enclosing RaopAudioHandler */
	Channel tempAudioChannel = null;
	synchronized(RaopAudioHandler.this) {
		tempAudioChannel = audioChannel;
	}

	if ((tempAudioChannel != null) && tempAudioChannel.isOpen() && tempAudioChannel.isReadable()) {
		tempAudioChannel.getPipeline().sendUpstream(new UpstreamMessageEvent(
			tempAudioChannel,
			evt.getMessage(),
			evt.getRemoteAddress())
		);
	}
}
 
Example 36
Project: SecureKeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 37
Project: SecureKeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("message received called " + e.getMessage());
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("New message " + e.toString()
                    + " from " + ctx.getChannel());
        }
        NettyServerCnxn cnxn = (NettyServerCnxn)ctx.getAttachment();
        synchronized(cnxn) {
            processMessage(e, cnxn);
        }
    } catch(Exception ex) {
        LOG.error("Unexpected exception in receive", ex);
        throw ex;
    }
}
 
Example 38
Project: elasticsearch-client-http   File: HttpClient.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpContext<R, T> httpContext = httpContextMap.get(ctx.getChannel());
    if (httpContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<R, T> action = httpContext.getHttpAction();
            ActionListener<T> listener = httpContext.getListener();
            httpContext.setHttpResponse(httpResponse);
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        httpContextMap.remove(ctx.getChannel());
    }
}
 
Example 39
Project: voyage   File: RpcRequestEncode.java   View source code 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	RpcRequest request = (RpcRequest) e.getMessage();
	ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
	//先写入标示的魔数
	baos.write(Constants.MAGIC_BYTES);
	MySerializerFactory.getInstance(Constants.DEFAULT_RPC_CODE_MODE).encodeRequest(baos, request);
	ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(baos.toByteArray());
	Channels.write(ctx, e.getFuture(), buffer);
}
 
Example 40
Project: voyage   File: RpcResponseEncode.java   View source code 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	RpcResponse response = (RpcResponse) e.getMessage();
	ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
	//先写入标示的魔数
	baos.write(Constants.MAGIC_BYTES);
	MySerializerFactory.getInstance(Constants.DEFAULT_RPC_CODE_MODE).encodeResponse(baos, response);
	ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(baos.toByteArray());
	Channels.write(ctx, e.getFuture(), buffer);
}