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:id.co.teleanjar.ppobws.restclient.RestClientService.java

public Map<String, Object> inquiry(String idpel, String idloket, String merchantCode) throws IOException {
    String uri = "http://localhost:8080/ppobws/api/produk";
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = createHeaders("superuser", "passwordku");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri).queryParam("idpel", idpel)
            .queryParam("idloket", idloket).queryParam("merchantcode", merchantCode);
    HttpEntity<?> entity = new HttpEntity<>(headers);

    ResponseEntity<String> httpResp = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET,
            entity, String.class);
    String json = httpResp.getBody();
    LOGGER.info("JSON [{}]", json);
    LOGGER.info("STATUS [{}]", httpResp.getStatusCode().toString());

    Map<String, Object> map = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();

    map = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {
    });/*from  w  ww  .  j  a  v  a 2s  .  c  o m*/
    return map;
}

From source file:com.wavemaker.tools.deployment.tomcat.TomcatManager.java

private String getUrl(String application, Command command) {
    if (!application.startsWith("/")) {
        application = "/" + application;
    }// ww  w  . j a  v a2 s.c o m
    UriComponentsBuilder uri = newUriBuilder();
    uri.path(this.managerPath);
    uri.pathSegment(command.toString().toLowerCase());
    uri.queryParam("path", application);
    return uri.build().toUriString();
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.MvcExceptionHandlerTests.java

@Test
public void test() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();/*ww  w.  j  a va2  s  .c  o m*/
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    // Calling protected resource - requires CSRF token
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + "/hello")
            .queryParam(DEFAULT_CSRF_PARAMETER_NAME, loginInfo.getXsrfToken());
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.GET, entity, String.class);

    String data = responseEntity.getBody();
    assertEquals("Hello World!", data);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.MvcExceptionHandlerTests.java

@Test
public void testNotFound() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();/*w w  w  .  ja  va2 s.co  m*/
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    // Calling protected resource - requires CSRF token
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + "/badurl")
            .queryParam(DEFAULT_CSRF_PARAMETER_NAME, loginInfo.getXsrfToken());

    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.GET, entity, String.class);
    assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
}

From source file:org.avidj.zuul.client.ZuulRestClient.java

@Override
public boolean lock(String sessionId, List<String> path, LockType type, LockScope scope) {
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    Map<String, String> parameters = new HashMap<>();
    parameters.put("id", sessionId); // set the session id
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(serviceUrl + lockPath(path))
            .queryParam("t", type(type)).queryParam("s", scope(scope));

    ResponseEntity<String> result = restTemplate.exchange(uriBuilder.build().encode().toUri(), HttpMethod.PUT,
            entity, String.class);

    LOG.info(result.toString());/*from  www  . j  a v a  2 s.  c  o m*/
    HttpStatus code = result.getStatusCode();
    return code.equals(HttpStatus.CREATED);
}

From source file:com.codeabovelab.dm.cluman.cluster.registry.DockerRegistryAuthAdapter.java

private URI getPath(AuthInfo authInfo) throws URISyntaxException {
    UriComponentsBuilder builder = newInstance().uri(new URI(authInfo.getRealm())).queryParam("service",
            authInfo.getService());/*  w ww .  j a  v  a2  s .  c om*/
    String scope = authInfo.getScope();
    if (StringUtils.hasText(scope)) {
        builder.queryParam("scope", scope);
    }
    return builder.build().toUri();
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.MvcExceptionHandlerTests.java

@Test
public void testExceptionHandler() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();//from  w ww.j av a 2 s.  c o m
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    // Calling protected resource - requires CSRF token
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + "/exc")
            .queryParam(DEFAULT_CSRF_PARAMETER_NAME, loginInfo.getXsrfToken());

    ResponseEntity<ResponseDataVO> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.GET, entity, ResponseDataVO.class);

    ResponseDataVO data = responseEntity.getBody();
    assertEquals(500, data.getErrorVO().getCode());
    assertTrue("contains message", data.getErrorVO().getMessage().contains("kk"));
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode());

}

From source file:org.workspace7.moviestore.utils.MovieDBHelper.java

/**
 * This method queries the external API and caches the movies, for the demo purpose we just query only first page
 *
 * @return - the status code of the invocation
 *///from  w  ww .  j av  a 2s .com
protected int queryAndCache() {

    if (this.moviesCache.isEmpty()) {

        log.info("No movies exist in cache, loading cache ..");

        UriComponentsBuilder moviesUri = UriComponentsBuilder
                .fromUriString(movieStoreProps.getApiEndpointUrl() + "/movie/popular")
                .queryParam("api_key", movieStoreProps.getApiKey());

        final URI requestUri = moviesUri.build().toUri();

        log.info("Request URI:{}", requestUri);

        ResponseEntity<String> response = restTemplate.getForEntity(requestUri, String.class);

        log.info("Response Status:{}", response.getStatusCode());

        Map<String, Movie> movieMap = new HashMap<>();

        if (200 == response.getStatusCode().value()) {
            String jsonBody = response.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode root = objectMapper.readTree(jsonBody);
                JsonNode results = root.path("results");
                results.elements().forEachRemaining(movieNode -> {
                    String id = movieNode.get("id").asText();
                    Movie movie = Movie.builder().id(id).overview(movieNode.get("overview").asText())
                            .popularity(movieNode.get("popularity").floatValue())
                            .posterPath("http://image.tmdb.org/t/p/w92" + movieNode.get("poster_path").asText())
                            .logoPath("http://image.tmdb.org/t/p/w45" + movieNode.get("poster_path").asText())
                            .title(movieNode.get("title").asText())
                            .price(ThreadLocalRandom.current().nextDouble(1.0, 10.0)).build();
                    movieMap.put(id, movie);
                });
            } catch (IOException e) {
                log.error("Error reading response:", e);
            }

            log.debug("Got {} movies", movieMap);
            moviesCache.putAll(movieMap);
        }
        return response.getStatusCode().value();
    } else {
        log.info("Cache already loaded with movies ... will use cache");
        return 200;
    }
}

From source file:com.tce.oauth2.spring.client.controller.OAuthController.java

@RequestMapping("/oauth2callback")
public String callback(@RequestParam("code") String authorizationCode, HttpServletRequest request) {

    // call OAuth Server with response code to get the access token
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(OAUTH_URL + "/oauth/token")
            .queryParam("grant_type", "authorization_code").queryParam("code", authorizationCode)
            .queryParam("redirect_uri", OAUTH_REDIRECT_URI);
    ResponseEntity<OAuthToken> response = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, new HttpEntity<>(createHeaders(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET)),
            OAuthToken.class);
    if (response.getStatusCode().is4xxClientError()) {
        return "redirect:/login";
    }//from   w w w  .jav  a2  s .  c  om

    // get the access token
    OAuthToken oauthToken = response.getBody();
    // set access token to the session
    request.getSession().setAttribute("access_token", oauthToken.getAccessToken());
    // get the user information
    return "redirect:/userinfo";
}

From source file:com.cloud.baremetal.networkservice.Force10BaremetalSwitchBackend.java

private String buildLink(String switchIp, String path) {
    UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
    builder.scheme("http");
    builder.host(switchIp);//from   ww w. j  a v a  2  s  .  c om
    builder.port(8008);
    builder.path(path);
    return builder.build().toUriString();
}