@Test public void toUriWithIpv6HostAlreadyEncoded() throws URISyntaxException { UriComponents uriComponents = UriComponentsBuilder.fromUriString( "http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich").build(true); UriComponents encoded = uriComponents.encode(); assertEquals(new URI("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich"), encoded.toUri()); }
public static String addFragmentComponent(String urlString, String component) { URI uri = URI.create(urlString); UriComponentsBuilder builder = UriComponentsBuilder.fromUri(uri); builder.fragment(hasText(uri.getFragment()) ? uri.getFragment() + "&" + component : component); return builder.build().toUriString(); }
private URI getUrlToUse() { MultiValueMap<String, String> params = this.queryParamsBuilder.buildAndExpand().encode().getQueryParams(); if (!params.isEmpty()) { return UriComponentsBuilder.fromUri(this.url).queryParams(params).build(true).toUri(); } return this.url; } }
/** * Asserts the request was redirected to the given URL template. * <p>This method accepts exact matches against the expanded and encoded URL template. * @param urlTemplate a URL template; the expanded URL will be encoded * @param uriVars zero or more URI variables to populate the template * @see UriComponentsBuilder#fromUriString(String) */ public static ResultMatcher redirectedUrlTemplate(String urlTemplate, Object... uriVars) { String uri = UriComponentsBuilder.fromUriString(urlTemplate).buildAndExpand(uriVars).encode().toUriString(); return redirectedUrl(uri); }
@RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> post(@RequestBody Tenant tenant) { Tenant savedTenant = this.tenantService.save(tenant); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(savedTenant.getId()).toUri()); return new ResponseEntity<>(savedTenant, httpHeaders, HttpStatus.CREATED); }
@Test // SPR-9317 public void fromUriEncodedQuery() throws URISyntaxException { URI uri = new URI("http://www.example.org/?param=aGVsbG9Xb3JsZA%3D%3D"); String fromUri = UriComponentsBuilder.fromUri(uri).build().getQueryParams().get("param").get(0); String fromUriString = UriComponentsBuilder.fromUriString(uri.toString()) .build().getQueryParams().get("param").get(0); assertEquals(fromUri, fromUriString); }
@Test // SPR-16710 public void fromMethodNameWithStringReturnType() { UriComponents uriComponents = fromMethodName( BookingControllerWithString.class, "getBooking", 21L).buildAndExpand(42); assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString()); }
/** * Check if the request is a same-origin one, based on {@code Origin}, and * {@code Host} headers. * * <p><strong>Note:</strong> as of 5.1 this method ignores * {@code "Forwarded"} and {@code "X-Forwarded-*"} headers that specify the * client-originated address. Consider using the {@code ForwardedHeaderFilter} * to extract and use, or to discard such headers. * * @return {@code true} if the request is a same-origin one, {@code false} in case * of a cross-origin request */ public static boolean isSameOrigin(ServerHttpRequest request) { String origin = request.getHeaders().getOrigin(); if (origin == null) { return true; } URI uri = request.getURI(); String actualScheme = uri.getScheme(); String actualHost = uri.getHost(); int actualPort = getPort(uri.getScheme(), uri.getPort()); Assert.notNull(actualScheme, "Actual request scheme must not be null"); Assert.notNull(actualHost, "Actual request host must not be null"); Assert.isTrue(actualPort != -1, "Actual request port must not be undefined"); UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build(); return (actualScheme.equals(originUrl.getScheme()) && actualHost.equals(originUrl.getHost()) && actualPort == getPort(originUrl.getScheme(), originUrl.getPort())); }
@Test public void plain() throws URISyntaxException { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); UriComponents result = builder.scheme("http").host("example.com") .path("foo").queryParam("bar").fragment("baz") .build(); assertEquals("http", result.getScheme()); assertEquals("example.com", result.getHost()); assertEquals("foo", result.getPath()); assertEquals("bar", result.getQuery()); assertEquals("baz", result.getFragment()); URI expected = new URI("http://example.com/foo?bar#baz"); assertEquals("Invalid result URI", expected, result.toUri()); }
@Test public void fromHierarchicalUri() throws URISyntaxException { URI uri = new URI("http://example.com/foo?bar#baz"); UriComponents result = UriComponentsBuilder.fromUri(uri).build(); assertEquals("http", result.getScheme()); assertEquals("example.com", result.getHost()); assertEquals("/foo", result.getPath()); assertEquals("bar", result.getQuery()); assertEquals("baz", result.getFragment()); assertEquals("Invalid result URI", uri, result.toUri()); }
@Test public void fromOpaqueUri() throws URISyntaxException { URI uri = new URI("mailto:foo@bar.com#baz"); UriComponents result = UriComponentsBuilder.fromUri(uri).build(); assertEquals("mailto", result.getScheme()); assertEquals("foo@bar.com", result.getSchemeSpecificPart()); assertEquals("baz", result.getFragment()); assertEquals("Invalid result URI", uri, result.toUri()); }
@RequestMapping(path = REQUEST_MAPPING_PATH, method = {RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS}) public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId, ServerHttpRequest request, ServerHttpResponse response) { String endpointLocalPath = getEndpointLocalPath(request.getPath().pathWithinApplication().value()); URI uri = UriComponentsBuilder.fromPath(endpointLocalPath) .query(request.getURI().getRawQuery()) .build(true) .toUri(); return super.forward(instanceId, uri, request.getMethod(), request.getHeaders(), () -> BodyInserters.fromDataBuffers(request.getBody())).flatMap(clientResponse -> { response.setStatusCode(clientResponse.statusCode()); response.getHeaders().addAll(filterHeaders(clientResponse.headers().asHttpHeaders())); return response.writeAndFlushWith(clientResponse.body(BodyExtractors.toDataBuffers()).window(1)); }); } }
@RequestMapping(value = "/dept", method = RequestMethod.POST) public ResponseEntity<Void> createUser(@RequestBody DeptJson deptJson, UriComponentsBuilder ucBuilder) { Department dept = deptJson.getDept(); System.out.println("Creating Dept " + deptJson.getDept()); dept = deptRepo.save(dept); System.out.println("saved Dept " + dept); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/dept/{id}").buildAndExpand(dept.getDeptId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } }
@RequestMapping(method = RequestMethod.POST, value = "/{user}/customers") ResponseEntity<Customer> addCustomer(@PathVariable Long user, @RequestBody Customer c) { Customer customer = crmService.addCustomer(user, c.getFirstName(), c.getLastName()); URI uriOfNewResource = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/users/{user}/customers/{customer}") .buildAndExpand(user, customer.getId()) .toUri(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(uriOfNewResource); return new ResponseEntity<>(customer, httpHeaders, HttpStatus.CREATED); }
@ApiOperation("getForEntity Uri") @RequestMapping(value = "/get3/{id}", method = RequestMethod.GET) @ResponseBody public Object getForEntity3(@PathVariable Long id) { String url = HOST_MALL_ADMIN + "/brand/{id}"; UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build().expand(id).encode(); ResponseEntity<CommonResult> responseEntity = restTemplate.getForEntity(uriComponents.toUri(), CommonResult.class); return responseEntity.getBody(); }
@RequestMapping(path = "/workbooks/{workbookId}/comments", method = RequestMethod.POST) public @ResponseBody ResponseEntity<?> createComments(@PathVariable("workbookId") String workbookId, @RequestBody Comment comment) { comment.setDomainType(WORKBOOK); comment.setDomainId(workbookId); commentRepository.saveAndFlush(comment); final URI location = ServletUriComponentsBuilder .fromCurrentServletMapping().path("/api/workbooks/{workbookId}/comments/{commentId}").build() .expand(workbookId, comment.getId()).toUri(); return ResponseEntity.created(location).build(); }
public static String constructTokenEndpointUrl(String issuer) throws URISyntaxException { URI uri; if (!IdentityZoneHolder.isUaa()) { String zone_issuer = IdentityZoneHolder.get().getConfig() != null ? IdentityZoneHolder.get().getConfig().getIssuer() : null; if(zone_issuer != null) { uri = validateIssuer(zone_issuer); return UriComponentsBuilder.fromUri(uri).pathSegment("oauth/token").build().toUriString(); } } uri = validateIssuer(issuer); String hostToUse = uri.getHost(); if (hasText(IdentityZoneHolder.get().getSubdomain())) { hostToUse = IdentityZoneHolder.get().getSubdomain() + "." + hostToUse; } return UriComponentsBuilder.fromUri(uri).host(hostToUse).pathSegment("oauth/token").build().toUriString(); }
@RequestMapping(path = "/", produces = "text/html") public String home(HttpServletRequest request, Map<String, Object> model) { if (isForceSsl() && !request.isSecure()) { String securedUrl = ServletUriComponentsBuilder.fromCurrentRequest() .scheme("https").build().toUriString(); return "redirect:" + securedUrl; } renderHome(model); return "home"; }
@RequestMapping(value={"/" + WEBFINGER_URL}, produces = MediaType.APPLICATION_JSON_VALUE) public String webfinger(@RequestParam("resource") String resource, @RequestParam(value = "rel", required = false) String rel, Model model) { && resourceUri.getScheme() != null && resourceUri.getScheme().equals("acct")) { UserInfo user = userService.getByEmailAddress(resourceUri.getUserInfo() + "@" + resourceUri.getHost()); user = userService.getByUsername(resourceUri.getUserInfo()); // first part is the username UriComponents issuerComponents = UriComponentsBuilder.fromHttpUrl(config.getIssuer()).build(); if (!Strings.nullToEmpty(issuerComponents.getHost()) .equals(Strings.nullToEmpty(resourceUri.getHost()))) { logger.info("Host mismatch, expected " + issuerComponents.getHost() + " got " + resourceUri.getHost()); model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME;