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:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationFlowTest() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();/*from w  ww . j a v  a 2  s. c o m*/

    // Calling protected remotelog service
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    // Try without token first - It should be 'Forbidden'
    // http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate      
    ResponseEntity<String> responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entityRemotelog, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode());

    // Try now with the CSRF token - It should work well
    // This implies passing JSESSIONID and CSRF Token
    headers.set(DEFAULT_CSRF_HEADER_NAME, loginInfo.getXsrfToken());
    entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityRemotelog, String.class);
    assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode());

    // Calling here logout
    builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + basicAuthenticationLogoutEndpointPath);
    HttpEntity<Void> entityLogout = new HttpEntity<Void>(headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityLogout, String.class);
    assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode());

    // Try to call remotelog again (after logout)
    // This implies passing JSESSIONID and CSRF Token - We expect this not to work as the CSRF token has been removed and the session invalidated
    entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityRemotelog, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), String.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    int cookiesAdded = 0;
    headers = getAppBasicAuthHttpHeaders();
    for (String cookie : cookies) {
        if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) {
            headers.add("Cookie", cookie);
            cookiesAdded++;/*ww  w .j av  a2 s  .  c o m*/
        }
    }
    assertEquals(2, cookiesAdded);

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true")
                .queryParam(DEFAULT_CSRF_COOKIE_NAME,
                        IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody()))
                .build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), String.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString();

    MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>();
    tokenParams.add("response_type", "token");
    tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
    tokenParams.add("code", newCode);
    tokenParams.add("redirect_uri", appUrl);
    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers,
            HttpMethod.POST, new URI(tokenUrl));
    ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();

    BasicCookieStore cookieStore = new BasicCookieStore();
    ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, loginResponse);
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf);

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem(startsWith("JSESSIONID")));
    assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf")));
    if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) {
        assertThat(cookies, hasItem(startsWith("Saved-Account-")));
    }
    assertThat(cookies, hasItem(startsWith("Current-User")));
    cookieStore.clear();
    setCookiesFromResponse(cookieStore, loginResponse);
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, profilePage);
    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody()));
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

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

/**
 * Create a new entity/*from w  w  w. ja  v  a 2  s.co  m*/
 * @param entity the Entity to add
 * @return the listener to notify of completion
 */
public ListenableFuture<Void> addEntity(Entity entity) {
    return adapt(request(HttpMethod.POST,
            UriComponentsBuilder.fromHttpUrl(baseURL).path("v2/entities").toUriString(), entity, Void.class));
}

From source file:io.syndesis.runtime.credential.CredentialITCase.java

@Test
public void shouldInitiateCredentialFlow() throws UnsupportedEncodingException {
    final ResponseEntity<AcquisitionResponse> acquisitionResponse = post(
            "/api/v1/connectors/test-provider/credentials", Collections.singletonMap("returnUrl", "/ui#state"),
            AcquisitionResponse.class, tokenRule.validToken(), HttpStatus.ACCEPTED);

    assertThat(acquisitionResponse.hasBody()).as("Should present a acquisition response in the HTTP body")
            .isTrue();/* ww  w.j  av  a 2 s. c om*/

    final AcquisitionResponse response = acquisitionResponse.getBody();
    assertThat(response.getType()).isEqualTo(Type.OAUTH2);

    final String redirectUrl = response.getRedirectUrl();
    assertThat(redirectUrl).as("Should redirect to Salesforce and containthe correct callback URL")
            .startsWith("https://test/oauth2/authorize?client_id=testClientId&response_type=code&redirect_uri=")
            .contains(encode("/api/v1/credentials/callback", "ASCII"));

    final MultiValueMap<String, String> params = UriComponentsBuilder.fromHttpUrl(redirectUrl).build()
            .getQueryParams();

    final String state = params.getFirst("state");

    assertThat(state).as("state parameter should be set").isNotEmpty();

    final State responseStateInstruction = response.state();
    assertThat(responseStateInstruction).as("acquisition response should contain the state instruction")
            .isNotNull();
    assertThat(responseStateInstruction.persist()).isEqualByComparingTo(State.Persist.COOKIE);
    assertThat(responseStateInstruction.spec()).isNotEmpty();

    final CredentialFlowState credentialFlowState = clientSideState
            .restoreFrom(Cookie.valueOf(responseStateInstruction.spec()), CredentialFlowState.class);

    final CredentialFlowState expected = new OAuth2CredentialFlowState.Builder().key("test-state")
            .providerId("test-provider").build();

    assertThat(credentialFlowState).as("The flow state should be as expected")
            .isEqualToIgnoringGivenFields(expected, "returnUrl");
    final URI returnUrl = credentialFlowState.getReturnUrl();
    assertThat(returnUrl).isNotNull();
    assertThat(returnUrl.isAbsolute()).isTrue();
    assertThat(returnUrl.getPath()).isEqualTo("/ui");
    assertThat(returnUrl.getFragment()).isEqualTo("state");
}

From source file:org.obiba.mica.core.service.MailService.java

private String getNotificationsUrl() {
    return UriComponentsBuilder.fromHttpUrl(getAgateUrl()).path(DEFAULT_REST_PREFIX)
            .path(DEFAULT_NOTIFICATIONS_PATH).build().toUriString();
}

From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java

private String makeAggregateCounterUrl(TimeSeriesType timeSeriesType, TimeSeriesDataRequest dataRequest) {

    String baseUrl = String.format(aggregateCounterUrlPattern, xdServerBaseUrl, dataRequest.getHouseId(),
            timeSeriesType.name().toLowerCase());

    UriComponentsBuilder ucb = UriComponentsBuilder.fromHttpUrl(baseUrl)
            .queryParam("resolution", dataRequest.getResolution().name().toLowerCase())
            .queryParam("from", dataRequest.getFromDateTime()).queryParam("to", dataRequest.getToDateTime());

    String url = ucb.build().toString();

    return url;/*  w  w w .jav a 2 s  . com*/
}

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

/**
 * Get an entity/*from  w w w . j a v  a  2 s  .  co m*/
 * @param entityId the entity ID
 * @param type optional entity type to avoid ambiguity when multiple entities have the same ID, null or zero-length for empty
 * @param attrs the list of attributes to retreive for this entity, null or empty means all attributes
 * @return the entity
 */
public ListenableFuture<Entity> getEntity(String entityId, String type, Collection<String> attrs) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}");
    addParam(builder, "type", type);
    addParam(builder, "attrs", attrs);
    return adapt(request(HttpMethod.GET, builder.buildAndExpand(entityId).toUriString(), null, Entity.class));
}

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());
    }// w w w .j  a v  a 2s. c  o m
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public InputStream getProject(String bootVersion, String mvnGroup, String mvnArtifact, String mvnVersion,
        String mvnName, String mvnDesc, String packaging, String pkg, String lang, String javaVersion,
        String deps) throws Exception {
    // set connection timeouts
    timeoutFromPrefs();/*  ww w. j  av  a  2s. c o  m*/
    // prepare parameterized url
    final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
            "http://start.spring.io");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(serviceUrl.concat("/starter.zip"))
            .queryParam("type", "maven-project").queryParam("bootVersion", bootVersion)
            .queryParam("groupId", mvnGroup).queryParam("artifactId", mvnArtifact)
            .queryParam("version", mvnVersion).queryParam("packaging", packaging).queryParam("name", mvnName)
            .queryParam("description", mvnDesc).queryParam("language", lang)
            .queryParam("javaVersion", javaVersion).queryParam("packageName", pkg)
            .queryParam("dependencies", deps);
    final URI uri = builder.build().encode().toUri();
    // setup request object
    RequestEntity<Void> req = RequestEntity.get(uri).accept(APPLICATION_OCTET_STREAM)
            .header("User-Agent", REST_USER_AGENT).build();
    // connect
    logger.info("Getting Spring Initializr project");
    logger.log(INFO, "Service URL: {0}", uri.toString());
    long start = System.currentTimeMillis();
    ResponseEntity<byte[]> respEntity = rt.exchange(req, byte[].class);
    // analyze response outcome
    final HttpStatus statusCode = respEntity.getStatusCode();
    if (statusCode == OK) {
        final ByteArrayInputStream stream = new ByteArrayInputStream(respEntity.getBody());
        logger.log(INFO, "Retrieved archived project from Spring Initializr service. Took {0} msec",
                System.currentTimeMillis() - start);
        return stream;
    } else {
        // log status code
        final String errMessage = String.format(
                "Spring initializr service connection problem. HTTP status code: %s", statusCode.toString());
        logger.severe(errMessage);
        // throw exception in order to set error message
        throw new RuntimeException(errMessage);
    }
}