Java Code Examples for org.jboss.netty.handler.codec.http.HttpRequest

The following are top voted examples for showing how to use org.jboss.netty.handler.codec.http.HttpRequest. 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: traccar-service   File: PathAwayProtocolDecoder.java   Source Code and License 6 votes vote down vote up
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    HttpRequest request = (HttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

    DeviceSession deviceSession = getDeviceSession(
            channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
    if (deviceSession == null) {
        return null;
    }

    Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));

    position.setValid(true);
    position.setLatitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setAltitude(parser.nextDouble(0));
    position.setSpeed(parser.nextDouble(0));
    position.setCourse(parser.nextDouble(0));

    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        channel.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    return position;
}
 
Example 2
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 6 votes vote down vote up
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, CorsConfig config) {
    if (!config.isCorsSupportEnabled()) {
        return;
    }
    String originHeader = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(originHeader)) {
        final String originHeaderVal;
        if (config.isAnyOriginSupported()) {
            originHeaderVal = ANY_ORIGIN;
        } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HOST))) {
            originHeaderVal = originHeader;
        } else {
            originHeaderVal = null;
        }
        if (originHeaderVal != null) {
            resp.headers().add(ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
        }
    }
    if (config.isCredentialsAllowed()) {
        resp.headers().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
}
 
Example 3
Project: opentsdb-flume   File: LegacyHttpSource.java   Source Code and License 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 4
Project: opentsdb-flume   File: LegacyHttpSource.java   Source Code and License 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 5
Project: opentsdb-flume   File: LegacyHttpSource.java   Source Code and License 6 votes vote down vote up
public void parse(HttpRequest req) throws IOException {

      final JsonParser parser = jsonFactory.createJsonParser(
              new ChannelBufferInputStream(req.getContent()));

      parser.nextToken(); // Skip the wrapper

      while (parser.nextToken() != JsonToken.END_OBJECT) {

        final String metric = parser.getCurrentName();

        JsonToken currentToken = parser.nextToken();
        if (currentToken == JsonToken.START_OBJECT) {
          parseMetricObject(metric, parser);
        } else if (currentToken == JsonToken.START_ARRAY) {
          int illegalTokens = parseMetricArray(metric, parser);
          if(illegalTokens > 0) {
              logger.warn("{} illegal tokens encountered", illegalTokens);
          }
        } else {
          logger.warn("Illegal token: expected {} or {}, but was {}: {}",new Object[] {
                  JsonToken.START_OBJECT, JsonToken.START_ARRAY, currentToken, parser.getText()});
        }
      }
    }
 
Example 6
Project: Camel   File: DefaultNettyHttpBinding.java   Source Code and License 6 votes vote down vote up
@Override
public Message toCamelMessage(HttpRequest request, Exchange exchange, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toCamelMessage: {}", request);

    NettyHttpMessage answer = new NettyHttpMessage(request, null);
    answer.setExchange(exchange);
    if (configuration.isMapHeaders()) {
        populateCamelHeaders(request, answer.getHeaders(), exchange, configuration);
    }

    if (configuration.isDisableStreamCache()) {
        // keep the body as is, and use type converters
        answer.setBody(request.getContent());
    } else {
        // turn the body into stream cached
        NettyChannelBufferStreamCache cache = new NettyChannelBufferStreamCache(request.getContent());
        answer.setBody(cache);
    }
    return answer;
}
 
Example 7
Project: Camel   File: NettyHttpEndpoint.java   Source Code and License 6 votes vote down vote up
@Override
public Exchange createExchange(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    Exchange exchange = createExchange();

    // use the http binding
    HttpRequest request = (HttpRequest) messageEvent.getMessage();
    Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
    exchange.setIn(in);
    
    // setup the common message headers 
    updateMessageHeader(in, ctx, messageEvent);

    // honor the character encoding
    String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class);
    String charset = NettyHttpHelper.getCharsetFromContentType(contentType);
    if (charset != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, charset);
        in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset);
    }

    return exchange;
}
 
Example 8
Project: Camel   File: HttpServerChannelHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Extracts the username and password details from the HTTP basic header Authorization.
 * <p/>
 * This requires that the <tt>Authorization</tt> HTTP header is provided, and its using Basic.
 * Currently Digest is <b>not</b> supported.
 *
 * @return {@link HttpPrincipal} with username and password details, or <tt>null</tt> if not possible to extract
 */
protected static HttpPrincipal extractBasicAuthSubject(HttpRequest request) {
    String auth = request.headers().get("Authorization");
    if (auth != null) {
        String constraint = ObjectHelper.before(auth, " ");
        if (constraint != null) {
            if ("Basic".equalsIgnoreCase(constraint.trim())) {
                String decoded = ObjectHelper.after(auth, " ");
                // the decoded part is base64 encoded, so we need to decode that
                ChannelBuffer buf = ChannelBuffers.copiedBuffer(decoded.getBytes());
                ChannelBuffer out = Base64.decode(buf);
                String userAndPw = out.toString(Charset.defaultCharset());
                String username = ObjectHelper.before(userAndPw, ":");
                String password = ObjectHelper.after(userAndPw, ":");
                HttpPrincipal principal = new HttpPrincipal(username, password);

                LOG.debug("Extracted Basic Auth principal from HTTP header: {}", principal);
                return principal;
            }
        }
    }
    return null;
}
 
Example 9
Project: Camel   File: HttpServerMultiplexChannelHandler.java   Source Code and License 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 10
Project: Camel   File: NettyHttpProducer.java   Source Code and License 6 votes vote down vote up
@Override
protected Object getRequestBody(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String uri = NettyHttpHelper.createURL(exchange, getEndpoint());
    URI u = NettyHttpHelper.createURI(exchange, uri, getEndpoint());

    HttpRequest request = getEndpoint().getNettyHttpBinding().toNettyRequest(exchange.getIn(), u.toString(), getConfiguration());
    String actualUri = request.getUri();
    exchange.getIn().setHeader(Exchange.HTTP_URL, actualUri);
    // Need to check if we need to close the connection or not
    if (!HttpHeaders.isKeepAlive(request)) {
        // just want to make sure we close the channel if the keepAlive is not true
        exchange.setProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    if (getConfiguration().isBridgeEndpoint()) {
        // Need to remove the Host key as it should be not used when bridging/proxying
        exchange.getIn().removeHeader("host");
    }

    return request;
}
 
Example 11
Project: Camel   File: NettyHttpConverter.java   Source Code and License 6 votes vote down vote up
/**
 * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types.
 */
@FallbackConverter
public static Object convertToHttpRequest(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // if we want to covert to HttpRequest
    if (value != null && HttpRequest.class.isAssignableFrom(type)) {

        // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage
        // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the
        // HttpRequest from the NettyHttpMessage
        NettyHttpMessage msg;
        if (exchange.hasOut()) {
            msg = exchange.getOut(NettyHttpMessage.class);
        } else {
            msg = exchange.getIn(NettyHttpMessage.class);
        }
        if (msg != null && msg.getBody() == value) {
            // ensure the http request content is reset so we can read all the content out-of-the-box
            HttpRequest request = msg.getHttpRequest();
            request.getContent().resetReaderIndex();
            return request;
        }
    }

    return null;
}
 
Example 12
Project: Camel   File: NettyHttpAccessHttpRequestTest.java   Source Code and License 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("netty-http:http://0.0.0.0:{{port}}/foo")
                .to("mock:input")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        // we can get the original http request
                        HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest();
                        assertNotNull(request);
                    }
                })
                .transform().constant("Bye World");
        }
    };
}
 
Example 13
Project: finagle-java-example-master-slave   File: VideoCache.java   Source Code and License 6 votes vote down vote up
public VideoCache(ExecutorService pool, PropertyPlaceholder propsHolder, Service<HttpRequest, HttpResponse> client) {
    this.pool = pool;
    this.client = client;
    this.propsHolder = propsHolder;
    propsHolder.generatePropertyMap();
    
    this.productReader = new ProductFileReader(propsHolder.getPropertyMap().get("campaignProductListLocation"));
   
    JedisPoolConfig jedisConfig = new JedisPoolConfig();
    jedisConfig.setMaxTotal(Integer.parseInt(propsHolder.getPropertyMap().get("maxJedisPoolSize")));
    jedisConfig.setTestOnBorrow(true);
    jedisConfig.setLifo(false);
    String redisHost = propsHolder.getPropertyMap().get("redisServer");
    int redisPort = Integer.parseInt(propsHolder.getPropertyMap().get("redisPort"));
    this.jedisPool = new JedisPool(jedisConfig, redisHost, redisPort);
}
 
Example 14
Project: eventsource-android   File: EventSourceChannelHandler.java   Source Code and License 6 votes vote down vote up
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
    throws Exception {
  HttpRequest request =
      new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toString());
  request.addHeader(Names.ACCEPT, "text/event-stream");

  if (headers != null) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      request.addHeader(entry.getKey(), entry.getValue());
    }
  }

  request.addHeader(Names.HOST, uri.getHost());
  request.addHeader(Names.ORIGIN, uri.getScheme() + "://" + uri.getHost());
  request.addHeader(Names.CACHE_CONTROL, "no-cache");
  if (lastEventId != null) {
    request.addHeader("Last-Event-ID", lastEventId);
  }
  e.getChannel().write(request);
  channel = e.getChannel();
}
 
Example 15
Project: AirSpeakerMobile   File: RtspLoggingHandler.java   Source Code and License 6 votes vote down vote up
@Override
	public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt)
		throws Exception
	{	//[id: 0x42320e48, /192.168.20.58:60810 => /192.168.20.128:5000] RECEIVED: DefaultHttpRequest(chunked: false) OPTIONS * RTSP/1.0 CSeq: 0 X-Apple-Device-ID: 0xf0c1f145b120 Apple-Challenge: aegvjDkBxWjPQlDBfGZnXA== DACP-ID: D3DADC2D4FD6B073 Active-Remote: 850148892 User-Agent: AirPlay/190.9
		final HttpRequest req = (HttpRequest)evt.getMessage();
		LogManager.i("====================messageReceived:"+req.toString());
		final Level level = Level.FINE;
//		if (Constants.DEBUG) {
			final String content = req.getContent().toString(Charset.defaultCharset());

			final StringBuilder s = new StringBuilder();
			s.append(">");
			s.append(req.getMethod());
			s.append(" ");
			s.append(req.getUri());
			s.append("\n");
			OUT:for(final Map.Entry<String, String> header: req.getHeaders()) {
				s.append("  ");
				s.append(header.getKey());
				s.append(": ");
				s.append(header.getValue());
				s.append("\n");
				if("Active-Remote".equalsIgnoreCase(header.getKey())){
					remote = "Active-Remote: "+header.getValue() ;
					LogManager.e("remote============"+remote);
					break OUT ;
				}
				
			}
			s.append(content);
//			LogManager.i("messageReceived:"+s.toString());
//		}

		super.messageReceived(ctx, evt);
	}
 
Example 16
Project: incubator-tajo   File: DirectoryRetriever.java   Source Code and License 6 votes vote down vote up
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: " 
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
Example 17
Project: incubator-tajo   File: DirectoryRetriever.java   Source Code and License 6 votes vote down vote up
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: "
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
Example 18
Project: tajo-cdh   File: DirectoryRetriever.java   Source Code and License 6 votes vote down vote up
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: " 
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
Example 19
Project: tajo-cdh   File: DirectoryRetriever.java   Source Code and License 6 votes vote down vote up
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: "
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
Example 20
Project: glowroot   File: HttpServerHandler.java   Source Code and License 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 21
Project: trap   File: WebServerSocketHandler.java   Source Code and License 6 votes vote down vote up
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res)
{
	// Generate an error page if response status code is not OK (200).
	if (res.getStatus().getCode() != 200)
	{
		res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
		setContentLength(res, res.getContent().readableBytes());
	}
	
	// Send the response and close the connection if necessary.
	ChannelFuture f = ctx.getChannel().write(res);
	if (!isKeepAlive(req) || (res.getStatus().getCode() != 200))
	{
		f.addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example 22
Project: rest4j   File: RAPServerCodec.java   Source Code and License 6 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg)
        throws Exception
{
  HttpRequest nettyRequest = (HttpRequest) msg;
  URI uri = new URI(nettyRequest.getUri());
  RestRequestBuilder builder = new RestRequestBuilder(uri);
  builder.setMethod(nettyRequest.getMethod().getName());
  for (Map.Entry<String, String> e : nettyRequest.getHeaders())
  {
    builder.unsafeAddHeaderValue(e.getKey(), e.getValue());
  }
  ChannelBuffer buf = nettyRequest.getContent();
  if (buf != null)
  {
    if (buf.hasArray())
    {
      // TODO make a copy?
      builder.setEntity(buf.array());
    }
  }

  return builder.build();
}
 
Example 23
Project: netty-servlet   File: HttpServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    if (event.getMessage() instanceof HttpRequest) {
        try {
            HttpServletRequest httpServletRequest = new NettyHttpServletRequestAdaptor((HttpRequest) event.getMessage(), ctx.getChannel());
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.setContent(new DynamicChannelBuffer(200));
            HttpServletResponse httpServletResponse = new NettyHttpServletResponseAdaptor(response, ctx.getChannel());
            dispatcher.dispatch(httpServletRequest,httpServletResponse);
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,response.getContent().writerIndex());
            ChannelFuture future = ctx.getChannel().write(response);
            future.addListener(ChannelFutureListener.CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 24
Project: tools-idea   File: DelegatingHttpRequestHandlerBase.java   Source Code and License 6 votes vote down vote up
@Override
public final void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
  if (!(event.getMessage() instanceof HttpRequest)) {
    context.sendUpstream(event);
    return;
  }

  HttpRequest request = (HttpRequest)event.getMessage();
  //if (BuiltInServer.LOG.isDebugEnabled()) {
  //BuiltInServer.LOG.debug(request.toString());
  //}

  if (!process(context, request, new QueryStringDecoder(request.getUri()))) {
    Responses.sendStatus(request, context, NOT_FOUND);
  }
}
 
Example 25
Project: java-test-demo   File: HttpServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    String uri = request.getUri();
    
    System.out.println("uri:" + uri);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    ChannelBuffer buffer = new DynamicChannelBuffer(2048);
    buffer.writeBytes("hello!! 你好".getBytes("UTF-8"));
    response.setContent(buffer);
    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    response.setHeader("Content-Length", response.getContent().writerIndex());
    Channel ch = e.getChannel();
    // Write the initial line and the header.
    ch.write(response);
    ch.disconnect();
    ch.close();

}
 
Example 26
Project: feluca   File: NettyHttpRequest.java   Source Code and License 6 votes vote down vote up
public NettyHttpRequest(org.jboss.netty.handler.codec.http.HttpRequest request)
{
	this.request = request;
	this.params = new HashMap<String, String>();

	String uri = request.getUri();
	int pathEndPos = uri.indexOf('?');
	if (pathEndPos < 0)
	{
		this.path = uri;
	}
	else
	{
		this.path = uri.substring(0, pathEndPos);
		decodeQueryString(uri, pathEndPos + 1, params);
	}
}
 
Example 27
Project: ApolloDev   File: ApolloHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
	if (ctx.getAttachment() == null) {
		Object msg = e.getMessage();
		if (msg instanceof HttpRequest || msg instanceof JagGrabRequest) {
			Session s = new UpdateSession(ctx.getChannel(), serverContext);
			s.messageReceived(msg);
			// we don't bother to set it as an attachment, as the connection
			// will be closed once the request is completed anyway
		} else {
			HandshakeMessage handshakeMessage = (HandshakeMessage) msg;
			switch (handshakeMessage.getServiceId()) {
			case HandshakeConstants.SERVICE_GAME:
				ctx.setAttachment(new LoginSession(ctx.getChannel(), ctx, serverContext));
				break;
			case HandshakeConstants.SERVICE_UPDATE:
				ctx.setAttachment(new UpdateSession(ctx.getChannel(), serverContext));
				break;
			default:
				throw new IllegalStateException("Invalid service id");
			}
		}
	} else {
		((Session) ctx.getAttachment()).messageReceived(e.getMessage());
	}
}
 
Example 28
Project: rtsp_multicast_pfc   File: RtspServerListener.java   Source Code and License 6 votes vote down vote up
/**
 * Metodo que extrae la cabecera de una peticion el CSeq
 */
private int getcSeq(HttpRequest request) throws RtspRequestException {

	int cSeq;
	String str_cSeq;


	str_cSeq = request.getHeader("CSeq");

	if(str_cSeq==null){
		throw new RtspRequestException("Request not contains CSeq header", RtspResponseStatuses.BAD_REQUEST);
	}

	try {
		cSeq = Integer.parseInt(str_cSeq);
	}
	catch(Exception e) {
		throw new RtspRequestException("CSeq header must be a number", RtspResponseStatuses.BAD_REQUEST);
	}

	return cSeq;	
}
 
Example 29
Project: zuul-netty   File: HttpRequestFrameworkHandler.java   Source Code and License 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 30
Project: zuul-netty   File: HttpResponseFrameworkHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e.getMessage();
        HttpRequest request = (HttpRequest) ctx.getAttachment();

        LOG.debug("handler: {} is calling response-handler: {}", tag, responseHandler.getClass().getSimpleName());
        responseHandler.responseReceived(new HttpRequestFrameworkAdapter(request), new HttpResponseFrameworkAdapter(response));

        ctx.setAttachment(null);
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.writeRequested(ctx, e);
}
 
Example 31
Project: httptunnel   File: HttpTunnelClientSendHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDisconnect() {
	emulateConnectAndOpen();

	channel.write(NettyTestUtils.createData(1234L));
	assertEquals(1, sink.events.size());
	checkIsSendDataRequestWithData(sink.events.poll(),
			NettyTestUtils.createData(1234L));

	channel.disconnect();
	Channels.fireMessageReceived(channel,
			HttpTunnelMessageUtils.createSendDataResponse());
	assertEquals(1, sink.events.size());

	HttpRequest request = NettyTestUtils.checkIsDownstreamMessageEvent(
			sink.events.poll(), HttpRequest.class);
	assertTrue(HttpTunnelMessageUtils.isCloseTunnelRequest(request, USER_AGENT));
	assertEquals("newTunnel",
			HttpTunnelMessageUtils.extractTunnelId(request));
	Channels.fireMessageReceived(channel,
			HttpTunnelMessageUtils.createTunnelCloseResponse());
	assertEquals(1, sink.events.size());
	NettyTestUtils.checkIsStateEvent(sink.events.poll(),
			ChannelState.CONNECTED, null);
}
 
Example 32
Project: httptunnel   File: HttpTunnelClientChannelSendHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
	// If this tunnel has already been opened then don't try open it
	if (tunnelId == null) {
		if (LOG.isDebugEnabled())
			LOG.debug("connection to " + e.getValue() + " succeeded - sending open tunnel request");

		final HttpRequest request = HttpTunnelMessageUtils.createOpenTunnelRequest(tunnelChannel.getServerHostName(), tunnelChannel.getUserAgent());
		final Channel channel = ctx.getChannel();
		final DownstreamMessageEvent event = new DownstreamMessageEvent(channel, Channels.future(channel), request, channel.getRemoteAddress());

		queuedWrites.offer(new TimedMessageEventWrapper(event, requestTimer.time()));
		pendingRequestCount.incrementAndGet();
	}

	// Send our first chunk of data
	this.sendQueuedData(ctx);
}
 
Example 33
Project: httptunnel   File: HttpTunnelClientChannelSendHandler.java   Source Code and License 6 votes vote down vote up
private synchronized void sendQueuedData(ChannelHandlerContext ctx) {
	if (disconnecting.get()) {
		if (LOG.isDebugEnabled())
			LOG.debug("sending close request for tunnel " + tunnelId);

		final HttpRequest closeRequest = HttpTunnelMessageUtils.createCloseTunnelRequest(tunnelChannel.getServerHostName(), tunnelId, tunnelChannel.getUserAgent());
		Channels.write(ctx, Channels.future(ctx.getChannel()), closeRequest);
	}
	else {
		if (LOG.isDebugEnabled())
			LOG.debug("sending next request for tunnel " + tunnelId);

		final TimedMessageEventWrapper wrapper = queuedWrites.poll();
		try {
			sendRequestTime = System.nanoTime();
			ctx.sendDownstream(wrapper.getEvent());
		}
		finally {
			wrapper.getContext().stop();
		}
	}
}
 
Example 34
Project: httptunnel   File: HttpTunnelAcceptedChannelHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	final HttpRequest request = (HttpRequest) e.getMessage();
	final String userAgent = parent.getConfig().getUserAgent();

	try {
		// send channel
		if (HttpTunnelMessageUtils.isOpenTunnelRequest(request, userAgent))
			this.handleOpenTunnel(ctx);
		// send channel
		else if (HttpTunnelMessageUtils.isSendDataRequest(request, userAgent))
			this.handleSendData(ctx, request);
		// poll channel
		else if (HttpTunnelMessageUtils.isReceiveDataRequest(request, userAgent))
			this.handleReceiveData(ctx, request);
		// send channel
		else if (HttpTunnelMessageUtils.isCloseTunnelRequest(request, userAgent))
			this.handleCloseTunnel(ctx, request);
		else
			throw new IllegalArgumentException("invalid request to netty HTTP tunnel gateway");
	}
	catch (Exception ex) {
		this.respondWithRejection(ctx, request, ex.getMessage());
	}
}
 
Example 35
Project: httptunnel   File: HttpTunnelClientSendHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testClose() {
	emulateConnectAndOpen();

	channel.close();
	assertEquals(1, sink.events.size());
	HttpRequest request = NettyTestUtils.checkIsDownstreamMessageEvent(
			sink.events.poll(), HttpRequest.class);
	assertTrue(HttpTunnelMessageUtils.isCloseTunnelRequest(request, USER_AGENT));
	assertEquals("newTunnel",
			HttpTunnelMessageUtils.extractTunnelId(request));
	Channels.fireMessageReceived(channel,
			HttpTunnelMessageUtils.createTunnelCloseResponse());
	assertEquals(1, sink.events.size());
	NettyTestUtils.checkIsStateEvent(sink.events.poll(), ChannelState.OPEN,
			false);
}
 
Example 36
Project: httptunnel   File: HttpTunnelAcceptedChannelHandler.java   Source Code and License 6 votes vote down vote up
private void handleSendData(ChannelHandlerContext ctx, HttpRequest request) {
	final HttpTunnelAcceptedChannel tunnel = parent.getTunnel(HttpTunnelMessageUtils.extractTunnelId(request));
	if (tunnel == null) {
		// If the tunnel doesn't exist then close it on the other end
		this.respondWith(ctx, HttpTunnelMessageUtils.createTunnelCloseResponse()).addListener(ChannelFutureListener.CLOSE);
		return;
	}

	tunnel.ping();

	if (LOG.isDebugEnabled())
		LOG.debug("send data request received for tunnel " + tunnel.getTunnelId());

	if (HttpHeaders.getContentLength(request, 0) == 0 || request.getContent() == null || request.getContent().readableBytes() == 0) {
		this.respondWithRejection(ctx, request, "Send data requests must contain data");
		return;
	}

	tunnel.internalReceiveMessage(request.getContent());
	this.respondWith(ctx, HttpTunnelMessageUtils.createSendDataResponse());
}
 
Example 37
Project: traccar-service   File: Mta6ProtocolDecoder.java   Source Code and License 5 votes vote down vote up
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    HttpRequest request = (HttpRequest) msg;
    ChannelBuffer buf = request.getContent();

    buf.skipBytes("id=".length());
    int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '&');
    String uniqueId = buf.toString(buf.readerIndex(), index - buf.readerIndex(), StandardCharsets.US_ASCII);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, uniqueId);
    if (deviceSession == null) {
        return null;
    }
    buf.skipBytes(uniqueId.length());
    buf.skipBytes("&bin=".length());

    short packetId = buf.readUnsignedByte();
    short offset = buf.readUnsignedByte(); // dataOffset
    short packetCount = buf.readUnsignedByte();
    buf.readUnsignedByte(); // reserved
    buf.readUnsignedByte(); // timezone
    buf.skipBytes(offset - 5);

    if (channel != null) {
        sendContinue(channel);
        sendResponse(channel, packetId, packetCount);
    }

    if (packetId == 0x31 || packetId == 0x32 || packetId == 0x36) {
        if (simple) {
            return parseFormatA1(deviceSession, buf);
        } else {
            return parseFormatA(deviceSession, buf);
        }
    } //else if (0x34 0x38 0x4F 0x59)

    return null;
}
 
Example 38
Project: Elasticsearch   File: HttpPipeliningHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) {
    final Object msg = e.getMessage();
    if (msg instanceof HttpRequest) {
        ctx.sendUpstream(new OrderedUpstreamMessageEvent(sequence++, e.getChannel(), msg, e.getRemoteAddress()));
    } else {
        ctx.sendUpstream(e);
    }
}
 
Example 39
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 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 40
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 5 votes vote down vote up
private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
    final HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), OK);
    if (setOrigin(response)) {
        setAllowMethods(response);
        setAllowHeaders(response);
        setAllowCredentials(response);
        setMaxAge(response);
        setPreflightHeaders(response);
        ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        forbidden(ctx, request);
    }
}
 
Example 41
Project: hadoop   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String outputBaseStr,
    String user, int reduce, HttpRequest request, HttpResponse response,
    boolean keepAliveParam, Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  for (String mapId : mapIds) {
    String base = outputBaseStr + mapId;
    MapOutputInfo outputInfo = getMapOutputInfo(base, mapId, reduce, user);
    if (mapOutputInfoMap.size() < mapOutputMetaInfoCacheSize) {
      mapOutputInfoMap.put(mapId, outputInfo);
    }
    // Index file
    Path indexFileName =
        lDirAlloc.getLocalPathToRead(base + "/file.out.index", conf);
    IndexRecord info =
        indexCache.getIndexInformation(mapId, reduce, indexFileName, user);
    ShuffleHeader header =
        new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
    DataOutputBuffer dob = new DataOutputBuffer();
    header.write(dob);

    contentLength += info.partLength;
    contentLength += dob.getLength();
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example 42
Project: aliyun-oss-hadoop-fs   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String outputBaseStr,
    String user, int reduce, HttpRequest request, HttpResponse response,
    boolean keepAliveParam, Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  for (String mapId : mapIds) {
    String base = outputBaseStr + mapId;
    MapOutputInfo outputInfo = getMapOutputInfo(base, mapId, reduce, user);
    if (mapOutputInfoMap.size() < mapOutputMetaInfoCacheSize) {
      mapOutputInfoMap.put(mapId, outputInfo);
    }
    // Index file
    Path indexFileName =
        lDirAlloc.getLocalPathToRead(base + "/file.out.index", conf);
    IndexRecord info =
        indexCache.getIndexInformation(mapId, reduce, indexFileName, user);
    ShuffleHeader header =
        new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
    DataOutputBuffer dob = new DataOutputBuffer();
    header.write(dob);

    contentLength += info.partLength;
    contentLength += dob.getLength();
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example 43
Project: aliyun-oss-hadoop-fs   File: TestShuffleHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected Shuffle getShuffle(final Configuration conf) {
  return new Shuffle(conf) {
    @Override
    protected void verifyRequest(String appid, ChannelHandlerContext ctx,
        HttpRequest request, HttpResponse response, URL requestUri)
        throws IOException {
      SocketChannel channel = (SocketChannel)(ctx.getChannel());
      socketKeepAlive = channel.getConfig().isKeepAlive();
    }
  };
}
 
Example 44
Project: aliyun-oss-hadoop-fs   File: TestShuffleHandler.java   Source Code and License 5 votes vote down vote up
public HttpRequest createMockHttpRequest() {
  HttpRequest mockHttpRequest = Mockito.mock(HttpRequest.class);
  Mockito.doReturn(HttpMethod.GET).when(mockHttpRequest).getMethod();
  Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      String uri = "/mapOutput?job=job_12345_1&reduce=1";
      for (int i = 0; i < 100; i++)
        uri = uri.concat("&map=attempt_12345_1_m_" + i + "_0");
      return uri;
    }
  }).when(mockHttpRequest).getUri();
  return mockHttpRequest;
}
 
Example 45
Project: big-c   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String outputBaseStr,
    String user, int reduce, HttpRequest request, HttpResponse response,
    boolean keepAliveParam, Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  for (String mapId : mapIds) {
    String base = outputBaseStr + mapId;
    MapOutputInfo outputInfo = getMapOutputInfo(base, mapId, reduce, user);
    if (mapOutputInfoMap.size() < mapOutputMetaInfoCacheSize) {
      mapOutputInfoMap.put(mapId, outputInfo);
    }
    // Index file
    Path indexFileName =
        lDirAlloc.getLocalPathToRead(base + "/file.out.index", conf);
    IndexRecord info =
        indexCache.getIndexInformation(mapId, reduce, indexFileName, user);
    ShuffleHeader header =
        new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
    DataOutputBuffer dob = new DataOutputBuffer();
    header.write(dob);

    contentLength += info.partLength;
    contentLength += dob.getLength();
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example 46
Project: fastcatsearch3   File: HttpServiceController.java   Source Code and License 5 votes vote down vote up
public void dispatchRequest(HttpRequest request, HttpChannel httpChannel) {
	// request에서 uri를 보고 외부요청을 확인하여 channel에 최종 결과를 write한다.
	HttpAction action = createAction(request, httpChannel);
	if (action != null) {
		try {
			executorService.execute(action);
		} catch (Exception e) {
			logger.error("Action job allocation error!", e);
		}
	}else{
		httpChannel.sendError(HttpResponseStatus.NOT_FOUND, null);
	}
}
 
Example 47
Project: fastcatsearch3   File: HttpRequestHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    // the netty HTTP handling always copy over the buffer to its own buffer, either in NioWorker internally
    // when reading, or using a cumalation buffer
    httpTransportModule.dispatchRequest(request, new NettyHttpChannel(e.getChannel(), request));
    super.messageReceived(ctx, e);
}
 
Example 48
Project: opentsdb-plugins   File: SimpleAuthenticationPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public AuthState authenticateHTTP(Channel channel, HttpRequest httpRequest) {
    AuthState ret = null;
    try {
        Iterable<Map.Entry<String, String>> headers = httpRequest.headers();
        Iterator entries = headers.iterator();
        while (entries.hasNext()) {
            Map.Entry thisEntry = (Map.Entry) entries.next();
            String key = (String) thisEntry.getKey();
            String value = (String) thisEntry.getValue();
            if (key.trim().toLowerCase().equals("authorization")) {
                String[] fieldsRaw = value.split(" ");
                if (fieldsRaw.length == 2 && fieldsRaw[0].trim().toLowerCase().equals("opentsdb")) {
                    String[] fieldsArray = fieldsRaw[1].trim().toLowerCase().split(":");
                    Map<String, String> fields = AuthenticationUtil.stringToMap(fieldsRaw[1], ":");
                    LOG.debug("Validating Digest Credentials");

                    if (this.authenticate((String) fields.get("accessKey"), fields)) {
                        if(this.authenticate((String) fields.get("accessKey"), fields)) {
                            ret = new SimpleAuthStateImpl((String) fields.get("accessKey"), AuthState.AuthStatus.SUCCESS, "Access Granted");
                        } else {
                            ret = new SimpleAuthStateImpl((String) fields.get("accessKey"), AuthState.AuthStatus.FORBIDDEN, "Access Denied");
                        }
                    }
                } else {
                    throw new IllegalArgumentException("Improperly formatted Authorization Header: " + value);
                }
            }
        }
        if (ret == null) {
            throw new IllegalArgumentException("No Authorization Header Found");
        }
    } catch (IllegalArgumentException ex) {
        ret = new SimpleAuthStateImpl("unknown", ex);
    }
    return ret;
}
 
Example 49
Project: netty-http-3.x   File: FormParser.java   Source Code and License 5 votes vote down vote up
@Override
public void init(HttpRequest httpRequest) {
	try {
		decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, httpRequest);
	} catch (ErrorDataDecoderException e) {
		throw new ContentParseException(e);
	} catch (Exception ignored) {
	}
}
 
Example 50
Project: netty-http-3.x   File: Response.java   Source Code and License 5 votes vote down vote up
public static Response create(HttpRequest httpRequest) {
	Response response = new Response();
	response.requestPath = httpRequest.getUri();
	response.contentType = StringUtils.defaultIfEmpty(httpRequest.headers().get(HttpHeaders.Names.CONTENT_TYPE), ContentType.TEXT_PLAIN.getMimeType());
	response.shouldKeepAlive = HttpHeaders.isKeepAlive(httpRequest);
	return response;
}
 
Example 51
Project: netty-http-3.x   File: RemoteRequestHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent messageEvent) throws Exception {
	if (!readingChunks) {
		HttpRequest httpRequest = (HttpRequest) messageEvent.getMessage();

		request = Request.create(httpRequest, messageEvent);
		response = new Response();

		content.setLength(0);
		content.append(httpRequest.getContent().toString(Context.DEFAULT_CHARSET));

		if (httpRequest.isChunked()) {
			readingChunks = true;
		} else {
			ready = true;
		}
	} else {
		HttpChunk httpChunk = (HttpChunk) messageEvent.getMessage();
		content.append(httpChunk.getContent().toString(Context.DEFAULT_CHARSET));

		if (httpChunk.isLast()) {
			ready = true;
			readingChunks = false;
		}
	}

	if (ready) {
		ready = false;
		handleMessage(context, messageEvent);
	}
}
 
Example 52
Project: HeliosStreams   File: WebSocketServiceHandler.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @see org.jboss.netty.channel.ChannelUpstreamHandler#handleUpstream(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelEvent)
 */
@Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
	log.warn("ChannelEvent: {}", e);
	if(e instanceof MessageEvent) {
		Object message = ((MessageEvent)e).getMessage();
		if (message instanceof HttpRequest) {
			handleRequest(ctx, (HttpRequest) message, (MessageEvent)e);
		} else if (message instanceof WebSocketFrame) {
			handleRequest(ctx, (WebSocketFrame) message);
		}
	} else {
		ctx.sendUpstream(e);
	}			
}
 
Example 53
Project: HeliosStreams   File: WebSocketServiceHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Sends an HTTP response
 * @param ctx The channel handler context
 * @param req The HTTP request being responded to
 * @param res The HTTP response to send
 */
private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
    // Generate an error page if response status code is not OK (200).
    if (res.getStatus().getCode() != 200) {
        res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
        setContentLength(res, res.getContent().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write(res);
    if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 54
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
	 * Handles a prepared WebSocket API invocation to retrieve a static file
	 * @param request The prepared HTTP request so we can piggy-back on the existing RpcHandler services.
	 * @param response The JSONResponse to write back to
	 * @throws IOException thrown on IO errors
	 */
	protected void invokeForFile(HttpRequest request, JSONResponse response) throws IOException {
		JsonGenerator generator = response.writeHeader(true);		
		InvocationChannel ichannel = new InvocationChannel();		
		HttpQuery query = new HttpQuery(tsdb, request, ichannel);
		String baseRoute = query.getQueryBaseRoute();
//		http_commands.get(baseRoute).execute(tsdb, query);
		HttpResponse resp = (HttpResponse)ichannel.getWrites().get(0);
		byte[] regionBytes = (byte[])ichannel.getWrites().get(1);
		
		List<Map.Entry<String, String>> responseHeaders = resp.getHeaders();
		for(Map.Entry<String, String> entry: responseHeaders) {
			generator.writeStringField(entry.getKey(), entry.getValue());
			//log.info("Reponse Header: [{}] : [{}]", entry.getKey(), entry.getValue());
		}
		
		String cType = resp.getHeader("Content-Type");
		if(cType!=null) {
			if(cType.startsWith("text")) {
				generator.writeStringField("content", new String(regionBytes));
			} else {
				ChannelBuffer b64 = Base64.encode(ChannelBuffers.wrappedBuffer(regionBytes));
				byte[] bytes = new byte[b64.readableBytes()];
				b64.readBytes(bytes);
				generator.writeBinaryField("content", bytes);
			}
		}
		
		response.closeGenerator();
	}
 
Example 55
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
 * Handles a prepared WebSocket API invocation
 * @param asMap true if the JSON reponse is a map, false if it is an array
 * @param request The prepared HTTP request so we can piggy-back on the existing RpcHandler services.
 * @param response The JSONResponse to write back to
 * @throws IOException thrown on IO errors
 */
protected void invoke(boolean asMap, HttpRequest request, JSONResponse response) throws IOException {
	try {
		JsonGenerator generator = response.writeHeader(asMap);
		InvocationChannel ichannel = new InvocationChannel();
		HttpQuery query = new HttpQuery(tsdb, request, ichannel);
		String baseRoute = query.getQueryBaseRoute();
		rpcHandler.messageReceived(null, new UpstreamMessageEvent(ichannel, request, null));
		HttpResponse resp = (HttpResponse)ichannel.getWrites().get(0);			
		ChannelBuffer content = resp.getContent();
		ChannelBufferInputStream cbis =  new ChannelBufferInputStream(content);
		ObjectReader reader = jsonMapper.reader();
		JsonNode contentNode = reader.readTree(cbis);
		cbis.close();
		if(asMap) {
			ObjectNode on = (ObjectNode)contentNode;
			Iterator<Map.Entry<String, JsonNode>> nodeIter = on.fields();
			while(nodeIter.hasNext()) {
				Map.Entry<String, JsonNode> node = nodeIter.next();
				generator.writeObjectField(node.getKey(), node.getValue());
			}
		} else {
			ArrayNode an = (ArrayNode)contentNode;
			for(int i = 0; i < an.size(); i++) {
				generator.writeObject(an.get(i));
			}			
		}
		response.closeGenerator();
	} catch (Exception ex) {
		throw new RuntimeException(ex);
	}
	
}
 
Example 56
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
 * WebSocket invoker for OpenTSDB HTTP <a href="http://opentsdb.net/docs/build/html/api_http/stats.html">api/stats</a> API call
 * @param request The JSONRequest
 */
@JSONRequestHandler(name="stats", description="Collects TSDB wide stats and returns them in JSON format to the caller")
public void stats(JSONRequest request) {
	try {
		HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/stats?json=true");
		invoke(false, httpRequest, request.response(ResponseType.RESP));
	} catch (Exception ex) {
		log.error("Failed to invoke stats", ex);
		request.error("Failed to invoke stats", ex).send();
	}
}
 
Example 57
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
 * WebSocket invoker for OpenTSDB HTTP <a href="http://opentsdb.net/docs/build/html/api_http/s.html">/s</a> static file retrieval API call
 * @param request The JSONRequest
 */
@JSONRequestHandler(name="s", description="Retrieves a static file")
public void file(JSONRequest request) {
	try {
		String fileName = request.getArgument("s").replace("\"", "");
		HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ("/s/" + fileName));
		invokeForFile(httpRequest, request.response(ResponseType.RESP));
	} catch (Exception ex) {
		log.error("Failed to invoke s/file", ex);
		request.error("Failed to invoke s/file", ex).send();
	}
}
 
Example 58
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
 * WebSocket invoker for OpenTSDB HTTP <a href="http://opentsdb.net/docs/build/html/api_http/version.html">/s</a> OpenTSDB version info API call
 * @param request The JSONRequest
 */
@JSONRequestHandler(name="dropcaches", description="Drops all OpenTSDB server caches")
public void dropcaches(JSONRequest request) {
	try {
		HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/dropcaches?json=true");
		invoke(true, httpRequest, request.response(ResponseType.RESP));
	} catch (Exception ex) {
		log.error("Failed to invoke dropcaches", ex);
		request.error("Failed to invoke dropcaches", ex).send();
	}
}
 
Example 59
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
 * WebSocket invoker for OpenTSDB HTTP <a href="http://opentsdb.net/docs/build/html/api_http/logs.html">/s</a> logs API call
 * @param request The JSONRequest
 */
@JSONRequestHandler(name="logs", description="Returns JSONized OpenTSDB log file entries")
public void logs(JSONRequest request) {
	try {
		HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/logs?json=true");
		invoke(true, httpRequest, request.response(ResponseType.RESP));
	} catch (Exception ex) {
		log.error("Failed to invoke logs", ex);
		request.error("Failed to invoke logs", ex).send();
	}
}
 
Example 60
Project: HeliosStreams   File: TSDBJSONService.java   Source Code and License 5 votes vote down vote up
/**
 * WebSocket invoker for OpenTSDB HTTP <a href="http://opentsdb.net/docs/build/html/api_http/dropcaches.html">/s</a> drop caches API call
 * @param request The JSONRequest
 */
@JSONRequestHandler(name="version", description="Retrieves the OpenTSDB version info")
public void version(JSONRequest request) {
	try {
		HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/version?json=true");
		invoke(true, httpRequest, request.response(ResponseType.RESP));
	} catch (Exception ex) {
		log.error("Failed to invoke version", ex);
		request.error("Failed to invoke version", ex).send();
	}
}