Java Code Examples for io.netty.handler.codec.http.QueryStringDecoder#path()

The following examples show how to use io.netty.handler.codec.http.QueryStringDecoder#path() . 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: Router.java    From litchi with Apache License 2.0 6 votes vote down vote up
public RouteResult<T> route(HttpMethod method, String uri) {
	PatternRouter<T> router = routers.get(method);
	if (router == null) {
		return null;
	}

	QueryStringDecoder decoder = new QueryStringDecoder(uri);
	String[] tokens = decodePathTokens(uri);

	RouteResult<T> ret = router.route(uri, decoder.path(), tokens);
	if (ret != null) {
		return new RouteResult<T>(uri, decoder.path(), ret.pathParams(), decoder.parameters(), ret.target());
	}

	return null;
}
 
Example 2
Source File: DisconnectHandler.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 HttpRequest) {
    final HttpRequest req = (HttpRequest) msg;
    final HttpMethod requestMethod = req.method();
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
    final String requestPath = queryDecoder.path();

    boolean disconnect = queryDecoder.parameters().containsKey(DISCONNECT);
    if (disconnect) {
      if (log.isDebugEnabled())
        log.debug("Received HTTP disconnect request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      final String sessionId = PipelineUtils.getSessionId(requestPath);
      final Packet disconnectPacket = new Packet(PacketType.DISCONNECT, sessionId);
      disconnectPacket.setOrigin(PipelineUtils.getOrigin(req));
      ctx.fireChannelRead(disconnectPacket);
      ReferenceCountUtil.release(msg);
      return;
    }
  }
  ctx.fireChannelRead(msg);
}
 
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: FunctionsChannelHandler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
	if (!request.getDecoderResult().isSuccess()) {
		sendError(ctx, BAD_REQUEST);
		return;
	}
				
	String uri = request.getUri();
	QueryStringDecoder decoder = new QueryStringDecoder(uri);			
	SimpleHttpRequest req = new SimpleHttpRequest(decoder.path(), decoder.parameters());
				
	String cookieString = request.headers().get(HttpHeaders.Names.COOKIE);
	if (cookieString != null) {
		Set<Cookie> cookies = CookieDecoder.decode(cookieString);
		req.setCookies(cookies);
	} else {
		req.setCookies(Collections.emptySet());
	}
	req.setHeaders(request.headers());
	copyHttpBodyData(request, req);
	
	SimpleHttpResponse resp =  eventHandler.apply(req);
	ctx.write( HttpEventHandler.buildHttpResponse(resp.toString(), resp.getStatus(), resp.getContentType()) );
	ctx.flush().close();
	
}
 
Example 5
Source File: HttpEventRoutingHandler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
		throws Exception {
	if (msg instanceof HttpRequest) {
		HttpRequest request = (HttpRequest) msg;

		String uri = request.getUri();
		QueryStringDecoder decoder = new QueryStringDecoder(uri);
		String path = decoder.path();
		//System.out.println("path "+path);
		
		HttpResponse response = findHandler(request, path).handle(request, decoder);			
		 
		ctx.write(response);
		ctx.flush().close();
	}
}
 
Example 6
Source File: HttpRequestExecutor.java    From Okra with Apache License 2.0 6 votes vote down vote up
@Override
public void onExecute() {
    if (null == request) {
        throw new NullPointerException("request");
    }
    try {
        QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
        switch (decoder.path()) {
            case "/test":
                response(session.channel(), "{state:0}");
                return;
            case "/favicon.ico":
                break;
        }
        simple(session.channel(), FORBIDDEN);
    } catch (Exception e) {
        session.channel().close();
        LOG.info("HTTP Api throw exception : ", e);
    }
}
 
Example 7
Source File: ApiDescriptionRequestHandler.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleRequest(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelException {

    if (isApiDescription(segments)) {
        String path = decoder.path();
        if (("/".equals(path) && HttpMethod.OPTIONS.equals(req.method()))
                || (segments.length == 2 && segments[1].equals("api-description"))) {
            handleApiDescription(ctx);
            return;
        }
        throw new MethodNotAllowedException();
    } else {
        chain.handleRequest(ctx, req, decoder, segments);
    }
}
 
Example 8
Source File: RequestLog.java    From Sparkngin with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Constructor
 * @param httpReq HttpRequest object to be sent to Sparkngin
 */
public RequestLog(HttpRequest httpReq, Pattern[] headerMatcher) {
  QueryStringDecoder decoder = new QueryStringDecoder(httpReq.getUri());
  String path = decoder.path() ;
  List<String> segments = StringUtil.split(path, '/') ;
  this.trackerName = segments.get(1) ;
  this.site = segments.get(2) ;
  
  this.uri = httpReq.getUri() ;
  this.method = httpReq.getMethod().name() ;
  requestHeaders = new HashMap<String, String>() ;
  Iterator<Entry<String, String>> i = httpReq.headers().iterator() ;
  while(i.hasNext()) {
    Entry<String, String> entry =i.next();
    String key = entry.getKey() ;
    if(extractHeader(key, headerMatcher)) {
      requestHeaders.put(key, entry.getValue()) ;
    }
  }
}
 
Example 9
Source File: ApiDescriptionRequestHandler.java    From serve with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleRequest(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelException {

    if (isApiDescription(segments)) {
        String path = decoder.path();
        if (("/".equals(path) && HttpMethod.OPTIONS.equals(req.method()))
                || (segments.length == 2 && segments[1].equals("api-description"))) {
            handleApiDescription(ctx);
            return;
        }
        throw new MethodNotAllowedException();
    } else {
        chain.handleRequest(ctx, req, decoder, segments);
    }
}
 
Example 10
Source File: Router.java    From redant with Apache License 2.0 5 votes vote down vote up
/**
 * If there's no match, returns the result with {@link #notFound(Object) notFound}
 * as the target if it is set, otherwise returns {@code null}.
 */
public RouteResult<T> route(HttpMethod method, String uri) {
    MethodlessRouter<T> router = routers.get(method);
    if (router == null) {
        router = anyMethodRouter;
    }

    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    String[] tokens = decodePathTokens(uri);

    RouteResult<T> ret = router.route(uri, decoder.path(), tokens);
    if (ret != null) {
        return new RouteResult<T>(uri, decoder.path(), ret.pathParams(), decoder.parameters(), ret.target());
    }

    if (router != anyMethodRouter) {
        ret = anyMethodRouter.route(uri, decoder.path(), tokens);
        if (ret != null) {
            return new RouteResult<T>(uri, decoder.path(), ret.pathParams(), decoder.parameters(), ret.target());
        }
    }

    if (notFound != null) {
        return new RouteResult<T>(uri, decoder.path(), Collections.<String, String>emptyMap(), decoder.parameters(), notFound);
    }

    return null;
}
 
Example 11
Source File: URIBean.java    From xian with Apache License 2.0 5 votes vote down vote up
private URIBean(String uri) {
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri, true);
    String path = queryStringDecoder.path();
    int groupIndex = path.indexOf('/') + 1,
            unitIndex = path.indexOf('/', groupIndex) + 1,
            uriExtensionIndex = path.indexOf('/', unitIndex) + 1;
    if (groupIndex == 0 || unitIndex == 0) {
        throw new IllegalArgumentException("URI is illegal: " + uri);
    }
    group = path.substring(groupIndex, unitIndex - 1);
    if (uriExtensionIndex == 0) {
        unit = path.substring(unitIndex);
    } else {
        unit = path.substring(unitIndex, uriExtensionIndex - 1);
        uriExtension = path.substring(uriExtensionIndex);
    }
    Map<String, List<String>> parameters = queryStringDecoder.parameters();
    parameters.forEach((key, values) -> {
        if (values == null || values.isEmpty()) {
            //空参数统一对应空字符串
            uriParameters.put(key, "");
        } else if (values.size() == 1) {
            uriParameters.put(key, values.get(0));
        } else {
            uriParameters.put(key, values);
        }
    });
}
 
Example 12
Source File: FSImageHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private static String getPath(QueryStringDecoder decoder)
        throws FileNotFoundException {
  String path = decoder.path();
  if (path.startsWith(WEBHDFS_PREFIX)) {
    return path.substring(WEBHDFS_PREFIX_LENGTH);
  } else {
    throw new FileNotFoundException("Path: " + path + " should " +
            "start with " + WEBHDFS_PREFIX);
  }
}
 
Example 13
Source File: FSImageHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
private static String getPath(QueryStringDecoder decoder)
        throws FileNotFoundException {
  String path = decoder.path();
  if (path.startsWith(WEBHDFS_PREFIX)) {
    return path.substring(WEBHDFS_PREFIX_LENGTH);
  } else {
    throw new FileNotFoundException("Path: " + path + " should " +
            "start with " + WEBHDFS_PREFIX);
  }
}
 
Example 14
Source File: URIBean.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Check the uri is xian pattern or not.
 * xian pattern uri must starts with /${group}/${unit}
 * TODO combine URI checking with UriBean creation. And use UriBean reference instead of URI string later on for performance consideration.
 *
 * @param uri the URI to be checked
 * @return true if it is xian pattern false other wise.
 */
public static boolean checkUri(String uri) {
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri, true);
    String path = queryStringDecoder.path();
    int groupIndex = path.indexOf('/') + 1,
            unitIndex = path.indexOf('/', groupIndex) + 1;
    if (groupIndex == 0 || unitIndex == 0) {
        LOG.warn("URI is illegal: " + uri);
        return false;
    }
    return true;
}
 
Example 15
Source File: Router.java    From bitchat with Apache License 2.0 5 votes vote down vote up
/**
 * If there's no match, returns the result with {@link #notFound(Object) notFound}
 * as the target if it is set, otherwise returns {@code null}.
 */
public RouteResult<T> route(HttpMethod method, String uri) {
    MethodlessRouter<T> router = routers.get(method);
    if (router == null) {
        router = anyMethodRouter;
    }

    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    String[] tokens = decodePathTokens(uri);

    RouteResult<T> ret = router.route(uri, decoder.path(), tokens);
    if (ret != null) {
        return new RouteResult<T>(uri, decoder.path(), ret.pathParams(), decoder.parameters(), ret.target());
    }

    if (router != anyMethodRouter) {
        ret = anyMethodRouter.route(uri, decoder.path(), tokens);
        if (ret != null) {
            return new RouteResult<T>(uri, decoder.path(), ret.pathParams(), decoder.parameters(), ret.target());
        }
    }

    if (notFound != null) {
        return new RouteResult<T>(uri, decoder.path(), Collections.<String, String>emptyMap(), decoder.parameters(), notFound);
    }

    return null;
}
 
Example 16
Source File: MP4Handler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Nullable
protected UUID getRecordingId(QueryStringDecoder uri, int start, int end, @Nullable String finl) {
   try {
      String path = uri.path();
      String recording = path.substring(start, end);

      UUID uuid = UUID.fromString(recording);
      if (uuid.version() != 1) {
         DOWNLOAD_UUID_BAD.inc();
         log.debug("failed to retreive recording id because uuid wasn't version 1: {}", uri);
         return null;
      }

      if (finl != null) {
         String fin = path.substring(end);
         if (!finl.equals(fin)) {
            DOWNLOAD_URL_BAD.inc();
            log.debug("failed to retreive recording id because url was wrong: {}", uri);
            return null;
         }
      }

      return uuid;
   } catch (Exception ex) {
      DOWNLOAD_ID_BAD.inc();
      return null;
   }
}
 
Example 17
Source File: HandshakeHandler.java    From socketio with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof HttpRequest) {
    final HttpRequest req = (HttpRequest) msg;
    final HttpMethod requestMethod = req.method();
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
    final String requestPath = queryDecoder.path();

    if (!requestPath.startsWith(handshakePath)) {
      log.warn("Received HTTP bad request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
      ChannelFuture f = ctx.channel().writeAndFlush(res);
      f.addListener(ChannelFutureListener.CLOSE);
      ReferenceCountUtil.release(req);
      return;
    }

    if (HttpMethod.GET.equals(requestMethod) && requestPath.equals(handshakePath)) {
      if (log.isDebugEnabled())
        log.debug("Received HTTP handshake request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      handshake(ctx, req, queryDecoder);
      ReferenceCountUtil.release(req);
      return;
    }
  }

  super.channelRead(ctx, msg);
}
 
Example 18
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
    if (msg == null || ctx == null) {
        return;
    }
    try {
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;
            // logger.debug("{}", httpRequest);
            logger.debug("Stream Server recieved request \t{}:{}", httpRequest.method(), httpRequest.uri());
            String requestIP = "("
                    + ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress() + ")";
            if (!whiteList.contains(requestIP) && !whiteList.equals("DISABLE")) {
                logger.warn("The request made from {} was not in the whitelist and will be ignored.", requestIP);
                return;
            } else if ("GET".equalsIgnoreCase(httpRequest.method().toString())) {
                // Some browsers send a query string after the path when refreshing a picture.
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.uri());
                switch (queryStringDecoder.path()) {
                    case "/ipcamera.m3u8":
                        if (ipCameraGroupHandler.hlsTurnedOn) {
                            String debugMe = ipCameraGroupHandler.getPlayList();
                            logger.debug("playlist is:{}", debugMe);
                            sendString(ctx, debugMe, "application/x-mpegurl");
                        } else {
                            logger.warn(
                                    "HLS requires the groups startStream channel to be turned on first. Just starting it now.");
                            String channelPrefix = "ipcamera:" + ipCameraGroupHandler.getThing().getThingTypeUID()
                                    + ":" + ipCameraGroupHandler.getThing().getUID().getId() + ":";
                            ipCameraGroupHandler.handleCommand(new ChannelUID(channelPrefix + CHANNEL_START_STREAM),
                                    OnOffType.valueOf("ON"));
                        }
                        break;
                    case "/ipcamera.jpg":
                        sendSnapshotImage(ctx, "image/jpg");
                        break;
                    case "/snapshots.mjpeg":
                        logger.warn("snapshots.mjpeg is not yet implemented, use ipcamera.jpg or HLS.");
                        // ipCameraGroupHandler.setupSnapshotStreaming(true, ctx, false);
                        // handlingSnapshotStream = true;
                        break;
                    case "/ipcamera.mjpeg":
                        logger.warn("ipcamera.mjpeg is not yet implemented, use ipcamera.jpg or HLS.");
                        // ipCameraGroupHandler.setupMjpegStreaming(true, ctx);
                        // handlingMjpeg = true;
                        break;
                    case "/autofps.mjpeg":
                        logger.warn("autofps.mjpeg is not yet implemented, use ipcamera.jpg or HLS.");
                        // ipCameraGroupHandler.setupSnapshotStreaming(true, ctx, true);
                        // handlingSnapshotStream = true;
                        break;
                    default:
                        if (httpRequest.uri().contains(".ts")) {
                            // String path = resolveIndexToPath(httpRequest.uri());
                            sendFile(ctx, resolveIndexToPath(httpRequest.uri()) + httpRequest.uri().substring(2),
                                    "video/MP2T");
                        } else if (httpRequest.uri().contains(".jpg")) {
                            // Allow access to the preroll and postroll jpg files
                            sendFile(ctx, httpRequest.uri(), "image/jpg");
                        } else if (httpRequest.uri().contains(".m4s")) {
                            sendFile(ctx, httpRequest.uri(), "video/mp4");
                        } else if (httpRequest.uri().contains(".mp4")) {
                            sendFile(ctx, httpRequest.uri(), "video/mp4");
                        }
                }
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
 
Example 19
Source File: ResourceHandler.java    From socketio with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof HttpRequest) {
    HttpRequest req = (HttpRequest) msg;
    QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
    String requestPath = queryDecoder.path();
    URL resUrl = resources.get(requestPath);
    if (resUrl != null) {
      if (log.isDebugEnabled())
        log.debug("Received HTTP resource request: {} {} from channel: {}", req.method(), requestPath, ctx.channel());

      URLConnection fileUrl = resUrl.openConnection();
      long lastModified = fileUrl.getLastModified();
      // check if file has been modified since last request
      if (isNotModified(req, lastModified)) {
        sendNotModified(ctx);
        return;
      }
      // create resource input-stream and check existence
      final InputStream is = fileUrl.getInputStream();
      if (is == null) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
      }
      // create ok response
      HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
      // set Content-Length header
      HttpUtil.setContentLength(res, fileUrl.getContentLengthLong());
      // set Content-Type header
      setContentTypeHeader(res, fileUrl);
      // set Date, Expires, Cache-Control and Last-Modified headers
      setDateAndCacheHeaders(res, lastModified);
      // write initial response header
      ctx.write(res);

      // write the content stream
      ctx.pipeline().addBefore(ctx.name(), "chunked-writer-handler", new ChunkedWriteHandler());
      ChannelFuture writeFuture = ctx.writeAndFlush(new ChunkedStream(is, fileUrl.getContentLength()));
      // add operation complete listener so we can close the channel and the input stream
      writeFuture.addListener(ChannelFutureListener.CLOSE);
      ReferenceCountUtil.release(msg);
      return;
    }
  }
  super.channelRead(ctx, msg);
}
 
Example 20
Source File: HttpRequestParamDecoder.java    From fastjgame with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    DecoderResult decoderResult = msg.decoderResult();
    if (!decoderResult.isSuccess()) {
        ctx.writeAndFlush(HttpResponseHelper.newBadRequestResponse())
                .addListener(ChannelFutureListener.CLOSE);
        logger.warn("decode failed.", decoderResult.cause());
        return;
    }
    HttpMethod method = msg.method();
    // 仅限get和post请求
    if (method != HttpMethod.GET && method != HttpMethod.POST) {
        ctx.writeAndFlush(HttpResponseHelper.newBadRequestResponse())
                .addListener(ChannelFutureListener.CLOSE);
        logger.info("unsupported method {}", method.name());
        return;
    }

    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(msg.uri());
    String path = queryStringDecoder.path();
    Map<String, String> paramsMap = new LinkedHashMap<>();

    if (method == HttpMethod.GET) {
        for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) {
            paramsMap.put(entry.getKey(), entry.getValue().get(0));
        }
    } else {
        // You <strong>MUST</strong> call {@link #destroy()} after completion to release all resources.
        HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(msg);
        try {
            for (InterfaceHttpData httpData : postRequestDecoder.getBodyHttpDatas()) {
                if (httpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) httpData;
                    paramsMap.put(attribute.getName(), attribute.getValue());
                }
            }
        } finally {
            postRequestDecoder.destroy();
        }
    }
    final HttpRequestParam httpRequestParam = new HttpRequestParam(method, paramsMap);
    publish(new HttpRequestEvent(ctx.channel(), path, httpRequestParam, portExtraInfo));
}