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

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project bagheera, under directory /src/test/java/com/mozilla/bagheera/http/.

Source file: AccessFilterTest.java

  22 
vote

private MessageEvent createMockEvent(Channel channel,HttpVersion protocolVersion,HttpMethod method,String uri){
  MessageEvent event=createMock(UpstreamMessageEvent.class);
  expect(event.getChannel()).andReturn(channel).anyTimes();
  expect(event.getFuture()).andReturn(new DefaultChannelFuture(channel,false)).anyTimes();
  expect(event.getRemoteAddress()).andReturn(remoteAddr);
  expect(event.getMessage()).andReturn(new BagheeraHttpRequest(protocolVersion,method,uri));
  replay(channel,event);
  return event;
}
 

Example 2

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/channel/.

Source file: SmppSessionLogger.java

  22 
vote

/** 
 * Logs the specified event to the  {@link InternalLogger} returned by{@link #getLogger()}. If hex dump has been enabled for this handler, the hex dump of the  {@link ChannelBuffer} in a {@link MessageEvent} willbe logged together.
 */
protected void log(Direction direction,ChannelEvent evt){
  if (evt instanceof MessageEvent) {
    MessageEvent me=(MessageEvent)evt;
    if ((me.getMessage() instanceof ChannelBuffer) && this.options.isLogBytesEnabled()) {
      ChannelBuffer buffer=(ChannelBuffer)me.getMessage();
      if (direction == Direction.UP) {
        logger.info("read bytes: [{}]",hexDump(buffer));
      }
 else       if (direction == Direction.DOWN) {
        logger.info("write bytes: [{}]",hexDump(buffer));
      }
    }
  }
}
 

Example 3

From project flazr, under directory /src/main/java/com/flazr/rtmp/client/.

Source file: ClientHandshakeHandler.java

  22 
vote

@Override public void handleUpstream(final ChannelHandlerContext ctx,final ChannelEvent ce) throws Exception {
  if (!handshakeDone || !rtmpe || !(ce instanceof MessageEvent)) {
    super.handleUpstream(ctx,ce);
    return;
  }
  final MessageEvent me=(MessageEvent)ce;
  if (me.getMessage() instanceof RtmpPublisher.Event) {
    super.handleUpstream(ctx,ce);
    return;
  }
  final ChannelBuffer in=(ChannelBuffer)((MessageEvent)ce).getMessage();
  handshake.cipherUpdateIn(in);
  Channels.fireMessageReceived(ctx,in);
}
 

Example 4

From project galaxy, under directory /src/co/paralleluniverse/galaxy/netty/.

Source file: OneToOneCodec.java

  22 
vote

@Override public void handleDownstream(ChannelHandlerContext ctx,ChannelEvent evt) throws Exception {
  if (!(evt instanceof MessageEvent)) {
    ctx.sendDownstream(evt);
    return;
  }
  final MessageEvent e=(MessageEvent)evt;
  final Object originalMessage=e.getMessage();
  final Object encodedMessage=encode(ctx,e.getChannel(),originalMessage);
  if (originalMessage == encodedMessage)   ctx.sendDownstream(evt);
 else   if (encodedMessage != null)   ctx.sendDownstream(new DownstreamMessageEvent(ctx.getChannel(),e.getFuture(),encodedMessage,e.getRemoteAddress()));
}
 

Example 5

From project thumbslug, under directory /src/test/java/org/candlepin/thumbslug/.

Source file: HttpRequestLoggerTest.java

  22 
vote

@Test public void testIpAddressIsSet() throws Exception {
  HttpRequestLogger logger=new HttpRequestLogger("nofile");
  ChannelHandlerContext ctx=mock(ChannelHandlerContext.class);
  MessageEvent e=mock(MessageEvent.class);
  DefaultHttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,"/");
  when(e.getMessage()).thenReturn(request);
  InetSocketAddress mockAddress=createIpAddress();
  when(e.getRemoteAddress()).thenReturn(mockAddress);
  logger.handleUpstream(ctx,e);
  assertEquals("192.168.0.3",logger.getInetAddress());
}
 

Example 6

From project adbcj, under directory /mysql/netty/src/main/java/org/adbcj/mysql/netty/.

Source file: MysqlConnectionManager.java

  21 
vote

public void handleDownstream(ChannelHandlerContext context,ChannelEvent event) throws Exception {
  if (!(event instanceof MessageEvent)) {
    context.sendDownstream(event);
    return;
  }
  MessageEvent e=(MessageEvent)event;
  if (!(e.getMessage() instanceof ClientRequest)) {
    context.sendDownstream(event);
    return;
  }
  ChannelBuffer buffer=ChannelBuffers.buffer(1024);
  ChannelBufferOutputStream out=new ChannelBufferOutputStream(buffer);
  encoder.encode((ClientRequest)e.getMessage(),out);
  Channels.write(context,e.getFuture(),buffer);
}
 

Example 7

From project efflux, under directory /src/main/java/com/biasedbit/efflux/network/.

Source file: ControlPacketDecoder.java

  21 
vote

public void handleUpstream(ChannelHandlerContext ctx,ChannelEvent evt) throws Exception {
  if (!(evt instanceof MessageEvent)) {
    ctx.sendUpstream(evt);
    return;
  }
  MessageEvent e=(MessageEvent)evt;
  if (!(e.getMessage() instanceof ChannelBuffer)) {
    return;
  }
  ChannelBuffer buffer=(ChannelBuffer)e.getMessage();
  if ((buffer.readableBytes() % 4) != 0) {
    LOG.debug("Invalid RTCP packet received: total length should be multiple of 4 but is {}",buffer.readableBytes());
    return;
  }
  List<ControlPacket> controlPacketList=new ArrayList<ControlPacket>(2);
  while (buffer.readableBytes() > 0) {
    try {
      controlPacketList.add(ControlPacket.decode(buffer));
    }
 catch (    Exception e1) {
      LOG.debug("Exception caught while decoding RTCP packet.",e1);
    }
  }
  if (!controlPacketList.isEmpty()) {
    Channels.fireMessageReceived(ctx,new CompoundControlPacket(controlPacketList),e.getRemoteAddress());
  }
}
 

Example 8

From project fast-http, under directory /src/test/java/org/neo4j/smack/pipeline/http/.

Source file: TestHttpDecoder.java

  21 
vote

private void testDecoding(ChannelBuffer buf,RequestMatcher... requestMatchers) throws Exception {
  DummyInputGate inputGate=new DummyInputGate();
  HttpDecoder decoder=new HttpDecoder(inputGate);
  MessageEvent msg=mock(MessageEvent.class);
  when(msg.getMessage()).thenReturn(buf);
  ChannelConfig channelConfig=mock(ChannelConfig.class);
  when(channelConfig.getBufferFactory()).thenReturn(new HeapChannelBufferFactory());
  Channel channel=mock(Channel.class);
  when(channel.getConfig()).thenReturn(channelConfig);
  ChannelHandlerContext ctx=mock(ChannelHandlerContext.class);
  when(ctx.getChannel()).thenReturn(channel);
  decoder.messageReceived(ctx,msg);
  assertThat("Should yield " + requestMatchers.length + " input requests",inputGate.requests.size(),is(requestMatchers.length));
  for (int i=0; i < requestMatchers.length; i++) {
    requestMatchers[i].assertMatches(inputGate.requests.get(i));
  }
}
 

Example 9

From project httptunnel, under directory /src/main/java/com/yammer/httptunnel/server/.

Source file: HttpTunnelAcceptedChannelSink.java

  21 
vote

@Override public void eventSunk(ChannelPipeline pipeline,ChannelEvent e) throws Exception {
  final HttpTunnelAcceptedChannel channel=(HttpTunnelAcceptedChannel)e.getChannel();
  if (e instanceof ChannelStateEvent) {
    final ChannelStateEvent event=(ChannelStateEvent)e;
switch (event.getState()) {
case OPEN:
{
        final boolean opened=(Boolean)event.getValue();
        if (!opened)         channel.internalClose(true,e.getFuture());
        break;
      }
case INTEREST_OPS:
{
      final int interestOps=(Integer)event.getValue();
      channel.internalSetInterestOps(interestOps,event.getFuture());
      break;
    }
}
return;
}
if (e instanceof MessageEvent) {
final MessageEvent message=(MessageEvent)e;
channel.sendMessage(message);
return;
}
}
 

Example 10

From project netty-icap, under directory /src/test/java/ch/mimo/netty/handler/codec/icap/socket/.

Source file: TrickleDownstreamHandler.java

  21 
vote

@Override public void handleDownstream(ChannelHandlerContext ctx,ChannelEvent e) throws Exception {
  if (e instanceof MessageEvent) {
    MessageEvent event=(MessageEvent)e;
    ChannelBuffer buffer=(ChannelBuffer)event.getMessage();
    while (buffer.readableBytes() > 0) {
      ChannelBuffer newBuffer=ChannelBuffers.dynamicBuffer();
      if (buffer.readableBytes() >= chunkSize) {
        newBuffer.writeBytes(buffer.readBytes(chunkSize));
      }
 else {
        newBuffer.writeBytes(buffer.readBytes(buffer.readableBytes()));
      }
      Thread.sleep(latency);
      write(ctx,e.getFuture(),newBuffer,event.getRemoteAddress());
    }
  }
 else {
    ctx.sendDownstream(e);
  }
}
 

Example 11

From project pasc-paxos, under directory /src/main/java/com/yahoo/pasc/paxos/messages/serialization/.

Source file: ManualEncoder.java

  21 
vote

public void handleDownstream(final ChannelHandlerContext ctx,ChannelEvent evt){
  if (!(evt instanceof MessageEvent)) {
    ctx.sendDownstream(evt);
    return;
  }
  MessageEvent e=(MessageEvent)evt;
  PaxosMessage originalMessage=(PaxosMessage)e.getMessage();
  int size=getSize(originalMessage,true);
  ChannelBuffer encodedMessage=encode(originalMessage,true,size,pool.getDirectBuffer(size));
  ChannelFuture future=e.getFuture();
  if (LOG.isTraceEnabled()) {
    LOG.trace("Encoded message with bytes {} ",ChannelBuffers.copiedBuffer(encodedMessage).array());
  }
  write(ctx,future,encodedMessage,e.getRemoteAddress());
}
 

Example 12

From project SpoutAPI, under directory /src/main/java/org/spout/api/protocol/.

Source file: PostprocessEncoder.java

  21 
vote

@Override public void handleDownstream(ChannelHandlerContext ctx,ChannelEvent evt) throws Exception {
  if (locked.get()) {
    throw new IllegalStateException("Encode attempted when channel was locked");
  }
  ChannelProcessor processor=this.processor.get();
  if (processor == null) {
    super.handleDownstream(ctx,evt);
    if (evt instanceof MessageEvent) {
      checkForSetupMessage(((MessageEvent)evt).getMessage());
    }
  }
 else   if (!(evt instanceof MessageEvent)) {
    super.handleDownstream(ctx,evt);
  }
 else {
    MessageEvent e=(MessageEvent)evt;
    Object originalMessage=e.getMessage();
    Object encodedMessage=encode(ctx,e.getChannel(),originalMessage);
    if (originalMessage == encodedMessage) {
      ctx.sendDownstream(evt);
    }
 else     if (encodedMessage != null) {
      if (encodedMessage instanceof ChannelBuffer) {
synchronized (this) {
          encodedMessage=processor.write(ctx,(ChannelBuffer)encodedMessage);
          write(ctx,e.getFuture(),encodedMessage,e.getRemoteAddress());
        }
      }
 else {
        write(ctx,e.getFuture(),encodedMessage,e.getRemoteAddress());
      }
    }
    checkForSetupMessage(originalMessage);
  }
}
 

Example 13

From project TomP2P, under directory /src/main/java/net/tomp2p/message/.

Source file: TomP2PDecoderUDP.java

  21 
vote

@Override public void handleUpstream(final ChannelHandlerContext ctx,final ChannelEvent evt) throws Exception {
  if (!(evt instanceof MessageEvent)) {
    ctx.sendUpstream(evt);
    return;
  }
  final MessageEvent e=(MessageEvent)evt;
  final Object originalMessage=e.getMessage();
  if (!(originalMessage instanceof ChannelBuffer)) {
    ctx.sendUpstream(evt);
    return;
  }
  Message message=decode(ctx,e.getChannel(),(ChannelBuffer)originalMessage,e.getRemoteAddress());
  if (message != null) {
    Channels.fireMessageReceived(ctx,message,e.getRemoteAddress());
  }
}
 

Example 14

From project Agot-Java, under directory /src/main/java/got/server/.

Source file: ServerHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e){
  System.out.println("Receive Message");
  Message message=new Message();
  message.setMsg("ehlo");
  e.getChannel().write(message);
}
 

Example 15

From project AirReceiver, under directory /src/main/java/org/phlo/AirReceiver/.

Source file: RaopRtpRetransmitRequestHandler.java

  19 
vote

@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);
  requestRetransmits(ctx.getChannel(),m_audioClock.getNextSecondsTime());
}
 

Example 16

From project ardverk-dht, under directory /components/http/src/main/java/org/ardverk/dht/http/.

Source file: HttpTransport.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,final MessageEvent e) throws IOException {
  HttpRequest httpRequest=(HttpRequest)e.getMessage();
  SocketAddress src=e.getRemoteAddress();
  ChannelBuffer content=httpRequest.getContent();
  ByteArrayInputStream bais=new ByteArrayInputStream(content.array());
  Decoder decoder=codec.createDecoder(src,bais);
  RequestMessage request=(RequestMessage)decoder.read();
  decoder.close();
  ResponseMessage response=HttpTransport.this.handleRequest(request);
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Encoder encoder=codec.createEncoder(baos);
  encoder.write(response);
  encoder.close();
  byte[] encoded=baos.toByteArray();
  HttpResponse httpResponse=new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK);
  httpResponse.setContent(ChannelBuffers.copiedBuffer(encoded));
  httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH,encoded.length);
  httpResponse.setHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
  Channel channel=e.getChannel();
  ChannelFuture future=channel.write(httpResponse);
  future.addListener(ChannelFutureListener.CLOSE);
  future.addListener(new MessageListener(request,response));
}
 

Example 17

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: NettyServer.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e){
  try {
    NettyDataPack dataPack=(NettyDataPack)e.getMessage();
    List<ByteBuffer> req=dataPack.getDatas();
    List<ByteBuffer> res=responder.respond(req,connectionMetadata);
    if (res != null) {
      dataPack.setDatas(res);
      e.getChannel().write(dataPack);
    }
  }
 catch (  IOException ex) {
    LOG.warn("unexpect error");
  }
}
 

Example 18

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.

Source file: JsonHttpRequestHandler.java

  19 
vote

/** 
 * Handles incoming HTTP data
 * @param ctx Channel Handler Context
 * @param e Message event
 */
@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object msg=e.getMessage();
  if (msg instanceof HttpRequest) {
    handleHttpRequest(ctx,e,(HttpRequest)msg);
  }
 else   if (msg instanceof WebSocketFrame) {
    handleWebSocketFrame(ctx,(WebSocketFrame)msg);
  }
 else {
    throw new UnsupportedOperationException("Message of type '" + msg.getClass().getName() + "' is not supported.");
  }
}
 

Example 19

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: ClientMessageHandler.java

  19 
vote

@Override public void messageReceived(final ChannelHandlerContext ctx,final MessageEvent e) throws Exception {
  final Object o=e.getMessage();
  if (o instanceof ApplicationMessage) {
    logger.trace("Received application message ({})- routing to handleApplicationMessage(...)",o);
    handleApplicationMessage(ctx,(ApplicationMessage)o);
  }
 else   super.messageReceived(ctx,e);
}
 

Example 20

From project enterprise, under directory /com/src/main/java/org/neo4j/com/.

Source file: Server.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent event) throws Exception {
  try {
    ChannelBuffer message=(ChannelBuffer)event.getMessage();
    handleRequest(message,event.getChannel());
  }
 catch (  Throwable e) {
    msgLog.logMessage("Error handling request",e);
    ctx.getChannel().close();
    tryToFinishOffChannel(ctx.getChannel());
    throw Exceptions.launderedException(e);
  }
}
 

Example 21

From project floodlight, under directory /src/main/java/net/floodlightcontroller/core/internal/.

Source file: Controller.java

  19 
vote

@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 {
        processOFMessage(ofm);
      }
 catch (      Exception ex) {
        Channels.fireExceptionCaught(ctx.getChannel(),ex);
      }
    }
    OFSwitchImpl.flush_all();
  }
}
 

Example 22

From project flume, under directory /flume-ng-core/src/main/java/org/apache/flume/source/.

Source file: SyslogTcpSource.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent mEvent){
  ChannelBuffer buff=(ChannelBuffer)mEvent.getMessage();
  while (buff.readable()) {
    Event e=syslogUtils.extractEvent(buff);
    if (e == null) {
      logger.debug("Parsed partial event, event will be generated when " + "rest of the event is received.");
      continue;
    }
    try {
      getChannelProcessor().processEvent(e);
      counterGroup.incrementAndGet("events.success");
    }
 catch (    ChannelException ex) {
      counterGroup.incrementAndGet("events.dropped");
      logger.error("Error writting to channel, event dropped",ex);
    }
  }
}
 

Example 23

From project giraph, under directory /src/main/java/org/apache/giraph/comm/netty/.

Source file: ByteCounter.java

  19 
vote

@Override public void handleUpstream(ChannelHandlerContext ctx,ChannelEvent e) throws Exception {
  if (e instanceof MessageEvent && ((MessageEvent)e).getMessage() instanceof ChannelBuffer) {
    ChannelBuffer b=(ChannelBuffer)((MessageEvent)e).getMessage();
    bytesReceived.addAndGet(b.readableBytes());
    receivedRequests.incrementAndGet();
    if (LOG.isDebugEnabled()) {
      LOG.debug("handleUpstream: " + ctx.getName() + " buffer size = "+ b.readableBytes()+ ", total bytes = "+ bytesReceived.get());
    }
  }
  super.handleUpstream(ctx,e);
}
 

Example 24

From project gnip4j, under directory /mock-server/src/main/java/com/zaubersoftware/gnip4j/server/netty/.

Source file: HttpGnipServerHandler.java

  19 
vote

@Override public void messageReceived(final ChannelHandlerContext ctx,final MessageEvent e) throws Exception {
  final HttpRequest request=(HttpRequest)e.getMessage();
  if (request.getMethod() != GET) {
    sendError(ctx,METHOD_NOT_ALLOWED);
    return;
  }
  final String uri=request.getUri();
  if (uri.equals("/fake-stream")) {
    final HttpResponse response=new DefaultHttpResponse(HTTP_1_1,OK);
    response.setHeader(TRANSFER_ENCODING,"chunked");
    response.setChunked(true);
    final Channel ch=e.getChannel();
    ch.write(response);
    ch.write(getChunkedInput());
  }
 else   if (uri.equals("/")) {
    final HttpResponse response=new DefaultHttpResponse(HTTP_1_1,OK);
    response.setStatus(MOVED_PERMANENTLY);
    response.setHeader(LOCATION,"/fake-stream");
    final Channel ch=e.getChannel();
    ChannelFuture writeFuture;
    writeFuture=ch.write(response);
    writeFuture.addListener(ChannelFutureListener.CLOSE);
  }
 else {
    sendError(ctx,NOT_FOUND);
    return;
  }
}
 

Example 25

From project graylog2-server, under directory /src/main/java/org/graylog2/inputs/gelf/.

Source file: GELFDispatcher.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Metrics.newMeter(GELFDispatcher.class,"ReceivedMessages","messages",TimeUnit.SECONDS).mark();
  ChannelBuffer buffer=(ChannelBuffer)e.getMessage();
  byte[] readable=new byte[buffer.readableBytes()];
  buffer.toByteBuffer().get(readable,buffer.readerIndex(),buffer.readableBytes());
  GELFMessage msg=new GELFMessage(readable);
switch (msg.getGELFType()) {
case CHUNKED:
    Metrics.newMeter(GELFDispatcher.class,"DispatchedMessagesChunks","messages",TimeUnit.SECONDS).mark();
  server.getGELFChunkManager().insert(msg);
break;
case ZLIB:
case GZIP:
case UNCOMPRESSED:
case UNSUPPORTED:
Metrics.newMeter(GELFDispatcher.class,"DispatchedNonChunkedMessages","messages",TimeUnit.SECONDS).mark();
processor.messageReceived(msg);
break;
}
}
 

Example 26

From project hotpotato, under directory /src/functionaltest/java/com/biasedbit/hotpotato/pipelining/.

Source file: Http11PipeliningTestClient.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  HttpResponse response=(HttpResponse)e.getMessage();
  String body=response.getContent().toString(CharsetUtil.UTF_8);
  int number=Integer.parseInt(body.substring(1));
  if (this.lastReceived != null) {
    if (number <= this.lastReceived.getAndIncrement()) {
      System.err.println(">> OUT OF ORDER! Expecting " + (this.lastReceived.get() - 1) + " but got "+ number);
      this.lastReceived.set(number);
    }
 else {
      System.out.println(">> " + number + " (IN ORDER)");
    }
  }
 else {
    this.lastReceived=new AtomicInteger(number);
    System.out.println(">> " + number + " (FIRST, IN ORDER)");
  }
}
 

Example 27

From project http-client, under directory /src/main/java/com/biasedbit/http/connection/.

Source file: PipeliningHttpConnection.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
synchronized (this.mutex) {
    if ((this.terminate != null) || this.requests.isEmpty()) {
      return;
    }
    if (!this.readingChunks) {
      HttpResponse response=(HttpResponse)e.getMessage();
      this.receivedResponseForRequest(response);
      if (response.isChunked() && ((response.getContent() == null) || (response.getContent().readableBytes() == 0))) {
        this.readingChunks=true;
      }
 else {
        ChannelBuffer content=response.getContent();
        if (content.readable()) {
          this.receivedContentForRequest(content,true);
        }
        this.responseForRequestComplete();
      }
    }
 else {
      HttpChunk chunk=(HttpChunk)e.getMessage();
      if (chunk.isLast()) {
        this.readingChunks=false;
        this.receivedContentForRequest(chunk.getContent(),true);
        this.responseForRequestComplete();
      }
 else {
        this.receivedContentForRequest(chunk.getContent(),false);
      }
    }
  }
}
 

Example 28

From project idigi-java-monitor-api, under directory /netty/src/main/java/com/idigi/api/monitor/netty/.

Source file: ConnectHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent event) throws Exception {
  if (event.getMessage() instanceof ConnectResponse) {
    logger.info("Connected to iDigi monitor #{}.",request.monitorId);
    ctx.getPipeline().replace("decoder","decoder",new MessageDataBlockDecoder());
  }
  ctx.sendUpstream(event);
}
 

Example 29

From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/tcp/.

Source file: TCPListener.java

  19 
vote

public void messageReceived(ChannelHandlerContext ctx,MessageEvent e){
  channels.add(e.getChannel());
  ChannelBuffer buffer=(ChannelBuffer)e.getMessage();
  try {
    handoffQueue.put(buffer.array());
  }
 catch (  InterruptedException ie) {
    Thread.currentThread().interrupt();
  }
}
 

Example 30

From project james, under directory /protocols-imap4/src/main/java/org/apache/james/imapserver/netty/.

Source file: ImapChannelUpstreamHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  ImapSession session=(ImapSession)attributes.get(ctx.getChannel());
  ImapResponseComposer response=(ImapResponseComposer)ctx.getAttachment();
  ImapMessage message=(ImapMessage)e.getMessage();
  ChannelPipeline cp=ctx.getPipeline();
  try {
    if (cp.get(NettyConstants.EXECUTION_HANDLER) != null) {
      cp.addBefore(NettyConstants.EXECUTION_HANDLER,NettyConstants.HEARTBEAT_HANDLER,heartbeatHandler);
    }
 else {
      cp.addBefore(NettyConstants.CORE_HANDLER,NettyConstants.HEARTBEAT_HANDLER,heartbeatHandler);
    }
    final ResponseEncoder responseEncoder=new ResponseEncoder(encoder,response,session);
    processor.process(message,responseEncoder,session);
    if (session.getState() == ImapSessionState.LOGOUT) {
      Channel channel=ctx.getChannel();
      if (channel.isConnected()) {
        channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
      }
    }
    final IOException failure=responseEncoder.getFailure();
    if (failure != null) {
      final Logger logger=session.getLog();
      logger.info(failure.getMessage());
      if (logger.isDebugEnabled()) {
        logger.debug("Failed to write " + message,failure);
      }
      throw failure;
    }
  }
  finally {
    ctx.getPipeline().remove(NettyConstants.HEARTBEAT_HANDLER);
  }
  super.messageReceived(ctx,e);
}
 

Example 31

From project java-webserver, under directory /src/org/nikki/http/fastcgi/net/.

Source file: FastCGIChannelHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object message=e.getMessage();
  if (message instanceof FastCGIResponse) {
    FastCGIResponse response=(FastCGIResponse)message;
    ChannelBuffer buffer=response.getData();
    HttpResponse res=new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK);
    FastCGIUtil.parseHeaders(res,buffer);
    res.setContent(buffer.readBytes(buffer.readableBytes()));
    HttpSession session=module.getRequest(response.getId());
    if (session != null) {
      session.sendHttpResponse(res);
    }
  }
}
 

Example 32

From project l2jserver2, under directory /l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/game/net/handler/.

Source file: Lineage2PacketHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  final Object msg=e.getMessage();
  if (!(msg instanceof ClientPacket))   return;
  final ClientPacket packet=(ClientPacket)msg;
  packet.process(connection);
  super.messageReceived(ctx,e);
}
 

Example 33

From project Lily, under directory /global/rowlog/impl/src/main/java/org/lilyproject/rowlog/impl/.

Source file: RemoteListenerHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  RowLogMessage message=(RowLogMessage)e.getMessage();
  boolean result=consumer.processMessage(message);
  writeResult(e.getChannel(),result);
  semaphore.acquire();
}
 

Example 34

From project msgpack-rpc, under directory /java/src/main/java/org/msgpack/rpc/loop/netty/.

Source file: MessageHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e){
  Object m=e.getMessage();
  if (!(m instanceof Value)) {
    ctx.sendUpstream(e);
    return;
  }
  Value msg=(Value)m;
  handler.handleMessage(adaptor,msg);
}
 

Example 35

From project nettosphere, under directory /server/src/main/java/org/atmosphere/nettosphere/.

Source file: HttpStaticFileServerHandler.java

  19 
vote

protected void sendError(ChannelHandlerContext ctx,HttpResponseStatus status,MessageEvent e){
  HttpResponse response=new DefaultHttpResponse(HTTP_1_1,status);
  response.setHeader(CONTENT_TYPE,"text/plain; charset=UTF-8");
  response.setHeader(CONTENT_LENGTH,"0");
  response.setHeader("Server","Atmosphere-" + Version.getRawVersion());
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 

Example 36

From project netty-socketio, under directory /src/main/java/com/corundumstudio/socketio/handler/.

Source file: AuthorizeHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object msg=e.getMessage();
  if (msg instanceof HttpRequest) {
    HttpRequest req=(HttpRequest)msg;
    Channel channel=ctx.getChannel();
    QueryStringDecoder queryDecoder=new QueryStringDecoder(req.getUri());
    if (!configuration.isAllowCustomRequests() && !queryDecoder.getPath().startsWith(connectPath)) {
      HttpResponse res=new DefaultHttpResponse(HTTP_1_1,HttpResponseStatus.BAD_REQUEST);
      ChannelFuture f=channel.write(res);
      f.addListener(ChannelFutureListener.CLOSE);
      return;
    }
    if (queryDecoder.getPath().equals(connectPath)) {
      String origin=req.getHeader(HttpHeaders.Names.ORIGIN);
      authorize(channel,origin,queryDecoder.getParameters());
      return;
    }
  }
  ctx.sendUpstream(e);
}
 

Example 37

From project netty-xmpp, under directory /src/main/java/es/udc/pfc/xmpp/handler/.

Source file: XMLElementDecoder.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  if (!(e.getMessage() instanceof XMLEvent)) {
    ctx.sendUpstream(e);
    return;
  }
  final XMLEvent event=(XMLEvent)e.getMessage();
  if (event.isStartDocument() || event.isEndDocument())   return;
  if (depth < skip && event.isStartElement()) {
    ctx.sendUpstream(e);
    depth++;
    return;
  }
  if (depth <= skip && event.isEndElement()) {
    ctx.sendUpstream(e);
    depth--;
    return;
  }
  writer.add(event);
  if (event.isStartElement()) {
    depth++;
  }
 else   if (event.isEndElement()) {
    depth--;
    if (depth == skip) {
      writer.flush();
      Channels.fireMessageReceived(ctx,XMLElementImpl.fromElement(document.getDocumentElement()));
      writer.close();
      resetWriter();
    }
  }
}
 

Example 38

From project niosmtp, under directory /src/main/java/me/normanmaurer/niosmtp/transport/netty/internal/.

Source file: SMTPConnectHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object msg=e.getMessage();
  if (msg instanceof SMTPResponse) {
    ctx.getChannel().getPipeline().remove(this);
    future.setSMTPClientSession(getSession(ctx));
    future.setResult(new FutureResultImpl<SMTPResponse>((SMTPResponse)msg));
  }
 else {
    super.messageReceived(ctx,e);
  }
}
 

Example 39

From project omid, under directory /src/main/java/com/yahoo/omid/client/regionserver/.

Source file: Compacter.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object message=e.getMessage();
  if (message instanceof MinimumTimestamp) {
    Compacter.this.minTimestamp=((MinimumTimestamp)message).getTimestamp();
  }
 else {
    System.out.println("Wtf " + message);
  }
}
 

Example 40

From project opentsdb, under directory /src/tsd/.

Source file: RpcHandler.java

  19 
vote

@Override public void messageReceived(final ChannelHandlerContext ctx,final MessageEvent msgevent){
  try {
    final Object message=msgevent.getMessage();
    if (message instanceof String[]) {
      handleTelnetRpc(msgevent.getChannel(),(String[])message);
    }
 else     if (message instanceof HttpRequest) {
      handleHttpQuery(msgevent.getChannel(),(HttpRequest)message);
    }
 else {
      logError(msgevent.getChannel(),"Unexpected message type " + message.getClass() + ": "+ message);
      exceptions_caught.incrementAndGet();
    }
  }
 catch (  Exception e) {
    Object pretty_message=msgevent.getMessage();
    if (pretty_message instanceof String[]) {
      pretty_message=Arrays.toString((String[])pretty_message);
    }
    logError(msgevent.getChannel(),"Unexpected exception caught" + " while serving " + pretty_message,e);
    exceptions_caught.incrementAndGet();
  }
}
 

Example 41

From project osiris, under directory /src/osiris/net/.

Source file: OsirisUpstreamHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Packet packet=(Packet)e.getMessage();
  Class<GameEvent> clazz=GameEventLookup.lookup(packet.getHeader().getOpcode());
  if (clazz.getSuperclass().equals(GameEvent.class) && !clazz.equals(ServiceRequestEvent.class)) {
    GameEvent event;
synchronized (playerMap) {
      Player player=playerMap.get(e.getChannel().getId());
      event=clazz.getConstructor(Player.class,Packet.class).newInstance(player,packet);
    }
    ServerEngine.queueGameEvent(event);
  }
 else {
    GameEvent event=clazz.getConstructor(Channel.class,Packet.class).newInstance(e.getChannel(),packet);
    event.process();
    event=null;
  }
  clazz=null;
}
 

Example 42

From project ptest-server, under directory /src/main/java/com/mnxfst/testing/server/handler/.

Source file: TSHttpRequestHandler.java

  19 
vote

/** 
 * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext,org.jboss.netty.channel.MessageEvent)
 */
public void messageReceived(ChannelHandlerContext ctx,MessageEvent event) throws Exception {
  HttpRequest httpRequest=(HttpRequest)event.getMessage();
  boolean keepAlive=HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(httpRequest.getHeader(HttpHeaders.Names.CONNECTION));
  QueryStringDecoder decoder=new QueryStringDecoder(httpRequest.getUri());
  Map<String,List<String>> queryParams=decoder.getParameters();
  if (httpRequest.getMethod() == HttpMethod.POST) {
    decoder=new QueryStringDecoder("?" + httpRequest.getContent().toString(CharsetUtil.UTF_8));
    queryParams.putAll(decoder.getParameters());
  }
  if (queryParams.containsKey(REQUEST_PARAM_EXECUTE_TESTPLAN)) {
    executeTestplan(queryParams,keepAlive,event);
  }
 else   if (queryParams.containsKey(REQUEST_PARAM_COLLECT_EXECUTION_RESULTS)) {
    collectTestplanResults(queryParams,keepAlive,event);
  }
 else {
    List<Integer> codes=new ArrayList<Integer>();
    codes.add(ERROR_CODE_INVALID_OPTION_CODE);
    sendResponse(generateErrorMessage(codes,""),keepAlive,event);
  }
}
 

Example 43

From project scalatra-netty_1, under directory /src/main/java/org/jboss/netty/handler/codec/http2/.

Source file: HttpContentEncoder.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object msg=e.getMessage();
  if (!(msg instanceof HttpMessage)) {
    ctx.sendUpstream(e);
    return;
  }
  HttpMessage m=(HttpMessage)msg;
  String acceptedEncoding=m.getHeader(HttpHeaders.Names.ACCEPT_ENCODING);
  if (acceptedEncoding == null) {
    acceptedEncoding=HttpHeaders.Values.IDENTITY;
  }
  boolean offered=acceptEncodingQueue.offer(acceptedEncoding);
  assert offered;
  ctx.sendUpstream(e);
}
 

Example 44

From project sesam, under directory /sesam-bundles/sesam-monitor/src/main/java/be/vlaanderen/sesam/monitor/.

Source file: MonitorTask.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  log.debug("Received response");
  if (running.get()) {
    try {
      timewaited=System.currentTimeMillis() - start;
      if (timewaited > getResponseTimeoutMillis()) {
        logResult(NOTIFICATIONTYPE_TIMEOUT);
      }
 else {
        if (e.getMessage() instanceof HttpResponse) {
          HttpResponse response=(HttpResponse)e.getMessage();
          if (checkStatusCode(response) && checkHeaders(response) && checkBody(response)) {
            logResult(NOTIFICATIONTYPE_SUCCESS);
          }
        }
 else {
          log.warn("Was expecting a HttpMessage, not chunk");
        }
      }
      e.getChannel().close();
    }
 catch (    Exception ex) {
      log.warn("Exception while testing response: " + ex.getMessage());
    }
 finally {
      running.set(false);
    }
  }
 else {
    log.debug("received a response outside of test");
  }
}
 

Example 45

From project sitebricks, under directory /sitebricks-mail/src/main/java/com/google/sitebricks/mail/.

Source file: MailClientHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  String message=e.getMessage().toString();
  for (  String input : inputBuffer.processMessage(message)) {
    processMessage(input);
  }
}
 

Example 46

From project soja, under directory /soja-client/src/main/java/com/excilys/soja/client/handler/.

Source file: ClientHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  if (!(e.getMessage() instanceof Frame)) {
    LOGGER.error("Not a frame... {}",e.getMessage());
    return;
  }
  Channel channel=ctx.getChannel();
  Frame frame=(Frame)e.getMessage();
  if (frame.isCommand(Frame.COMMAND_ERROR)) {
    LOGGER.error("STOMP error '{}' : {}",frame.getHeaderValue(HEADER_MESSAGE),frame.getBody());
  }
 else {
    LOGGER.trace("Received frame from {} : {}",channel.getRemoteAddress(),frame);
    if (frame.isCommand(COMMAND_CONNECTED)) {
      handleConnected(channel,frame);
    }
 else     if (frame.isCommand(COMMAND_MESSAGE)) {
      handleMessage(channel,frame);
    }
 else     if (frame.isCommand(COMMAND_RECEIPT)) {
      handleReceipt(channel,frame);
    }
 else     if (frame.isCommand(COMMAND_HEARBEAT)) {
      handleHeartBeat(channel,frame);
    }
 else {
      LOGGER.error("The command '{}' is unkown and can't be managed",frame.getCommand());
    }
  }
}
 

Example 47

From project stilts, under directory /stomp-client/src/main/java/org/projectodd/stilts/stomp/client/protocol/.

Source file: AbstractClientControlFrameHandler.java

  19 
vote

@Override public void messageReceived(ChannelHandlerContext channelContext,MessageEvent e) throws Exception {
  log.trace("received: " + e.getMessage());
  if (e.getMessage() instanceof StompFrame) {
    handleStompFrame(channelContext,(StompFrame)e.getMessage());
  }
  super.messageReceived(channelContext,e);
}
 

Example 48

From project ubuntu-packaging-floodlight, under directory /src/main/java/net/floodlightcontroller/core/internal/.

Source file: Controller.java

  19 
vote

@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 {
        processOFMessage(ofm);
      }
 catch (      Exception ex) {
        Channels.fireExceptionCaught(ctx.getChannel(),ex);
      }
    }
    OFSwitchImpl.flush_all();
  }
}
 

Example 49

From project usergrid-stack, under directory /mongo-emulator/src/main/java/org/usergrid/mongo/commands/.

Source file: Collstats.java

  19 
vote

@Override public OpReply execute(MongoChannelHandler handler,ChannelHandlerContext ctx,MessageEvent e,OpQuery opQuery){
  ApplicationInfo application=SubjectUtils.getApplication(Identifier.from(opQuery.getDatabaseName()));
  OpReply reply=new OpReply(opQuery);
  if (application == null) {
    return reply;
  }
  EntityManager em=handler.getEmf().getEntityManager(application.getId());
  String collectionName=(String)opQuery.getQuery().get("collstats");
  long count=0;
  try {
    count=em.getApplicationCollectionSize(collectionName);
  }
 catch (  Exception e1) {
  }
  reply.addDocument(map(entry("ns",opQuery.getDatabaseName() + "." + collectionName),entry("count",count),entry("size",count * 40),entry("avgObjSize",40.0),entry("storageSize",8192),entry("numExtents",1),entry("nindexes",1),entry("lastExtentSize",8192),entry("paddingFactor",1.0),entry("flags",1),entry("totalIndexSize",8192),entry("indexSizes",map("_id_",8192)),entry("ok",1.0)));
  return reply;
}