org.springframework.web.util.UriComponents Java Examples
The following examples show how to use
org.springframework.web.util.UriComponents.
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: ServletUriComponentsBuilderTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void fromRequestWithForwardedHostAndPort() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("http"); request.setServerName("localhost"); request.setServerPort(80); request.setRequestURI("/mvc-showcase"); request.addHeader("X-Forwarded-Proto", "https"); request.addHeader("X-Forwarded-Host", "84.198.58.199"); request.addHeader("X-Forwarded-Port", "443"); HttpServletRequest requestToUse = adaptFromForwardedHeaders(request); UriComponents result = ServletUriComponentsBuilder.fromRequest(requestToUse).build(); assertEquals("https://84.198.58.199/mvc-showcase", result.toString()); }
Example #2
Source File: RedirectView.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Convert model to request parameters and redirect to the given URL. * @see #appendQueryProperties * @see #sendRedirect */ @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException { String targetUrl = createTargetUrl(model, request); targetUrl = updateTargetUrl(targetUrl, model, request, response); FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request); if (!CollectionUtils.isEmpty(flashMap)) { UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build(); flashMap.setTargetRequestPath(uriComponents.getPath()); flashMap.addTargetRequestParams(uriComponents.getQueryParams()); FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request); if (flashMapManager == null) { throw new IllegalStateException("FlashMapManager not found despite output FlashMap having been set"); } flashMapManager.saveOutputFlashMap(flashMap, request, response); } sendRedirect(request, response, targetUrl, this.http10Compatible); }
Example #3
Source File: RestServiceTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void toEntityFileValueValid() throws ParseException { String generatedId = "id"; String downloadUriAsString = "http://somedownloaduri"; ServletUriComponentsBuilder mockBuilder = mock(ServletUriComponentsBuilder.class); UriComponents downloadUri = mock(UriComponents.class); FileMeta fileMeta = mock(FileMeta.class); Attribute fileAttr = when(mock(Attribute.class).getName()).thenReturn("fileAttr").getMock(); when(fileAttr.getDataType()).thenReturn(FILE); when(idGenerator.generateId()).thenReturn(generatedId); when(fileMetaFactory.create(generatedId)).thenReturn(fileMeta); when(mockBuilder.replacePath(anyString())).thenReturn(mockBuilder); when(mockBuilder.replaceQuery(null)).thenReturn(mockBuilder); when(downloadUri.toUriString()).thenReturn(downloadUriAsString); when(mockBuilder.build()).thenReturn(downloadUri); when(servletUriComponentsBuilderFactory.fromCurrentRequest()).thenReturn(mockBuilder); byte[] content = {'a', 'b'}; MockMultipartFile mockMultipartFile = new MockMultipartFile("name", "fileName", "contentType", content); assertEquals(fileMeta, restService.toEntityValue(fileAttr, mockMultipartFile, null)); }
Example #4
Source File: AuthUtils.java From jakduk-api with MIT License | 6 votes |
/** * 회원 프로필 이미지 URL을 생성한다. * * @param sizeType size 타입 * @param id UserImage의 ID */ public String generateUserPictureUrl(Constants.IMAGE_SIZE_TYPE sizeType, String id) { if (StringUtils.isBlank(id)) return null; String urlPathUserPicture = null; switch (sizeType) { case LARGE: urlPathUserPicture = jakdukProperties.getApiUrlPath().getUserPictureLarge(); break; case SMALL: urlPathUserPicture = jakdukProperties.getApiUrlPath().getUserPictureSmall(); break; } UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(jakdukProperties.getApiServerUrl()) .path("/{urlPathGallery}/{id}") .buildAndExpand(urlPathUserPicture, id); return uriComponents.toUriString(); }
Example #5
Source File: ServletUriComponentsBuilder.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Initialize a builder with a scheme, host,and port (but not path and query). */ private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest request) { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); String scheme = uriComponents.getScheme(); String host = uriComponents.getHost(); int port = uriComponents.getPort(); ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder(); builder.scheme(scheme); builder.host(host); if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) { builder.port(port); } return builder; }
Example #6
Source File: DefaultContainerImageMetadataResolverTest.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
private void mockManifestRestTemplateCall(Map<String, Object> mapToReturn, String registryHost, String registryPort, String repository, String tag) { UriComponents manifestUriComponents = UriComponentsBuilder.newInstance() .scheme("https") .host(registryHost) .port(StringUtils.hasText(registryPort) ? registryPort : null) .path("v2/{repository}/manifests/{tag}") .build().expand(repository, tag); when(mockRestTemplate.exchange( eq(manifestUriComponents.toUri()), eq(HttpMethod.GET), any(HttpEntity.class), eq(Map.class))).thenReturn(new ResponseEntity<>(mapToReturn, HttpStatus.OK)); }
Example #7
Source File: ConstructBuildURI.java From levelup-java-examples with Apache License 2.0 | 6 votes |
@Test public void construct_uri_queryparmeter_spring () { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("http") .host("www.leveluplunch.com") .path("/{lanuage}/{type}/") .queryParam("test", "a", "b") .build() .expand("java", "examples") .encode(); assertEquals("http://www.leveluplunch.com/java/examples/?test=a&test=b", uriComponents.toUriString()); }
Example #8
Source File: WxApiMethodInfo.java From FastBootWeixin with Apache License 2.0 | 6 votes |
private UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) { CompositeUriComponentsContributor contributor = defaultUriComponentsContributor; int paramCount = method.getParameterTypes().length; int argCount = args.length; if (paramCount != argCount) { throw new IllegalArgumentException("方法参数量为" + paramCount + " 与真实参数量不匹配,真实参数量为" + argCount); } final Map<String, Object> uriVars = new HashMap<>(8); for (int i = 0; i < paramCount; i++) { MethodParameter param = new SynthesizingMethodParameter(method, i); param.initParameterNameDiscovery(parameterNameDiscoverer); contributor.contributeMethodArgument(param, args[i], builder, uriVars); } // We may not have all URI var values, expand only what we have return builder.build().expand(name -> uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE); }
Example #9
Source File: CustomFieldSearchController.java From wallride with Apache License 2.0 | 6 votes |
@RequestMapping(method = RequestMethod.GET) public String search( @PathVariable String language, @Validated @ModelAttribute("form") CustomFieldSearchForm form, BindingResult result, @PageableDefault(50) Pageable pageable, Model model, HttpServletRequest servletRequest) throws UnsupportedEncodingException { Page<CustomField> customFields = customfieldService.getCustomFields(form.toCustomFieldSearchRequest(), pageable); model.addAttribute("customFields", customFields); model.addAttribute("pageable", pageable); model.addAttribute("pagination", new Pagination<>(customFields, servletRequest)); UriComponents uriComponents = ServletUriComponentsBuilder .fromRequest(servletRequest) .queryParams(ControllerUtils.convertBeanForQueryParams(form, conversionService)) .build(); if (!StringUtils.isEmpty(uriComponents.getQuery())) { model.addAttribute("query", URLDecoder.decode(uriComponents.getQuery(), "UTF-8")); } return "customfield/index"; }
Example #10
Source File: ServletUriComponentsBuilder.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Initialize a builder with a scheme, host,and port (but not path and query). */ private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest request) { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); String scheme = uriComponents.getScheme(); String host = uriComponents.getHost(); int port = uriComponents.getPort(); ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder(); builder.scheme(scheme); builder.host(host); if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) { builder.port(port); } return builder; }
Example #11
Source File: MottoController.java From Spring-Boot-2-Fundamentals with MIT License | 6 votes |
/** Append to list of mottos, but only if the motto is unique */ @PostMapping public ResponseEntity<Message> uniqueAppend(@RequestBody Message message, UriComponentsBuilder uriBuilder) { // Careful, this lookup is O(n) if (motto.contains(message)) { return ResponseEntity.status(HttpStatus.CONFLICT).build(); } else { motto.add(message); UriComponents location = MvcUriComponentsBuilder .fromMethodCall(on(MottoController.class).retrieveById(motto.size())) .build(); return ResponseEntity .created(location.toUri()) .header("X-Copyright", "Packt 2018") .body(new Message("Accepted #" + motto.size())); } }
Example #12
Source File: ArticleSearchController.java From wallride with Apache License 2.0 | 6 votes |
@RequestMapping(method = RequestMethod.GET) public String search( @PathVariable String language, @Validated @ModelAttribute("form") ArticleSearchForm form, BindingResult result, @PageableDefault(50) Pageable pageable, Model model, HttpServletRequest servletRequest) throws UnsupportedEncodingException { Page<Article> articles = articleService.getArticles(form.toArticleSearchRequest(), pageable); model.addAttribute("articles", articles); model.addAttribute("pageable", pageable); model.addAttribute("pagination", new Pagination<>(articles, servletRequest)); UriComponents uriComponents = ServletUriComponentsBuilder .fromRequest(servletRequest) .queryParams(ControllerUtils.convertBeanForQueryParams(form, conversionService)) .build(); if (!StringUtils.isEmpty(uriComponents.getQuery())) { model.addAttribute("query", URLDecoder.decode(uriComponents.getQuery(), "UTF-8")); } return "article/index"; }
Example #13
Source File: DataModelServiceStub.java From wecube-platform with Apache License 2.0 | 5 votes |
/** * Issue a request from request url with place holders and param map * * @param requestUrl request url with place holders * @param paramMap generated param map * @return common response dto */ public UrlToResponseDto initiateGetRequest(String requestUrl, Map<String, Object> paramMap) { UrlToResponseDto responseDto; // combine url with param map UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(requestUrl); UriComponents uriComponents = uriComponentsBuilder.buildAndExpand(paramMap); String uriStr = uriComponents.toString(); responseDto = sendGetRequest(uriStr); return responseDto; }
Example #14
Source File: SimpleMethodLinkBuilderTest.java From springlets with Apache License 2.0 | 5 votes |
/** * Test method for {@link io.springlets.web.mvc.support.SimpleMethodLinkBuilder#toUri()}. */ @Test public void testToUri() { // Setup when(linkFactory.toUri(eq(METHOD_NAME), isNull(Object[].class), anyMapOf(String.class, Object.class))).thenReturn(uriMethod); when(linkFactory.toUri(eq(METHOD_NAME), argThat(isParametersOfOneElement()), anyMapOf(String.class, Object.class))).thenReturn(uriMethodParams); when(linkFactory.toUri(eq(METHOD_NAME), isNull(Object[].class), argThat(isPathVariablesOfVariable(VARIABLE_NAME, VARIABLE_VALUE)))) .thenReturn(uriMethodVars); when(linkFactory.toUri(eq(METHOD_NAME), argThat(isParametersOfOneElement()), argThat(isPathVariablesOfVariable(VARIABLE_NAME, VARIABLE_VALUE)))) .thenReturn(uriMethodParamsVars); // Exercise UriComponents uri1 = builder.toUri(); UriComponents uri2 = builder.arg(0, new Object()).toUri(); UriComponents uri3 = builder.with(VARIABLE_NAME, VARIABLE_VALUE).toUri(); UriComponents uri4 = builder.arg(0, new Object()) .with(VARIABLE_NAME, VARIABLE_VALUE).toUri(); // Verify assertThat(uri1).isNotNull().isEqualTo(uriMethod); assertThat(uri2).isNotNull().isEqualTo(uriMethodParams); assertThat(uri3).isNotNull().isEqualTo(uriMethodVars); assertThat(uri4).isNotNull().isEqualTo(uriMethodParamsVars); }
Example #15
Source File: RedirectAuthenticationFailureHandler.java From pizzeria with MIT License | 5 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(request.getServletPath()); uriComponentsBuilder.queryParam(queryParam); uriComponentsBuilder.queryParam(StringUtils.defaultIfEmpty(request.getQueryString(), StringUtils.EMPTY)); UriComponents uriComponents = uriComponentsBuilder.build(); String returnUrlWithQueryParameter = uriComponents.toUriString(); LOGGER.debug(returnUrlWithQueryParameter); redirectStrategy.sendRedirect(request, response, returnUrlWithQueryParameter); }
Example #16
Source File: DataModelServiceStub.java From wecube-platform with Apache License 2.0 | 5 votes |
/** * Issue a request from request url with place holders and param map * * @param requestUrl request url with place holders * @param paramMap generated param map * @Param chainRequestDto chain request dto scope */ public UrlToResponseDto initiatePostRequest(String requestUrl, Map<String, Object> paramMap, List<Map<String, Object>> requestBodyParamMap) { UrlToResponseDto urlToResponseDto; // combine url with param map UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(requestUrl); UriComponents uriComponents = uriComponentsBuilder.buildAndExpand(paramMap); String uriStr = uriComponents.toString(); urlToResponseDto = sendPostRequest(uriStr, requestBodyParamMap); return urlToResponseDto; }
Example #17
Source File: WiremockServerRestDocsHypermediaApplicationTests.java From spring-cloud-contract with Apache License 2.0 | 5 votes |
@ResponseBody @RequestMapping("/link") public String resource(HttpServletRequest request) { UriComponents uriComponents = UriComponentsBuilder .fromHttpRequest(new ServletServerHttpRequest(request)).build(); return "link: " + uriComponents.toUriString(); }
Example #18
Source File: UriUtils.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
private static UriComponents createEntityTypeMetadataAttributeUriComponents( ServletUriComponentsBuilder builder, String entityTypeId, String attributeName) { builder = builder.cloneBuilder(); builder.path(ApiNamespace.API_PATH); builder.pathSegment(RestControllerV2.API_VERSION, entityTypeId, "meta", attributeName); return builder.build(); }
Example #19
Source File: Users.java From wallride with Apache License 2.0 | 5 votes |
private String path(UriComponentsBuilder builder, User user, boolean encode) { Map<String, Object> params = new HashMap<>(); builder.path("/author/{code}"); params.put("code", user.getLoginId()); UriComponents components = builder.buildAndExpand(params); if (encode) { components = components.encode(); } return components.toUriString(); }
Example #20
Source File: MvcUriComponentsBuilderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void fromControllerWithCustomBaseUrlViaStaticCall() { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://example.org:9090/base"); UriComponents uriComponents = fromController(builder, PersonControllerImpl.class).build(); assertEquals("http://example.org:9090/base/people", uriComponents.toString()); assertEquals("http://example.org:9090/base", builder.toUriString()); }
Example #21
Source File: MvcUriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testFromMethodNameWithPathVarAndRequestParam() throws Exception { UriComponents uriComponents = fromMethodName( ControllerWithMethods.class, "methodForNextPage", "1", 10, 5).build(); assertThat(uriComponents.getPath(), is("/something/1/foo")); MultiValueMap<String, String> queryParams = uriComponents.getQueryParams(); assertThat(queryParams.get("limit"), contains("5")); assertThat(queryParams.get("offset"), contains("10")); }
Example #22
Source File: APIDocRetrievalService.java From api-layer with Eclipse Public License 2.0 | 5 votes |
/** * Creates a URL from the routing metadata 'apiml.routes.api-doc.serviceUrl' when 'apiml.apiInfo.swaggerUrl' is * not present * * @param instanceInfo the information about service instance * @return the URL of API doc endpoint * @deprecated Added to support services which were on-boarded before 'apiml.apiInfo.swaggerUrl' parameter was * introduced. It will be removed when all services will be using the new configuration style. */ @Deprecated private String createApiDocUrlFromRouting(InstanceInfo instanceInfo, RoutedServices routes) { String scheme; int port; if (instanceInfo.isPortEnabled(InstanceInfo.PortType.SECURE)) { scheme = "https"; port = instanceInfo.getSecurePort(); } else { scheme = "http"; port = instanceInfo.getPort(); } String path = null; RoutedService route = routes.findServiceByGatewayUrl("api/v1/api-doc"); if (route != null) { path = route.getServiceUrl(); } if (path == null) { throw new ApiDocNotFoundException("No API Documentation defined for service " + instanceInfo.getAppName().toLowerCase() + " ."); } UriComponents uri = UriComponentsBuilder .newInstance() .scheme(scheme) .host(instanceInfo.getHostName()) .port(port) .path(path) .build(); return uri.toUriString(); }
Example #23
Source File: CorsUtils.java From spring-analysis-note with MIT License | 5 votes |
/** * Returns {@code true} if the request is a valid CORS one by checking {@code Origin} * header presence and ensuring that origins are different. */ public static boolean isCorsRequest(HttpServletRequest request) { String origin = request.getHeader(HttpHeaders.ORIGIN); if (origin == null) { return false; } UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build(); String scheme = request.getScheme(); String host = request.getServerName(); int port = request.getServerPort(); return !(ObjectUtils.nullSafeEquals(scheme, originUrl.getScheme()) && ObjectUtils.nullSafeEquals(host, originUrl.getHost()) && getPort(scheme, port) == getPort(originUrl.getScheme(), originUrl.getPort())); }
Example #24
Source File: MvcUriComponentsBuilderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void fromMethodCallWithCustomBaseUrlViaInstance() { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://example.org:9090/base"); MvcUriComponentsBuilder mvcBuilder = relativeTo(builder); UriComponents result = mvcBuilder.withMethodCall(on(ControllerWithMethods.class).myMethod(null)).build(); assertEquals("http://example.org:9090/base/something/else", result.toString()); assertEquals("http://example.org:9090/base", builder.toUriString()); }
Example #25
Source File: MvcUriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testFromMethodCallWithPathVar() { UriComponents uriComponents = fromMethodCall(on( ControllerWithMethods.class).methodWithPathVariable("1")).build(); assertThat(uriComponents.toUriString(), startsWith("http://localhost")); assertThat(uriComponents.toUriString(), endsWith("/something/1/foo")); }
Example #26
Source File: ServletUriComponentsBuilderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test // SPR-16650 public void fromRequestWithForwardedPrefixTrailingSlash() throws Exception { this.request.addHeader("X-Forwarded-Prefix", "/foo/"); this.request.setContextPath("/spring-mvc-showcase"); this.request.setRequestURI("/spring-mvc-showcase/bar"); HttpServletRequest requestToUse = adaptFromForwardedHeaders(this.request); UriComponents result = ServletUriComponentsBuilder.fromRequest(requestToUse).build(); assertEquals("http://localhost/foo/bar", result.toUriString()); }
Example #27
Source File: HttpRequestTools.java From WeBASE-Node-Manager with Apache License 2.0 | 5 votes |
/** * convert map to query params * ex: uri:permission, * params: (groupId, 1) (address, 0x01) * * result: permission?groupId=1&address=0x01 */ public static String getQueryUri(String uriHead, Map<String, String> map) { MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); for (Map.Entry<String, String> entry : map.entrySet()) { params.add(entry.getKey(), entry.getValue()); } UriComponents uriComponents = UriComponentsBuilder.newInstance() .queryParams(params).build(); return uriHead + uriComponents.toString(); }
Example #28
Source File: MvcUriComponentsBuilderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void usesForwardedHostAndPortFromHeader() throws Exception { request.addHeader("X-Forwarded-Host", "foobar:8088"); adaptRequestFromForwardedHeaders(); UriComponents uriComponents = fromController(PersonControllerImpl.class).build(); assertThat(uriComponents.toUriString(), startsWith("http://foobar:8088")); }
Example #29
Source File: AppCenterManager.java From carina with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) private RequestEntity<String> buildRequestEntity(String hostUrl, String path, MultiValueMap<String, String> listQueryParams, HttpMethod httpMethod) { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("https") .host(hostUrl) .path(path) .queryParams(listQueryParams) .build(); return new RequestEntity(setHeaders(), httpMethod, uriComponents.toUri()); }
Example #30
Source File: MvcUriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testFromMethodNameWithCustomBaseUrlViaStaticCall() throws Exception { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://example.org:9090/base"); UriComponents uriComponents = fromMethodName(builder, ControllerWithMethods.class, "methodWithPathVariable", new Object[] {"1"}).build(); assertEquals("http://example.org:9090/base/something/1/foo", uriComponents.toString()); assertEquals("http://example.org:9090/base", builder.toUriString()); }