Example usage for org.springframework.web.util UriComponentsBuilder build

List of usage examples for org.springframework.web.util UriComponentsBuilder build

Introduction

In this page you can find the example usage for org.springframework.web.util UriComponentsBuilder build.

Prototype

public UriComponents build() 

Source Link

Document

Build a UriComponents instance from the various components contained in this builder.

Usage

From source file:org.jasig.cas.web.flow.FrontChannelLogoutAction.java

@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response,
        final RequestContext context) throws Exception {

    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    final Integer startIndex = getLogoutIndex(context);
    if (logoutRequests != null && startIndex != null) {
        for (int i = startIndex; i < logoutRequests.size(); i++) {
            final LogoutRequest logoutRequest = logoutRequests.get(i);
            if (logoutRequest.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED) {
                // assume it has been successful
                logoutRequest.setStatus(LogoutRequestStatus.SUCCESS);

                // save updated index
                putLogoutIndex(context, i + 1);

                // redirect to application with SAML logout message
                final UriComponentsBuilder builder = UriComponentsBuilder
                        .fromHttpUrl(logoutRequest.getService().getId());
                builder.queryParam("SAMLRequest", URLEncoder
                        .encode(logoutManager.createFrontChannelLogoutMessage(logoutRequest), "UTF-8"));
                return result(REDIRECT_APP_EVENT, "logoutUrl", builder.build().toUriString());
            }//from   w w w.j  ava  2 s  .co m
        }
    }

    // no new service with front-channel logout -> finish logout
    return new Event(this, FINISH_EVENT);
}

From source file:com.example.securelogin.domain.service.passwordreissue.PasswordReissueServiceImpl.java

@Override
public String createAndSendReissueInfo(String username) {

    String rowSecret = passwordGenerator.generatePassword(10, passwordGenerationRules);

    if (!accountSharedService.exists(username)) {
        return rowSecret;
    }//ww w  .  j av  a  2 s .  c o  m

    Account account = accountSharedService.findOne(username);

    String token = UUID.randomUUID().toString();

    LocalDateTime expiryDate = dateFactory.newTimestamp().toLocalDateTime().plusSeconds(tokenLifeTimeSeconds);

    PasswordReissueInfo info = new PasswordReissueInfo();
    info.setUsername(username);
    info.setToken(token);
    info.setSecret(passwordEncoder.encode(rowSecret));
    info.setExpiryDate(expiryDate);

    passwordReissueInfoRepository.create(info);

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance();
    uriBuilder.scheme(protocol).host(host).port(port).path(contextPath).pathSegment("reissue")
            .pathSegment("resetpassword").queryParam("form").queryParam("token", info.getToken());
    String passwordResetUrl = uriBuilder.build().toString();

    mailSharedService.send(account.getEmail(), passwordResetUrl);

    return rowSecret;

}

From source file:org.springframework.data.rest.webmvc.config.RepositoryRestMvConfigurationIntegrationTests.java

/**
 * @see DATAREST-271/*from   w  w w .  j a va 2  s .co m*/
 */
@Test
public void assetConsidersPaginationCustomization() {

    HateoasPageableHandlerMethodArgumentResolver resolver = context
            .getBean(HateoasPageableHandlerMethodArgumentResolver.class);

    UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
    resolver.enhance(builder, null, new PageRequest(0, 9000, Direction.ASC, "firstname"));

    MultiValueMap<String, String> params = builder.build().getQueryParams();

    assertThat(params.containsKey("myPage"), is(true));
    assertThat(params.containsKey("mySort"), is(true));

    assertThat(params.get("mySize"), hasSize(1));
    assertThat(params.get("mySize").get(0), is("7000"));
}

From source file:org.mitre.openid.connect.client.service.impl.TestSignedAuthRequestUrlBuilder.java

/**
 * This test takes the URI from the result of building a signed request
 * and checks that the JWS object parsed from the request URI matches up
 * with the expected claim values./*w  w  w.ja v  a 2  s. c  o  m*/
 */
@Test
public void buildAuthRequestUrl() {

    String requestUri = urlBuilder.buildAuthRequestUrl(serverConfig, clientConfig, redirectUri, nonce, state,
            options, null);

    // parsing the result
    UriComponentsBuilder builder = null;

    try {
        builder = UriComponentsBuilder.fromUri(new URI(requestUri));
    } catch (URISyntaxException e1) {
        fail("URISyntaxException was thrown.");
    }

    UriComponents components = builder.build();
    String jwtString = components.getQueryParams().get("request").get(0);
    JWTClaimsSet claims = null;

    try {
        SignedJWT jwt = SignedJWT.parse(jwtString);
        claims = jwt.getJWTClaimsSet();
    } catch (ParseException e) {
        fail("ParseException was thrown.");
    }

    assertEquals(responseType, claims.getClaim("response_type"));
    assertEquals(clientConfig.getClientId(), claims.getClaim("client_id"));

    List<String> scopeList = Arrays.asList(((String) claims.getClaim("scope")).split(" "));
    assertTrue(scopeList.containsAll(clientConfig.getScope()));

    assertEquals(redirectUri, claims.getClaim("redirect_uri"));
    assertEquals(nonce, claims.getClaim("nonce"));
    assertEquals(state, claims.getClaim("state"));
    for (String claim : options.keySet()) {
        assertEquals(options.get(claim), claims.getClaim(claim));
    }
}

From source file:org.mitre.openid.connect.client.service.impl.TestSignedAuthRequestUrlBuilder.java

@Test
public void buildAuthRequestUrl_withLoginHint() {

    String requestUri = urlBuilder.buildAuthRequestUrl(serverConfig, clientConfig, redirectUri, nonce, state,
            options, loginHint);//from  w w w.  j a va 2s . co m

    // parsing the result
    UriComponentsBuilder builder = null;

    try {
        builder = UriComponentsBuilder.fromUri(new URI(requestUri));
    } catch (URISyntaxException e1) {
        fail("URISyntaxException was thrown.");
    }

    UriComponents components = builder.build();
    String jwtString = components.getQueryParams().get("request").get(0);
    JWTClaimsSet claims = null;

    try {
        SignedJWT jwt = SignedJWT.parse(jwtString);
        claims = jwt.getJWTClaimsSet();
    } catch (ParseException e) {
        fail("ParseException was thrown.");
    }

    assertEquals(responseType, claims.getClaim("response_type"));
    assertEquals(clientConfig.getClientId(), claims.getClaim("client_id"));

    List<String> scopeList = Arrays.asList(((String) claims.getClaim("scope")).split(" "));
    assertTrue(scopeList.containsAll(clientConfig.getScope()));

    assertEquals(redirectUri, claims.getClaim("redirect_uri"));
    assertEquals(nonce, claims.getClaim("nonce"));
    assertEquals(state, claims.getClaim("state"));
    for (String claim : options.keySet()) {
        assertEquals(options.get(claim), claims.getClaim(claim));
    }
    assertEquals(loginHint, claims.getClaim("login_hint"));
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception {
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode());
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void simpleAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception {
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode());
}

From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java

private String makeAggregateCounterUrl(TimeSeriesType timeSeriesType, TimeSeriesDataRequest dataRequest) {

    String baseUrl = String.format(aggregateCounterUrlPattern, xdServerBaseUrl, dataRequest.getHouseId(),
            timeSeriesType.name().toLowerCase());

    UriComponentsBuilder ucb = UriComponentsBuilder.fromHttpUrl(baseUrl)
            .queryParam("resolution", dataRequest.getResolution().name().toLowerCase())
            .queryParam("from", dataRequest.getFromDateTime()).queryParam("to", dataRequest.getToDateTime());

    String url = ucb.build().toString();

    return url;//from   w  w w. j  a  va 2 s . c om
}

From source file:org.springframework.data.rest.webmvc.mongodb.MongoWebTests.java

/**
 * @see DATAREST-160//from w ww.java  2s  . com
 */
@Test
public void returnConflictWhenConcurrentlyEditingVersionedEntity() throws Exception {

    Link receiptLink = client.discoverUnique("receipts");

    Receipt receipt = new Receipt();
    receipt.amount = new BigDecimal(50);
    receipt.saleItem = "Springy Tacos";

    String stringReceipt = mapper.writeValueAsString(receipt);

    MockHttpServletResponse createdReceipt = postAndGet(receiptLink, stringReceipt, MediaType.APPLICATION_JSON);
    Link tacosLink = client.assertHasLinkWithRel("self", createdReceipt);
    assertJsonPathEquals("$.saleItem", "Springy Tacos", createdReceipt);

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(tacosLink.getHref());
    String concurrencyTag = createdReceipt.getHeader("ETag");

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
            .contentType(MediaType.APPLICATION_JSON).header("If-Match", concurrencyTag))
            .andExpect(status().is2xxSuccessful());

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
            .contentType(MediaType.APPLICATION_JSON).header("If-Match", concurrencyTag))
            .andExpect(status().isPreconditionFailed());
}

From source file:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles/new", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getNewArticlesAround(@RequestParam Double lat, @RequestParam Double lon)
        throws InterruptedException, ExecutionException, JsonProcessingException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(GEO_URL).queryParam("lat", lat.toString())
            .queryParam("lon", lon.toString());

    RestTemplate template = new RestTemplate();
    List<Map<String, Object>> geoResponse = template.getForObject(builder.build().encode().toUri(), List.class);

    Iterator<Map<String, Object>> it = geoResponse.iterator();
    List<Future<ResponseEntity<Map>>> jobs = new ArrayList<>();

    // to be able to merge answers from rating to geoitems there is a need 
    // to map the article to its articleID
    // (articleID) => (articleItem)
    Map<String, Map<String, Object>> mappedResponseObjects = new HashMap<>();
    while (it.hasNext()) {
        Map<String, Object> item = it.next();

        AsyncRestTemplate async = new AsyncRestTemplate();
        Future<ResponseEntity<Map>> futureResult = async.getForEntity((String) item.get("rating"), Map.class);
        jobs.add(futureResult);/*from w  ww  .jav a 2s  .co m*/
        mappedResponseObjects.put((String) item.get("articleID"), item);
    }

    for (Future<ResponseEntity<Map>> job : jobs) {
        Map<String, Object> ratingMap = job.get().getBody();
        String articleID = (String) ratingMap.get("articleID");

        mappedResponseObjects.get(articleID).putAll(ratingMap);
    }

    WeightingPolicy policy = new WeightingPolicyImpl();
    List<Map<String, Object>> orderedResponse = policy.sortExcludingRating(mappedResponseObjects.values());
    List<Map<String, Object>> result = new ResponseMapFilterImpl().filter(orderedResponse);

    return new ResponseEntity<>(objectMapper.writeValueAsString(result), HttpStatus.OK);
}