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

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

Introduction

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

Prototype

public static UriComponentsBuilder fromUriString(String uri) 

Source Link

Document

Create a builder that is initialized with the given URI string.

Usage

From source file:com.teradata.benchto.driver.presto.PrestoClient.java

private URI buildQueryInfoURI(String queryId) {
    checkState(!prestoURL.isEmpty());//  w w  w  .j a va 2  s.  co  m

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(prestoURL).pathSegment("v1", "query",
            queryId);

    return URI.create(uriBuilder.toUriString());
}

From source file:org.hobsoft.contacts.server.controller.ContactsController.java

@RequestMapping(value = "/contacts", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<Object> create(Contact contact) {
    contactRepository.create(contact);/*from w  w w  .j a  v  a2  s .  c  om*/

    Link link = contactResourceAssembler.toResource(contact).getId();
    URI location = UriComponentsBuilder.fromUriString(link.getHref()).build().toUri();

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER);
}

From source file:tds.assessment.web.endpoints.AssessmentControllerIntegrationTests.java

@Test
public void shouldReturnAssessmentByKey() throws Exception {
    EnhancedRandom rand = EnhancedRandomBuilder.aNewEnhancedRandomBuilder().collectionSizeRange(2, 5)
            .stringLengthRange(1, 20).build();
    Assessment assessment = rand.nextObject(Assessment.class);
    assessment.setKey("(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016");
    assessment.setAssessmentId("IRP-Perf-ELA-11");
    assessment.setSelectionAlgorithm(Algorithm.VIRTUAL);
    assessment.setSubject("ELA");
    assessment.setStartAbility(50F);/* w  w w .  ja v  a 2s  .c  om*/
    assessment.setDeleteUnansweredItems(true);

    when(assessmentSegmentService.findAssessment("SBAC_PT", "(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016"))
            .thenReturn(Optional.of(assessment));

    URI uri = UriComponentsBuilder
            .fromUriString("/SBAC_PT/assessments/(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016").build().toUri();

    MvcResult result = http.perform(get(uri).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("key", is("(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016")))
            .andExpect(jsonPath("assessmentId", is("IRP-Perf-ELA-11")))
            .andExpect(jsonPath("subject", is("ELA")))
            .andExpect(jsonPath("selectionAlgorithm", is(Algorithm.VIRTUAL.name()))).andReturn();

    Assessment parsedAssessment = objectMapper.readValue(result.getResponse().getContentAsByteArray(),
            Assessment.class);
    assertThat(parsedAssessment).isEqualTo(assessment);
}

From source file:org.awesomeagile.testing.google.FakeGoogleController.java

@ResponseBody
@RequestMapping(method = RequestMethod.GET, path = "/oauth2/auth")
public ResponseEntity<?> authenticate(@RequestParam("client_id") String clientId,
        @RequestParam(value = "client_secret", required = false) String clientSecret,
        @RequestParam("response_type") String responseType, @RequestParam("redirect_uri") String redirectUri,
        @RequestParam("scope") String scope) {
    // Validate client_id and client_secret
    if (!this.clientId.equals(clientId) || (clientSecret != null && !this.clientSecret.equals(clientSecret))) {
        return ResponseEntity.<String>badRequest().body("Wrong client_id or client_secret!");
    }//from  w  ww . j  a  v a 2 s  .  co  m
    if (!prefixMatches(redirectUri)) {
        return wrongRedirectUriResponse();
    }
    String code = RandomStringUtils.randomAlphanumeric(64);
    String token = RandomStringUtils.randomAlphanumeric(64);
    codeToToken.put(code, new AccessToken(token, scope, "", System.currentTimeMillis() + EXPIRATION_MILLIS));
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectUri).queryParam(CODE, code);
    return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, builder.build().toUriString())
            .build();
}

From source file:com.teradata.benchto.driver.graphite.GraphiteClient.java

private URI buildLoadMetricsURI(Map<String, String> metrics, long fromEpochSecond, long toEpochSecond) {
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(graphiteURL).path("/render")
            .queryParam("format", "json").queryParam("from", fromEpochSecond)
            .queryParam("until", toEpochSecond);

    for (Map.Entry<String, String> metric : metrics.entrySet()) {
        String metricQueryExpr = metric.getValue();
        String metricName = metric.getKey();

        uriBuilder.queryParam("target", format("alias(%s,'%s')", metricQueryExpr, metricName));
    }/*w w  w  .ja v  a2s  .c o  m*/

    return URI.create(uriBuilder.toUriString());
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@SuppressWarnings("unchecked")
@Override//from w w w.  j a  va2s.  c om
public Map<String, Object> loginForClient(String username, String password, String clientId,
        UriComponents inUrlComponents) {
    final Map<String, Object> responsePayload = new HashMap<String, Object>();

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());

    // login for csrf
    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build();

    ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers,
            String.class);

    final List<String> cookies = new ArrayList<String>();
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", username);
    formData.add("password", password);
    formData.add(CSRF, getCsrf(cookies));

    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));
    headers.add(HttpHeaders.REFERER, loginUri.toUriString());

    // login.do
    response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(),
            HttpMethod.POST, formData, headers, String.class);

    if (response.getStatusCode() != HttpStatus.FOUND
            || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) {
        responsePayload.put("error", "bad credentials");
        return responsePayload;
    }

    removeCookie(cookies, "X-Uaa-Csrf");
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));
    removeExpiredCookies(cookies);
    headers.remove(HttpHeaders.REFERER);
    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));

    // authorize
    final ResponseEntity<JsonNode> authResponse = exchangeForType(
            uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
                    .queryParam("response_type", "code").queryParam("client_id", clientId)
                    .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(),
            HttpMethod.GET, null, headers, JsonNode.class);

    if (authResponse.getStatusCode() == HttpStatus.OK) {
        removeCookie(cookies, "X-Uaa-Csrf");
        cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE));
        // return approval data
        final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>();

        for (final String cookie : cookies) {
            parsedCookies.add(HttpCookie.parse(cookie).get(0));
        }

        responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>());

        for (final HttpCookie parsedCookie : parsedCookies) {
            if (!parsedCookie.getName().startsWith("Saved-Account")) {
                parsedCookie.setPath(inUrlComponents.getPath());
                ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE))
                        .add(httpCookieToString(parsedCookie));
            }
        }

        responsePayload.put("json", authResponse.getBody());
    } else {
        // get auth_code from Location Header
        responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]);
    }

    return responsePayload;
}

From source file:com.nec.harvest.controller.KounyuController.java

/** {@inheritDoc} */
@Override//www .  jav  a2 s. c om
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String orgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
    if (logger.isDebugEnabled()) {
        logger.debug("Redering kounyu report...");
    }

    // Automatically build a redirect link
    UriComponents uriComponents = UriComponentsBuilder
            .fromUriString(Constants.KOUNYU_PATH + "/{orgCode}/{monthly}").build();
    String businessDate = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
    URI uri = uriComponents.expand(proGNo, orgCode, businessDate).encode().toUri();

    logger.info("Redirect to cash management screen with params in session...");
    return "redirect:" + uri.toString();
}

From source file:fi.vrk.xroad.catalog.collector.actors.FetchWsdlActor.java

private String buildUri(XRoadServiceIdentifierType service) {
    assert service.getXRoadInstance() != null;
    assert service.getMemberClass() != null;
    assert service.getMemberCode() != null;
    assert service.getServiceCode() != null;

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getHost()).path(WSDL_CONTEXT_PATH)
            .queryParam("xRoadInstance", service.getXRoadInstance())
            .queryParam("memberClass", service.getMemberClass())
            .queryParam("memberCode", service.getMemberCode())
            .queryParam("serviceCode", service.getServiceCode());
    if (!Strings.isNullOrEmpty(service.getSubsystemCode())) {
        builder = builder.queryParam("subsystemCode", service.getSubsystemCode());
    }/*from ww  w.  j  av a  2  s .  c  o m*/
    if (!Strings.isNullOrEmpty(service.getServiceVersion())) {
        builder = builder.queryParam("version", service.getServiceVersion());
    }
    return builder.toUriString();
}

From source file:cz.cvut.zuul.support.spring.provider.RemoteResourceTokenServices.java

public void afterPropertiesSet() {
    Assert.notNull(restTemplate, "restTemplate must not be null");
    Assert.hasText(tokenInfoEndpointUrl, "tokenInfoEndpointUrl must not be blank");

    if (decorateErrorHandler) {
        restTemplate.setErrorHandler(new TokenValidationErrorHandler(restTemplate.getErrorHandler()));
    }//  ww  w .  j a  v  a  2 s.c  o m
    //add query parameter with placeholder for token value
    tokenInfoEndpointUrl = UriComponentsBuilder.fromUriString(tokenInfoEndpointUrl)
            .queryParam(tokenParameterName, "{value}").build().toUriString();
}

From source file:com.nec.harvest.controller.KoguchiController.java

/** {@inheritDoc} */
@Override// ww w .  j  a v a 2s. c o  m
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
    logger.info("Load koguchi page");

    //
    String businessDate = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);

    // Build a link to redirect
    UriComponents uriComponent = UriComponentsBuilder
            .fromUriString(Constants.KOGUCHI_PATH + "/{orgCode}/{monthly}").build();
    URI uri = uriComponent.expand(proGNo, userOrgCode, businessDate).encode().toUri();
    return "redirect:" + uri.toString();
}