io.netty.handler.codec.http.QueryStringDecoder 源码实例Demo

类 io.netty.handler.codec.http.QueryStringDecoder 源码实例Demo

下面列出了 io.netty.handler.codec.http.QueryStringDecoder 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop   文件: WebHdfsHandler.java

@Override
public void channelRead0(final ChannelHandlerContext ctx,
                         final HttpRequest req) throws Exception {
  Preconditions.checkArgument(req.getUri().startsWith(WEBHDFS_PREFIX));
  QueryStringDecoder queryString = new QueryStringDecoder(req.getUri());
  params = new ParameterParser(queryString, conf);
  DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
  ugi = ugiProvider.ugi();
  path = params.path();

  injectToken();
  ugi.doAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      handle(ctx, req);
      return null;
    }
  });
}
 
源代码2 项目: serve   文件: InferenceRequestHandler.java

private void handleInvocations(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelNotFoundException, ModelVersionNotFoundException {
    String modelName =
            ("invocations".equals(segments[1]))
                    ? NettyUtils.getParameter(decoder, "model_name", null)
                    : segments[2];
    if (modelName == null || modelName.isEmpty()) {
        if (ModelManager.getInstance().getStartupModels().size() == 1) {
            modelName = ModelManager.getInstance().getStartupModels().iterator().next();
        }
    }
    predict(ctx, req, decoder, modelName, null);
}
 
源代码3 项目: serve   文件: InferenceRequestHandler.java

private void handleLegacyPredict(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelNotFoundException, ModelVersionNotFoundException {

    String modelVersion = null;
    if (segments.length == 4 && "predict".equals(segments[3])) {
        modelVersion = segments[2];
    } else if (segments.length < 3 || !"predict".equals(segments[2])) {
        throw new ResourceNotFoundException();
    }

    predict(ctx, req, decoder, segments[1], modelVersion);
}
 
源代码4 项目: glowroot   文件: BasicSmokeIT.java

@Test
public void shouldCheckActiveTraceModalPages() throws Exception {
    App app = app();
    GlobalNavbar globalNavbar = globalNavbar();
    JvmSidebar jvmSidebar = new JvmSidebar(driver);

    app.open();
    globalNavbar.clickJvmLink();
    jvmSidebar.clickThreadDumpLink();

    WebElement viewTraceLink = Utils.getWithWait(driver, Utils.linkText("view trace"));
    String href = viewTraceLink.getAttribute("href");
    String traceId = new QueryStringDecoder(href).parameters().get("modal-trace-id").get(0);
    clickLink("view trace");
    clickAroundInTraceModal(traceId, true);
}
 
源代码5 项目: serve   文件: ManagementRequestHandler.java

private void handleScaleModel(
        ChannelHandlerContext ctx,
        QueryStringDecoder decoder,
        String modelName,
        String modelVersion)
        throws ModelNotFoundException, ModelVersionNotFoundException {
    int minWorkers = NettyUtils.getIntParameter(decoder, "min_worker", 1);
    int maxWorkers = NettyUtils.getIntParameter(decoder, "max_worker", minWorkers);
    if (modelVersion == null) {
        modelVersion = NettyUtils.getParameter(decoder, "model_version", null);
    }
    if (maxWorkers < minWorkers) {
        throw new BadRequestException("max_worker cannot be less than min_worker.");
    }
    boolean synchronous =
            Boolean.parseBoolean(NettyUtils.getParameter(decoder, "synchronous", null));

    ModelManager modelManager = ModelManager.getInstance();
    if (!modelManager.getDefaultModels().containsKey(modelName)) {
        throw new ModelNotFoundException("Model not found: " + modelName);
    }
    updateModelWorkers(
            ctx, modelName, modelVersion, minWorkers, maxWorkers, synchronous, false, null);
}
 
源代码6 项目: timely   文件: SearchLookupRequest.java

@Override
public HttpGetRequest parseQueryParameters(QueryStringDecoder decoder) throws Exception {
    final SearchLookupRequest search = new SearchLookupRequest();
    if (!decoder.parameters().containsKey("m")) {
        throw new IllegalArgumentException("m parameter is required for lookup");
    }
    final String m = decoder.parameters().get("m").get(0);
    // TODO are you parsing json yourself here? that's always a bad idea.
    final int tagIdx = m.indexOf("{");
    if (-1 == tagIdx) {
        search.setQuery(m);
    } else {
        search.setQuery(m.substring(0, tagIdx));
        final String[] tags = m.substring(tagIdx + 1, m.length() - 1).split(",");
        for (final String tag : tags) {
            final String[] tParts = tag.split("=");
            final Tag t = new Tag(tParts[0], tParts[1]);
            search.addTag(t);
        }
    }
    if (decoder.parameters().containsKey("limit")) {
        search.setLimit(Integer.parseInt(decoder.parameters().get("limit").get(0)));
    }
    return search;
}
 

@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);
    }
}
 
源代码8 项目: nettice   文件: BaseAction.java

/**
 * 获取请求参数 Map
 */
private Map<String, List<String>> getParamMap(){
	Map<String, List<String>> paramMap = new HashMap<String, List<String>>();
	
	Object msg = DataHolder.getRequest();
	HttpRequest request = (HttpRequest) msg;
	HttpMethod method = request.method();
	if(method.equals(HttpMethod.GET)){
		String uri = request.uri();
		QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, Charset.forName(CharEncoding.UTF_8));
		paramMap = queryDecoder.parameters();
		
	}else if(method.equals(HttpMethod.POST)){
		FullHttpRequest fullRequest = (FullHttpRequest) msg;
		paramMap = getPostParamMap(fullRequest);
	}
	
	return paramMap;
}
 
源代码9 项目: arcusplatform   文件: MP4Handler.java

@Override
public void channelRead0(@Nullable ChannelHandlerContext ctx, @Nullable FullHttpRequest request) throws Exception {
   if (ctx == null) {
      log.error("channel context should not be null");
      return;
   }

   if (request == null) {
      sendErrorResponse(ctx,HttpResponseStatus.INTERNAL_SERVER_ERROR);
      return;
   }

   try {
      QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
      UUID id = getRecordingId(decoder, UUID_START, UUID_END, ".mp4");
      if (id == null || !validateRequest(request, id, decoder)) {
         sendErrorResponse(ctx,HttpResponseStatus.BAD_REQUEST);
         return;
      }

      stream(id, ctx, request);
   } catch (Exception ex) {
      sendErrorResponse(ctx,HttpResponseStatus.BAD_REQUEST);
   }
}
 
源代码10 项目: socketio   文件: HandshakeHandler.java

private void handshake(final ChannelHandlerContext ctx, final HttpRequest req, final QueryStringDecoder queryDecoder)
    throws IOException {
  // Generate session ID
  final String sessionId = UUID.randomUUID().toString();
  if (log.isDebugEnabled())
    log.debug("New sessionId: {} generated", sessionId);

  // Send handshake response
  final String handshakeMessage = getHandshakeMessage(sessionId, queryDecoder);

  ByteBuf content = PipelineUtils.copiedBuffer(ctx.alloc(), handshakeMessage);
  HttpResponse res = PipelineUtils.createHttpResponse(PipelineUtils.getOrigin(req), content, false);
  ChannelFuture f = ctx.writeAndFlush(res);
  f.addListener(ChannelFutureListener.CLOSE);
  if (log.isDebugEnabled())
    log.debug("Sent handshake response: {} to channel: {}", handshakeMessage, ctx.channel());
}
 

@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();
	
}
 
源代码12 项目: bitchat   文件: Router.java

/**
 * Returns allowed methods for a specific URI.
 * <p>
 * For {@code OPTIONS *}, use {@link #allAllowedMethods()} instead of this method.
 */
public Set<HttpMethod> allowedMethods(String uri) {
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    String[] tokens = PathPattern.removeSlashesAtBothEnds(decoder.path()).split("/");

    if (anyMethodRouter.anyMatched(tokens)) {
        return allAllowedMethods();
    }

    Set<HttpMethod> ret = new HashSet<HttpMethod>(routers.size());
    for (Entry<HttpMethod, MethodlessRouter<T>> entry : routers.entrySet()) {
        MethodlessRouter<T> router = entry.getValue();
        if (router.anyMatched(tokens)) {
            HttpMethod method = entry.getKey();
            ret.add(method);
        }
    }

    return ret;
}
 
源代码13 项目: riposte   文件: RequestInfoTest.java

@Test
public void getQueryParamSingle_returns_null_if_param_value_list_is_empty() {
    // given
    QueryStringDecoder queryParamsMock = mock(QueryStringDecoder.class);
    Map<String, List<String>> params = new HashMap<>();
    params.put("foo", Collections.emptyList());
    doReturn(params).when(queryParamsMock).parameters();
    RequestInfo<?> requestInfoSpy = getSpy();
    doReturn(queryParamsMock).when(requestInfoSpy).getQueryParams();

    // when
    String value = requestInfoSpy.getQueryParamSingle("foo");

    // then
    assertThat(value, nullValue());
}
 
源代码14 项目: Okra   文件: HttpRequestExecutor.java

@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);
    }
}
 

private void handleScaleModel(
        ChannelHandlerContext ctx, QueryStringDecoder decoder, String modelName)
        throws ModelNotFoundException {
    int minWorkers = NettyUtils.getIntParameter(decoder, "min_worker", 1);
    int maxWorkers = NettyUtils.getIntParameter(decoder, "max_worker", minWorkers);
    if (maxWorkers < minWorkers) {
        throw new BadRequestException("max_worker cannot be less than min_worker.");
    }
    boolean synchronous =
            Boolean.parseBoolean(NettyUtils.getParameter(decoder, "synchronous", null));

    ModelManager modelManager = ModelManager.getInstance();
    if (!modelManager.getModels().containsKey(modelName)) {
        throw new ModelNotFoundException("Model not found: " + modelName);
    }
    updateModelWorkers(ctx, modelName, minWorkers, maxWorkers, synchronous, null);
}
 
源代码16 项目: cantor   文件: HandlerRequest.java

HandlerRequest(FullHttpRequest request, Channel channel) {
    this.uri = request.uri();
    mergeURISlash();
    SocketAddress socketAddress = channel.remoteAddress();
    if (InetSocketAddress.class.isAssignableFrom(socketAddress.getClass())) {
        InetSocketAddress inetSocketAddress = InetSocketAddress.class.cast(socketAddress);
        if (inetSocketAddress.getAddress() != null) {
            remoteHostAddress = inetSocketAddress.getAddress().getHostAddress();
        } else {
            remoteHostAddress = inetSocketAddress.getHostString();
        }
        remotePort = inetSocketAddress.getPort();
    }
    this.version = request.protocolVersion();
    this.method = request.method().name();
    this.content = ByteBufUtil.getBytes(request.content());
    this.headers = new HttpHeaders(request.headers());
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri(), true);
    this.query = new HashMap<>();
    queryStringDecoder.parameters().forEach((k, valueList) -> {
        if (null != valueList && valueList.size() > EMPTY)
            this.query.put(k, valueList.get(0));
    });
}
 
源代码17 项目: dorado   文件: HttpRequestImpl.java

public HttpRequestImpl(FullHttpRequest request) {
	this.request = request;
	this.parameters = new HashMap<>();
	this.headers = request.headers();
	this.multipartFiles = new ArrayList<>();

	this.uriParser = new URIParser();

	// 解析querystring上面的参数
	queryStringDecoder = new QueryStringDecoder(request.uri());
	uriParser.parse(queryStringDecoder.path());
	parameters.putAll(queryStringDecoder.parameters());
	in = new InputStreamImpl(request);

	if (request.method() == HttpMethod.POST) {
		parseHttpPostRequest(request);
	}
}
 

protected void captureQueryParameters(HttpRequest httpRequest) {
    // capture query parameters. it is safe to assume the query string is UTF-8, since it "should" be in US-ASCII (a subset of UTF-8),
    // but sometimes does include UTF-8 characters.
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri(), StandardCharsets.UTF_8);

    try {
        for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) {
            for (String value : entry.getValue()) {
                harEntry.getRequest().getQueryString().add(new HarNameValuePair(entry.getKey(), value));
            }
        }
    } catch (IllegalArgumentException e) {
        // QueryStringDecoder will throw an IllegalArgumentException if it cannot interpret a query string. rather than cause the entire request to
        // fail by propagating the exception, simply skip the query parameter capture.
        harEntry.setComment("Unable to decode query parameters on URI: " + httpRequest.getUri());
        log.info("Unable to decode query parameters on URI: " + httpRequest.getUri(), e);
    }
}
 
源代码19 项目: Jinx   文件: HttpPostRequestParameters.java

Map<String, List<String>> getHttpRequestParameters() {
    if (_parsed) {
        return params;
    }

    byte[] body = getHttpRequestBodyAsBytes();
    if (body == null) {
        _parsed = true;
        return params;
    }

    QueryStringDecoder decoder = new QueryStringDecoder("?" + new String(body));
    params.putAll(decoder.parameters());
    _parsed = true;
    return params;
}
 
源代码20 项目: redant   文件: Router.java

private String[] decodePathTokens(String uri) {
    // Need to split the original URI (instead of QueryStringDecoder#path) then decode the tokens (components),
    // otherwise /test1/123%2F456 will not match /test1/:p1

    int qPos = uri.indexOf("?");
    String encodedPath = (qPos >= 0) ? uri.substring(0, qPos) : uri;

    String[] encodedTokens = PathPattern.removeSlashesAtBothEnds(encodedPath).split("/");

    String[] decodedTokens = new String[encodedTokens.length];
    for (int i = 0; i < encodedTokens.length; i++) {
        String encodedToken = encodedTokens[i];
        decodedTokens[i] = QueryStringDecoder.decodeComponent(encodedToken);
    }

    return decodedTokens;
}
 
源代码21 项目: redant   文件: Router.java

/**
 * Returns allowed methods for a specific URI.
 * <p>
 * For {@code OPTIONS *}, use {@link #allAllowedMethods()} instead of this method.
 */
public Set<HttpMethod> allowedMethods(String uri) {
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    String[] tokens = PathPattern.removeSlashesAtBothEnds(decoder.path()).split("/");

    if (anyMethodRouter.anyMatched(tokens)) {
        return allAllowedMethods();
    }

    Set<HttpMethod> ret = new HashSet<HttpMethod>(routers.size());
    for (Entry<HttpMethod, MethodlessRouter<T>> entry : routers.entrySet()) {
        MethodlessRouter<T> router = entry.getValue();
        if (router.anyMatched(tokens)) {
            HttpMethod method = entry.getKey();
            ret.add(method);
        }
    }

    return ret;
}
 
源代码22 项目: s3ninja   文件: Aws4HashCalculator.java

private void appendCanonicalQueryString(WebContext ctx, StringBuilder canonicalRequest) {
    QueryStringDecoder qsd = new QueryStringDecoder(ctx.getRequest().uri(), Charsets.UTF_8);

    List<Tuple<String, List<String>>> queryString = Tuple.fromMap(qsd.parameters());
    queryString.sort(Comparator.comparing(Tuple::getFirst));

    Monoflop mf = Monoflop.create();
    for (Tuple<String, List<String>> param : queryString) {
        if (!Strings.areEqual(param.getFirst(), "X-Amz-Signature")) {
            if (param.getSecond().isEmpty()) {
                appendQueryStringValue(param.getFirst(), "", canonicalRequest, mf.successiveCall());
            } else {
                for (String value : param.getSecond()) {
                    appendQueryStringValue(param.getFirst(), value, canonicalRequest, mf.successiveCall());
                }
            }
        }
    }

    canonicalRequest.append("\n");
}
 

@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();
	}
}
 

private static String getPath(ServiceRequestContext ctx) {
    // check the path param first
    final String path = ctx.pathParam("path");
    if (!isNullOrEmpty(path)) {
        return path;
    }

    // then check HTTP query
    final String query = ctx.query();
    if (query != null) {
        final List<String> params = new QueryStringDecoder(query, false).parameters().get("path");
        if (params != null) {
            return params.get(0);
        }
    }
    // return empty string if there's no path
    return "";
}
 

private void handleInvocations(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelNotFoundException {
    String modelName =
            ("invocations".equals(segments[1]))
                    ? NettyUtils.getParameter(decoder, "model_name", null)
                    : segments[2];
    if (modelName == null || modelName.isEmpty()) {
        if (ModelManager.getInstance().getStartupModels().size() == 1) {
            modelName = ModelManager.getInstance().getStartupModels().iterator().next();
        }
    }
    predict(ctx, req, decoder, modelName);
}
 
源代码26 项目: big-c   文件: TestParameterParser.java

@Test
public void testDeserializeHAToken() throws IOException {
  Configuration conf = DFSTestUtil.newHAConfiguration(LOGICAL_NAME);
  final Token<DelegationTokenIdentifier> token = new
      Token<DelegationTokenIdentifier>();
  QueryStringDecoder decoder = new QueryStringDecoder(
    WebHdfsHandler.WEBHDFS_PREFIX + "/?"
    + NamenodeAddressParam.NAME + "=" + LOGICAL_NAME + "&"
    + DelegationParam.NAME + "=" + token.encodeToUrlString());
  ParameterParser testParser = new ParameterParser(decoder, conf);
  final Token<DelegationTokenIdentifier> tok2 = testParser.delegationToken();
  Assert.assertTrue(HAUtil.isTokenForLogicalUri(tok2));
}
 
源代码27 项目: serve   文件: InferenceRequestHandler.java

@Override
protected void handleRequest(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelException {
    if (isInferenceReq(segments)) {
        if (endpointMap.getOrDefault(segments[1], null) != null) {
            handleCustomEndpoint(ctx, req, segments, decoder);
        } else {
            switch (segments[1]) {
                case "ping":
                    ModelManager.getInstance().workerStatus(ctx);
                    break;
                case "models":
                case "invocations":
                    validatePredictionsEndpoint(segments);
                    handleInvocations(ctx, req, decoder, segments);
                    break;
                case "predictions":
                    handlePredictions(ctx, req, segments);
                    break;
                default:
                    handleLegacyPredict(ctx, req, decoder, segments);
                    break;
            }
        }
    } else {
        chain.handleRequest(ctx, req, decoder, segments);
    }
}
 
源代码28 项目: serve   文件: ManagementRequestHandler.java

private RegisterModelRequest parseRequest(FullHttpRequest req, QueryStringDecoder decoder) {
    RegisterModelRequest in;
    CharSequence mime = HttpUtil.getMimeType(req);
    if (HttpHeaderValues.APPLICATION_JSON.contentEqualsIgnoreCase(mime)) {
        in =
                JsonUtils.GSON.fromJson(
                        req.content().toString(CharsetUtil.UTF_8), RegisterModelRequest.class);
    } else {
        in = new RegisterModelRequest(decoder);
    }
    return in;
}
 
源代码29 项目: serve   文件: InvalidRequestHandler.java

@Override
protected void handleRequest(
        ChannelHandlerContext ctx,
        FullHttpRequest req,
        QueryStringDecoder decoder,
        String[] segments)
        throws ModelException {
    throw new ResourceNotFoundException();
}
 

private ApplicationRequestItem toApplicationRequestItem(io.gravitee.repository.log.model.Log log) {
    ApplicationRequestItem req = new ApplicationRequestItem();
    req.setId(log.getId());
    req.setTransactionId(log.getTransactionId());
    req.setApi(log.getApi());
    req.setMethod(log.getMethod());
    req.setPath(new QueryStringDecoder(log.getUri()).toString());
    req.setPlan(log.getPlan());
    req.setResponseTime(log.getResponseTime());
    req.setStatus(log.getStatus());
    req.setTimestamp(log.getTimestamp());
    req.setUser(log.getUser());
    return req;
}
 
源代码评论
动弹
沙发等你来抢
 类方法
 同包方法