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; }
/** * 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; }
/** * 请求分发与处理 * * @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; }
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 ""; }
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) { StringUtils.Pair url = HttpUtils.parseUriIntoUrlBaseAndPath(msg.uri()); HttpRequest request = new HttpRequest(); if (url.left == null) { String requestScheme = provider.isSsl() ? "https" : "http"; String host = msg.headers().get(HttpUtils.HEADER_HOST); request.setUrlBase(requestScheme + "://" + host); } else { request.setUrlBase(url.left); } request.setUri(url.right); request.setMethod(msg.method().name()); msg.headers().forEach(h -> request.addHeader(h.getKey(), h.getValue())); QueryStringDecoder decoder = new QueryStringDecoder(url.right); decoder.parameters().forEach((k, v) -> request.putParam(k, v)); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { byte[] bytes = new byte[content.readableBytes()]; content.readBytes(bytes); request.setBody(bytes); } writeResponse(request, ctx); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
@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; } }); }
@Override public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception { Preconditions.checkArgument(req.uri().startsWith(WEBHDFS_PREFIX)); QueryStringDecoder queryString = new QueryStringDecoder(req.uri()); 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; } }); }
@Test public void test() { System.out.println(new JsonArray().add("1").add( "$header.h1").encode()); System.out.println(matchValue("devices/new/$param.param0/test/$param.param1", "[\\w./$]*([\\w$" + ".]+)")); String url = "devices/new/$param.param0/test/$param.param0"; Pattern pattern = Pattern.compile("[\\w./]+([\\w$.]+)[\\w./]*"); Matcher matcher = pattern.matcher(url); System.out.println(matcher.matches()); if (matcher.matches()) { if (matcher.groupCount() > 0) { for (int i = 0; i < matcher.groupCount(); i++) { String group = matcher.group(i + 1); if (group != null) { final String k = "param" + i; final String value = QueryStringDecoder.decodeComponent(group.replace("+", "%2b")); System.out.println(value); } } } } }
private List<String> matchValue(String baseString, String regex) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(baseString); List<String> matchValues = new ArrayList<>(); if (matcher.matches()) { if (matcher.groupCount() > 0) { for (int i = 0; i < matcher.groupCount(); i++) { String group = matcher.group(i + 1); if (group != null) { final String value = QueryStringDecoder.decodeComponent(group.replace("+", "%2b")); matchValues.add(value); } } } } return matchValues; }
@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; }
@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()); }
@Test public void getQueryParamSingle_returns_first_item_if_param_value_list_has_multiple_entries() { // given QueryStringDecoder queryParamsMock = mock(QueryStringDecoder.class); Map<String, List<String>> params = new HashMap<>(); params.put("foo", Arrays.asList("bar", "stuff")); doReturn(params).when(queryParamsMock).parameters(); RequestInfo<?> requestInfoSpy = getSpy(); doReturn(queryParamsMock).when(requestInfoSpy).getQueryParams(); // when String value = requestInfoSpy.getQueryParamSingle("foo"); // then assertThat(value, is("bar")); }
public Map<String, List<String>> parameters() { if (parameters != null) { return parameters; } Map<String, List<String>> ret = Maps.newHashMap(); if (HttpMethod.GET.equals(method()) || HttpMethod.DELETE.equals(method())) { ret.putAll(new QueryStringDecoder(uri()).parameters()); return ret; } else if (headers().contains(HttpHeaderNames.CONTENT_TYPE) && headers().get(HttpHeaderNames.CONTENT_TYPE) .startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString()) && (HttpMethod.POST.equals(method()) || HttpMethod.PUT.equals(method()))) { ret.putAll(new QueryStringDecoder("/dummy?" + content().toString(CharsetUtil.UTF_8)).parameters()); } return ret; }
@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); } }
/** * 获取请求参数 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; }
@Nullable @Override public String execute(@NotNull QueryStringDecoder urlDecoder, @NotNull FullHttpRequest request, @NotNull ChannelHandlerContext context) throws IOException { final JsonReader reader = createJsonReader(request); reader.beginObject(); final String name = reader.nextName(); final String url = reader.nextString(); reader.endObject(); if (URL_PARAM_NAME.equals(name) && url != null && url.startsWith(JetBrainsProtocolHandler.PROTOCOL)) { JetBrainsProtocolHandler.processJetBrainsLauncherParameters(url); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { JBProtocolCommand.handleCurrentCommand(); } }, ModalityState.any()); } sendOk(request, context); return null; }
@Nullable @Override public String execute(@NotNull QueryStringDecoder urlDecoder, @NotNull FullHttpRequest request, @NotNull ChannelHandlerContext context) throws IOException { final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); if (frame instanceof Window) { sendOk(request, context); Runnable runnable = new Runnable() { public void run() { Window window = (Window)frame; window.toFront(); window.requestFocusInWindow(); AppIcon.getInstance().requestFocus(frame); } }; //noinspection SSBasedInspection SwingUtilities.invokeLater(runnable); return "Success"; } sendStatus(HttpResponseStatus.NOT_FOUND, false, context.channel()); return "Can't find IDE Frame"; }
@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(); } }
@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(); }
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { QueryStringDecoder queryString = new QueryStringDecoder(request.uri()); String streamId = streamId(request); // Check arguments: path must match and latency parameter must be present if (!PATH.equals(queryString.path()) || missing(queryString, LATENCY)) { sendDummy(ctx, streamId); return; } int latency = latency(queryString); if (missing(queryString, X) && missing(queryString, Y)) { handlePage(ctx, streamId, latency); } else { handleImage(queryString, ctx, streamId, latency); } }
private void readHeaders(ChannelHandlerContext ctx, HttpRequest msg) { if(req == null && context == null) { context = new HttpBridletContextImpl(); req = new HttpBridletRequestImpl( msg ); QueryStringDecoder decoderQuery = new QueryStringDecoder(msg.getUri()); req.setQueryString(decoderQuery.parameters()); req.setCookies(parseCookies(msg.headers().get(COOKIE))); // new getMethod if(req.isForm()) { decoder = new HttpPostRequestDecoder(FACTORY, msg); } } else { sendBadRequest(ctx); } }
private void debugHeadersAndCookies(HttpRequest request) { StringBuilder headersandaccokies = new StringBuilder(); // echo the header for now for (Map.Entry<String, String> h : request.headers()) { headersandaccokies.append("HEADER: " + h.getKey() + " = " + h.getValue() + "\r\n"); } headersandaccokies.append("\r\n"); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); 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) { headersandaccokies.append("PARAM: " + key + " = " + val + "\r\n"); } } headersandaccokies.append("\r\n"); } debug(headersandaccokies.toString()); }
@Override public boolean accept(ChannelHandlerContext ctx, HttpRequest req) { if (req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri)) { try { User superAdmin = AuthHeadersBaseHttpHandler.validateAuth(userDao, req); if (superAdmin != null) { ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).set(superAdmin); queryStringDecoder = new QueryStringDecoder(req.uri()); return true; } } catch (IllegalAccessException e) { //return 403 and stop processing. ctx.writeAndFlush(Response.forbidden(e.getMessage())); return true; } } return false; }
/** * Creates a new TSDBHttpRequest * @param request The incoming HTTP request * @param channel The channel the request came in on * @param ctx The http request router's channel handler context */ protected TSDBHttpRequest(final HttpRequest request, final Channel channel, final ChannelHandlerContext ctx) { this.request = request; this.channel = channel; this.ctx = ctx; final QueryStringDecoder decoder = new QueryStringDecoder(request.uri()); path = decoder.path(); final StringBuilder b = new StringBuilder("/api/"); pathElements = PATH_SPLIT.split(path); for(String part: pathElements) { if(part==null || part.trim().isEmpty() || "api".equals(part)) { continue; } b.append(part); break; } route = b.toString(); }
/** * 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 (Map.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; }
@Test public void shouldCheckActiveTraceModalPages() throws Exception { App app = app(); GlobalNavbar globalNavbar = globalNavbar(); JvmSidebar jvmSidebar = new JvmSidebar(driver); app.open(); globalNavbar.getJvmLink().click(); jvmSidebar.getThreadDumpLink().click(); WebElement viewTraceLink = Utils.withWait(driver, By.linkText("view trace")); String href = viewTraceLink.getAttribute("href"); String traceId = new QueryStringDecoder(href).parameters().get("modal-trace-id").get(0); viewTraceLink.click(); clickAroundInTraceModal(traceId, true); }
public Request(Server server, Channel channel, FullHttpRequest request, RouteResult<Action> routeResult) { this.server = server; this.channel = channel; this.request = request; this.routeResult = routeResult; // Get client IP while the client is still connected; Netty may not allow // us to get this info later when the connection may be closed clientIp = getClientIpFromChannel(); remoteIp = getRemoteIpFromClientIpOrReverseProxy(); // Parse body params String contentTye = request.headers().get(HttpHeaderNames.CONTENT_TYPE); if (HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.contentEqualsIgnoreCase(contentTye)) { String content = request.content().toString(server.charset()); QueryStringDecoder qsd = new QueryStringDecoder("?" + content); bodyParams = qsd.parameters(); } else { bodyParams = Collections.<String, List<String>>emptyMap(); } }
protected void readHttpRequest(HttpRequest msg) throws Exception { HttpRequest req = (HttpRequest) msg; AbstractHandler.this.req = req; if (!req.getMethod().equals(HttpMethod.POST) || !isValidHeaders(req.headers())) { finish(ctx); return; } keepAlive = HttpHeaders.isKeepAlive(req); String encoding = req.headers().get(HttpHeaders.Names.ACCEPT_ENCODING); if (encoding != null && encoding.indexOf("gzip") != -1) { gzip = true; } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.getUri()); _params = queryStringDecoder.parameters(); if (LOG.isDebugEnabled()) { LOG.debug("Receive request -> {}", req.getUri()); } }
public Observable<Void> simulateTimeout(HttpServerRequest<ByteBuf> httpRequest, HttpServerResponse<ByteBuf> response) { String uri = httpRequest.getUri(); QueryStringDecoder decoder = new QueryStringDecoder(uri); List<String> timeout = decoder.parameters().get("timeout"); byte[] contentBytes; HttpResponseStatus status = HttpResponseStatus.NO_CONTENT; if (null != timeout && !timeout.isEmpty()) { try { Thread.sleep(Integer.parseInt(timeout.get(0))); contentBytes = "".getBytes(); } catch (Exception e) { contentBytes = e.getMessage().getBytes(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; } } else { status = HttpResponseStatus.BAD_REQUEST; contentBytes = "Please provide a timeout parameter.".getBytes(); } response.setStatus(status); return response.writeBytesAndFlush(contentBytes); }
public HttpRequest decode(FullHttpRequest fullHttpRequest) { HttpRequest httpRequest = new HttpRequest(); if (fullHttpRequest != null) { setMethod(httpRequest, fullHttpRequest); setPath(httpRequest, fullHttpRequest); setQueryString(httpRequest, new QueryStringDecoder(fullHttpRequest.uri())); setHeaders(httpRequest, fullHttpRequest); setCookies(httpRequest, fullHttpRequest); setBody(httpRequest, fullHttpRequest); httpRequest.withKeepAlive(isKeepAlive(fullHttpRequest)); httpRequest.withSecure(isSecure); } return httpRequest; }
@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); }
@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); }
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()); }
/** * 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()) ; } } }
/** * 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; }
@Override public ClientHttpResponse execute() throws IOException { path = findUriPath(uri); requestMeta = createRequestMeta(method.name(), uri); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri.getRawSchemeSpecificPart()); queryParams = queryStringDecoder.parameters(); Object[] args = this.collectArguments(); // 异常流程,直接抛异常出去 return this.invoke(args); }
public static Map<String, List<String>> decodeQueryString(String url) { Preconditions.checkNotNull(url); QueryStringDecoder decoder = new QueryStringDecoder(getRawQueryParameters(url)); Map<String, List<String>> params = new DefaultValueMap<>(ImmutableList.of()); params.putAll(decoder.parameters()); return params; }
private static Optional<String> getExpression(ServiceRequestContext ctx) { final String query = ctx.query(); if (query != null) { final List<String> expression = new QueryStringDecoder(query, false).parameters().get( "expression"); if (expression != null) { return Optional.of(expression.get(0)); } } return Optional.empty(); }