Java Code Examples for io.netty.handler.codec.http.FullHttpRequest#uri()

The following examples show how to use io.netty.handler.codec.http.FullHttpRequest#uri() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultWebSocketHandler.java    From netstrap with Apache License 2.0 6 votes vote down vote up
/**
 * 处理Http请求或握手请求
 */
private void handleHttpRequest(ChannelHandlerContext context, FullHttpRequest request) {

    if (!request.decoderResult().isSuccess()) {
        context.close();
        return;
    }

    if (nettyConfig.getEndpoint().equals(request.uri())) {
        //建立WebSocket连接
        SslConfig ssl = nettyConfig.getSsl();
        WebSocketServerHandshakerFactory wsFactory =
                new WebSocketServerHandshakerFactory(ssl.isEnable() ? "wss://" : "ws://" + request.headers().get(HttpHeaderNames.HOST) + request.uri(), null, false);

        handshake = wsFactory.newHandshaker(request);
        if (handshake == null) {
            // 不支持
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(context.channel());
        } else {
            handshake.handshake(context.channel(), request);
        }
    } else {
        // 处理普通http请求
        httpHandler.handleHttpRequest(context, request);
    }
}
 
Example 2
Source File: DefaultDispatcher.java    From ace with Apache License 2.0 6 votes vote down vote up
/**
 * 请求分发与处理
 *
 * @param request http协议请求
 * @return 处理结果
 * @throws InvocationTargetException 调用异常
 * @throws IllegalAccessException    参数异常
 */
public Object doDispatcher(FullHttpRequest request) throws InvocationTargetException, IllegalAccessException {
    Object[] args;
    String uri = request.uri();
    if (uri.endsWith("favicon.ico")) {
        return "";
    }

    AceServiceBean aceServiceBean = Context.getAceServiceBean(uri);
    AceHttpMethod aceHttpMethod = AceHttpMethod.getAceHttpMethod(request.method().toString());
    ByteBuf content = request.content();
    //如果要多次解析,请用 request.content().copy()
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    Map<String, List<String>> requestMap = decoder.parameters();
    Object result = aceServiceBean.exec(uri, aceHttpMethod, requestMap, content == null ? null : content.toString(CharsetUtil.UTF_8));
    String contentType = request.headers().get("Content-Type");
    if (result == null) {
        ApplicationInfo mock = new ApplicationInfo();
        mock.setName("ace");
        mock.setVersion("1.0");
        mock.setDesc(" mock  !!! ");
        result = mock;
    }
    return result;

}
 
Example 3
Source File: WebSocketHandler.java    From socketio with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof FullHttpRequest) {
    FullHttpRequest req = (FullHttpRequest) msg;
    if (req.method() == HttpMethod.GET && req.uri().startsWith(connectPath)) {
      final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
      final String requestPath = queryDecoder.path();

      if (log.isDebugEnabled())
        log.debug("Received HTTP {} handshake request: {} from channel: {}", getTransportType().getName(), req, ctx.channel());

      try {
        handshake(ctx, req, requestPath);
      } catch (Exception e) {
        log.error("Error during {} handshake : {}", getTransportType().getName(), e);
      } finally {
        ReferenceCountUtil.release(msg);
      }
      return;
    }
  } else if (msg instanceof WebSocketFrame && isCurrentHandlerSession(ctx)) {
    handleWebSocketFrame(ctx, (WebSocketFrame) msg);
    return;
  }
  ctx.fireChannelRead(msg);
}
 
Example 4
Source File: PassthroughHandler.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
        final FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER);
        HttpUtil.setKeepAlive(response, true);
        HttpUtil.setContentLength(response, 0);
        if (api.getSslContext() != null) {
            final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
            sslEngine.setUseClientMode(false);
            ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));

            final String uri = request.uri();
            final String[] parts = uri.split(":");
            ctx
                    .channel()
                    .attr(BASE)
                    .set("https://" + parts[0]
                            + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
        }
        ctx.writeAndFlush(response);
        return;
    }
    final FullHttpRequest req = request.copy(); // copy to use in a separated thread
    api.getExecutor().execute(() -> doHttpRequest(req, ctx));
}
 
Example 5
Source File: Http2RequestHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    QueryStringDecoder queryString = new QueryStringDecoder(request.uri());
    String streamId = streamId(request);
    int latency = toInt(firstValue(queryString, LATENCY_FIELD_NAME), 0);
    if (latency < MIN_LATENCY || latency > MAX_LATENCY) {
        sendBadRequest(ctx, streamId);
        return;
    }
    String x = firstValue(queryString, IMAGE_COORDINATE_X);
    String y = firstValue(queryString, IMAGE_COORDINATE_Y);
    if (x == null || y == null) {
        handlePage(ctx, streamId, latency, request);
    } else {
        handleImage(x, y, ctx, streamId, latency, request);
    }
}
 
Example 6
Source File: UrlReWriterHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest request = (FullHttpRequest) msg;

        String requestUri = request.uri();
        String mapToURI = mapTo(requestUri);
        log.trace("Mapping from {} to {}", requestUri, mapToURI);
        request.setUri(mapToURI);
    }

    super.channelRead(ctx, msg);
}
 
Example 7
Source File: HttpRequest.java    From lannister with Apache License 2.0 5 votes vote down vote up
protected HttpRequest(FullHttpRequest fullHttpRequest) throws URISyntaxException {
	super(fullHttpRequest.protocolVersion(), fullHttpRequest.method(), fullHttpRequest.uri(),
			fullHttpRequest.content().copy());

	this.headers().set(fullHttpRequest.headers());
	this.trailingHeaders().set(fullHttpRequest.trailingHeaders());
	this.setDecoderResult(fullHttpRequest.decoderResult());
	this.uri = createUriWithNormalizing(fullHttpRequest.uri());

	this.parameters = parameters();
	this.cookies = cookies();
	this.pathParameters = Maps.newHashMap();
}
 
Example 8
Source File: DFWSRequestHandler.java    From dfactor with MIT License 5 votes vote down vote up
@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
		// Handle a bad request
		if (!req.decoderResult().isSuccess()) {
			_sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
			return;
		}
		// Allow only GET methods
		if (req.method() != HttpMethod.GET) {
			_sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
			return;
		}
		
		// Send the index page
		final String uri = req.uri();
		if (_wsUri.equals(uri)) {
//			String webSocketLocation = _getWebSocketLocation(ctx.pipeline(), req, _wsUri);
//			ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
//			FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
//			
//			res.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
//			HttpHeaders.setContentLength(res, content.readableBytes());
//			
//			_sendHttpResponse(ctx, req, res);
			
			ctx.fireChannelRead(req.setUri(_wsUri).retain());
		} else {
			_sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
		}
		
		
		
	}
 
Example 9
Source File: HttpServerHandler.java    From cantor with Apache License 2.0 5 votes vote down vote up
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (FullHttpRequest.class.isAssignableFrom(msg.getClass())) {
            FullHttpRequest req = FullHttpRequest.class.cast(msg);
            DecoderResult result = req.decoderResult();

            if (result.isFailure()) {
                if (log.isWarnEnabled())
                    log.warn("http decoder failure", result.cause());
                ReferenceCountUtil.release(msg);
                ctx.writeAndFlush(HttpResponses.badRequest());
                ctx.channel().close();
                return;
            }

            if (HttpUtil.is100ContinueExpected(req))
                ctx.writeAndFlush(new DefaultFullHttpResponse(req.protocolVersion(), CONTINUE));

            FullHttpRequest safeReq = new DefaultFullHttpRequest(req.protocolVersion(),
                                                                 req.method(),
                                                                 req.uri(),
//                                                                 Buffers.safeByteBuf(req.content(), ctx.alloc()),
                                                                 req.content(),
                                                                 req.headers(),
                                                                 req.trailingHeaders());
            channelRead(ctx, safeReq);
        } else
            ctx.fireChannelRead(msg);
    }
 
Example 10
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    final String uri = msg.uri();
    final String[] split = uri.split(":");
    checkArgument(split.length == 2, "invalid destination url");

    ctx.fireUserEventTriggered(new ProxySuccessEvent(
            new InetSocketAddress(split[0], Integer.parseInt(split[1])),
            new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK)));
}
 
Example 11
Source File: HttpDecoder.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, FullHttpRequest in, List<Object> out)
    throws Exception {
    switch (in.uri()) {
        case "/ping":
            if (in.method() == GET) {
                getPing(ctx, in, out);
                return;
            }

            throw new HttpException(HttpResponseStatus.METHOD_NOT_ALLOWED);
        case "/v1/batch":
            if (in.method() == POST) {
                if (matchContentType(in, "application/json")) {
                    postBatch(ctx, in, out);
                    return;
                }
                log.error("Unsupported Media Type");
                throw new HttpException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
            }
            log.error("HTTP Method Not Allowed");
            throw new HttpException(HttpResponseStatus.METHOD_NOT_ALLOWED);
        default:
            /* do nothing */
            break;
    }

    throw new HttpException(HttpResponseStatus.NOT_FOUND);
}
 
Example 12
Source File: ApiController.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getQueryParams(FullHttpRequest request) throws IOException {
  Map<String, String> map = new HashMap<>();
  String uri = request.uri();
  int index = uri.lastIndexOf("?");
  if (index != -1 && index != uri.length() - 1) {
    String[] params = uri.substring(index + 1).split("&");
    for (String param : params) {
      String[] kv = param.split("=");
      if (kv.length == 2) {
        map.put(kv[0], kv[1]);
      }
    }
  }
  return map;
}
 
Example 13
Source File: TextWebSocketFrameHandler.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 得到Http请求的Query String
 * 
 * @param req
 * @param name
 * @return
 */
private static String getRequestParameter(FullHttpRequest req, String name) {
    QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
    Map<String, List<String>> parameters = decoder.parameters();
    Set<Entry<String, List<String>>> entrySet = parameters.entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        if (entry.getKey().equalsIgnoreCase(name)) {
            return entry.getValue().get(0);
        }
    }
    return null;
}
 
Example 14
Source File: HttpServerHandler.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final FullHttpRequest request) {
    String requestPath = request.uri();
    String requestBody = request.content().toString(CharsetUtil.UTF_8);
    HttpMethod method = request.method();
    if (!URL_PATTERN.matcher(requestPath).matches()) {
        response(GSON.toJson(ResponseContentUtil.handleBadRequest("Not support request!")),
                channelHandlerContext, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    if ("/scaling/job/start".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.POST)) {
        startJob(channelHandlerContext, requestBody);
        return;
    }
    if (requestPath.contains("/scaling/job/progress/") && method.equals(HttpMethod.GET)) {
        getJobProgress(channelHandlerContext, requestPath);
        return;
    }
    if ("/scaling/job/list".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.GET)) {
        listAllJobs(channelHandlerContext);
        return;
    }
    if ("/scaling/job/stop".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.POST)) {
        stopJob(channelHandlerContext, requestBody);
        return;
    }
    response(GSON.toJson(ResponseContentUtil.handleBadRequest("Not support request!")),
            channelHandlerContext, HttpResponseStatus.BAD_REQUEST);
}
 
Example 15
Source File: HttpRequestMessage.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Used for conversion from {@link FullHttpRequest} to {@link HttpRequestMessage} */
public HttpRequestMessage(FullHttpRequest request) {
  this(request.protocolVersion(), request.method(), request.uri(), request.content());
  request.headers().forEach((entry) -> headers().set(entry.getKey(), entry.getValue()));
}
 
Example 16
Source File: StaticSite.java    From crate with Apache License 2.0 4 votes vote down vote up
public static FullHttpResponse serveSite(Path siteDirectory,
                                         FullHttpRequest request,
                                         ByteBufAllocator alloc) throws IOException {
    if (request.method() != HttpMethod.GET) {
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
    }
    String sitePath = request.uri();
    while (sitePath.length() > 0 && sitePath.charAt(0) == '/') {
        sitePath = sitePath.substring(1);
    }

    // we default to index.html, or what the plugin provides (as a unix-style path)
    // this is a relative path under _site configured by the plugin.
    if (sitePath.length() == 0) {
        sitePath = "index.html";
    }

    final String separator = siteDirectory.getFileSystem().getSeparator();
    // Convert file separators.
    sitePath = sitePath.replace("/", separator);
    Path file = siteDirectory.resolve(sitePath);

    // return not found instead of forbidden to prevent malicious requests to find out if files exist or don't exist
    if (!Files.exists(file) || FileSystemUtils.isHidden(file) ||
        !file.toAbsolutePath().normalize().startsWith(siteDirectory.toAbsolutePath().normalize())) {

        return Responses.contentResponse(
            HttpResponseStatus.NOT_FOUND, alloc, "Requested file [" + file + "] was not found");
    }

    BasicFileAttributes attributes = readAttributes(file, BasicFileAttributes.class);
    if (!attributes.isRegularFile()) {
        // If it's not a regular file, we send a 403
        final String msg = "Requested file [" + file + "] is not a valid file.";
        return Responses.contentResponse(HttpResponseStatus.NOT_FOUND, alloc, msg);
    }
    try {
        byte[] data = Files.readAllBytes(file);
        var resp = Responses.contentResponse(HttpResponseStatus.OK, alloc, data);
        resp.headers().set(HttpHeaderNames.CONTENT_TYPE, guessMimeType(file.toAbsolutePath().toString()));
        return resp;
    } catch (IOException e) {
        return Responses.contentResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, alloc, e.getMessage());
    }
}
 
Example 17
Source File: NettyRestHandler.java    From turbo-rpc with Apache License 2.0 4 votes vote down vote up
private String toString(FullHttpRequest httpRequest) {
	String uri = httpRequest.uri();
	HttpMethod httpMethod = httpRequest.method();

	return httpMethod.name() + " " + uri;
}
 
Example 18
Source File: WsServerHandler.java    From openzaly with Apache License 2.0 4 votes vote down vote up
private void doHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
	if (request.decoderResult().isFailure()) {
		ctx.close();
		return;
	}

	// 握手使用get方法,所以我们控制只接受get方法
	if (HttpMethod.GET != request.method()) {
		ctx.close();
		return;
	}

	String wsUrl = "ws://" + request.headers().get(HttpHeaderNames.HOST) + AKAXIN_WS_PATH;

	WebSocketServerHandshakerFactory webSocketFactory = new WebSocketServerHandshakerFactory(wsUrl, null, true);
	wsHandshaker = webSocketFactory.newHandshaker(request);
	if (wsHandshaker != null) {
		//
		ChannelFuture channelFuture = wsHandshaker.handshake(ctx.channel(), request);
		if (channelFuture.isSuccess()) {
			// 握手并且验证用户webSessionId
			QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri());
			List<String> sessionIds = queryDecoder.parameters().get("sessionId");
			if (sessionIds != null && sessionIds.size() > 0) {
				String sessionId = sessionIds.get(0);
				String siteUserId = WebSessionCache.getSiteUserId(sessionId);
				// test siteUserId
				siteUserId = "77151873-0fc7-4cf1-8bd6-67d00190fcf6";
				if (StringUtils.isNotBlank(siteUserId)) {
					ChannelSession channelSession = ctx.channel().attr(ChannelConst.CHANNELSESSION).get();
					// siteUserId && sessionId 放入Channel缓存中
					channelSession.setUserId(siteUserId);
					WebChannelManager.addChannelSession(siteUserId, channelSession);
				} else {
					// cant get authed message ,so close the channel
					// ctx.close();
				}
			} else {
				ctx.close();
			}
			System.out.println("client handshaker success parm=" + queryDecoder.parameters());

		}
	} else {
		WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
	}

}
 
Example 19
Source File: RequestContext.java    From mpush with Apache License 2.0 4 votes vote down vote up
public RequestContext(FullHttpRequest request, HttpCallback callback) {
    this.callback = callback;
    this.request = request;
    this.uri = request.uri();
    this.readTimeout = parseTimeout();
}
 
Example 20
Source File: NettyServerHandler.java    From java-study with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	if(! (msg instanceof FullHttpRequest)){
		result="未知请求!";
		send(ctx,result,HttpResponseStatus.BAD_REQUEST);
		return;
 	}
	FullHttpRequest httpRequest = (FullHttpRequest)msg;
	try{
		String path=httpRequest.uri();			//获取路径
		String body = getBody(httpRequest); 	//获取参数
		HttpMethod method=httpRequest.method();//获取请求方法
		//如果不是这个路径,就直接返回错误
		if(!"/test".equalsIgnoreCase(path)){
			result="非法请求!";
			send(ctx,result,HttpResponseStatus.BAD_REQUEST);
			return;
		}
		System.out.println("接收到:"+method+" 请求");
		//如果是GET请求
		if(HttpMethod.GET.equals(method)){ 
			//接受到的消息,做业务逻辑处理...
			System.out.println("body:"+body);
			result="GET请求";
			send(ctx,result,HttpResponseStatus.OK);
			return;
		}
		//如果是POST请求
		if(HttpMethod.POST.equals(method)){ 
			//接受到的消息,做业务逻辑处理...
			System.out.println("body:"+body);
			result="POST请求";
			send(ctx,result,HttpResponseStatus.OK);
			return;
		}
		
		//如果是PUT请求
		if(HttpMethod.PUT.equals(method)){ 
			//接受到的消息,做业务逻辑处理...
			System.out.println("body:"+body);
			result="PUT请求";
			send(ctx,result,HttpResponseStatus.OK);
			return;
		}
		//如果是DELETE请求
		if(HttpMethod.DELETE.equals(method)){ 
			//接受到的消息,做业务逻辑处理...
			System.out.println("body:"+body);
			result="DELETE请求";
			send(ctx,result,HttpResponseStatus.OK);
			return;
		}
	}catch(Exception e){
		System.out.println("处理请求失败!");
		e.printStackTrace();
	}finally{
		//释放请求
		httpRequest.release();
	}
}