io.undertow.util.PathTemplateMatcher Java Examples

The following examples show how to use io.undertow.util.PathTemplateMatcher. 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: HandlerTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedPathsAndSource() {
    Handler.config.setPaths(Arrays.asList(
        mkPathChain(null, "/my-api/first", "post", "third"),
        mkPathChain(MockEndpointSource.class.getName(), null, null, "secondBeforeFirst", "third"),
        mkPathChain(null, "/my-api/second", "put", "third")
    ));
    Handler.init();

    Map<HttpString, PathTemplateMatcher<String>> methodToMatcher = Handler.methodToMatcherMap;

    PathTemplateMatcher<String> getMatcher = methodToMatcher.get(Methods.GET);
    PathTemplateMatcher.PathMatchResult<String> getFirst = getMatcher.match("/my-api/first");
    Assert.assertNotNull(getFirst);
    PathTemplateMatcher.PathMatchResult<String> getSecond = getMatcher.match("/my-api/second");
    Assert.assertNotNull(getSecond);
    PathTemplateMatcher.PathMatchResult<String> getThird = getMatcher.match("/my-api/third");
    Assert.assertNull(getThird);
}
 
Example #2
Source File: PathTemplateHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    PathTemplateMatcher.PathMatchResult<HttpHandler> match = pathTemplateMatcher.match(exchange.getRelativePath());
    if (match == null) {
        next.handleRequest(exchange);
        return;
    }
    exchange.putAttachment(PATH_TEMPLATE_MATCH, new PathTemplateMatch(match.getMatchedTemplate(), match.getParameters()));
    exchange.putAttachment(io.undertow.util.PathTemplateMatch.ATTACHMENT_KEY, new io.undertow.util.PathTemplateMatch(match.getMatchedTemplate(), match.getParameters()));
    if (rewriteQueryParameters) {
        for (Map.Entry<String, String> entry : match.getParameters().entrySet()) {
            exchange.addQueryParam(entry.getKey(), entry.getValue());
        }
    }
    match.getValue().handleRequest(exchange);
}
 
Example #3
Source File: Handler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Add a PathChain (having a non-null path) to the handler data structures.
 */
private static void addPathChain(PathChain pathChain) {
	HttpString method = new HttpString(pathChain.getMethod());

	// Use a random integer as the id for a given path.
	Integer randInt = new Random().nextInt();
	while (handlerListById.containsKey(randInt.toString())) {
		randInt = new Random().nextInt();
	}

	// Flatten out the execution list from a mix of middleware chains and handlers.
	List<HttpHandler> handlers = getHandlersFromExecList(pathChain.getExec());
	if(handlers.size() > 0) {
		// If a matcher already exists for the given type, at to that instead of
		// creating a new one.
		PathTemplateMatcher<String> pathTemplateMatcher = methodToMatcherMap.containsKey(method)
			? methodToMatcherMap.get(method)
			: new PathTemplateMatcher<>();

		if(pathTemplateMatcher.get(pathChain.getPath()) == null) { pathTemplateMatcher.add(pathChain.getPath(), randInt.toString()); }
		methodToMatcherMap.put(method, pathTemplateMatcher);
		handlerListById.put(randInt.toString(), handlers);
	}
}
 
Example #4
Source File: ParameterHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
	PathTemplateMatcher.PathMatchResult<String> result = pathTemplateMatcher.match(exchange.getRequestPath());
	
	if (result != null) {
		exchange.putAttachment(ATTACHMENT_KEY,
				new io.undertow.util.PathTemplateMatch(result.getMatchedTemplate(), result.getParameters()));
		for (Map.Entry<String, String> entry : result.getParameters().entrySet()) {
			exchange.addQueryParam(entry.getKey(), entry.getValue());
			
			exchange.addPathParam(entry.getKey(), entry.getValue());
		}
	}
	
	Handler.next(exchange, next);
}
 
Example #5
Source File: RoutingHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public synchronized RoutingHandler addAll(RoutingHandler routingHandler) {
    for (Entry<String, PathTemplateMatcher<RoutingMatch>> entry : routingHandler.getMatches().entrySet()) {
        String method = entry.getKey();
        PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
        if (matcher == null) {
            matches.put(method, matcher = new PathTemplateMatcher<>());
        }
        matcher.addAll(entry.getValue());
        // If we use allMethodsMatcher.addAll() we can have duplicate
        // PathTemplates which we want to ignore here so it does not crash.
        for (PathTemplate template : entry.getValue().getPathTemplates()) {
            if (allMethodsMatcher.get(template.getTemplateString()) == null) {
                allMethodsMatcher.add(template, new RoutingMatch());
            }
        }
    }
    return this;
}
 
Example #6
Source File: ParameterHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
	PathTemplateMatcher.PathMatchResult<String> result = pathTemplateMatcher.match(exchange.getRequestPath());
	
	if (result != null) {
		exchange.putAttachment(ATTACHMENT_KEY,
				new io.undertow.util.PathTemplateMatch(result.getMatchedTemplate(), result.getParameters()));
		for (Map.Entry<String, String> entry : result.getParameters().entrySet()) {
			exchange.addQueryParam(entry.getKey(), entry.getValue());
			
			exchange.addPathParam(entry.getKey(), entry.getValue());
		}
	}
	
	Handler.next(exchange, next);
}
 
Example #7
Source File: RoutingHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public synchronized RoutingHandler addAll(RoutingHandler routingHandler) {
    for (Entry<HttpString, PathTemplateMatcher<RoutingMatch>> entry : routingHandler.getMatches().entrySet()) {
        HttpString method = entry.getKey();
        PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
        if (matcher == null) {
            matches.put(method, matcher = new PathTemplateMatcher<>());
        }
        matcher.addAll(entry.getValue());
        // If we use allMethodsMatcher.addAll() we can have duplicate
        // PathTemplates which we want to ignore here so it does not crash.
        for (PathTemplate template : entry.getValue().getPathTemplates()) {
            if (allMethodsMatcher.get(template.getTemplateString()) == null) {
                allMethodsMatcher.add(template, new RoutingMatch());
            }
        }
    }
    return this;
}
 
Example #8
Source File: PathTemplateHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    PathTemplateMatcher.PathMatchResult<HttpHandler> match = pathTemplateMatcher.match(exchange.getRelativePath());
    if (match == null) {
        next.handleRequest(exchange);
        return;
    }
    exchange.putAttachment(PATH_TEMPLATE_MATCH, new PathTemplateMatch(match.getMatchedTemplate(), match.getParameters()));
    exchange.putAttachment(io.undertow.util.PathTemplateMatch.ATTACHMENT_KEY, new io.undertow.util.PathTemplateMatch(match.getMatchedTemplate(), match.getParameters()));
    if (rewriteQueryParameters) {
        for (Map.Entry<String, String> entry : match.getParameters().entrySet()) {
            exchange.addQueryParam(entry.getKey(), entry.getValue());
        }
    }
    match.getValue().handleRequest(exchange);
}
 
Example #9
Source File: RoutingHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    PathTemplateMatcher<RoutingMatch> matcher = matches.get(exchange.getRequestMethod());
    if (matcher == null) {
        handleNoMatch(exchange);
        return;
    }
    PathTemplateMatcher.PathMatchResult<RoutingMatch> match = matcher.match(exchange.getRelativePath());
    if (match == null) {
        handleNoMatch(exchange);
        return;
    }
    exchange.putAttachment(PathTemplateMatch.ATTACHMENT_KEY, match);
    if (rewriteQueryParameters) {
        for (Map.Entry<String, String> entry : match.getParameters().entrySet()) {
            exchange.addQueryParam(entry.getKey(), entry.getValue());
        }
    }
    for (HandlerHolder handler : match.getValue().predicatedHandlers) {
        if (handler.predicate.resolve(exchange)) {
            handler.handler.handleRequest(exchange);
            return;
        }
    }
    if (match.getValue().defaultHandler != null) {
        match.getValue().defaultHandler.handleRequest(exchange);
    } else {
        fallbackHandler.handleRequest(exchange);
    }
}
 
Example #10
Source File: Handler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * On the first step of the request, match the request against the configured
 * paths. If the match is successful, store the chain id within the exchange.
 * Otherwise return false.
 *
 * @param httpServerExchange
 *            The current requests server exchange.
 * @return true if a handler has been defined for the given path.
 */
public static boolean start(HttpServerExchange httpServerExchange) {
	// Get the matcher corresponding to the current request type.
	PathTemplateMatcher<String> pathTemplateMatcher = methodToMatcherMap.get(httpServerExchange.getRequestMethod());
	if (pathTemplateMatcher != null) {
		// Match the current request path to the configured paths.
		PathTemplateMatcher.PathMatchResult<String> result = pathTemplateMatcher
				.match(httpServerExchange.getRequestPath());
		if (result != null) {
			// Found a match, configure and return true;
			// Add path variables to query params.
			httpServerExchange.putAttachment(ATTACHMENT_KEY,
					new io.undertow.util.PathTemplateMatch(result.getMatchedTemplate(), result.getParameters()));
			for (Map.Entry<String, String> entry : result.getParameters().entrySet()) {
				// the values shouldn't be added to query param. but this is left as it was to keep backward compatability
				httpServerExchange.addQueryParam(entry.getKey(), entry.getValue());
				
				// put values in path param map
				httpServerExchange.addPathParam(entry.getKey(), entry.getValue());
			}
			String id = result.getValue();
			httpServerExchange.putAttachment(CHAIN_ID, id);
			httpServerExchange.putAttachment(CHAIN_SEQ, 0);
			return true;
		}
	}
	return false;
}
 
Example #11
Source File: RoutingHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public synchronized RoutingHandler add(HttpString method, String template, Predicate predicate, HttpHandler handler) {
    PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
    if (matcher == null) {
        matches.put(method, matcher = new PathTemplateMatcher<>());
    }
    RoutingMatch res = matcher.get(template);
    if (res == null) {
        matcher.add(template, res = new RoutingMatch());
    }
    if (allMethodsMatcher.get(template) == null) {
        allMethodsMatcher.add(template, res);
    }
    res.predicatedHandlers.add(new HandlerHolder(predicate, handler));
    return this;
}
 
Example #12
Source File: RoutingHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public synchronized RoutingHandler add(HttpString method, String template, HttpHandler handler) {
    PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
    if (matcher == null) {
        matches.put(method, matcher = new PathTemplateMatcher<>());
    }
    RoutingMatch res = matcher.get(template);
    if (res == null) {
        matcher.add(template, res = new RoutingMatch());
    }
    if (allMethodsMatcher.get(template) == null) {
        allMethodsMatcher.add(template, res);
    }
    res.defaultHandler = handler;
    return this;
}
 
Example #13
Source File: JsrWebSocketFilter.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    container = (ServerWebSocketContainer) filterConfig.getServletContext().getAttribute(ServerContainer.class.getName());
    container.deploymentComplete();
    pathTemplateMatcher = new PathTemplateMatcher<>();
    WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) filterConfig.getServletContext().getAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
    for (ConfiguredServerEndpoint endpoint : container.getConfiguredServerEndpoints()) {
        if (info == null || info.getServerExtensions().isEmpty()) {
            pathTemplateMatcher.add(endpoint.getPathTemplate(), container.handshakes(endpoint));
        } else {
            pathTemplateMatcher.add(endpoint.getPathTemplate(), container.handshakes(endpoint, info.getServerExtensions()));
        }
    }
    this.callback = new EndpointSessionHandler(container);
}
 
Example #14
Source File: RoutingHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public synchronized RoutingHandler add(String method, String template, Predicate predicate, HttpHandler handler) {
    PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
    if (matcher == null) {
        matches.put(method, matcher = new PathTemplateMatcher<>());
    }
    RoutingMatch res = matcher.get(template);
    if (res == null) {
        matcher.add(template, res = new RoutingMatch());
    }
    if (allMethodsMatcher.get(template) == null) {
        allMethodsMatcher.add(template, res);
    }
    res.predicatedHandlers.add(new HandlerHolder(predicate, handler));
    return this;
}
 
Example #15
Source File: RoutingHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public synchronized RoutingHandler add(String method, String template, HttpHandler handler) {
    PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
    if (matcher == null) {
        matches.put(method, matcher = new PathTemplateMatcher<>());
    }
    RoutingMatch res = matcher.get(template);
    if (res == null) {
        matcher.add(template, res = new RoutingMatch());
    }
    if (allMethodsMatcher.get(template) == null) {
        allMethodsMatcher.add(template, res);
    }
    res.defaultHandler = handler;
    return this;
}
 
Example #16
Source File: RoutingHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    PathTemplateMatcher<RoutingMatch> matcher = matches.get(exchange.getRequestMethod());
    if (matcher == null) {
        handleNoMatch(exchange);
        return;
    }
    PathTemplateMatcher.PathMatchResult<RoutingMatch> match = matcher.match(exchange.getRelativePath());
    if (match == null) {
        handleNoMatch(exchange);
        return;
    }
    exchange.putAttachment(PathTemplateMatch.ATTACHMENT_KEY, match);
    if (rewriteQueryParameters) {
        for (Map.Entry<String, String> entry : match.getParameters().entrySet()) {
            exchange.addQueryParam(entry.getKey(), entry.getValue());
        }
    }
    for (HandlerHolder handler : match.getValue().predicatedHandlers) {
        if (handler.predicate.resolve(exchange)) {
            handler.handler.handleRequest(exchange);
            return;
        }
    }
    if (match.getValue().defaultHandler != null) {
        match.getValue().defaultHandler.handleRequest(exchange);
    } else {
        fallbackHandler.handleRequest(exchange);
    }
}
 
Example #17
Source File: RoutingHandler.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
Map<String, PathTemplateMatcher<RoutingMatch>> getMatches() {
    return matches;
}
 
Example #18
Source File: RoutingHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
Map<HttpString, PathTemplateMatcher<RoutingMatch>> getMatches() {
    return matches;
}
 
Example #19
Source File: JsrWebSocketFilter.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (req.getHeader(HttpHeaderNames.UPGRADE) != null) {
        final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp);

        String path;
        if (req.getPathInfo() == null) {
            path = req.getServletPath();
        } else {
            path = req.getServletPath() + req.getPathInfo();
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        PathTemplateMatcher.PathMatchResult<WebSocketHandshakeHolder> matchResult = pathTemplateMatcher.match(path);
        if (matchResult != null) {
            Handshake handshaker = null;
            for (Handshake method : matchResult.getValue().handshakes) {
                if (method.matches(facade)) {
                    handshaker = method;
                    break;
                }
            }

            if (handshaker != null) {
                if (container.isClosed()) {
                    resp.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                    return;
                }
                facade.putAttachment(HandshakeUtil.PATH_PARAMS, matchResult.getParameters());
                facade.putAttachment(HandshakeUtil.PRINCIPAL, req.getUserPrincipal());
                final Handshake selected = handshaker;
                ServletRequestContext src = ServletRequestContext.requireCurrent();
                final HttpSessionImpl session = src.getCurrentServletContext().getSession(src.getExchange(), false);
                handshaker.handshake(facade, new Consumer<ChannelHandlerContext>() {
                    @Override
                    public void accept(ChannelHandlerContext context) {
                        UndertowSession channel = callback.connected(context, selected.getConfig(), facade, src.getOriginalResponse().getHeader(io.netty.handler.codec.http.HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL.toString()));
                        if (session != null && channel != null) {
                            final Session underlying;
                            if (System.getSecurityManager() == null) {
                                underlying = session.getSession();
                            } else {
                                underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
                            }
                            List<UndertowSession> connections;
                            synchronized (underlying) {
                                connections = (List<UndertowSession>) underlying.getAttribute(SESSION_ATTRIBUTE);
                                if (connections == null) {
                                    underlying.setAttribute(SESSION_ATTRIBUTE, connections = new ArrayList<>());
                                }
                                connections.add(channel);
                            }
                            final List<UndertowSession> finalConnections = connections;
                            context.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
                                @Override
                                public void operationComplete(Future<? super Void> future) throws Exception {
                                    synchronized (underlying) {
                                        finalConnections.remove(channel);
                                    }
                                }
                            });
                        }
                    }
                });
                return;
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example #20
Source File: RoutingHandler.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 *
 * Removes the specified route from the handler
 *
 * @param method The method to remove
 * @param path the path tempate to remove
 * @return this handler
 */
public RoutingHandler remove(HttpString method, String path) {
    PathTemplateMatcher<RoutingMatch> handler = matches.get(method);
    if(handler != null) {
        handler.remove(path);
    }
    return this;
}
 
Example #21
Source File: RoutingHandler.java    From quarkus-http with Apache License 2.0 3 votes vote down vote up
/**
 *
 * Removes the specified route from the handler
 *
 * @param method The method to remove
 * @param path the path tempate to remove
 * @return this handler
 */
public RoutingHandler remove(String method, String path) {
    PathTemplateMatcher<RoutingMatch> handler = matches.get(method);
    if(handler != null) {
        handler.remove(path);
    }
    return this;
}