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

The following examples show how to use io.netty.handler.codec.http.QueryStringDecoder#parameters() . 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: 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 2
Source File: HttpUtil.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * parse the given http query string
 *
 * @param queryString the standard http query string
 * @param hasPath     whether the query string contains uri
 * @return the parsed json object. if the given query string is empty then an empty json object is returned.
 */
public static JSONObject parseQueryString(String queryString, boolean hasPath) {
    JSONObject uriParameters = new JSONObject();
    if (queryString == null) return uriParameters;
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(queryString, hasPath);
    Map<String, List<String>> parameters = queryStringDecoder.parameters();
    parameters.forEach((key, values) -> {
        if (values == null || values.isEmpty()) {
            LOG.debug("空参数统一对应空字符串");
            uriParameters.put(key, "");
        } else if (values.size() == 1)
            uriParameters.put(key, values.get(0));
        else
            uriParameters.put(key, values);
    });
    return uriParameters;
}
 
Example 3
Source File: RequestUtils.java    From tutorials with MIT License 6 votes vote down vote up
static StringBuilder formatParams(HttpRequest request) {
    StringBuilder responseData = new StringBuilder();
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
    Map<String, List<String>> params = queryStringDecoder.parameters();
    if (!params.isEmpty()) {
        for (Entry<String, List<String>> p : params.entrySet()) {
            String key = p.getKey();
            List<String> vals = p.getValue();
            for (String val : vals) {
                responseData.append("Parameter: ")
                    .append(key.toUpperCase())
                    .append(" = ")
                    .append(val.toUpperCase())
                    .append("\r\n");
            }
        }
        responseData.append("\r\n");
    }
    return responseData;
}
 
Example 4
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 5
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 6
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 7
Source File: NettyHttpServletRequest.java    From spring-boot-starter-netty with GNU General Public License v3.0 5 votes vote down vote up
private void stringToInsertMap(String source) {
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(source);
    Map<String, List<String>> params = queryStringDecoder.parameters();
    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        List<String> valueList = entry.getValue();
        String[] valueArray = new String[valueList.size()];
        paramMap.put(entry.getKey(), valueList.toArray(valueArray));
    }
}
 
Example 8
Source File: SearchQueryDecoder.java    From elastic-rabbitmq with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
    DecoderResult result = httpRequest.decoderResult();
    if (!result.isSuccess()) {
        throw new BadRequestException(result.cause());
    }
    logger.info("Get search request: " + httpRequest.uri());

    // only decode get path is enough
    Map<String, List<String>> requestParameters;
    QueryStringDecoder stringDecoder = new QueryStringDecoder(httpRequest.uri());
    requestParameters = stringDecoder.parameters();

    QueryMeta meta = new QueryMeta();

    for(Map.Entry<String, List<String>> entry : requestParameters.entrySet()) {
        if (entry.getKey().equals("options[]")) {
            // add filters
            List<String> filters = entry.getValue();
            filters.forEach(filter -> {
                String[] typeVal = filter.split(":");
                meta.addMeta(typeVal[0], typeVal[1]);
            });
        } else if (entry.getKey().equals("orderby")) {
            meta.setOrderBy(entry.getValue().get(0));
        } else {
            logger.warn("Unknown query parameter, ignore it:" + entry.toString());
        }
    }

    DecodedSearchRequest searchRequest = new DecodedSearchRequest(httpRequest, meta, orderNumber++);
    ctx.fireChannelRead(searchRequest);
}
 
Example 9
Source File: CseClientHttpRequest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse execute() {
  path = findUriPath(uri);
  requestMeta = createRequestMeta(method.name(), uri);

  QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri.getRawSchemeSpecificPart());
  queryParams = queryStringDecoder.parameters();

  Map<String, Object> swaggerArguments = this.collectArguments();

  // 异常流程,直接抛异常出去
  return this.invoke(swaggerArguments);
}
 
Example 10
Source File: NettyHttpServerRequest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @see HttpServerRequest#getQueryParameter(java.lang.String)
 */
@Override
public String getQueryParameter(String name) {
    synchronized (request) {
        if (queryParameters == null) {
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
            queryParameters = queryStringDecoder.parameters();
        }
    }
    return queryParameters.get(name).get(0);
}
 
Example 11
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 12
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 13
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 14
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 15
Source File: HttpRequestDecomposer.java    From api-gateway-core with Apache License 2.0 4 votes vote down vote up
/**
 * 如果content-type为application/x-www-form-urlencoded,将内容转换成map
 * @return
 */
public Map<String, List<String>> getContentFormUrlEncoded() {
    String content = request.content().toString(StandardCharsets.UTF_8);
    QueryStringDecoder stringDecoder = new QueryStringDecoder("?" + content, StandardCharsets.UTF_8);
    return stringDecoder.parameters();
}
 
Example 16
Source File: PipelineUtils.java    From socketio with Apache License 2.0 4 votes vote down vote up
public static String extractParameter(QueryStringDecoder queryDecoder, String key) {
  final Map<String, List<String>> params = queryDecoder.parameters();
  List<String> paramsByKey = params.get(key);
  return (paramsByKey != null) ? paramsByKey.get(0) : null;
}
 
Example 17
Source File: ParameterParser.java    From hadoop with Apache License 2.0 4 votes vote down vote up
ParameterParser(QueryStringDecoder decoder, Configuration conf) {
  this.path = decodeComponent(decoder.path().substring
      (WEBHDFS_PREFIX_LENGTH), Charsets.UTF_8);
  this.params = decoder.parameters();
  this.conf = conf;
}
 
Example 18
Source File: FSImageHandler.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private static String getOp(QueryStringDecoder decoder) {
  Map<String, List<String>> parameters = decoder.parameters();
  return parameters.containsKey("op")
      ? StringUtils.toUpperCase(parameters.get("op").get(0)) : null;
}
 
Example 19
Source File: AbstractHttpServiceComponent2.java    From uavstack with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, List<String>> parseQueryString(String s) {

    QueryStringDecoder decoder = new QueryStringDecoder(s);
    return decoder.parameters();
}
 
Example 20
Source File: FSImageHandler.java    From big-c with Apache License 2.0 4 votes vote down vote up
private static String getOp(QueryStringDecoder decoder) {
  Map<String, List<String>> parameters = decoder.parameters();
  return parameters.containsKey("op")
      ? StringUtils.toUpperCase(parameters.get("op").get(0)) : null;
}