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

The following examples show how to use org.jboss.netty.channel.MessageEvent. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: feeyo-hlsserver   Source File: HlsStreamsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	
	VelocityBuilder velocityBuilder = new VelocityBuilder();
	Map<String,Object> model = new HashMap<String, Object>();
	
	model.put("streams", HlsLiveStreamMagr.INSTANCE().getAllLiveStream()); 
	
	String htmlText = velocityBuilder.generate("streams.vm", "UTF8", model);
	
	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length());
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");

	ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, Charset.defaultCharset());// CharsetUtil.UTF_8);
	response.setContent(buffer);

	ChannelFuture channelFuture = ctx.getChannel().write(response);
	if (channelFuture.isSuccess()) {
		channelFuture.getChannel().close();
	}
	
}
 
Example 2
Source Project: voyage   Source File: NettyRpcServerHandler.java    License: Apache License 2.0 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 3
Source Project: usergrid   Source File: MongoProxyServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived( ChannelHandlerContext ctx, MessageEvent e ) {

    Message message = null;
    if ( e.getMessage() instanceof Message ) {
        message = ( Message ) e.getMessage();
    }

    OpReply reply = OpReply.errorReply( "not implemented" );

    if ( message != null ) {
        logger.info( message.getClass().getName() );
        reply.setResponseTo( message.getRequestID() );
    }

    e.getChannel().write( reply );
}
 
Example 4
Source Project: mt-flume   Source File: SyslogUDPSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent mEvent) {
  try {
    syslogUtils.setEventSize(maxsize);
    Event e = syslogUtils.extractEvent((ChannelBuffer)mEvent.getMessage());
    if (e == null) {
      return;
    }
    getChannelProcessor().processEvent(e);
    counterGroup.incrementAndGet("events.success");
  } catch (ChannelException ex) {
    counterGroup.incrementAndGet("events.dropped");
    logger.error("Error writting to channel", ex);
    return;
  }
}
 
Example 5
Source Project: zuul-netty   Source File: HttpRequestFrameworkHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) e.getMessage();
        InterruptsImpl callback = new InterruptsImpl(request, e.getChannel());
        LOG.debug("handler: {} is calling request-handler: {}", tag, requestHandler.getClass().getSimpleName());
        requestHandler.requestReceived(new HttpRequestFrameworkAdapter(request));


        if (callback.isInterrupted()) {
            //plugin requested that execution is interrupted i.e. not passed down the pipeline
            return;
        }
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.messageReceived(ctx, e);
}
 
Example 6
Source Project: phoenix-omid   Source File: TSOClientRaw.java    License: Apache License 2.0 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 7
Source Project: mt-flume   Source File: SyslogTcpSource.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: big-c   Source File: RpcProgram.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  RpcInfo info = (RpcInfo) e.getMessage();
  RpcCall call = (RpcCall) info.header();
  
  SocketAddress remoteAddress = info.remoteAddress();
  if (LOG.isTraceEnabled()) {
    LOG.trace(program + " procedure #" + call.getProcedure());
  }
  
  if (this.progNumber != call.getProgram()) {
    LOG.warn("Invalid RPC call program " + call.getProgram());
    sendAcceptedReply(call, remoteAddress, AcceptState.PROG_UNAVAIL, ctx);
    return;
  }

  int ver = call.getVersion();
  if (ver < lowProgVersion || ver > highProgVersion) {
    LOG.warn("Invalid RPC call version " + ver);
    sendAcceptedReply(call, remoteAddress, AcceptState.PROG_MISMATCH, ctx);
    return;
  }
  
  handleInternal(ctx, info);
}
 
Example 9
Source Project: glowroot   Source File: HttpServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (!readingChunks) {
        request = (HttpRequest) e.getMessage();
        String uri = request.getUri();
        if (uri.equals("/exception")) {
            throw new Exception("Test");
        }
        if (request.isChunked()) {
            readingChunks = true;
        } else {
            writeResponse(e);
        }
    } else {
        HttpChunk chunk = (HttpChunk) e.getMessage();
        if (chunk.isLast()) {
            readingChunks = false;
            writeResponse(e);
        }
    }
}
 
Example 10
Source Project: usergrid   Source File: MongoProxyInboundHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived( ChannelHandlerContext ctx, final MessageEvent e ) throws Exception {
    ChannelBuffer msg = ( ChannelBuffer ) e.getMessage();
    Message mongo_message = MongoMessageDecoder.decode( msg );
    if ( mongo_message != null ) {
        System.out.println( ">>> " + mongo_message.toString() );
    }
    synchronized ( trafficLock ) {
        outboundChannel.write( msg );
        // If outboundChannel is saturated, do not read until notified in
        // OutboundHandler.channelInterestChanged().
        if ( !outboundChannel.isWritable() ) {
            e.getChannel().setReadable( false );
        }
    }
}
 
Example 11
@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 12
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpInvocationContext<Request, Response> httpInvocationContext = contextMap.get(ctx.getChannel());
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<Request, Response> action = httpInvocationContext.getHttpAction();
            ActionListener<Response> listener = httpInvocationContext.getListener();
            httpInvocationContext.httpResponse = httpResponse;
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpInvocationContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        contextMap.remove(ctx.getChannel());
    }
}
 
Example 13
Source Project: whiteboard   Source File: MyServerHandler.java    License: 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 14
Source Project: android-netty   Source File: ChannelEncoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
	
	PowerManager.WakeLock wakeLock = WakeLockWrapper.getWakeLockInstance(mContext, ChannelEncoder.class.getSimpleName());
	wakeLock.acquire();

	try {
		String jsonString = event.getMessage().toString();

		LogByCodeLab.i(String.format("WRITE [%s]", jsonString));

		ChannelBuffer cb = new BigEndianHeapChannelBuffer(24);
		cb.writeBytes(new byte[24]);

		Channels.write(ctx, event.getFuture(), cb);
	} finally {
		wakeLock.release();
	}
}
 
Example 15
Source Project: dubbo-2.6.5   Source File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    super.writeRequested(ctx, e);
    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    try {
        handler.sent(channel, e.getMessage());
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 16
Source Project: james-project   Source File: ImapLineHandlerAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    ChannelBuffer buf = (ChannelBuffer) e.getMessage();
    byte[] data;
    if (buf.hasArray()) {
        data = buf.array();
    } else {
        data = new byte[buf.readableBytes()];
        buf.readBytes(data);
    }
    lineHandler.onLine(session, data);
}
 
Example 17
Source Project: Flink-CEPplus   Source File: NetworkFailureHandler.java    License: 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 18
@Override
public synchronized void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (this.framingEnabled) {
        super.messageReceived(ctx, e);
    } else {
        ctx.sendUpstream(e);
    }
}
 
Example 19
Source Project: pinpoint   Source File: PinpointServerAcceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    final Channel channel = e.getChannel();

    DefaultPinpointServer pinpointServer = (DefaultPinpointServer) channel.getAttachment();
    if (pinpointServer != null) {
        Object message = e.getMessage();

        pinpointServer.messageReceived(message);
    }

    super.messageReceived(ctx, e);
}
 
Example 20
Source Project: flink   Source File: NetworkFailureHandler.java    License: 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();
	sourceChannel.write(msg);
}
 
Example 21
Source Project: DataLink   Source File: SessionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Top-level method that handles all requests and multiplexes to the right api
 */
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
    Request request = new Request(ctx, buffer.toByteBuffer());

    switch (ApiKeys.forId(request.getRequestId())) {
        case METADATA:
            handleMetadataRequest(ctx, request);
            break;
        case GROUP_COORDINATOR:
            handleGroupCoordinatorRequest(ctx, request);
            break;
        case JOIN_GROUP:
            handleJoinGroupRequest(ctx, request);
            break;
        case HEARTBEAT:
            handleHeartbeatRequest(ctx, request);
            break;
        case SYNC_GROUP:
            handleSyncGroupRequest(ctx, request);
            break;
        case LEAVE_GROUP:
            handleLeaveGroupRequest(ctx, request);
            break;
        default:
            throw new DatalinkException("Unknown api code " + request.getRequestId());
    }
}
 
Example 22
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    super.messageReceived(ctx, e);

    AbstractClientPacket clientPacket = clientPacketHandler.handle((ChannelBuffer) e.getMessage(), this);
    if (clientPacket != null && clientPacket.read()) {
        clientPacket.run();
    }
    if (clientPacket != null) {
        if (log.isDebugEnabled()) {
            log.debug("Received packet: " + clientPacket);
        }
    }
}
 
Example 23
Source Project: dubbox   Source File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    try {
        handler.received(channel, e.getMessage());
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 24
Source Project: feeyo-hlsserver   Source File: HttpServerRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isFilter(ChannelHandlerContext ctx, MessageEvent messageEvent, IRequestHandler requestHandler) {    	
  	List<IFilter> filters = filterChain.get(requestHandler.getType());
  	if ( filters != null ) {
	for (IFilter filter : filters) {
		if (filter.doFilter(ctx, messageEvent)) {
			continue;
		} else {
			return false;
		}
	}
  	}
return true;
  }
 
Example 25
Source Project: feeyo-hlsserver   Source File: HlsTrafficFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean doFilter(ChannelHandlerContext ctx, MessageEvent e) {
    boolean isPassed = false;

    HttpRequest request = (DefaultHttpRequest) e.getMessage();
    String[] path = request.getUri().split("/");
    String requestFile = path[3];

    if (requestFile.endsWith(".ts")) {
        isPassed = true;
    } else {
    	isPassed = true;
    }
    return isPassed;
}
 
Example 26
Source Project: usergrid   Source File: ServerStatus.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OpReply execute( MongoChannelHandler handler, ChannelHandlerContext ctx, MessageEvent e, OpQuery opQuery ) {
    OpReply reply = new OpReply( opQuery );
    reply.addDocument( map( entry( "host", "api.usergrid.com:27017" ), entry( "version", "1.8.1" ),
            entry( "process", "mongod" ), entry( "uptime", 1000.0 ), entry( "uptimeEstimate", 1000.0 ),
            entry( "localTime", map( "$date", DateUtils.instance.iso8601DateNow() ) ), entry( "globalLock",
            map( entry( "totalTime", 1.0 ), entry( "lockTime", 1000.0 ), entry( "ratio", 0.00001 ),
                    entry( "currentQueue",
                            map( entry( "total", 0 ), entry( "readers", 0 ), entry( "writers", 0 ) ) ),
                    entry( "activeClients",
                            map( entry( "total", 0 ), entry( "readers", 0 ), entry( "writers", 0 ) ) ) ) ),
            entry( "mem", map( entry( "bits", 64 ), entry( "resident", 20 ), entry( "virtual", 2048 ),
                    entry( "supported", true ), entry( "mapped", 80 ) ) ),
            entry( "connections", map( entry( "current", 1 ), entry( "available", 256 ) ) ),
            entry( "extra_info", map( "note", "fields vary by platform" ) ), entry( "indexCounters", map( "btree",
            map( entry( "accesses", 0 ), entry( "hits", 0 ), entry( "misses", 0 ), entry( "resets", 0 ),
                    entry( "missRatio", 0.0 ) ) ) ), entry( "backgroundFlushing",
            map( entry( "flushes", 24 ), entry( "total_ms", 256 ), entry( "average_ms", 4.0 ),
                    entry( "last_ms", 16 ),
                    entry( "last_finished", map( "$date", DateUtils.instance.iso8601DateNow() ) ) ) ),
            entry( "cursors",
                    map( entry( "totalOpen", 0 ), entry( "clientCursors_size", 0 ), entry( "timedOut", 0 ) ) ),
            entry( "network",
                    map( entry( "bytesIn", 1024 ), entry( "bytesOut", 1024 ), entry( "numRequests", 32 ) ) ),
            entry( "opcounters",
                    map( entry( "insert", 0 ), entry( "query", 1 ), entry( "update", 0 ), entry( "delete", 0 ),
                            entry( "getmore", 0 ), entry( "command", 1 ) ) ), entry( "asserts",
            map( entry( "regular", 0 ), entry( "warning", 0 ), entry( "msg", 0 ), entry( "user", 0 ),
                    entry( "rollovers", 0 ) ) ), entry( "writeBacksQueued", false ), entry( "ok", 1.0 ) ) );
    return reply;
}
 
Example 27
Source Project: voyage   Source File: RpcResponseEncode.java    License: Apache License 2.0 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);
}
 
Example 28
Source Project: Elasticsearch   Source File: CorsHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    if (config.isCorsSupportEnabled() && e.getMessage() instanceof HttpRequest) {
        request = (HttpRequest) e.getMessage();
        if (isPreflightRequest(request)) {
            handlePreflight(ctx, request);
            return;
        }
        if (config.isShortCircuit() && !validateOrigin()) {
            forbidden(ctx, request);
            return;
        }
    }
    super.messageReceived(ctx, e);
}
 
Example 29
Source Project: dubbox   Source File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    super.writeRequested(ctx, e);
    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    try {
        handler.sent(channel, e.getMessage());
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 30
Source Project: dubbox-hystrix   Source File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    super.writeRequested(ctx, e);
    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    try {
        handler.sent(channel, e.getMessage());
    } finally {
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}