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

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

Introduction

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

Prototype

@Nullable
public final String getScheme() 

Source Link

Document

Return the scheme.

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(':');
        }/* ww w.  ja  va  2s .  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.mitre.discovery.util.WebfingerURLNormalizer.java

/**
 * Normalize the resource string as per OIDC Discovery.
 * @param identifier//from w  w  w .j  a  va  2  s. c  om
 * @return the normalized string, or null if the string can't be normalized
 */
public static UriComponents normalizeResource(String identifier) {
    // try to parse the URI
    // NOTE: we can't use the Java built-in URI class because it doesn't split the parts appropriately

    if (Strings.isNullOrEmpty(identifier)) {
        logger.warn("Can't normalize null or empty URI: " + identifier);
        return null; // nothing we can do
    } else {

        //UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(identifier);
        UriComponentsBuilder builder = UriComponentsBuilder.newInstance();

        Matcher m = pattern.matcher(identifier);
        if (m.matches()) {
            builder.scheme(m.group(2));
            builder.userInfo(m.group(6));
            builder.host(m.group(8));
            String port = m.group(10);
            if (!Strings.isNullOrEmpty(port)) {
                builder.port(Integer.parseInt(port));
            }
            builder.path(m.group(11));
            builder.query(m.group(13));
            builder.fragment(m.group(15)); // we throw away the hash, but this is the group it would be if we kept it
        } else {
            // doesn't match the pattern, throw it out
            logger.warn("Parser couldn't match input: " + identifier);
            return null;
        }

        UriComponents n = builder.build();

        if (Strings.isNullOrEmpty(n.getScheme())) {
            if (!Strings.isNullOrEmpty(n.getUserInfo()) && Strings.isNullOrEmpty(n.getPath())
                    && Strings.isNullOrEmpty(n.getQuery()) && n.getPort() < 0) {

                // scheme empty, userinfo is not empty, path/query/port are empty
                // set to "acct" (rule 2)
                builder.scheme("acct");

            } else {
                // scheme is empty, but rule 2 doesn't apply
                // set scheme to "https" (rule 3)
                builder.scheme("https");
            }
        }

        // fragment must be stripped (rule 4)
        builder.fragment(null);

        return builder.build();
    }

}

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 w  w w .  ja va2s  .c  o  m
    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: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   w ww .ja  v  a 2s  . com*/

    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: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.mitre.discovery.web.DiscoveryEndpoint.java

@RequestMapping(value = { "/" + WEBFINGER_URL }, produces = MediaType.APPLICATION_JSON_VALUE)
public String webfinger(@RequestParam("resource") String resource,
        @RequestParam(value = "rel", required = false) String rel, Model model) {

    if (!Strings.isNullOrEmpty(rel) && !rel.equals("http://openid.net/specs/connect/1.0/issuer")) {
        logger.warn("Responding to webfinger request for non-OIDC relation: " + rel);
    }//w w w.ja  va2 s . co m

    if (!resource.equals(config.getIssuer())) {
        // it's not the issuer directly, need to check other methods

        UriComponents resourceUri = WebfingerURLNormalizer.normalizeResource(resource);
        if (resourceUri != null && resourceUri.getScheme() != null && resourceUri.getScheme().equals("acct")) {
            // acct: URI (email address format)

            // check on email addresses first
            UserInfo user = userService
                    .getByEmailAddress(resourceUri.getUserInfo() + "@" + resourceUri.getHost());

            if (user == null) {
                // user wasn't found, see if the local part of the username matches, plus our issuer host

                user = userService.getByUsername(resourceUri.getUserInfo()); // first part is the username

                if (user != null) {
                    // username matched, check the host component
                    UriComponents issuerComponents = UriComponentsBuilder.fromHttpUrl(config.getIssuer())
                            .build();
                    if (!Strings.nullToEmpty(issuerComponents.getHost())
                            .equals(Strings.nullToEmpty(resourceUri.getHost()))) {
                        logger.info("Host mismatch, expected " + issuerComponents.getHost() + " got "
                                + resourceUri.getHost());
                        model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
                        return HttpCodeView.VIEWNAME;
                    }

                } else {

                    // if the user's still null, punt and say we didn't find them

                    logger.info("User not found: " + resource);
                    model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
                    return HttpCodeView.VIEWNAME;
                }

            }

        } else {
            logger.info("Unknown URI format: " + resource);
            model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
            return HttpCodeView.VIEWNAME;
        }
    }

    // if we got here, then we're good, return ourselves
    model.addAttribute("resource", resource);
    model.addAttribute("issuer", config.getIssuer());

    return "webfingerView";
}

From source file:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java

public MockHttpServletRequest buildRequest(ServletContext servletContext) {
    String charset = getCharset();
    String httpMethod = webRequest.getHttpMethod().name();
    UriComponents uriComponents = uriComponents();

    MockHttpServletRequest result = new HtmlUnitMockHttpServletRequest(servletContext, httpMethod,
            uriComponents.getPath());/*from   w  w w  . ja  v  a2  s  .c o  m*/
    parent(result, parentBuilder);
    result.setServerName(uriComponents.getHost()); // needs to be first for additional headers
    authType(result);
    result.setCharacterEncoding(charset);
    content(result, charset);
    contextPath(result, uriComponents);
    contentType(result);
    cookies(result);
    headers(result);
    locales(result);
    servletPath(uriComponents, result);
    params(result, uriComponents);
    ports(uriComponents, result);
    result.setProtocol("HTTP/1.1");
    result.setQueryString(uriComponents.getQuery());
    result.setScheme(uriComponents.getScheme());
    pathInfo(uriComponents, result);

    return parentPostProcessor == null ? result : parentPostProcessor.postProcessRequest(result);
}

From source file:org.springframework.web.util.WebUtils.java

private static int getPort(UriComponents component) {
    int port = component.getPort();
    if (port == -1) {
        if ("http".equals(component.getScheme())) {
            port = 80;//  w  w w .java2  s  . c  om
        } else if ("https".equals(component.getScheme())) {
            port = 443;
        }
    }
    return port;
}