List of usage examples for org.springframework.web.util UriComponents getPath
@Nullable public abstract String getPath();
From source file:org.mitre.discovery.util.WebfingerURLNormalizer.java
/** * Normalize the resource string as per OIDC Discovery. * @param identifier//w w w . j av a2s. co m * @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:com.microservice.training.hal.HalBrowser.java
/** * Returns the View to redirect to to access the HAL browser. * /*from ww w . j ava 2 s .co m*/ * @param request must not be {@literal null}. * @param browserRelative * @return */ private View getRedirectView(HttpServletRequest request, boolean browserRelative) { ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequest(request); UriComponents components = builder.build(); String path = components.getPath() == null ? "" : components.getPath(); if (!browserRelative) { builder.path(BROWSER); } builder.path(INDEX); builder.fragment(browserRelative ? path.substring(0, path.lastIndexOf("/browser")) : path); return new RedirectView(builder.build().toUriString()); }
From source file:springfox.documentation.swagger2.web.Swagger2Controller.java
@ApiIgnore @RequestMapping(value = "${springfox.documentation.swagger.v2.path:" + DEFAULT_URL + "}", method = RequestMethod.GET, produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE }) public @ResponseBody ResponseEntity<Json> getDocumentation( @RequestParam(value = "group", required = false) String swaggerGroup, HttpServletRequest servletRequest) { String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME); Documentation documentation = documentationCache.documentationByGroup(groupName); if (documentation == null) { return new ResponseEntity<Json>(HttpStatus.NOT_FOUND); }//from ww w . j a v a2 s . c om Swagger swagger = mapper.mapDocumentation(documentation); if (isNullOrEmpty(swagger.getHost())) { final UriComponents uriComponents = componentsFrom(servletRequest); swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath()); swagger.host(hostName(uriComponents)); } return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK); }
From source file:de.blizzy.documentr.markdown.macro.impl.GoogleDocsMacro.java
@Override public String getHtml(IMacroContext macroContext) { String macroParams = macroContext.getParameters(); String googleUrl = StringUtils.substringBefore(macroParams, " ").trim(); //$NON-NLS-1$ String width = StringUtils.substringAfter(macroParams, " ").trim(); //$NON-NLS-1$ UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(googleUrl).build(); String path = uriComponents.getPath(); MultiValueMap<String, String> params = uriComponents.getQueryParams(); if (path.startsWith("/spreadsheet/")) { //$NON-NLS-1$ String key = params.get("key").get(0); //$NON-NLS-1$ UriComponents components = UriComponentsBuilder.fromHttpUrl("https://docs.google.com/spreadsheet/pub") //$NON-NLS-1$ .queryParam("key", key) //$NON-NLS-1$ .queryParam("output", "html") //$NON-NLS-1$ //$NON-NLS-2$ .queryParam("widget", "true") //$NON-NLS-1$ //$NON-NLS-2$ .build();//from w w w .ja va2 s . c o m return buildIframe(components); } else if (path.startsWith("/document/")) { //$NON-NLS-1$ String id = params.get("id").get(0); //$NON-NLS-1$ UriComponents components = UriComponentsBuilder.fromHttpUrl("https://docs.google.com/document/pub") //$NON-NLS-1$ .queryParam("id", id) //$NON-NLS-1$ .queryParam("embedded", "true") //$NON-NLS-1$ //$NON-NLS-2$ .build(); return buildIframe(components); } else if (path.startsWith("/presentation/")) { //$NON-NLS-1$ String id = params.get("id").get(0); //$NON-NLS-1$ UriComponents components = UriComponentsBuilder .fromHttpUrl("https://docs.google.com/presentation/embed") //$NON-NLS-1$ .queryParam("id", id) //$NON-NLS-1$ .queryParam("start", "false") //$NON-NLS-1$ //$NON-NLS-2$ .queryParam("loop", "false") //$NON-NLS-1$ //$NON-NLS-2$ .queryParam("delayms", String.valueOf(TimeUnit.MILLISECONDS.convert(3, TimeUnit.SECONDS))) //$NON-NLS-1$ .build(); return buildIframe(components); } else if (path.startsWith("/drawings/")) { //$NON-NLS-1$ String id = params.get("id").get(0); //$NON-NLS-1$ if (StringUtils.isBlank(width)) { width = "960"; //$NON-NLS-1$ } UriComponents components = UriComponentsBuilder.fromHttpUrl("https://docs.google.com/drawings/pub") //$NON-NLS-1$ .queryParam("id", id) //$NON-NLS-1$ .queryParam("w", width) //$NON-NLS-1$ .build(); return buildImg(components); } else { return null; } }
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(':'); }// www .ja v a 2 s. c om 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: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);/*w w w .j a v a2s . 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 ava 2 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: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();/*ww w .ja v a 2 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")); }
From source file:org.wallride.job.UpdatePostViewsItemWriter.java
@Override public void write(List<? extends List> items) throws Exception { WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext, "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet"); if (context == null) { throw new ServiceException("GuestServlet is not ready yet"); }/* w w w . j a va 2 s . co m*/ final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class); for (List item : items) { UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) item.get(0)).build(); logger.info("Processing [{}]", uriComponents.toString()); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setRequestURI(uriComponents.getPath()); request.setQueryString(uriComponents.getQuery()); MockHttpServletResponse response = new MockHttpServletResponse(); BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService); BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request, response); try { rewriteMatch.execute(request, response); } catch (ServletException e) { throw new ServiceException(e); } catch (IOException e) { throw new ServiceException(e); } request.setRequestURI(rewriteMatch.getMatchingUrl()); HandlerExecutionChain handler; try { handler = mapping.getHandler(request); } catch (Exception e) { throw new ServiceException(e); } if (!(handler.getHandler() instanceof HandlerMethod)) { continue; } HandlerMethod method = (HandlerMethod) handler.getHandler(); if (!method.getBeanType().equals(ArticleDescribeController.class) && !method.getBeanType().equals(PageDescribeController.class)) { continue; } // Last path mean code of post String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1); Post post = postRepository.findOneByCodeAndLanguage(code, rewriteMatch.getBlogLanguage().getLanguage()); if (post == null) { logger.debug("Post not found [{}]", code); continue; } logger.info("Update the PageView. Post ID [{}]: {} -> {}", post.getId(), post.getViews(), item.get(1)); post.setViews(Long.parseLong((String) item.get(1))); postRepository.saveAndFlush(post); } }
From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java
@Test public void testImplicitGrant() 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 id_token"); postBody.add("source", "credentials"); postBody.add("username", user.getUserName()); postBody.add("password", "secret"); ResponseEntity<Void> responseEntity = restOperations.exchange(loginUrl + "/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 w w . j a va 2s . c om 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")); validateToken("access_token", params.toSingleValueMap(), scopes); validateToken("id_token", params.toSingleValueMap(), scopes); }