Java Code Examples for org.jboss.netty.channel.MessageEvent#getMessage()

The following examples show how to use org.jboss.netty.channel.MessageEvent#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RpcProgram.java    From hadoop with 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 2
Source File: RpcProgram.java    From big-c with 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 3
Source File: ChunkingExtension.java    From NioSmtpClient with Apache License 2.0 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 4
Source File: RpcUtil.java    From big-c with Apache License 2.0 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 5
Source File: MyServerHandler.java    From whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	Channel channel = e.getChannel();
	SerializablePath newPath = (SerializablePath) e.getMessage();
	Commons.myUUID = newPath.getMyUUID();

	recordMyUUID(Commons.myUUID, channel);
	System.out.println("������յ���Ϣ,�豸��ʾ��--" + Commons.myUUID);
	if ("send_uuid".equals(newPath.getOPType()))
		return;

	if ("clear".equals(newPath.getOPType())) {
		if (MetadataRepositories.getInstance().getBufferShapes().size() != 0) {
			System.out.println("������������ͼ������");
			MetadataRepositories.getInstance().getBufferShapes().clear();
		}
		return;
	}

	MetadataRepositories.getInstance().getBufferShapes().add(newPath);
	// // ��DZ��͑���д����ͼ������
	sendNewShapeToClient(newPath);
}
 
Example 6
Source File: RaopRtspChallengeResponseHandler.java    From Android-Airplay-Server with MIT License 6 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	final HttpResponse resp = (HttpResponse)evt.getMessage();

	synchronized(this) {
		if (m_challenge != null) {
			try {
				/* Get appropriate response to challenge and
				 * add to the response base-64 encoded. XXX
				 */
				final String sig = Base64.encodePadded(getSignature());

				resp.setHeader(HeaderSignature, sig);
			}
			finally {
				/* Forget last challenge */
				m_challenge = null;
				m_localAddress = null;
			}
		}
	}

	super.writeRequested(ctx, evt);
}
 
Example 7
Source File: MyClientHandler.java    From whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception
{
	try
	{
		if (mPainterCanvas != null)
		{
			Object message = e.getMessage();
			String hostAddress = ((InetSocketAddress) e.getRemoteAddress()).getAddress().getHostAddress();
			System.out.println("�ͻ��˶��յ�" + hostAddress + "��������Ϣ");

			// ���շ���˷��͹���������ͼ�������б�
			if (message instanceof List)
			{
				List<SerializablePath> paths = (List<SerializablePath>) message;
				MetadataRepositories.getInstance().getBufferShapes().addAll(paths);
				mPainterCanvas.repaint(true);
				ShapeRepositories.getInstance().getUndoCaches().addAll(paths);

			} else if (message instanceof SerializablePath)
			{
				Commons.pickRemotePathFirst = false;
				// ���շ���˷��͹�����һ��������µ�ͼ������
				currentRemotePath = (SerializablePath) message;
				MetadataRepositories.getInstance().getBufferShapes().add(currentRemotePath);

				// ����Զ�̿ͻ��˷�������ʷͼ�����ݣ����ȱ��汾�ؿͻ��˵���ʷͼ������
				Utils.pickUndoCaches();
				Commons.lastRemotePath = currentRemotePath;
				mPainterCanvas.repaint(false);
			}
		}

	} catch (Exception e2)
	{
		Log.i(TAG, e2.toString());
	}
}
 
Example 8
Source File: TestOutOfOrderWrite.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
  // Get handle from create response
  ChannelBuffer buf = (ChannelBuffer) e.getMessage();
  XDR rsp = new XDR(buf.array());
  if (rsp.getBytes().length == 0) {
    LOG.info("rsp length is zero, why?");
    return;
  }
  LOG.info("rsp length=" + rsp.getBytes().length);

  RpcReply reply = RpcReply.read(rsp);
  int xid = reply.getXid();
  // Only process the create response
  if (xid != 0x8000004c) {
    return;
  }
  int status = rsp.readInt();
  if (status != Nfs3Status.NFS3_OK) {
    LOG.error("Create failed, status =" + status);
    return;
  }
  LOG.info("Create succeeded");
  rsp.readBoolean(); // value follow
  handle = new FileHandle();
  handle.deserialize(rsp);
  channel = e.getChannel();
}
 
Example 9
Source File: HttpKeepAliveHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest && isKeepAliveSupported) {
        ctx.setAttachment(e.getMessage());
    }
    super.messageReceived(ctx, e);
}
 
Example 10
Source File: NetworkFailureHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
	if (blocked.get()) {
		return;
	}

	ChannelBuffer msg = (ChannelBuffer) event.getMessage();
	Channel targetChannel = sourceToTargetChannels.get(event.getChannel());
	if (targetChannel == null) {
		throw new IllegalStateException("Could not find a target channel for the source channel");
	}
	targetChannel.write(msg);
}
 
Example 11
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    final Object message = e.getMessage();
    if (message instanceof Packet) {
        final Packet packet = (Packet) message;
        final short packetType = packet.getPacketType();
        switch (packetType) {
            case PacketType.APPLICATION_RESPONSE:
                this.requestManager.messageReceived((ResponsePacket) message, objectUniqName);
                return;
            // have to handle a request message through connector
            case PacketType.APPLICATION_REQUEST:
                this.messageListener.handleRequest((RequestPacket) message, pinpointClient);
                return;
            case PacketType.APPLICATION_SEND:
                this.messageListener.handleSend((SendPacket) message, pinpointClient);
                return;
            case PacketType.APPLICATION_STREAM_CREATE:
            case PacketType.APPLICATION_STREAM_CLOSE:
            case PacketType.APPLICATION_STREAM_CREATE_SUCCESS:
            case PacketType.APPLICATION_STREAM_CREATE_FAIL:
            case PacketType.APPLICATION_STREAM_RESPONSE:
            case PacketType.APPLICATION_STREAM_PING:
            case PacketType.APPLICATION_STREAM_PONG:
                PinpointClientHandlerContext context = getChannelContext(channel);
                context.handleStreamEvent((StreamPacket) message);
                return;
            case PacketType.CONTROL_SERVER_CLOSE:
                handleClosedPacket(e.getChannel());
                return;
            case PacketType.CONTROL_HANDSHAKE_RESPONSE:
                handleHandshakePacket((ControlHandshakeResponsePacket) message, e.getChannel());
                return;
            default:
                logger.warn("{} messageReceived() failed. unexpectedMessage received:{} address:{}", objectUniqName, message, e.getRemoteAddress());
        }
    } else {
        logger.warn("{} messageReceived() failed. invalid messageReceived:{}", objectUniqName, message);
    }
}
 
Example 12
Source File: RaopRtpRetransmitRequestHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	if (evt.getMessage() instanceof RaopRtpPacket.AudioTransmit)
		audioTransmitReceived(ctx, (RaopRtpPacket.AudioTransmit)evt.getMessage());
	else if (evt.getMessage() instanceof RaopRtpPacket.AudioRetransmit)
		audioRetransmitReceived(ctx, (RaopRtpPacket.AudioRetransmit)evt.getMessage());

	super.messageReceived(ctx, evt);

	/* Request retransmits if necessary */
	requestRetransmits(ctx.getChannel(), m_audioClock.getNextSecondsTime());
}
 
Example 13
Source File: ClientIOHandler.java    From nfs-client-java with Apache License 2.0 5 votes vote down vote up
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    byte[] rpcResponse = (byte[]) e.getMessage();
    // remove marking
    Xdr x = RecordMarkingUtil.removeRecordMarking(rpcResponse);
    // remove the request from timeout manager map
    int xid = x.getXid();
    _connection.notifySender(Integer.valueOf(xid), x);
}
 
Example 14
Source File: HttpAppResolvingHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    //only set this on request - proceeding chunks will be routed on same outbound connection
    if (e.getMessage() instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) e.getMessage();

        request.setHeader(ROUTE_HEADER, STATIC_ROUTE);
        LOG.debug("setting header {} to {}", ROUTE_HEADER, STATIC_ROUTE);

        request.setHeader("host", new URL(STATIC_ROUTE).getHost());
    }

    super.messageReceived(ctx, e);
}
 
Example 15
Source File: RegistrationClient.java    From big-c with 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 16
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception {
	final RaopRtpPacket packet = (RaopRtpPacket)evt.getMessage();

	/* Get control and timing channel from the enclosing RaopAudioHandler */
	Channel tempControlChannel = null;
	Channel tempTimingChannel = null;
	
	synchronized(RaopAudioHandler.this) {
		tempControlChannel = controlChannel;
		tempTimingChannel = timingChannel;
	}

	if (packet instanceof RaopRtpPacket.RetransmitRequest) {
		if ((tempControlChannel != null) && tempControlChannel.isOpen() && tempControlChannel.isWritable()){
			tempControlChannel.write(evt.getMessage());
		}
	}
	else if (packet instanceof RaopRtpPacket.TimingRequest) {
		if ((tempTimingChannel != null) && tempTimingChannel.isOpen() && tempTimingChannel.isWritable()){
			tempTimingChannel.write(evt.getMessage());
		}
	}
	else {
		super.writeRequested(ctx, evt);
	}
}
 
Example 17
Source File: FpmSessionHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
    FpmHeader fpmMessage = (FpmHeader) e.getMessage();

    initConnection(ctx, fpmMessage);

    fpmListener.fpmMessage(us, fpmMessage);
}
 
Example 18
Source File: OFChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 4 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();

        LoadMonitor.LoadLevel loadlevel;
        int packets_dropped = 0;
        int packets_allowed = 0;
        int lldps_allowed = 0;

        if (this.controller.overload_drop) {
            loadlevel = this.controller.loadmonitor.getLoadLevel();
        }
        else {
            loadlevel = LoadMonitor.LoadLevel.OK;
        }

        for (OFMessage ofm : msglist) {
            counters.messageReceived.updateCounterNoFlush();
            // Per-switch input throttling
            if (sw != null && sw.inputThrottled(ofm)) {
                counters.messageInputThrottled.updateCounterNoFlush();
                continue;
            }
            try {
                if (this.controller.overload_drop &&
                    !loadlevel.equals(LoadMonitor.LoadLevel.OK)) {
                    switch (ofm.getType()) {
                    case PACKET_IN:
                        switch (loadlevel) {
                        case VERYHIGH:
                            // Drop all packet-ins, including LLDP/BDDPs
                            packets_dropped++;
                            continue;
                        case HIGH:
                            // Drop all packet-ins, except LLDP/BDDPs
                            byte[] data = ((OFPacketIn)ofm).getPacketData();
                            if (data.length > 14) {
                                if (((data[12] == (byte)0x88) &&
                                     (data[13] == (byte)0xcc)) ||
                                    ((data[12] == (byte)0x89) &&
                                     (data[13] == (byte)0x42))) {
                                    lldps_allowed++;
                                    packets_allowed++;
                                    break;
                                }
                            }
                            packets_dropped++;
                            continue;
                        default:
                            // Load not high, go ahead and process msg
                            packets_allowed++;
                            break;
                        }
                        break;
                    default:
                        // Process all non-packet-ins
                        packets_allowed++;
                        break;
                    }
                }

                // Do the actual packet processing
                state.processOFMessage(this, 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);
            }
        }

        if (loadlevel != LoadMonitor.LoadLevel.OK) {
            if (log.isDebugEnabled()) {
                log.debug(
                    "Overload: Detected {}, packets dropped={}",
                    loadlevel.toString(), packets_dropped);
                log.debug(
                    "Overload: Packets allowed={} (LLDP/BDDPs allowed={})",
                    packets_allowed, lldps_allowed);
            }
        }
        // Flush all thread local queues etc. generated by this train
        // of messages.
        this.controller.flushAll();
    }
    else {
        Channels.fireExceptionCaught(ctx.getChannel(),
                                     new AssertionError("Message received from Channel is not a list"));
    }
}
 
Example 19
Source File: HttpKeepAliveHandler.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) ctx.getAttachment();

    if (e.getMessage() instanceof HttpResponse) {

        HttpResponse response = (HttpResponse) e.getMessage();

        if (!response.isChunked()) {

            if (isKeepAliveSupported && isKeepAlive(request)) {

                LOG.debug("keep-alive IS implemented for this connection");

                // Add 'Content-Length' header only for a keep-alive connection.
                response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
                // Add keep alive header as per:
                // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
                response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

            } else {

                //not chunked and keep alive not supported, closing connection
                LOG.debug("keep-alive NOT implemented for this connection");
                e.getFuture().addListener(ChannelFutureListener.CLOSE);

            }

        } else {
            //response is chunked

            //don't send a content-length for chunked transfer-encoding
            response.removeHeader(CONTENT_LENGTH);

            //keep-alive explicitly off
            if (!isKeepAliveSupported || !isKeepAlive(request)) {
                response.removeHeader(CONNECTION);
                LOG.debug("keep-alive NOT implemented for this connection as it is explicitly turned off");
            } else {
                LOG.debug("keep-alive IMPLIED for this connection as it is chunked");
            }
        }
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("found chunk");
        if (((HttpChunk) e.getMessage()).isLast()) {

            if (!isKeepAliveSupported || !isKeepAlive(request)) {
                //keep alive explicitly off
                LOG.debug("reached the last chunk and keep alive is turned off so closing the connection");
                e.getFuture().addListener(ChannelFutureListener.CLOSE);
            }

        }
    } else {
        LOG.debug("found something else");
    }

    super.writeRequested(ctx, e);
}
 
Example 20
Source File: MemcachedCommandHandler.java    From fqueue with Apache License 2.0 4 votes vote down vote up
/**
 * The actual meat of the matter. Turn CommandMessages into executions
 * against the physical cache, and then pass on the downstream messages.
 * 
 * @param channelHandlerContext
 * @param messageEvent
 * @throws Exception
 */

@Override
@SuppressWarnings("unchecked")
public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent)
		throws Exception {
	if (!(messageEvent.getMessage() instanceof CommandMessage)) {
		// Ignore what this encoder can't encode.
		channelHandlerContext.sendUpstream(messageEvent);
		return;
	}

	CommandMessage<CACHE_ELEMENT> command = (CommandMessage<CACHE_ELEMENT>) messageEvent.getMessage();
	Command cmd = command.cmd;
	int cmdKeysSize = command.keys.size();

	// first process any messages in the delete queue
	cache.asyncEventPing();

	// now do the real work
	if (this.verbose) {
		StringBuilder log = new StringBuilder();
		log.append(cmd);
		if (command.element != null) {
			log.append(" ").append(command.element.getKeystring());
		}
		for (int i = 0; i < cmdKeysSize; i++) {
			log.append(" ").append(command.keys.get(i));
		}
		logger.info(log.toString());
	}

	Channel channel = messageEvent.getChannel();
	if (cmd == Command.GET || cmd == Command.GETS) {
		handleGets(channelHandlerContext, command, channel);
	} else if (cmd == Command.SET) {
		handleSet(channelHandlerContext, command, channel);
	} else if (cmd == Command.CAS) {
		handleCas(channelHandlerContext, command, channel);
	} else if (cmd == Command.ADD) {
		handleAdd(channelHandlerContext, command, channel);
	} else if (cmd == Command.REPLACE) {
		handleReplace(channelHandlerContext, command, channel);
	} else if (cmd == Command.APPEND) {
		handleAppend(channelHandlerContext, command, channel);
	} else if (cmd == Command.PREPEND) {
		handlePrepend(channelHandlerContext, command, channel);
	} else if (cmd == Command.INCR) {
		handleIncr(channelHandlerContext, command, channel);
	} else if (cmd == Command.DECR) {
		handleDecr(channelHandlerContext, command, channel);
	} else if (cmd == Command.DELETE) {
		handleDelete(channelHandlerContext, command, channel);
	} else if (cmd == Command.STATS) {
		handleStats(channelHandlerContext, command, cmdKeysSize, channel);
	} else if (cmd == Command.VERSION) {
		handleVersion(channelHandlerContext, command, channel);
	} else if (cmd == Command.QUIT) {
		handleQuit(channel);
	} else if (cmd == Command.FLUSH_ALL) {
		handleFlush(channelHandlerContext, command, channel);
	} else if (cmd == null) {
		// NOOP
		handleNoOp(channelHandlerContext, command);
	} else {
		throw new UnknownCommandException("unknown command:" + cmd);

	}

}