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

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

Introduction

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

Prototype

public static UriComponentsBuilder fromHttpUrl(String httpUrl) 

Source Link

Document

Create a URI components builder from the given HTTP URL String.

Usage

From source file:gov.fda.open.demo.service.FDADataProxyServiceImplTest.java

/**
 * Test get drug summary not found./*from  www  .j a  va 2s .  c om*/
 */
@SuppressWarnings("serial")
@Test
@Loggable(LogLevel.OFF)
public void testGetDrugSummaryNotFound() {

    // Execute
    GetDrugAdverseSummaryRequest request = new GetDrugAdverseSummaryRequest(DRUG_NAME_2);

    // Setup Mock
    SearchTermBuilder searchParamBuilder = new SearchTermBuilder();
    searchParamBuilder.exists(request.getSummaryType().getField()).and()
            .appendTerm(MEDICINAL_PRODUCT, request.getDrugName()).and()
            .between(RECEIVED_DATE, request.getStartDate(), request.getEndDate());
    // build query String
    String searchTerm = searchParamBuilder.toString();

    StringBuilder drugURL = new StringBuilder(URI_VALUE);
    drugURL.append(FDADataProxyServiceImpl.DRUG_EVENT_SEARCH_URL);

    final Map<String, String> params = new HashMap<String, String>();
    params.put(SEARCH_KEY, searchTerm);
    params.put(APP_KEY, APP_VALUE);
    params.put(LIMIT_KEY, String.valueOf(100));
    params.put(SKIP_KEY, String.valueOf(0));

    URI httpUri = UriComponentsBuilder.fromHttpUrl(drugURL.toString()).buildAndExpand(params).toUri();

    // / Test case when HttpClientException is throw
    when(template.getForObject(httpUri, String.class))
            .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND) {
                @Override
                public String getResponseBodyAsString() {
                    return "{ \"error\": { \"code\": \"NOT_FOUND\", \"message\": \"No matches found!\" } }";
                }
            });

    GetDrugAdverseSummaryResponse response = fdaDataProxyService.getDrugAdverseSummary(request);
    assertNotNull(response);
    assertFalse(response.isSuccess());
    assertNotNull(response.getErrorCode());
    assertNotNull(response.getMessage());

}

From source file:minium.cucumber.rest.RemoteBackend.java

protected UriComponentsBuilder uriBuilderFor(String path) {
    return UriComponentsBuilder.fromHttpUrl(backendUrl + path);
}

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

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

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

    // Call remotelog once the access token has expired (we wait enough to make sure it has expired)
    Thread.sleep(getTokenExpirationDelayInSeconds() * 1000);

    // Call remotelog        
    result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    assertTrue(result.getBody().contains("Access token expired"));

    // Refresh the token
    refreshToken();/*from w w w.j a va2  s .c o m*/

    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(resourceServerBaseUrl + 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 source file:com.orange.ngsi2.client.Ngsi2Client.java

/**
 * Update existing or append some attributes to an entity
 * @param entityId the entity ID/*from   w  w w  .ja va2s.co  m*/
 * @param type optional entity type to avoid ambiguity when multiple entities have the same ID, null or zero-length for empty
 * @param attributes the attributes to update or to append
 * @param append if true, will only allow to append new attributes
 * @return the listener to notify of completion
 */
public ListenableFuture<Void> updateEntity(String entityId, String type, Map<String, Attribute> attributes,
        boolean append) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}");
    addParam(builder, "type", type);
    if (append) {
        addParam(builder, "options", "append");
    }
    return adapt(
            request(HttpMethod.POST, builder.buildAndExpand(entityId).toUriString(), attributes, Void.class));
}

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 w w . 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);
}

From source file:com.epam.training.storefront.controllers.pages.payment.PaymentDetailsPageController.java

@ModelAttribute("checkoutSteps")
public List<CheckoutSteps> addCheckoutStepsToModel(final HttpServletRequest request) {
    final String baseUrl = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
            .replacePath(request.getContextPath()).build().toUriString();

    return MultiStepCheckoutController.createCheckoutSteps(baseUrl);
}

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

@Test
public void obtainTokenFromOuth2LoginEndpoint() throws Exception {
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2AuthorizeEndpointPath);
    builder.queryParam("username", getUsername());
    builder.queryParam("password", getPassword());
    builder.queryParam("client_id", getClientId());
    builder.queryParam("response_type", "token");
    builder.queryParam("redirect_uri", "http://anywhere");

    HttpEntity<String> entity = new HttpEntity<>("");
    ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);

    // This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token.
    // Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the 
    // redirect_uri with the token after #
    assertEquals(HttpStatus.FOUND, result2.getStatusCode());

    // Obtain the token from redirection URL after #
    URI location = result2.getHeaders().getLocation();
    accessToken = extractToken(location.getFragment().toString());
    assertNotNull(accessToken);//from w  ww. j a va  2 s. co m

    if (!isJwtTokenStore) {
        // Temporarily we can't not apply the default token enhacer adding the authorities if we use a JwtTokenStore
        // TODO: Put again the login endpoint separated for CSRF and return the authorities there

        // Obtain the user credentials from redirection URL after #
        String extractUserAuthorities = extractUserAuthorities(location.getFragment().toString());
        assertNotNull(extractUserAuthorities);
    }
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping("/login-tester")
public @ResponseBody String jvoidLoginTester(@RequestParam("params") String jsonParams) {
    System.out.println("login-tester: jsonParams=>" + jsonParams);

    JSONObject jsonObj = null;/*from w w w. j  a va  2s  .  c  o m*/
    try {
        jsonObj = new JSONObject(jsonParams);
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println("Login-tester:jsonObj=>" + jsonObj);

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:9080/jvoidcore/login")
            .queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.POST, entity,
            String.class);
    System.out.println("returnString=>" + returnString);

    JSONObject returnJsonObj = null;
    try {
        returnJsonObj = new JSONObject();
        returnJsonObj.put("result", returnString);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return returnJsonObj.toString();
}

From source file:com.orange.ngsi2.client.Ngsi2Client.java

/**
 * Replace all the existing attributes of an entity with a new set of attributes
 * @param entityId the entity ID//from www .  ja  va2s . com
 * @param type optional entity type to avoid ambiguity when multiple entities have the same ID, null or zero-length for empty
 * @param attributes the new set of attributes
 * @return the listener to notify of completion
 */
public ListenableFuture<Void> replaceEntity(String entityId, String type, Map<String, Attribute> attributes) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}");
    addParam(builder, "type", type);
    return adapt(
            request(HttpMethod.PUT, builder.buildAndExpand(entityId).toUriString(), attributes, Void.class));
}

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

@Test
public void obtainAuthorizationCode() throws Exception {
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2AuthorizeEndpointPath);
    builder.queryParam("username", getUsername());
    builder.queryParam("password", getPassword());
    builder.queryParam("client_id", getClientId());
    builder.queryParam("response_type", "code");
    builder.queryParam("redirect_uri", "http://anywhere");
    // builder.queryParam("realm","oauth2-resource");

    // optional builder.queryParam("scope", "");
    // recommended (optional) builder.queryParam("state", "");

    //HttpEntity<String> entity = new HttpEntity("",headers);
    HttpEntity<String> entity = new HttpEntity("");
    ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);

    // check this! assertEquals(HttpStatus.FOUND, result2.getStatusCode());        

    // Obtain the token from redirection URL after #
    URI location = result2.getHeaders().getLocation();
    authorizationCode = extractAuthorizationCode(location.toString());
    assertNotNull(authorizationCode);/*from w  w w  . ja v a  2s. c o  m*/
}