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: 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 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: 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 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: 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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
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 38
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 39
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 40
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);
}