io.netty.handler.codec.http.QueryStringDecoder Java Examples

The following examples show how to use io.netty.handler.codec.http.QueryStringDecoder. 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: HandlerRequest.java    From cantor with Apache License 2.0 6 votes vote down vote up
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));
    });
}
 
Example #2
Source File: WebHdfsHandler.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@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;
    }
  });
}
 
Example #3
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 #4
Source File: QueryRequestConverter.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
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 "";
}
 
Example #5
Source File: RequestInfoTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: BasicSmokeIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: Aws4HashCalculator.java    From s3ninja with MIT License 6 votes vote down vote up
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");
}
 
Example #8
Source File: InferenceRequestHandler.java    From serve with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: InferenceRequestHandler.java    From serve with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: Router.java    From redant with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: InferenceRequestHandler.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #12
Source File: Router.java    From bitchat with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: Router.java    From redant with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: HttpPostRequestParameters.java    From Jinx with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
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 #16
Source File: ManagementRequestHandler.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #17
Source File: SearchLookupRequest.java    From timely with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #18
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 #19
Source File: BaseAction.java    From nettice with Apache License 2.0 6 votes vote down vote up
/**
 * 获取请求参数 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;
}
 
Example #20
Source File: MP4Handler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@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);
   }
}
 
Example #21
Source File: HarCaptureFilter.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #22
Source File: HandshakeHandler.java    From socketio with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #23
Source File: HttpRequestImpl.java    From dorado with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #24
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 #25
Source File: ManagementRequestHandler.java    From serve with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #26
Source File: ShardInstance.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
static boolean shouldEnsureOutputsPresent(RequestMetadata requestMetadata) {
  try {
    URI uri = new URI(requestMetadata.getCorrelatedInvocationsId());
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    return decoder
        .parameters()
        .getOrDefault("ENSURE_OUTPUTS_PRESENT", ImmutableList.of("false"))
        .get(0)
        .equals("true");
  } catch (URISyntaxException e) {
    return false;
  }
}
 
Example #27
Source File: TunnelSocketFrameHandler.java    From arthas with Apache License 2.0 5 votes vote down vote up
private void agentRegister(ChannelHandlerContext ctx, String requestUri) throws URISyntaxException {
    // generate a random agent id
    String id = RandomStringUtils.random(20, true, true).toUpperCase();

    QueryStringDecoder queryDecoder = new QueryStringDecoder(requestUri);
    List<String> idList = queryDecoder.parameters().get("id");
    if (idList != null && !idList.isEmpty()) {
        id = idList.get(0);
    }

    final String finalId = id;

    URI responseUri = new URI("response", null, "/", "method=agentRegister" + "&id=" + id, null);

    AgentInfo info = new AgentInfo();
    SocketAddress remoteAddress = ctx.channel().remoteAddress();
    if (remoteAddress instanceof InetSocketAddress) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
        info.setHost(inetSocketAddress.getHostString());
        info.setPort(inetSocketAddress.getPort());
    }
    info.setChannelHandlerContext(ctx);

    tunnelServer.addAgent(id, info);
    ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            tunnelServer.removeAgent(finalId);
        }

    });

    ctx.channel().writeAndFlush(new TextWebSocketFrame(responseUri.toString()));
}
 
Example #28
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 #29
Source File: AuthRequest.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * 一般是针对get请求的
 * @param request get请求对象
 */
public AuthRequest(HttpRequest request) {
    if (request.uri() != null) {
        QueryStringDecoder dec = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = dec.parameters();
        this.clientId = QueryParameter.getFirstElement(params, CLIENT_ID);
        this.responseType = QueryParameter.getFirstElement(params, RESPONSE_TYPE);
        this.redirectUri = QueryParameter.getFirstElement(params, REDIRECT_URI);
        this.state = QueryParameter.getFirstElement(params, STATE);
        this.scope = QueryParameter.getFirstElement(params, SCOPE);
        this.userId = QueryParameter.getFirstElement(params, USER_ID);
    }
}
 
Example #30
Source File: TestParameterParser.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@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));
}