Java Code Examples for org.springframework.web.util.UriComponents#toUriString()

The following examples show how to use org.springframework.web.util.UriComponents#toUriString() . 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: StyleServiceImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Build a downLoadUrl for the file identified by the given fileId. If this method is called
 * outside of a request context ( system initialization for example) the server context is used
 * for generating a relative path
 */
private String buildFileUrl(String fileId) {

  if (RequestContextHolder.getRequestAttributes() != null) {
    ServletUriComponentsBuilder currentRequest = ServletUriComponentsBuilder.fromCurrentRequest();
    UriComponents downloadUri =
        currentRequest
            .replacePath(FileDownloadController.URI + '/' + fileId)
            .replaceQuery(null)
            .build();
    return downloadUri.toUriString();
  } else {
    // TODO this is a workaround for the situation where the File url needs to be created without
    // a request
    // context, in order to fix the properly we would need to add a deploy time property
    // defining the file download server location
    return FileDownloadController.URI + '/' + fileId;
  }
}
 
Example 2
Source File: UrlGenerationUtils.java    From jakduk-api with MIT License 6 votes vote down vote up
/**
 * 사진첩 이미지 URL을 생성한다.
 *
 * @param sizeType size 타입
 * @param id Gallery ID
 */
public String generateGalleryUrl(Constants.IMAGE_SIZE_TYPE sizeType, String id) {

    if (StringUtils.isBlank(id))
        return null;

    String urlPathGallery = null;

    switch (sizeType) {
        case LARGE:
            urlPathGallery = apiUrlPathProperties.getGalleryImage();
            break;
        case SMALL:
            urlPathGallery = apiUrlPathProperties.getGalleryThumbnail();
            break;
    }

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(jakdukProperties.getApiServerUrl())
            .path("/{urlPathGallery}/{id}")
            .buildAndExpand(urlPathGallery, id);

    return uriComponents.toUriString();
}
 
Example 3
Source File: AuthUtils.java    From jakduk-api with MIT License 6 votes vote down vote up
/**
 * 회원 프로필 이미지 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 4
Source File: PostUtils.java    From wallride with Apache License 2.0 6 votes vote down vote up
private String path(UriComponentsBuilder builder, Page page, boolean encode) {
	Map<String, Object> params = new HashMap<>();

	List<String> codes = new LinkedList<>();
	Map<Page, String> paths = pageUtils.getPaths(page);
	paths.keySet().stream().map(p -> p.getCode()).forEach(codes::add);

	for (int i = 0; i < codes.size(); i++) {
		String key = "code" + i;
		builder.path("/{" + key + "}");
		params.put(key, codes.get(i));
	}

	UriComponents components = builder.buildAndExpand(params);
	if (encode) {
		components = components.encode();
	}
	return components.toUriString();
}
 
Example 5
Source File: PersonResourceProcessor.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public Resource<Person> process(Resource<Person> resource) {
	String id = Long.toString(resource.getContent().getId());
	UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath()
			.path("/people/{id}/photo").buildAndExpand(id);
	String uri = uriComponents.toUriString();
	resource.add(new Link(uri, "photo"));
	return resource;
}
 
Example 6
Source File: OpenIdAuthenticationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public String buildClaimsRetrieverUrl() {
    UriComponents uri = UriComponentsBuilder.newInstance()
            .scheme("https")
            .host(openIdConfiguration().getDomain())
            .path(openIdConfiguration().getTokenEndpoint())
            .build();
    return uri.toUriString();
}
 
Example 7
Source File: OpenIdAuthenticationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public String buildAuthorizeUrl() {
    log.trace("buildAuthorizeUrl, configuration: {}", this::openIdConfiguration);
    String scopeParameter = String.join("+", getScopes());

    UriComponents uri = UriComponentsBuilder.newInstance()
            .scheme("https")
            .host(openIdConfiguration().getDomain())
            .path(openIdConfiguration().getAuthenticationUrl())
            .queryParam("redirect_uri", openIdConfiguration().getCallbackURI())
            .queryParam("client_id", openIdConfiguration().getClientId())
            .queryParam("scope", scopeParameter)
            .queryParam("response_type", "code")
            .build();
    return uri.toUriString();
}
 
Example 8
Source File: UrlGenerationUtils.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * 글 상세 URL 생성
 *
 * @param board 게시판
 * @param seq 글번호
 */
public String generateArticleDetailUrl(String board, Integer seq) {

    if (StringUtils.isBlank(board) || Objects.isNull(seq))
        return null;

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(jakdukProperties.getWebServerUrl())
            .path("/board/{board}/{seq}")
            .buildAndExpand(board.toLowerCase(), seq);

    return uriComponents.toUriString();
}
 
Example 9
Source File: UrlGenerationUtils.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * 글 상세 API URL 생성
 *
 * @param board 게시판
 * @param seq 글번호
 */
public String generateArticleDetailApiUrl(String board, Integer seq) {

    if (StringUtils.isBlank(board) || Objects.isNull(seq))
        return null;

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(jakdukProperties.getApiServerUrl())
            .path("/api/board/{board}/{seq}")
            .buildAndExpand(board.toLowerCase(), seq);

    return uriComponents.toUriString();
}
 
Example 10
Source File: PostUtils.java    From wallride with Apache License 2.0 5 votes vote down vote up
private String path(UriComponentsBuilder builder, Article article, boolean encode) {
	Map<String, Object> params = new HashMap<>();
	builder.path("/{year}/{month}/{day}/{code}");
	params.put("year", String.format("%04d", article.getDate().getYear()));
	params.put("month", String.format("%02d", article.getDate().getMonth().getValue()));
	params.put("day", String.format("%02d", article.getDate().getDayOfMonth()));
	params.put("code", article.getCode());

	UriComponents components = builder.buildAndExpand(params);
	if (encode) {
		components = components.encode();
	}
	return components.toUriString();
}
 
Example 11
Source File: Users.java    From wallride with Apache License 2.0 5 votes vote down vote up
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 12
Source File: APIDocRetrievalService.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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 13
Source File: PersonResourceProcessor.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public Resource<Person> process(Resource<Person> resource) {
	String id = Long.toString(resource.getContent().getId());
	UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath()
			.path("/people/{id}/photo").buildAndExpand(id);
	String uri = uriComponents.toUriString();
	resource.add(new Link(uri, "photo"));
	return resource;
}
 
Example 14
Source File: DiscoveryNodeController.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private String getServerAddress(HttpServletRequest request) {
    UriComponents build = UriComponentsBuilder
            .newInstance()
            .scheme(request.getScheme())
            .host(request.getServerName())
            .port(request.getServerPort())
            .build();
    return build.toUriString();
}
 
Example 15
Source File: RedirectController.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@RequestMapping(value = "/uriComponentsBuilder", method = RequestMethod.GET)
public String uriComponentsBuilder() {
	String date = this.conversionService.convert(new LocalDate(2011, 12, 31), String.class);
	UriComponents redirectUri = UriComponentsBuilder.fromPath("/redirect/{account}").queryParam("date", date)
		.build().expand("a123").encode();
	return "redirect:" + redirectUri.toUriString();
}
 
Example 16
Source File: VoterTest.java    From vics with MIT License 5 votes vote down vote up
@Test
public void returnsTheElectorsWhenSearchingByAttributes() throws Exception {
    when(sessionService.extractUserFromPrincipal(any(Principal.class)))
            .thenReturn(Try.success(earlsdon()));
    pafApiStub.willSearchVoters("CV46PL", "McCall", "E05001221");

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("surname", "McCall");
    params.add("postcode", "CV46PL");
    params.add("wardCode", "E05001221");
    UriComponents uriComponents = UriComponentsBuilder.fromPath("/elector")
            .queryParams(params)
            .build();

    String url = uriComponents.toUriString();

    mockMvc.perform(get(url)
            .accept(APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$[0].full_name", is("McCall, John B")))
            .andExpect(jsonPath("$[0].first_name", is("John B")))
            .andExpect(jsonPath("$[0].surname", is("McCall")))
            .andExpect(jsonPath("$[0].ern", is("E050097474-LFF-305-0")))
            .andExpect(jsonPath("$[0].address.postcode", is("CV4 6PL")))
            .andExpect(jsonPath("$[0].address.line_1", is("Grange Farm House")))
            .andExpect(jsonPath("$[0].address.line_2", is("Crompton Lane")))
            .andExpect(jsonPath("$[0].address.post_town", is("Coventry")));
}
 
Example 17
Source File: WiremockServerWebTestClientApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping("/link")
public String link(ServerHttpRequest request) {
	UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(request)
			.build();
	return "link: " + uriComponents.toUriString();
}
 
Example 18
Source File: WiremockServerRestDocsHypermediaApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping("/link")
public String resource(HttpServletRequest request) {
	UriComponents uriComponents = UriComponentsBuilder
			.fromHttpRequest(new ServletServerHttpRequest(request)).build();
	return "link: " + uriComponents.toUriString();
}
 
Example 19
Source File: CseUriTemplateHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private URI createUri(String uriTemplate, UriComponentsBuilder builder, UriComponents uriComponents) {
  String strUri = uriComponents.toUriString();

  if (isCrossApp(uriTemplate, builder)) {
    int idx = strUri.indexOf('/', RestConst.URI_PREFIX.length());
    strUri = strUri.substring(0, idx) + ":" + strUri.substring(idx + 1);
  }

  try {
    // Avoid further encoding (in the case of strictEncoding=true)
    return new URI(strUri);
  } catch (URISyntaxException ex) {
    throw new IllegalStateException("Could not create URI object: " + ex.getMessage(), ex);
  }
}
 
Example 20
Source File: RedirectAuthenticationFailureHandler.java    From pizzeria with MIT License 5 votes vote down vote up
@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);
}