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:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) {

    if (authorizationCode == null) {
        throw new IllegalStateException("No authorization code found in the current request scope.");
    }/*w  w  w.  j  ava 2 s . co  m*/

    UriComponentsBuilder template = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri());
    template.queryParam("code", encode(authorizationCode));

    String state = authorizationRequest.getState();
    if (state != null) {
        template.queryParam("state", encode(state));
    }

    return template.build(true).toUriString();
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure,
        boolean fragment) {

    if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) {
        // we have no redirect for the user. very sad.
        throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.",
                failure);/*from w  w w .ja  va 2  s . c  o  m*/
    }

    UriComponentsBuilder template = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri());
    StringBuilder values = new StringBuilder();

    values.append("error=" + encode(failure.getOAuth2ErrorCode()));
    values.append("&error_description=" + encode(failure.getMessage()));

    if (authorizationRequest.getState() != null) {
        values.append("&state=" + encode(authorizationRequest.getState()));
    }

    if (failure.getAdditionalInformation() != null) {
        for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) {
            values.append("&" + encode(additionalInfo.getKey()) + "=" + encode(additionalInfo.getValue()));
        }
    }

    if (fragment) {
        template.fragment(values.toString());
    } else {
        template.query(values.toString());
    }

    return template.build(true).toUriString();

}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void test_authorization_code_grant_session_expires_during_app_approval() throws Exception {
    String username = "authuser" + generator.generate();
    ScimUser user = setUpUser(username, "", OriginKeys.UAA, IdentityZoneHolder.get().getId());

    String redirectUri = "http://localhost:8080/app/";
    String clientId = "authclient-" + generator.generate();
    String scopes = "openid,password.write,cloud_controller.read,scim.userids,password.write";
    setUpClients(clientId, scopes, scopes, GRANT_TYPES, false, redirectUri);

    String state = generator.generate();

    String url = UriComponentsBuilder.fromUriString(
            "/oauth/authorize?response_type=code&scope=openid&state={state}&client_id={clientId}&redirect_uri={redirectUri}")
            .buildAndExpand(state, clientId, redirectUri).encode().toUri().toString();

    String encodedRedirectUri = UriUtils.encodeQueryParam(redirectUri, "ISO-8859-1");
    MockHttpSession session = getAuthenticatedSession(user);

    MvcResult result = getMockMvc().perform(get(new URI(url)).session(session)).andDo(print())
            .andExpect(status().isOk()).andExpect(forwardedUrl("/oauth/confirm_access"))
            .andExpect(model().attribute("original_uri", "http://localhost" + url)).andReturn();
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void test_authorization_code_grant_redirect_when_session_expires() throws Exception {
    String redirectUri = "https://example.com/dashboard/?appGuid=app-guid&ace_config=test";

    String clientId = "authclient-" + generator.generate();
    String scopes = "openid";
    setUpClients(clientId, scopes, scopes, GRANT_TYPES, true, redirectUri);
    String username = "authuser" + generator.generate();
    String userScopes = "openid";
    ScimUser user = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId());
    String state = generator.generate();

    String url = UriComponentsBuilder.fromUriString(
            "/oauth/authorize?response_type=code&scope=openid&state={state}&client_id={clientId}&redirect_uri={redirectUri}")
            .buildAndExpand(state, clientId, redirectUri).encode().toUri().toString();

    String encodedRedirectUri = UriUtils.encodeQueryParam(redirectUri, "ISO-8859-1");

    MvcResult result = getMockMvc().perform(get(new URI(url))).andExpect(status().is3xxRedirection())
            .andReturn();//from   w ww  .j  av a 2  s.co m
    String location = result.getResponse().getHeader("Location");
    assertThat(location, endsWith("/login"));

    MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false);
    assertNotNull(session);
    SavedRequest savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST_SESSION_ATTRIBUTE);
    assertNotNull(savedRequest);
    assertEquals("http://localhost" + url, savedRequest.getRedirectUrl());

    getMockMvc().perform(get("/login").session(session)).andDo(print()).andExpect(status().isOk())
            .andExpect(content().string(containsString(FORM_REDIRECT_PARAMETER)))
            .andExpect(content().string(containsString(encodedRedirectUri)));

    //a failed login should survive the flow
    //attempt to login without a session
    result = getMockMvc()
            .perform(post("/login.do").with(cookieCsrf()).param("form_redirect_uri", url)
                    .param("username", username).param("password", "invalid"))
            .andExpect(status().isFound()).andExpect(header().string("Location", containsString("/login")))
            .andReturn();

    session = (MockHttpSession) result.getRequest().getSession(false);
    assertNotNull(session);
    savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST_SESSION_ATTRIBUTE);
    assertNotNull(savedRequest);

    getMockMvc().perform(get("/login").session(session)).andDo(print()).andExpect(status().isOk())
            .andExpect(content().string(containsString(FORM_REDIRECT_PARAMETER)))
            .andExpect(content().string(containsString(encodedRedirectUri)));

    //attempt to login without a session
    getMockMvc()
            .perform(post("/login.do").with(cookieCsrf()).param("form_redirect_uri", url)
                    .param("username", username).param("password", SECRET))
            .andExpect(status().isFound()).andExpect(header().string("Location", url));
}

From source file:org.cloudfoundry.identity.uaa.util.UaaTokenUtils.java

public static String constructTokenEndpointUrl(String issuer) throws URISyntaxException {
    try {/*from  w ww.j  a v a2 s . com*/
        new URL(issuer);
    } catch (MalformedURLException x) {
        throw new URISyntaxException(issuer, x.getMessage());
    }
    URI uri = new URI(issuer);
    String hostToUse = uri.getHost();
    if (hasText(IdentityZoneHolder.get().getSubdomain())) {
        hostToUse = IdentityZoneHolder.get().getSubdomain() + "." + hostToUse;
    }
    return UriComponentsBuilder.fromUriString(issuer).host(hostToUse).pathSegment("oauth/token").build()
            .toUriString();
}

From source file:org.haiku.haikudepotserver.dataobjects.RepositorySource.java

/**
 * <p>This is the URL at which one might find the packages for this repository.</p>
 */// ww  w. ja  v a2 s.co  m

public Optional<URL> tryGetPackagesBaseURL() {
    return tryGetBaseURL().map(bu -> {
        try {
            return UriComponentsBuilder.fromUriString(bu.toString()).pathSegment("packages").build().toUri()
                    .toURL();
        } catch (MalformedURLException mue) {
            throw new IllegalStateException("unable to reform a url for obtaining packages", mue);
        }
    });
}

From source file:org.haiku.haikudepotserver.dataobjects.RepositorySource.java

private Optional<URL> tryGetDownloadLeafURL(String leaf) {
    return tryGetBaseURL().map(bu -> {
        try {//from   ww  w. ja  v a  2s  .  co  m
            return UriComponentsBuilder.fromUriString(bu.toString()).pathSegment(leaf).build().toUri().toURL();
        } catch (MalformedURLException mue) {
            throw new IllegalStateException("unable to reform a url for obtaining packages", mue);
        }
    });
}

From source file:org.jasig.ssp.service.external.impl.ExternalStudentTestServiceImpl.java

@Override
public Object getTestDetails(String testCode, String subTestcode, Person person) throws IOException {
    String username = null;//  w  ww.ja va 2 s  .  c o  m
    String password = null;
    String baseUrl = null;
    String groupKey = null;
    Config unConfig = configService.getByName(SMARTER_MEASURE_USERNAME_CONFIG_NAME);
    Config pConfig = configService.getByName(SMARTER_MEASURE_PASSWORD_CONFIG_NAME);
    Config buConfig = configService.getByName(SMARTER_MEASURE_BASE_URL_CONFIG_NAME);
    Config gkConfig = configService.getByName(SMARTER_MEASURE_GROUP_KEY_CONFIG_NAME);
    if (unConfig != null && StringUtils.isNotBlank(unConfig.getValue())) {
        username = unConfig.getValue();
    } else {
        return null;
    }

    if (pConfig != null && StringUtils.isNotBlank(pConfig.getValue())) {
        password = pConfig.getValue();
    } else {
        return null;
    }

    if (buConfig != null && StringUtils.isNotBlank(buConfig.getValue())) {
        baseUrl = buConfig.getValue();
    } else {
        return null;
    }

    if (gkConfig != null && StringUtils.isNotBlank(gkConfig.getValue())) {
        groupKey = gkConfig.getValue();
    }

    if (StringUtils.isNotBlank(groupKey)) {
        URI targetUrl = UriComponentsBuilder.fromUriString(baseUrl).port(443).path("/users")
                .queryParam("AdministrativeGroupKey", groupKey).queryParam("FirstName", person.getFirstName())
                .queryParam("LastName", person.getLastName())
                .queryParam("Email", person.getPrimaryEmailAddress())
                .queryParam("InternalId", person.getSchoolId()).build().toUri();
        BasicAuthenticationRestTemplate client = new BasicAuthenticationRestTemplate(username, password, true);
        ResponseEntity<String> smUserJason = client.getForEntity(targetUrl, String.class);
        if (StringUtils.isNotBlank(smUserJason.getBody())) {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> value = null;
            try {
                value = mapper.readValue(smUserJason.getBody(), Map.class);
            } catch (final Exception e) {
                final String msg = "Failed to access attributes for the specified person:  "
                        + person.getSchoolId();
                throw new IOException(msg, e);
            }
            value = (Map<String, Object>) value.get("User");
            String urlRedirect = baseUrl + "/users/" + value.get("UserId") + "/reportlink";
            ResponseEntity<String> reportLink = client.getForEntity(urlRedirect, String.class);
            try {
                value = mapper.readValue(reportLink.getBody(), Map.class);
            } catch (final Exception e) {
                final String msg = "Failed to access attributes for the specified person:  "
                        + person.getSchoolId();
                throw new IOException(msg, e);
            }
            if (value != null) {
                return value.get("EntryLink");
            }
        }
    }
    throw new IOException(
            "Failed to access attributes for the specified person with school id:  " + person.getSchoolId());
}

From source file:org.openmhealth.shim.fitbit.FitbitShim.java

private ShimDataResponse getRangeData(OffsetDateTime fromTime, OffsetDateTime toTime,
        FitbitDataType fitbitDataType, boolean normalize, String accessToken, String tokenSecret)
        throws ShimException {

    String fromDateString = fromTime.toLocalDate().toString();
    String toDateString = toTime.toLocalDate().toString();

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL).path(
            "/1/user/-/{fitbitDataTypeEndpoint}/date/{fromDateString}/{toDateString}{stepTimeSeries}.json");
    String endpointUrl = uriComponentsBuilder.buildAndExpand(fitbitDataType.getEndPoint(), fromDateString,
            toDateString, (fitbitDataType == FitbitDataType.STEPS ? "/1d/1min" : "")).encode().toUriString();

    return executeRequest(endpointUrl, accessToken, tokenSecret, normalize, fitbitDataType);
}

From source file:org.openmhealth.shim.fitbit.FitbitShim.java

private ShimDataResponse getDaysData(OffsetDateTime dateTime, FitbitDataType fitbitDataType, boolean normalize,
        String accessToken, String tokenSecret) throws ShimException {

    String dateString = dateTime.toLocalDate().toString();

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .path("/1/user/-/{fitbitDataTypeEndpoint}/date/{dateString}{stepTimeSeries}.json");
    String endpointUrl = uriComponentsBuilder.buildAndExpand(fitbitDataType.getEndPoint(), dateString,
            (fitbitDataType == FitbitDataType.STEPS ? "/1d/1min" : "")).encode().toString();

    ApplicationAccessParameters parameters = findApplicationAccessParameters();
    HttpRequestBase dataRequest = OAuth1Utils.getSignedRequest(HttpMethod.GET, endpointUrl,
            parameters.getClientId(), parameters.getClientSecret(), accessToken, tokenSecret, null);

    HttpResponse response;// w w w. j  ava 2 s  .  co  m
    try {
        response = httpClient.execute(dataRequest);
        HttpEntity responseEntity = response.getEntity();

        StringWriter writer = new StringWriter();
        IOUtils.copy(responseEntity.getContent(), writer);

        ObjectMapper objectMapper = new ObjectMapper();

        if (normalize) {

            JsonNode jsonNode = objectMapper.readValue(writer.toString(), JsonNode.class);

            FitbitDataPointMapper dataPointMapper;

            switch (fitbitDataType) {
            case STEPS:
                dataPointMapper = new FitbitStepCountDataPointMapper();
                break;
            case ACTIVITY:
                dataPointMapper = new FitbitPhysicalActivityDataPointMapper();
                break;
            case WEIGHT:
                dataPointMapper = new FitbitBodyWeightDataPointMapper();
                break;
            case SLEEP:
                dataPointMapper = new FitbitSleepDurationDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                dataPointMapper = new FitbitBodyMassIndexDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            return ShimDataResponse.result(FitbitShim.SHIM_KEY,
                    dataPointMapper.asDataPoints(singletonList(jsonNode)));

        } else {
            /**
             * The fitbit API's system works by retrieving each day's
             * data. The date captured is not returned in the data from fitbit because
             * it's implicit so we create a JSON wrapper that includes it.
             */
            String jsonContent = "{\"result\": {\"date\": \"" + dateString + "\" " + ",\"content\": "
                    + writer.toString() + "}}";

            return ShimDataResponse.result(FitbitShim.SHIM_KEY, objectMapper.readTree(jsonContent));
        }
    } catch (IOException e) {
        throw new ShimException("Could not fetch data", e);
    } finally {
        dataRequest.releaseConnection();
    }
}