/** * Return a context-aware URl for the given relative URL with placeholders (named keys with braces {@code {}}). * For example, send in a relative URL {@code foo/{bar}?spam={spam}} and a parameter map * {@code {bar=baz,spam=nuts}} and the result will be {@code [contextpath]/foo/baz?spam=nuts}. * @param relativeUrl the relative URL part * @param params a map of parameters to insert as placeholders in the url * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly) */ public String getContextUrl(String relativeUrl, Map<String, ?> params) { String url = getContextPath() + relativeUrl; UriTemplate template = new UriTemplate(url); url = template.expand(params).toASCIIString(); if (this.response != null) { url = this.response.encodeURL(url); } return url; }
@Test // SPR-13627 public void matchCustomRegexWithNestedCurlyBraces() throws Exception { UriTemplate template = new UriTemplate("/site.{domain:co.[a-z]{2}}"); Map<String, String> result = template.match("/site.co.eu"); assertEquals("Invalid match", Collections.singletonMap("domain", "co.eu"), result); }
@Test public void fragments() throws Exception { UriTemplate template = new UriTemplate("/search#{fragment}"); assertTrue(template.matches("/search#foo")); template = new UriTemplate("/search?query={query}#{fragment}"); assertTrue(template.matches("/search?query=foo#bar")); }
/** * Constructor given URI template. * * @param uriTemplateValue * URI template used by the model */ public RestModelIdExtractor(final String uriTemplateValue) { this.uriTemplate = new UriTemplate(uriTemplateValue); }
@Test public void expandMapDuplicateVariables() throws Exception { UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}"); assertEquals(Arrays.asList("c", "c", "c"), template.getVariableNames()); URI result = template.expand(Collections.singletonMap("c", "cheeseburger")); assertEquals(new URI("/order/cheeseburger/cheeseburger/cheeseburger"), result); }
public static ControllerLinkBuilder linkTo(Class<?> controller, Method method, Object... parameters) { Assert.notNull(controller, "Controller type must not be null!"); Assert.notNull(method, "Method must not be null!"); UriTemplate template = DISCOVERER.getMappingAsUriTemplate(controller, method); URI uri = template.expand(parameters); return new ControllerLinkBuilder(getBuilder()).slash(uri); }
@Test public void getVariableNames() throws Exception { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); List<String> variableNames = template.getVariableNames(); assertEquals("Invalid variable names", Arrays.asList("hotel", "booking"), variableNames); }
/** * The lookup handler method, maps the SEOMapper method to the request URL. * <p>If no mapping is found, or if the URL is disabled, it will simply drop through * to the standard 404 handling.</p> * * @param urlPath the path to match. * @param request the http servlet request. * @return The HandlerMethod if one was found. */ @Override protected HandlerMethod lookupHandlerMethod(String urlPath, HttpServletRequest request) { logger.debug("looking up handler for path: " + urlPath); HandlerMethod handlerMethod = handlerMethods.get(urlPath); if (handlerMethod != null) { return handlerMethod; } for (String path : handlerMethods.keySet()) { UriTemplate template = new UriTemplate(path); if (template.matches(urlPath)) { request.setAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, template.match(urlPath)); return handlerMethods.get(path); } } return null; } }
@Override public Statement apply(Statement base, FrameworkMethod method, Object target) { try { RestTemplate client = new RestTemplate(); client.getForEntity(new UriTemplate(getUrl("/uaa/login", uaaPort)).toString(), String.class); client.getForEntity(new UriTemplate(getUrl("/api/index.html")).toString(), String.class); logger.debug("Basic connectivity test passed"); } catch (RestClientException e) { failTest(); } return super.apply(base, method, target); }
@Override public String transformUrl(Context context, CachingOptions cachingOptions, String url) throws UrlTransformationException { if (uriTemplate.matches(url)) { Map<String, String> variables = uriTemplate.match(url); for (Map.Entry<String, String> entry : variables.entrySet()) { RequestContext.getCurrent().getRequest().setAttribute(entry.getKey(), entry.getValue()); } url = uriTemplate.toString().replaceAll("\\{[^{}]+\\}", ""); url = url.replace("//", "/"); } return url; }
/** * Extracts the "pathVariable" from the given "uri". * * @param uri * The input uri * @param pathVariable * The path variable being extracted * @return the value of the pathVariable */ public String extractId(final String uri, final String pathVariable) { try { Map<String, String> pathVariables = this.uriTemplate.match(uri); return pathVariables.get(pathVariable); } catch (Exception e) { return null; } } }
private Optional<UriTemplate> findFirstMatchingUriTemplate(String url) { return dataTemplates.stream() .filter(t -> t.matches(url)) .findFirst(); }
@Required public void setUriTemplate(String uriTemplate) { this.uriTemplate = new UriTemplate(uriTemplate); }
public String getRecentHttpEndpoint(String endpoint) { URI uri = stringToUri(endpoint); String scheme = uri.getScheme(); String host = uri.getHost(); if ("wss".equals(scheme)) { scheme = "https"; } else { scheme = "http"; } return loggregatorRecentUriTemplate.expand(scheme, host).toString(); }
UriTemplate template = new UriTemplate(mapping); Map<String, Object> values = new HashMap<>(); Iterator<String> names = template.getVariableNames().iterator(); for (String variable : template.getVariableNames()) { if (!values.containsKey(variable)) { values.put(variable, SKIP_VALUE);
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; String roadName = template.match(httpRequest.getRequestURI()).get("name"); UserAgent userAgent = UserAgent.parse(httpRequest.getHeader("User-Agent")); products.forEach(product -> { userAgent.token(product).ifPresent(token -> { String version = token.getVersion().replaceAll("\\.", "-"); Tag roadTag = Tag.of("road", roadName); Tag productTag = Tag.of("product", product); Tag versionTag = Tag.of("version", version); ImmutableList<Tag> tags = ImmutableList.of(roadTag, productTag, versionTag); registry.counter("user-agent-metric-filter", tags).increment(); }); }); } chain.doFilter(request, response); }
public URI build() { return new UriTemplate(pattern()).expand(params); } }
@Test public void match() throws Exception { Map<String, String> expected = new HashMap<>(2); expected.put("booking", "42"); expected.put("hotel", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); Map<String, String> result = template.match("/hotels/1/bookings/42"); assertEquals("Invalid match", expected, result); }
@Test // SPR-16169 public void matchWithMultipleSegmentsAtTheEnd() { UriTemplate template = new UriTemplate("/account/{accountId}"); assertFalse(template.matches("/account/15/alias/5")); }