Example usage for org.springframework.web.util UriComponents getHost

List of usage examples for org.springframework.web.util UriComponents getHost

Introduction

In this page you can find the example usage for org.springframework.web.util UriComponents getHost.

Prototype

@Nullable
public abstract String getHost();

Source Link

Document

Return the host.

Usage

From source file:org.mitre.discovery.util.WebfingerURLNormalizer.java

public static String serializeURL(UriComponents uri) {
    if (uri.getScheme() != null && (uri.getScheme().equals("acct") || uri.getScheme().equals("mailto")
            || uri.getScheme().equals("tel") || uri.getScheme().equals("device"))) {

        // serializer copied from HierarchicalUriComponents but with "//" removed

        StringBuilder uriBuilder = new StringBuilder();

        if (uri.getScheme() != null) {
            uriBuilder.append(uri.getScheme());
            uriBuilder.append(':');
        }//from ww  w  . j  a  v  a2  s .  c o  m

        if (uri.getUserInfo() != null || uri.getHost() != null) {
            if (uri.getUserInfo() != null) {
                uriBuilder.append(uri.getUserInfo());
                uriBuilder.append('@');
            }
            if (uri.getHost() != null) {
                uriBuilder.append(uri.getHost());
            }
            if (uri.getPort() != -1) {
                uriBuilder.append(':');
                uriBuilder.append(uri.getPort());
            }
        }

        String path = uri.getPath();
        if (StringUtils.hasLength(path)) {
            if (uriBuilder.length() != 0 && path.charAt(0) != '/') {
                uriBuilder.append('/');
            }
            uriBuilder.append(path);
        }

        String query = uri.getQuery();
        if (query != null) {
            uriBuilder.append('?');
            uriBuilder.append(query);
        }

        if (uri.getFragment() != null) {
            uriBuilder.append('#');
            uriBuilder.append(uri.getFragment());
        }

        return uriBuilder.toString();
    } else {
        return uri.toUriString();
    }

}

From source file:org.appverse.web.framework.backend.frontfacade.mvc.swagger.provider.EurekaSwaggerResourcesProvider.java

private static String obtainUrlLocation(ServiceInstance instance, UriComponents current, String path,
        String swaggerHost) {/*from ww w.  j av  a  2s. c om*/
    String managementPath = "";
    if (instance.getMetadata().containsKey("managementPath")) {
        managementPath = instance.getMetadata().get("managementPath");
    }
    String hostUrl;
    if (swaggerHost != null && swaggerHost.length() > 0) {
        hostUrl = swaggerHost;
    } else {
        //tries to findout the host
        if (("https".equals(current.getScheme()) && 443 == current.getPort())
                || ("http".equals(current.getScheme()) && 80 == current.getPort()) || -1 == current.getPort()) {
            //default ports
            hostUrl = String.format("%s://%s", current.getScheme(), current.getHost());
        } else {
            //custom ports
            hostUrl = String.format("%s://%s:%d", current.getScheme(), current.getHost(), current.getPort());
        }
    }
    return hostUrl + managementPath + path;
}

From source file:org.cloudfoundry.identity.uaa.login.test.IntegrationTestRule.java

private boolean connectionAvailable() {
    UriComponents components = UriComponentsBuilder.fromHttpUrl(baseUrl).build();
    String host = components.getHost();
    int port = components.getPort();

    logger.info("Testing connectivity for " + baseUrl);
    try (Socket socket = new Socket(host, port)) {
        logger.info("Connectivity test succeeded for " + baseUrl);
        return true;

    } catch (IOException e) {
        logger.warn("Connectivity test failed for " + baseUrl, e);
        return false;
    }/*from w  w  w.  j  a  va  2s  . c  o  m*/
}

From source file:springfox.documentation.swagger2.web.Swagger2Controller.java

private String hostName(UriComponents uriComponents) {
    if ("DEFAULT".equals(hostNameOverride)) {
        String host = uriComponents.getHost();
        int port = uriComponents.getPort();
        if (port > -1) {
            return String.format("%s:%d", host, port);
        }//from  w  w  w . ja v a 2 s  . com
        return host;
    }
    return hostNameOverride;
}

From source file:org.mitre.openid.connect.service.impl.UUIDPairwiseIdentiferService.java

@Override
public String getIdentifier(UserInfo userInfo, ClientDetailsEntity client) {

    String sectorIdentifier = null;

    if (!Strings.isNullOrEmpty(client.getSectorIdentifierUri())) {
        UriComponents uri = UriComponentsBuilder.fromUriString(client.getSectorIdentifierUri()).build();
        sectorIdentifier = uri.getHost(); // calculate based on the host component only
    } else {/*from   w  ww .  j  ava  2s.  com*/
        Set<String> redirectUris = client.getRedirectUris();
        UriComponents uri = UriComponentsBuilder.fromUriString(Iterables.getOnlyElement(redirectUris)).build();
        sectorIdentifier = uri.getHost(); // calculate based on the host of the only redirect URI
    }

    if (sectorIdentifier != null) {
        // if there's a sector identifier, use that for the lookup
        PairwiseIdentifier pairwise = pairwiseIdentifierRepository.getBySectorIdentifier(userInfo.getSub(),
                sectorIdentifier);

        if (pairwise == null) {
            // we don't have an identifier, need to make and save one

            pairwise = new PairwiseIdentifier();
            pairwise.setIdentifier(UUID.randomUUID().toString());
            pairwise.setUserSub(userInfo.getSub());
            pairwise.setSectorIdentifier(sectorIdentifier);

            pairwiseIdentifierRepository.save(pairwise);
        }

        return pairwise.getIdentifier();
    } else {

        return null;
    }
}

From source file:de.blizzy.documentr.markdown.macro.impl.FlattrMacroTest.java

@Test
public void getHtml() {
    String html = macro.getHtml(macroContext);
    @SuppressWarnings("nls")
    String re = "^<a href=\"([^\"]+)\">"
            + "<img src=\"https://api\\.flattr\\.com/button/flattr-badge-large\\.png\"/>" + "</a>$"; //$NON-NLS-2$
    assertRE(re, html);//from   ww w.j a  v  a2 s. c o  m

    Matcher matcher = Pattern.compile(re, Pattern.DOTALL).matcher(html);
    matcher.find();
    String url = StringEscapeUtils.unescapeHtml4(matcher.group(1));
    UriComponents components = UriComponentsBuilder.fromHttpUrl(url).build();
    assertEquals("https", components.getScheme()); //$NON-NLS-1$
    assertEquals("flattr.com", components.getHost()); //$NON-NLS-1$
    assertEquals(-1, components.getPort());
    assertEquals("/submit/auto", components.getPath()); //$NON-NLS-1$
    MultiValueMap<String, String> params = components.getQueryParams();
    assertEquals(FLATTR_USER_ID, params.getFirst("user_id")); //$NON-NLS-1$
    assertEquals(PAGE_URL, params.getFirst("url")); //$NON-NLS-1$
    assertEquals(PAGE_TITLE, params.getFirst("title")); //$NON-NLS-1$
    assertEquals("text", params.getFirst("category")); //$NON-NLS-1$ //$NON-NLS-2$
    assertTrue(params.getFirst("tags").equals(TAG_1 + "," + TAG_2) || //$NON-NLS-1$ //$NON-NLS-2$
            params.getFirst("tags").equals(TAG_2 + "," + TAG_1)); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

@Test
public void testInvalidScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());
    postBody.add("scope", "read");

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    System.out.println(//  www.j  av a2 s  . c o  m
            "responseEntity.getHeaders().getLocation() = " + responseEntity.getHeaders().getLocation());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.getFirst("error"), is("invalid_scope"));
    Assert.assertThat(params.getFirst("access_token"), isEmptyOrNullString());
    Assert.assertThat(params.getFirst("credentials"), isEmptyOrNullString());
}

From source file:io.pivotal.cla.webdriver.AuthenticationTests.java

@Test
public void requiresAuthenticationAndCreatesValidOAuthTokenRequest() throws Exception {
    String redirect = mockMvc.perform(get("/sign/pivotal")).andExpect(status().is3xxRedirection()).andReturn()
            .getResponse().getRedirectedUrl();

    UriComponents redirectComponent = UriComponentsBuilder.fromHttpUrl(redirect).build();

    assertThat(redirectComponent.getScheme()).isEqualTo("https");
    assertThat(redirectComponent.getHost()).isEqualTo("github.com");
    MultiValueMap<String, String> params = redirectComponent.getQueryParams();
    assertThat(params.getFirst("client_id")).isEqualTo(config.getMain().getClientId());
    assertThat(urlDecode(params.getFirst("redirect_uri"))).isEqualTo("http://localhost/login/oauth2/github");
    assertThat(params.getFirst("state")).isNotNull();

    String[] scopes = urlDecode(params.getFirst("scope")).split(",");
    assertThat(scopes).containsOnly("user:email");
}

From source file:io.pivotal.cla.webdriver.AuthenticationTests.java

@Test
public void adminRequiresAuthenticationAndCreatesValidOAuthTokenRequest() throws Exception {
    String redirect = mockMvc.perform(get("/admin/cla/link")).andExpect(status().is3xxRedirection()).andReturn()
            .getResponse().getRedirectedUrl();

    UriComponents redirectComponent = UriComponentsBuilder.fromHttpUrl(redirect).build();

    assertThat(redirectComponent.getScheme()).isEqualTo("https");
    assertThat(redirectComponent.getHost()).isEqualTo("github.com");
    MultiValueMap<String, String> params = redirectComponent.getQueryParams();
    assertThat(params.getFirst("client_id")).isEqualTo(config.getMain().getClientId());
    assertThat(urlDecode(params.getFirst("redirect_uri"))).isEqualTo("http://localhost/login/oauth2/github");
    assertThat(params.getFirst("state")).isNotNull();

    String[] scopes = urlDecode(params.getFirst("scope")).split(",");
    assertThat(scopes).containsOnly("user:email", "repo:status", "admin:repo_hook", "admin:org_hook",
            "read:org");
}

From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

@Test
public void testDefaultScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();/*from  w  ww.ja va2 s  .  c o  m*/
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}