Java Code Examples for org.springframework.web.util.UriComponentsBuilder

The following examples show how to use org.springframework.web.util.UriComponentsBuilder. These examples are extracted from open source projects. 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 Project: JuniperBot   Source File: PatreonAPI.java    License: GNU General Public License v3.0 7 votes vote down vote up
public JSONAPIDocument<List<Member>> fetchPageOfMember(String campaignId,
                                                       int pageSize,
                                                       String pageCursor,
                                                       Collection<Member.MemberField> optionalFields) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(String.format("campaigns/%s/members", campaignId))
            .queryParam("include", "currently_entitled_tiers,user")
            .queryParam("page[count]", pageSize);
    if (pageCursor != null) {
        builder.queryParam("page[cursor]", pageCursor);
    }
    Set<Member.MemberField> optionalMemberAndDefaultFields = new HashSet<>();
    if (optionalFields != null) {
        optionalMemberAndDefaultFields.addAll(optionalFields);
    }
    optionalMemberAndDefaultFields.addAll(Member.MemberField.getDefaultFields());
    addFieldsParam(builder, Member.class, optionalMemberAndDefaultFields);
    addFieldsParam(builder, User.class, User.UserField.getDefaultFields());

    return execute(builder, new ParameterizedTypeReference<JSONAPIDocument<List<Member>>>() {
    });
}
 
Example 2
String handleInInterface(
@CookieValue("cookie") int cookieV,
@PathVariable("pathvar") String pathvarV,
@RequestHeader("header") String headerV,
@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
@RequestHeader Map<String, Object> headerMap,
@RequestParam("dateParam") Date dateParam,
@RequestParam Map<String, Object> paramMap,
String paramByConvention,
@Value("#{request.contextPath}") String value,
@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
Errors errors,
TestBean modelAttrByConvention,
Color customArg,
HttpServletRequest request,
HttpServletResponse response,
@SessionAttribute TestBean sessionAttribute,
@RequestAttribute TestBean requestAttribute,
User user,
@ModelAttribute OtherUser otherUser,
Model model,
UriComponentsBuilder builder);
 
Example 3
Source Project: jeecg   Source File: UserRestController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value="创建用户信息")
public ResponseEntity<?> create(@ApiParam(name="用户对象")@RequestBody TSUser user, UriComponentsBuilder uriBuilder) {
	//调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
	Set<ConstraintViolation<TSUser>> failures = validator.validate(user);
	if (!failures.isEmpty()) {
		return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
	}

	//保存用户
	userService.save(user);

	//按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象.
	String id = user.getId();
	URI uri = uriBuilder.path("/rest/user/" + id).build().toUri();
	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(uri);

	return new ResponseEntity(headers, HttpStatus.CREATED);
}
 
Example 4
private static String createToken(String jwtKey, String user, String path, Instant expireDate, Map<String, String> additionalClaims) {
    UriComponents components = UriComponentsBuilder.fromUriString(path).build();
    String query = components.getQuery();
    String pathClaim = components.getPath() + (!StringUtils.isBlank(query) ? "?" + components.getQuery() : "");
    Builder builder = JWT
            .create()
            .withIssuer("airsonic")
            .withSubject(user)
            .withClaim(CLAIM_PATH, pathClaim)
            .withExpiresAt(Date.from(expireDate));

    for (Entry<String, String> claim : additionalClaims.entrySet()) {
        builder = builder.withClaim(claim.getKey(), claim.getValue());
    }

    return builder.sign(getAlgorithm(jwtKey));
}
 
Example 5
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Optional<String> redirectUri = CookieUtils.getCookie(request, REDIRECT_URI_PARAM_COOKIE_NAME)
            .map(Cookie::getValue);

    if(redirectUri.isPresent() && !isAuthorizedRedirectUri(redirectUri.get())) {
        throw new ApiException("Sorry! We've got an Unauthorized Redirect URI and can't proceed with the authentication", HttpStatus.BAD_REQUEST);
    }

    String targetUrl = redirectUri.orElse(getDefaultTargetUrl());

    String token = jwtUtil.createToken(authentication);

    return UriComponentsBuilder.fromUriString(targetUrl)
            .queryParam("token", token)
            .build().toUriString();
}
 
Example 6
/**
 * 根据用户id 查询用户
 * @return
 */
@Test
public void get(){
	
	URI uri = UriComponentsBuilder
.fromUriString("http://localhost:8080/sbe/bootUser/{id}")
.build(1);
	User user = restTemplate.getForObject(uri, User.class);
	log.info("根据用户id 查询用户:"+"name:{},age:{}",user.getName(),user.getAge());
	
	RequestEntity<Void> req = RequestEntity.get(uri)
.accept(MediaType.APPLICATION_JSON_UTF8)
.build();
	ResponseEntity<User> responseEntity = restTemplate.exchange(req, User.class);
	User user2 = responseEntity.getBody();
	log.info("根据用户id 查询用户:"+"name:{},age:{}",user2.getName(),user2.getAge());
}
 
Example 7
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	for (Object contributor : this.contributors) {
		if (contributor instanceof UriComponentsContributor) {
			UriComponentsContributor ucc = (UriComponentsContributor) contributor;
			if (ucc.supportsParameter(parameter)) {
				ucc.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService);
				break;
			}
		}
		else if (contributor instanceof HandlerMethodArgumentResolver) {
			if (((HandlerMethodArgumentResolver) contributor).supportsParameter(parameter)) {
				break;
			}
		}
	}
}
 
Example 8
protected ServiceCallResponse callService(String serviceId,
											OAuth2AuthorizedClient authorizedClient,
											MultiValueMap<String, String> params) {

	ServicesConfig.ServiceConfig serviceConfig = this.servicesConfig.getConfig(serviceId);
	UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(serviceConfig.getUri());
	if (!params.isEmpty()) {
		uriBuilder.queryParams(params);
	}
	URI uri = uriBuilder.build().toUri();

	return this.webClient
			.get()
			.uri(uri)
			.attributes(oauth2AuthorizedClient(authorizedClient))
			.retrieve()
			.bodyToMono(ServiceCallResponse.class)
			.block();
}
 
Example 9
Source Project: gemfirexd-oss   Source File: ClientHttpRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the URL for the client's HTTP request.
 * <p/>
 * @param uriVariables a Map of URI path variables to values in order to expand the URI template into a URI.
 * @return a URL as a URI referring to the location of the resource requested by the client via HTTP.
 * @see #getURI()
 * @see java.net.URI
 * @see org.springframework.web.util.UriComponents
 * @see org.springframework.web.util.UriComponentsBuilder
 */
public URI getURL(final Map<String, ?> uriVariables) {
  final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(UriUtils.decode(getURI().toString()));

  if (isGet() || isDelete()) {
    final List<String> pathVariables = getPathVariables();

    // get query parameters to append to the URI/URL based on the request parameters that are not path variables...
    final Map<String, List<Object>> queryParameters = CollectionUtils.removeKeys(
      new LinkedMultiValueMap<String, Object>(getParameters()), new Filter<Map.Entry<String, List<Object>>>() {
        @Override public boolean accept(final Map.Entry<String, List<Object>> entry) {
          return !pathVariables.contains(entry.getKey());
        }
    });

    for (final String queryParameterName : queryParameters.keySet()) {
      uriBuilder.queryParam(queryParameterName, getParameters().get(queryParameterName).toArray());
    }
  }

  return uriBuilder.build().expand(uriVariables).encode().toUri();
}
 
Example 10
Source Project: alchemy   Source File: UserResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@code GET /users} : get all users.
 *
 * @param pageable the pagination information.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
 */
@GetMapping("/users")
public ResponseEntity<List<UserDTO>> getAllUsers(@RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder, Pageable pageable) {
    final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 11
Source Project: wallride   Source File: PostUtils.java    License: 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 12
Source Project: JuniperBot   Source File: DogSearchQuery.java    License: GNU General Public License v3.0 6 votes vote down vote up
public UriComponentsBuilder toUri() {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("images/search");
    if (size != null) {
        builder.queryParam("size", size.key);
    }
    if (CollectionUtils.isNotEmpty(mimeTypes)) {
        builder.queryParam("mime_types", mimeTypes.stream()
                .map(MimeType::getKey)
                .collect(Collectors.joining(",")));
    }
    if (format != null) {
        builder.queryParam("format", format.key);
    }
    if (hasBreeds != null) {
        builder.queryParam("has_breeds", hasBreeds.toString());
    }
    if (order != null) {
        builder.queryParam("order", order.key);
    }
    return builder
            .queryParam("page", page)
            .queryParam("limit", limit);
}
 
Example 13
Source Project: heimdall   Source File: OAuthInterceptorService.java    License: Apache License 2.0 6 votes vote down vote up
private void validateInProvider(Provider provider, String clientId, String accessToken) {
    if (provider.isProviderDefault()) {
        final App appActive = appRepository.findAppActive(clientId);

        final List<AccessToken> accessTokens = appActive.getAccessTokens();
        HeimdallException.checkThrow(accessTokens.stream().noneMatch(ac -> ac.getCode().equals(accessToken)), ExceptionMessage.PROVIDER_USER_UNAUTHORIZED);
    } else {

        RestTemplate template = new RestTemplate();
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(provider.getPath());

        try {
            ResponseEntity<String> entityResponse = template
                .exchange(uriComponentsBuilder.build().encode().toUri(), HttpMethod.POST, createHttpEntity(uriComponentsBuilder, provider.getProviderParams()), String.class);

            HeimdallException.checkThrow(!(Series.valueOf(entityResponse.getStatusCodeValue()) == Series.SUCCESSFUL), ExceptionMessage.PROVIDER_USER_UNAUTHORIZED);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new UnauthorizedException(ExceptionMessage.PROVIDER_USER_UNAUTHORIZED);
        }
    }
}
 
Example 14
public PartialTicketTextGenerator getTicketEmailGenerator(Event event, TicketReservation ticketReservation, Locale ticketLanguage) {
    return ticket -> {
        Organization organization = organizationRepository.getById(event.getOrganizationId());
        String ticketUrl = ticketUpdateUrl(event, ticket.getUuid());
        var ticketCategory = ticketCategoryRepository.getById(ticket.getCategoryId());

        var initialOptions = extensionManager.handleTicketEmailCustomText(event, ticketReservation, ticketReservationRepository.getAdditionalInfo(ticketReservation.getId()), ticketFieldRepository.findAllByTicketId(ticket.getId()))
            .map(CustomEmailText::toMap)
            .orElse(Map.of());
        if(event.getFormat() == Event.EventFormat.ONLINE) {
            initialOptions = new HashMap<>(initialOptions);
            var eventMetadata = Optional.ofNullable(eventRepository.getMetadataForEvent(event.getId()).getRequirementsDescriptions()).flatMap(m -> Optional.ofNullable(m.get(ticketLanguage.getLanguage())));
            var categoryMetadata = Optional.ofNullable(ticketCategoryRepository.getMetadata(event.getId(), ticketCategory.getId()).getRequirementsDescriptions()).flatMap(m -> Optional.ofNullable(m.get(ticketLanguage.getLanguage())));
            initialOptions.put("onlineCheckInUrl", ticketOnlineCheckIn(event, ticket.getUuid()));
            initialOptions.put("prerequisites", categoryMetadata.or(() -> eventMetadata).orElse(""));
        }
        var baseUrl = StringUtils.removeEnd(configurationManager.getFor(BASE_URL, ConfigurationLevel.event(event)).getRequiredValue(), "/");
        var calendarUrl = UriComponentsBuilder.fromUriString(baseUrl + "/api/v2/public/event/{eventShortName}/calendar/{currentLang}")
            .queryParam("type", "google")
            .build(Map.of("eventShortName", event.getShortName(), "currentLang", ticketLanguage.getLanguage()))
            .toString();
        return TemplateProcessor.buildPartialEmail(event, organization, ticketReservation, ticketCategory, templateManager, baseUrl, ticketUrl, calendarUrl, ticketLanguage, initialOptions).generate(ticket);
    };
}
 
Example 15
Source Project: bbs   Source File: SecureLink.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 生成视频重定向链接
 * @param link 链接
 * @param tagId 标签Id  -1表示管理后台打开链接,不校验权限
 * @param secret 密钥 16位字符
 * @return
 */
public static String createVideoRedirectLink(String link,Long tagId,String secret){
	Map<String,String> parameterMap = new HashMap<String,String>();
	parameterMap.put("link", link);
	parameterMap.put("tagId", String.valueOf(tagId));
	String parameter_json = JsonUtils.toJSONString(parameterMap);
	
	String ciphertext = AES.encrypt(parameter_json, secret, null);
	
	
	String newLink = UriComponentsBuilder.fromUriString("videoRedirect")
       .queryParam("jump", Base64.encodeBase64URL(ciphertext))
       .build().toString();
	
	return newLink;
}
 
Example 16
@Test
public void supportsParameter() {
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerWebExchange.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpRequest.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpResponse.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(HttpMethod.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Locale.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(TimeZone.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ZoneId.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriComponentsBuilder.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriBuilder.class)));

	assertFalse(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class)));
	assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class)));
	try {
		this.resolver.supportsParameter(this.testMethod.arg(Mono.class, ServerWebExchange.class));
		fail();
	}
	catch (IllegalStateException ex) {
		assertTrue("Unexpected error message:\n" + ex.getMessage(),
				ex.getMessage().startsWith(
						"ServerWebExchangeMethodArgumentResolver does not support reactive type wrapper"));
	}
}
 
Example 17
@Test
public void thymeleaf() throws MessagingException, IOException {
	RestTemplate rt = new RestTemplate();
	// @formatter:off
	UriComponentsBuilder builder = UriComponentsBuilder.fromPath(THYMELEAF_URL)
			.scheme("http")
			.host("localhost")
			.port(port)
			.queryParam("subject", "test")
			.queryParam("template", "register-thymeleaf")
			.queryParam("to", "[email protected]");
	RequestEntity<NestedBean> request = RequestEntity.
			post(builder.build().toUri()).
			contentType(MediaType.APPLICATION_JSON).
			body(new NestedBean(new SimpleBean("foo", 42)));
	// @formatter:on
	ResponseEntity<Void> response = rt.exchange(request, Void.class);
	assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode());
	AssertEmail.assertEquals(
			new ExpectedEmail("test", new ExpectedContent(getClass().getResourceAsStream("/expected/ogham/register_foo_42.html"), "text/html.*"), "[email protected]", "[email protected]"),
			greenMail.getReceivedMessages());
}
 
Example 18
@Test
public void thymeleaf() throws MessagingException, IOException {
	RestTemplate rt = new RestTemplate();
	// @formatter:off
	UriComponentsBuilder builder = UriComponentsBuilder.fromPath(THYMELEAF_URL)
			.scheme("http")
			.host("localhost")
			.port(port)
			.queryParam("subject", "test")
			.queryParam("template", "register-thymeleaf")
			.queryParam("to", "[email protected]");
	RequestEntity<NestedBean> request = RequestEntity.
			post(builder.build().toUri()).
			contentType(MediaType.APPLICATION_JSON).
			body(new NestedBean(new SimpleBean("foo", 42)));
	// @formatter:on
	ResponseEntity<Void> response = rt.exchange(request, Void.class);
	assertEquals("HTTP status should be 201: Created", HttpStatus.CREATED, response.getStatusCode());
	AssertEmail.assertEquals(
			new ExpectedEmail("test", new ExpectedContent(getClass().getResourceAsStream("/expected/spring/register_foo_42.html"), "text/html.*"), "[email protected]", "[email protected]"),
			greenMail.getReceivedMessages());
}
 
Example 19
Source Project: spring-cloud-commons   Source File: LoadBalancerUriTools.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean containsEncodedParts(URI uri) {
	boolean encoded = (uri.getRawQuery() != null
			&& uri.getRawQuery().contains(PERCENTAGE_SIGN))
			|| (uri.getRawPath() != null
					&& uri.getRawPath().contains(PERCENTAGE_SIGN))
			|| (uri.getRawFragment() != null
					&& uri.getRawFragment().contains(PERCENTAGE_SIGN));
	// Verify if it is really fully encoded. Treat partial encoded as unencoded.
	if (encoded) {
		try {
			UriComponentsBuilder.fromUri(uri).build(true);
			return true;
		}
		catch (IllegalArgumentException ignore) {
		}
		return false;
	}
	return false;
}
 
Example 20
Source Project: wallride   Source File: ArticleSearchController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(params = "query")
public String search(
        @PathVariable String language,
        String query,
        Model model,
        SessionStatus sessionStatus,
        RedirectAttributes redirectAttributes) {
    sessionStatus.setComplete();

    for (Map.Entry<String, Object> mapEntry : model.asMap().entrySet()) {
        redirectAttributes.addFlashAttribute(mapEntry.getKey(), mapEntry.getValue());
    }
    String url = UriComponentsBuilder.fromPath("/_admin/{language}/articles/index")
            .query(query)
            .buildAndExpand(language)
            .encode()
            .toUriString();
    return "redirect:" + url;
}
 
Example 21
Source Project: spring-analysis-note   Source File: MvcUriComponentsBuilder.java    License: MIT License 6 votes vote down vote up
private static UriComponentsBuilder applyContributors(UriComponentsBuilder builder, Method method, Object... args) {
	CompositeUriComponentsContributor contributor = getUriComponentsContributor();

	int paramCount = method.getParameterCount();
	int argCount = args.length;
	if (paramCount != argCount) {
		throw new IllegalArgumentException("Number of method parameters " + paramCount +
				" does not match number of argument values " + argCount);
	}

	final Map<String, Object> uriVars = new HashMap<>();
	for (int i = 0; i < paramCount; i++) {
		MethodParameter param = new SynthesizingMethodParameter(method, i);
		param.initParameterNameDiscovery(parameterNameDiscoverer);
		contributor.contributeMethodArgument(param, args[i], builder, uriVars);
	}

	// This may not be all the URI variables, supply what we have so far..
	return builder.uriVariables(uriVars);
}
 
Example 22
@Test
public void convert_map_to_uri_spring() {

	MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
	for (Entry<String, String> entry : mapToConvert.entrySet()) {
		params.add(entry.getKey(), entry.getValue());
	}

	UriComponents uriComponents = UriComponentsBuilder.newInstance()
			.scheme("http").host("www.leveluplunch.com")
			.queryParams(params).build();

	assertEquals(
			"http://www.leveluplunch.com?end-date=2014-11-26&itemsPerPage=25",
			uriComponents.toUriString());
}
 
Example 23
@Test
public void shouldFilterWhenGatewayRequestUrlSchemeIsForward() {
	URI uri = UriComponentsBuilder.fromUriString("forward://endpoint").build()
			.toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);

	assertThat(exchange.getAttributes().get(GATEWAY_ALREADY_ROUTED_ATTR)).isNull();

	forwardRoutingFilter.filter(exchange, chain);

	verifyNoMoreInteractions(chain);
	verify(dispatcherHandler).handle(exchange);

	assertThat(exchange.getAttributes().get(GATEWAY_ALREADY_ROUTED_ATTR)).isNull();
}
 
Example 24
Source Project: java-technology-stack   Source File: MvcUriComponentsBuilder.java    License: MIT License 5 votes vote down vote up
/**
 * An alternative to {@link #fromController(Class)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param controllerType the controller to build a URI for
 * @return a UriComponentsBuilder instance (never {@code null})
 */
public static UriComponentsBuilder fromController(@Nullable UriComponentsBuilder builder,
		Class<?> controllerType) {

	builder = getBaseUrlToUse(builder);

	// Externally configured prefix via PathConfigurer..
	String prefix = getPathPrefix(controllerType);
	builder.path(prefix);

	String mapping = getClassMapping(controllerType);
	builder.path(mapping);

	return builder;
}
 
Example 25
Source Project: bbs   Source File: SecureLink.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 生成安全链接
 * @param link 链接
 * @param fileName 文件名称
 * @param secret 密钥
 * @param expires 有效时间 单位/秒
 * @return
 */
public static String createSecureLink(String link,String fileName,String secret,Long expires){
	String time = String.valueOf((System.currentTimeMillis() / 1000) + expires);
	String md5 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(DigestUtils.md5(secret +  Configuration.getPath()+"/"+link + time));
	
	String newLink = UriComponentsBuilder.fromUriString(link)
       .replaceQueryParam("md5", md5)
       .replaceQueryParam("expires", time)
       .replaceQueryParam("fileName", fileName)
       .build().toString();
	
	return newLink;
}
 
Example 26
Source Project: tutorials   Source File: FooController.java    License: MIT License 5 votes vote down vote up
@GetMapping(params = { "page", "size" })
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size,
    final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
    final Page<Foo> resultPage = service.findPaginated(page, size);
    if (page > resultPage.getTotalPages()) {
        throw new MyResourceNotFoundException();
    }
    eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page,
        resultPage.getTotalPages(), size));

    return resultPage.getContent();
}
 
Example 27
Source Project: jetlinks-community   Source File: WechatMessageTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public UriComponentsBuilder createUriParameter(UriComponentsBuilder builder, Values context){
    builder.queryParam("agentid", this.getAgentId())
            .queryParam("msgtype","text")
            .queryParam("text",this.createMessage(context));
    if (StringUtils.hasText(toUser)) {
        builder.queryParam("touser", this.createUserIdList(context));
    }
    if (StringUtils.hasText(toParty)) {
        builder.queryParam("toparty", this.createDepartmentIdList(context));
    }
    return builder;
}
 
Example 28
Source Project: Spring-5.0-By-Example   Source File: FareResource.java    License: MIT License 5 votes vote down vote up
@PostMapping
public Mono<ResponseEntity<Fare>> requestFare(@RequestBody FareQuery fareQuery,UriComponentsBuilder uriBuilder){
  return this.fareService.requestFare(fareQuery).map(data -> {
    URI location = uriBuilder.path("/fares/{id}")
        .buildAndExpand(data.getId())
        .toUri();
    return ResponseEntity.created(location).build();
  });
}
 
Example 29
@Test
public void delete(){
	URI uri = UriComponentsBuilder
.fromUriString("http://localhost:8080/sbe/bootUser/{id}")
.build(1);
	restTemplate.delete(uri);
}
 
Example 30
@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());
}