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:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getArticlesAround(@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);//ww w  . j  a v  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");

        if ((Boolean) ratingMap.get("appropriate")) {
            mappedResponseObjects.get(articleID).putAll(ratingMap);
        } else {
            mappedResponseObjects.remove(articleID);
        }
    }

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

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

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

@Test
public void testRemoteLogIsProtected() throws Exception {
    RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO();
    remoteLogRequest.setLogLevel("DEBUG");
    remoteLogRequest.setMessage("This is my log message!");

    // We call remote log WITHOUT the access token
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath);
    ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);

    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    assertTrue("Wrong header: " + result.getHeaders(),
            result.getHeaders().getFirst("WWW-Authenticate").startsWith("Bearer realm="));
}

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

/**
 * @see DATAREST-160//  w w w  . j  a va2  s .  co m
 */
@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:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.implicit.Oauth2ImplicitFlowPredefinedTests.java

@Test
public void oauth2FlowTest() throws Exception {
    // Obtains the token
    obtainTokenFromOuth2LoginEndpoint();

    // Call remotelog        
    ResponseEntity<String> result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.OK, result.getStatusCode());

    if (!isJwtTokenStore) {
        // The following code is executed only if the token store is not a JwtTokenStore. The reason is that using this kind of store
        // the tokens can't be revoked (they just expire) and so this part of the test would fail.
        // A JwtTokenStore is not a proper store as the tokens are not stored anywhere (as they contain all the required info about the user
        // themselves. That's why the token revocation is not possible.
        // We call logout endpoint (we need to use the access token for this)
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(authServerBaseUrl + baseApiPath + oauth2LogoutEndpointPath);
        builder.queryParam("access_token", accessToken);

        ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(),
                HttpMethod.POST, null, String.class);
        assertEquals(HttpStatus.OK, result2.getStatusCode());

        // We try to call the protected API again (after having logged out which removes the token) - We expect not to be able to call the service.
        // This will throw a exception. In this case here in the test we receive an exception but really what happened was 'access denied'
        // A production client will receive the proper http error
        result = callRemoteLogWithAccessToken();
        assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    }/*from www.ja va  2  s.  c om*/
}

From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey()).queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code").queryParam("redirect_uri", getCallbackUrl());

    return uriBuilder.build().encode().toUriString();
}

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

@Test
public void basicAuthenticationRemoteLogServiceEnabledTest() throws Exception {
    TestLoginInfo loginInfo = login();//w  ww  .  j a  va  2  s  . co m

    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    // This test requires the test CSRF Token. This implies passing JSESSIONID and CSRF Token
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

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

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

@Test
public void simpleAuthenticationRemoteLogServiceEnabledTest() throws Exception {
    TestLoginInfo loginInfo = simpleLogin();

    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    // This test requires the test CSRF Token. This implies passing JSESSIONID and CSRF Token
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

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

From source file:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java

private UriComponents uriComponents() {
    URL url = webRequest.getUrl();
    UriComponentsBuilder uriBldr = UriComponentsBuilder.fromUriString(url.toExternalForm());
    return uriBldr.build();
}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

protected ResponseEntity<String> callRemoteLogWithAccessToken() {
    RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO();
    remoteLogRequest.setLogLevel("DEBUG");
    remoteLogRequest.setMessage("This is my log message!");

    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath);
    builder.queryParam("access_token", accessToken);

    ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);
    return result;
}

From source file:edu.harvard.i2b2.fhir.FetchInterceptor.java

void alterResponse(HttpServletResponse response, String path) throws IOException {
    ourLog.info("altering response");

    RestTemplate restTemplate = new MyGlobal().getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/json");

    HttpEntity entity = new HttpEntity(headers);
    Map<String, String> params = new HashMap<String, String>();
    String url = "http://localhost:8080/fhirRest/" + path;
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    HttpEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET,
            entity, String.class);
    String responseTxt = responseEntity.getBody();
    response.getWriter().println(responseTxt);

}