org.springframework.web.util.UriComponentsBuilder Java Examples

The following examples show how to use org.springframework.web.util.UriComponentsBuilder. 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: PatreonAPI.java    From JuniperBot with 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
Source File: OghamAutoConfigurationOghamPropertiesPrecedenceTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: CompositeUriComponentsContributor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: OghamAutoConfigurationSpringPropertiesOnlyTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: LoadBalancerUriTools.java    From spring-cloud-commons with 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 #6
Source File: RestTemplateDemoController.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
/**
 * 根据用户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
Source File: ArticleSearchController.java    From wallride with 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 #8
Source File: UserResource.java    From alchemy with 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 #9
Source File: SecureLink.java    From bbs with 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 #10
Source File: OAuth2AuthenticationSuccessHandler.java    From spring-boot-react-blog with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: AbstractFlowController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: ClientHttpRequest.java    From gemfirexd-oss with 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 #13
Source File: JWTSecurityService.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
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 #14
Source File: MvcUriComponentsBuilder.java    From spring-analysis-note with 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 #15
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 #16
Source File: TransformMapToQueryString.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: TicketReservationManager.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
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 #18
Source File: UserRestController.java    From jeecg with 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 #19
Source File: DogSearchQuery.java    From JuniperBot with 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 #20
Source File: OAuthInterceptorService.java    From heimdall with 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 #21
Source File: RequestMappingHandlerAdapterIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
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 #22
Source File: ServerWebExchangeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #23
Source File: MvcUriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromControllerWithCustomBaseUrlViaInstance() {
	UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://example.org:9090/base");
	MvcUriComponentsBuilder mvcBuilder = MvcUriComponentsBuilder.relativeTo(builder);
	UriComponents uriComponents = mvcBuilder.withController(PersonControllerImpl.class).build();

	assertEquals("http://example.org:9090/base/people", uriComponents.toString());
	assertEquals("http://example.org:9090/base", builder.toUriString());
}
 
Example #24
Source File: AuditResource.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
/**
 * {@code GET /audits} : get a page of {@link AuditEvent}s.
 *
 * @param pageable the pagination information.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body.
 */
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(@RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder, Pageable pageable) {
    Page<AuditEvent> page = auditEventService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example #25
Source File: RequestContextUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Convenience method that retrieves the {@link #getOutputFlashMap "output"
 * FlashMap}, updates it with the path and query params of the target URL,
 * and then saves it using the {@link #getFlashMapManager FlashMapManager}.
 * @param location the target URL for the redirect
 * @param request the current request
 * @param response the current response
 * @since 5.0
 */
public static void saveOutputFlashMap(String location, HttpServletRequest request, HttpServletResponse response) {
	FlashMap flashMap = getOutputFlashMap(request);
	if (CollectionUtils.isEmpty(flashMap)) {
		return;
	}

	UriComponents uriComponents = UriComponentsBuilder.fromUriString(location).build();
	flashMap.setTargetRequestPath(uriComponents.getPath());
	flashMap.addTargetRequestParams(uriComponents.getQueryParams());

	FlashMapManager manager = getFlashMapManager(request);
	Assert.state(manager != null, "No FlashMapManager. Is this a DispatcherServlet handled request?");
	manager.saveOutputFlashMap(flashMap, request, response);
}
 
Example #26
Source File: QQAuthServiceImpl.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Response<String> getOpenId(String accessToken) {
    String url = String.format(OPEN_ID_URL, accessToken);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();

    String resp = getRestTemplate().getForObject(uri, String.class);
    if (resp != null && resp.contains("openid")) {
        JSONObject jsonObject = ConvertToJson(resp);
        String openid = jsonObject.getString("openid");
        return Response.yes(openid);
    }
    log.error("QQ获得openid失败,resp:{}", resp);
    return Response.no(resp);
}
 
Example #27
Source File: PublishedBlogResource.java    From ddd-architecture-samples with MIT License 5 votes vote down vote up
@PostMapping(consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<?> post(@RequestBody PublishBlogRequest data, UriComponentsBuilder uriComponentsBuilder) {
    Blog blog = editBlogUseCase.publish(data.blogId);

    UriComponents uriComponents = uriComponentsBuilder.path("/published-blog/{id}").buildAndExpand(blog.getId());
    return ResponseEntity.created(uriComponents.toUri()).body(PublishedBlogDto.of(blog));
}
 
Example #28
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 #29
Source File: DefaultApplicationFactory.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
protected String getHealthUrl() {
	if (instance.getHealthUrl() != null) {
		return instance.getHealthUrl();
	}
	return UriComponentsBuilder.fromHttpUrl(getManagementBaseUrl()).path("/").path(getHealthEndpointPath())
			.toUriString();
}
 
Example #30
Source File: DockerOAuth2RegistryAuthorizer.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHeaders getAuthorizationHeaders(ContainerImage containerImage, RegistryConfiguration registryConfiguration) {

	Assert.isTrue(registryConfiguration.getAuthorizationType() == this.getType(),
			"Incorrect authorization type: " + registryConfiguration.getAuthorizationType());

	Assert.notNull(containerImage, "Valid containerImageName is required!");
	String imageRepository = containerImage.getRepository();
	Assert.hasText(imageRepository, "Valid repository name (e.g. namespace/repository-name without the tag)" +
			" is required for the authorization");

	final HttpHeaders requestHttpHeaders = new HttpHeaders();
	if (StringUtils.hasText(registryConfiguration.getUser()) && StringUtils.hasText(registryConfiguration.getSecret())) {
		// Use basic authentication to obtain the authorization token.
		// Usually the public docker hub authorization service doesn't require authentication for image pull requests.
		requestHttpHeaders.setBasicAuth(registryConfiguration.getUser(), registryConfiguration.getSecret());
	}

	String registryAuthUri = registryConfiguration.getExtra().containsKey(DOCKER_REGISTRY_AUTH_URI_KEY) ?
			registryConfiguration.getExtra().get(DOCKER_REGISTRY_AUTH_URI_KEY) : DEFAULT_DOCKER_REGISTRY_AUTH_URI;
	UriComponents uriComponents = UriComponentsBuilder.newInstance()
			.fromHttpUrl(registryAuthUri).build().expand(imageRepository);

	ResponseEntity<Map> authorization = this.getRestTemplate(registryConfiguration)
			.exchange(uriComponents.toUri(), HttpMethod.GET, new HttpEntity<>(requestHttpHeaders), Map.class);

	Map<String, String> authorizationBody = (Map<String, String>) authorization.getBody();

	final HttpHeaders responseHttpHeaders = new HttpHeaders();
	responseHttpHeaders.setBearerAuth(authorizationBody.get(TOKEN_KEY));
	return responseHttpHeaders;
}