/** * Private constructor accepting a collection of patterns. */ private PatternsRequestCondition(Collection<String> patterns, UrlPathHelper urlPathHelper, PathMatcher pathMatcher, boolean useSuffixPatternMatch, boolean useTrailingSlashMatch, List<String> fileExtensions) { this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns)); this.pathHelper = (urlPathHelper != null ? urlPathHelper : new UrlPathHelper()); this.pathMatcher = (pathMatcher != null ? pathMatcher : new AntPathMatcher()); this.useSuffixPatternMatch = useSuffixPatternMatch; this.useTrailingSlashMatch = useTrailingSlashMatch; if (fileExtensions != null) { for (String fileExtension : fileExtensions) { if (fileExtension.charAt(0) != '.') { fileExtension = "." + fileExtension; } this.fileExtensions.add(fileExtension); } } }
/** * Adds an alias to an existing well-known name or registers a new instance of a {@link UrlPathHelper} * under that well-known name, unless already registered. * @return a RuntimeBeanReference to this {@link UrlPathHelper} instance */ public static RuntimeBeanReference registerUrlPathHelper(RuntimeBeanReference urlPathHelperRef, ParserContext parserContext, Object source) { if (urlPathHelperRef != null) { if (parserContext.getRegistry().isAlias(URL_PATH_HELPER_BEAN_NAME)) { parserContext.getRegistry().removeAlias(URL_PATH_HELPER_BEAN_NAME); } parserContext.getRegistry().registerAlias(urlPathHelperRef.getBeanName(), URL_PATH_HELPER_BEAN_NAME); } else if (!parserContext.getRegistry().isAlias(URL_PATH_HELPER_BEAN_NAME) && !parserContext.getRegistry().containsBeanDefinition(URL_PATH_HELPER_BEAN_NAME)) { RootBeanDefinition urlPathHelperDef = new RootBeanDefinition(UrlPathHelper.class); urlPathHelperDef.setSource(source); urlPathHelperDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); parserContext.getRegistry().registerBeanDefinition(URL_PATH_HELPER_BEAN_NAME, urlPathHelperDef); parserContext.registerComponent(new BeanComponentDefinition(urlPathHelperDef, URL_PATH_HELPER_BEAN_NAME)); } return new RuntimeBeanReference(URL_PATH_HELPER_BEAN_NAME); }
@Test public void uriTemplateVariables() { PatternsRequestCondition patterns = new PatternsRequestCondition("/{path1}/{path2}"); RequestMappingInfo key = new RequestMappingInfo(patterns, null, null, null, null, null, null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/1/2"); String lookupPath = new UrlPathHelper().getLookupPathForRequest(request); this.handlerMapping.handleMatch(key, lookupPath, request); @SuppressWarnings("unchecked") Map<String, String> uriVariables = (Map<String, String>) request.getAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); assertNotNull(uriVariables); assertEquals("1", uriVariables.get("path1")); assertEquals("2", uriVariables.get("path2")); }
@Test public void uriTemplateVariablesDecode() { PatternsRequestCondition patterns = new PatternsRequestCondition("/{group}/{identifier}"); RequestMappingInfo key = new RequestMappingInfo(patterns, null, null, null, null, null, null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/group/a%2Fb"); UrlPathHelper pathHelper = new UrlPathHelper(); pathHelper.setUrlDecode(false); String lookupPath = pathHelper.getLookupPathForRequest(request); this.handlerMapping.setUrlPathHelper(pathHelper); this.handlerMapping.handleMatch(key, lookupPath, request); @SuppressWarnings("unchecked") Map<String, String> uriVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); assertNotNull(uriVariables); assertEquals("group", uriVariables.get("group")); assertEquals("a/b", uriVariables.get("identifier")); }
@Test public void matrixVariablesDecoding() { MockHttpServletRequest request; UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setUrlDecode(false); urlPathHelper.setRemoveSemicolonContent(false); this.handlerMapping.setUrlPathHelper(urlPathHelper ); request = new MockHttpServletRequest(); testHandleMatch(request, "/path{filter}", "/path;mvar=a%2fb"); MultiValueMap<String, String> matrixVariables = getMatrixVariables(request, "filter"); Map<String, String> uriVariables = getUriTemplateVariables(request); assertNotNull(matrixVariables); assertEquals(Arrays.asList("a/b"), matrixVariables.get("mvar")); assertEquals(";mvar=a/b", uriVariables.get("filter")); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); CounterFactory.initialize(new EmptyCounterFactory()); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); rateLimitKeyGenerator = new DefaultRateLimitKeyGenerator(this.properties()); UrlPathHelper urlPathHelper = new UrlPathHelper(); this.filter = new RateLimitPreFilter(this.properties(), this.routeLocator(), urlPathHelper, this.rateLimiter, rateLimitKeyGenerator); this.context = new RequestContext(); RequestContext.testSetCurrentContext(this.context); RequestContextHolder.setRequestAttributes(requestAttributes); this.context.clear(); this.context.setRequest(this.request); this.context.setResponse(this.response); }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { StopWatch stopWatch = createStopWatchIfNecessary(request); String path = new UrlPathHelper().getPathWithinApplication(request); int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); try { chain.doFilter(request, response); status = getStatus(response); } finally { if (!request.isAsyncStarted()) { stopWatch.stop(); request.removeAttribute(ATTRIBUTE_STOP_WATCH); recordMetrics(request, path, status, stopWatch.getTotalTimeMillis()); } } }
@Override public StoreCondition getMatchingCondition(HttpServletRequest request) { String path = new UrlPathHelper().getPathWithinApplication(request); String[] segments = path.split("/"); if (segments.length < 3) { return null; } ContentStoreInfo info = ContentStoreUtils.findStore(stores, segments[1]); if (info != null && (Store.class.isAssignableFrom(info.getInterface()) && "store".equals(storeType)) || (ContentStore.class.isAssignableFrom(info.getInterface()) && "contentstore".equals(storeType)) ) { return this; } return null; }
@Override public int compareTo(StoreCondition other, HttpServletRequest request) { if (this.isMappingForRequest(request) && other.isMappingForRequest(request) == false) return 1; else if (this.isMappingForRequest(request) == false && other.isMappingForRequest(request)) return -1; else { String path = new UrlPathHelper().getPathWithinApplication(request); String filename = FilenameUtils.getName(path); String extension = FilenameUtils.getExtension(filename); if (extension != null && "store".equals(storeType)) { return -1; } else if (extension != null && "contentstore".equals(storeType)) { return 1; } return 0; } }
@StoreType("store") @RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET, headers={"accept!=application/hal+json", /*"range"*/}) public void getContent(HttpServletRequest request, HttpServletResponse response, @PathVariable String store) throws ServletException, IOException { ContentStoreInfo info = ContentStoreUtils.findStore(storeService, store); if (info == null) { throw new IllegalArgumentException("Entity not a content repository"); } String path = new UrlPathHelper().getPathWithinApplication(request); String pathToUse = path.substring(ContentStoreUtils.storePath(info).length() + 1); Resource r = ((Store)info.getImpementation()).getResource(pathToUse); if (r == null) { throw new ResourceNotFoundException(); } request.setAttribute("SPRING_CONTENT_RESOURCE", r); handler.handleRequest(request, response); return; }
@StoreType("store") @RequestMapping(value = BASE_MAPPING, method = RequestMethod.DELETE, headers="accept!=application/hal+json") public void deleteContent(HttpServletRequest request, HttpServletResponse response, @PathVariable String store) throws HttpRequestMethodNotSupportedException { ContentStoreInfo info = ContentStoreUtils.findStore(storeService, store); if (info == null) { throw new IllegalArgumentException("Not a Store"); } String path = new UrlPathHelper().getPathWithinApplication(request); String pathToUse = path.substring(ContentStoreUtils.storePath(info).length() + 1); Resource r = ((Store)info.getImpementation()).getResource(pathToUse); if (r == null) { throw new ResourceNotFoundException(); } if (r instanceof DeletableResource == false) { throw new UnsupportedOperationException(); } ((DeletableResource)r).delete(); }
private void initLookupPath(ResourceUrlProvider urlProvider) { if (this.indexLookupPath == null) { UrlPathHelper pathHelper = urlProvider.getUrlPathHelper(); String requestUri = pathHelper.getRequestUri(this.request); String lookupPath = pathHelper.getLookupPathForRequest(this.request); this.indexLookupPath = requestUri.lastIndexOf(lookupPath); this.prefixLookupPath = requestUri.substring(0, this.indexLookupPath); if ("/".equals(lookupPath) && !"/".equals(requestUri)) { String contextPath = pathHelper.getContextPath(this.request); if (requestUri.equals(contextPath)) { this.indexLookupPath = requestUri.length(); this.prefixLookupPath = requestUri; } } } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = asHttp(request); HttpServletResponse httpResponse = asHttp(response); Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username")); Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password")); String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try { if (postToManagementEndpoints(resourcePath)) { logger.debug("Trying to authenticate user {} for management endpoint by X-Auth-Username method", username); processManagementEndpointUsernamePasswordAuthentication(username, password); } logger.debug("ManagementEndpointAuthenticationFilter is passing request down the filter chain"); chain.doFilter(request, response); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } }
/** * 获得第三个路径分隔符的位置 * * @param request * @throws IllegalStateException * 访问路径错误,没有三(四)个'/' */ private static String getURI(HttpServletRequest request) throws IllegalStateException { UrlPathHelper helper = new UrlPathHelper(); String uri = helper.getOriginatingRequestUri(request); String ctxPath = helper.getOriginatingContextPath(request); int start = 0, i = 0, count = 2; if (!StringUtils.isBlank(ctxPath)) { count++; } while (i < count && start != -1) { start = uri.indexOf('/', start + 1); i++; } if (start <= 0) { throw new IllegalStateException( "admin access path not like '/jeeadmin/jeecms/...' pattern: " + uri); } return uri.substring(start); }
/** * Private constructor accepting a collection of patterns. */ private PatternsRequestCondition(Collection<String> patterns, UrlPathHelper urlPathHelper, PathMatcher pathMatcher, boolean useSuffixPatternMatch, boolean useTrailingSlashMatch, List<String> fileExtensions) { this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns)); this.pathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper(); this.pathMatcher = pathMatcher != null ? pathMatcher : new AntPathMatcher(); this.useSuffixPatternMatch = useSuffixPatternMatch; this.useTrailingSlashMatch = useTrailingSlashMatch; if (fileExtensions != null) { for (String fileExtension : fileExtensions) { if (fileExtension.charAt(0) != '.') { fileExtension = "." + fileExtension; } this.fileExtensions.add(fileExtension); } } }
/** * 获得第三个路径分隔符的位置 * * @param request * @throws IllegalStateException * 访问路径错误,没有三(四)个'/' */ private static String getURI(HttpServletRequest request) throws IllegalStateException { UrlPathHelper helper = new UrlPathHelper(); String uri = helper.getOriginatingRequestUri(request); String ctxPath = helper.getOriginatingContextPath(request); int start = 0, i = 0, count = 2; if (!StringUtils.isBlank(ctxPath)) { count++; } while (i < count && start != -1) { start = uri.indexOf('/', start + 1); i++; } if (start <= 0) { throw new IllegalStateException( "admin access path not like '/jeeadmin/jspgou/...' pattern: " + uri); } return uri.substring(start); }
@Bean public ResourceUrlProvider mvcResourceUrlProvider() { ResourceUrlProvider urlProvider = new ResourceUrlProvider(); UrlPathHelper pathHelper = getPathMatchConfigurer().getUrlPathHelper(); if (pathHelper != null) { urlProvider.setUrlPathHelper(pathHelper); } PathMatcher pathMatcher = getPathMatchConfigurer().getPathMatcher(); if (pathMatcher != null) { urlProvider.setPathMatcher(pathMatcher); } return urlProvider; }
/** * Return a global {@link UrlPathHelper} instance for path matching * patterns in {@link HandlerMapping}s. * This instance can be configured using the {@link PathMatchConfigurer} * in {@link #configurePathMatch(PathMatchConfigurer)}. * @since 4.1 */ @Bean public UrlPathHelper mvcUrlPathHelper() { if (getPathMatchConfigurer().getUrlPathHelper() != null) { return getPathMatchConfigurer().getUrlPathHelper(); } else { return new UrlPathHelper(); } }
@Test public void defaultPathMatchConfiguration() throws Exception { ApplicationContext context = initContext(WebConfig.class); UrlPathHelper urlPathHelper = context.getBean(UrlPathHelper.class); PathMatcher pathMatcher = context.getBean(PathMatcher.class); assertNotNull(urlPathHelper); assertNotNull(pathMatcher); assertEquals(AntPathMatcher.class, pathMatcher.getClass()); }
@Test public void configurePathMatch() throws Exception { final PathMatcher pathMatcher = mock(PathMatcher.class); final UrlPathHelper pathHelper = mock(UrlPathHelper.class); List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>(); configurers.add(new WebMvcConfigurerAdapter() { @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseRegisteredSuffixPatternMatch(true) .setUseTrailingSlashMatch(false) .setUrlPathHelper(pathHelper) .setPathMatcher(pathMatcher); } }); delegatingConfig.setConfigurers(configurers); RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping(); assertNotNull(handlerMapping); assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch", true, handlerMapping.useRegisteredSuffixPatternMatch()); assertEquals("PathMatchConfigurer should configure SuffixPatternMatch", true, handlerMapping.useSuffixPatternMatch()); assertEquals("PathMatchConfigurer should configure TrailingSlashMatch", false, handlerMapping.useTrailingSlashMatch()); assertEquals("PathMatchConfigurer should configure UrlPathHelper", pathHelper, handlerMapping.getUrlPathHelper()); assertEquals("PathMatchConfigurer should configure PathMatcher", pathMatcher, handlerMapping.getPathMatcher()); }
public RateLimitPreFilter(final RateLimitProperties properties, final RouteLocator routeLocator, final UrlPathHelper urlPathHelper, final RateLimiter rateLimiter, final RateLimitKeyGenerator rateLimitKeyGenerator) { super(properties, routeLocator, urlPathHelper); this.rateLimiter = rateLimiter; this.rateLimitKeyGenerator = rateLimitKeyGenerator; }
public RateLimitPostFilter(final RateLimitProperties properties, final RouteLocator routeLocator, final UrlPathHelper urlPathHelper, final RateLimiter rateLimiter, final RateLimitKeyGenerator rateLimitKeyGenerator) { super(properties, routeLocator, urlPathHelper); this.rateLimiter = rateLimiter; this.rateLimitKeyGenerator = rateLimitKeyGenerator; }
@Before public void setUp() { MockitoAnnotations.initMocks(this); when(httpServletRequest.getContextPath()).thenReturn("/servicea/test"); when(httpServletRequest.getRequestURI()).thenReturn("/servicea/test"); RequestContext requestContext = new RequestContext(); requestContext.setRequest(httpServletRequest); RequestContext.testSetCurrentContext(requestContext); RequestContextHolder.setRequestAttributes(requestAttributes); rateLimitProperties = new RateLimitProperties(); UrlPathHelper urlPathHelper = new UrlPathHelper(); target = new RateLimitPostFilter(rateLimitProperties, routeLocator, urlPathHelper, rateLimiter, rateLimitKeyGenerator); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); when(httpServletRequest.getContextPath()).thenReturn("/servicea/test"); when(httpServletRequest.getRequestURI()).thenReturn("/servicea/test"); RequestContext requestContext = new RequestContext(); requestContext.setRequest(httpServletRequest); RequestContext.testSetCurrentContext(requestContext); RequestContextHolder.setRequestAttributes(requestAttributes); rateLimitProperties = new RateLimitProperties(); UrlPathHelper urlPathHelper = new UrlPathHelper(); target = new RateLimitPreFilter(rateLimitProperties, routeLocator, urlPathHelper, rateLimiter, rateLimitKeyGenerator); }
public boolean isMappingForRequest(HttpServletRequest request) { String path = new UrlPathHelper().getPathWithinApplication(request); String[] segments = path.split("/"); if (segments.length < 3) { return false; } ContentStoreInfo info = ContentStoreUtils.findStore(stores, segments[1]); if (info != null && (Store.class.isAssignableFrom(info.getInterface()) && "store".equals(storeType)) || (ContentStore.class.isAssignableFrom(info.getInterface()) && "contentstore".equals(storeType)) ) { return true; } return false; }
@StoreType("store") @RequestMapping(value = BASE_MAPPING, method = RequestMethod.PUT, headers={"content-type!=multipart/form-data", "accept!=application/hal+json"}) @ResponseBody public void putContent(HttpServletRequest request, HttpServletResponse response, @PathVariable String store) throws IOException, HttpRequestMethodNotSupportedException, InstantiationException, IllegalAccessException { ContentStoreInfo info = ContentStoreUtils.findStore(storeService, store); if (info == null) { throw new IllegalArgumentException("Not a Store"); } String path = new UrlPathHelper().getPathWithinApplication(request); String pathToUse = path.substring(ContentStoreUtils.storePath(info).length() + 1); Resource r = ((Store)info.getImpementation()).getResource(pathToUse); if (r == null) { throw new ResourceNotFoundException(); } if (r instanceof WritableResource == false) { throw new UnsupportedOperationException(); } InputStream in = request.getInputStream(); OutputStream out = ((WritableResource)r).getOutputStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); }
@StoreType("store") @RequestMapping(value = BASE_MAPPING, method = RequestMethod.PUT, headers = "content-type=multipart/form-data") @ResponseBody public void putMultipartContent(HttpServletRequest request, HttpServletResponse response, @PathVariable String store, @RequestParam("file") MultipartFile multiPart) throws IOException, HttpRequestMethodNotSupportedException, InstantiationException, IllegalAccessException { String path = new UrlPathHelper().getPathWithinApplication(request); handleMultipart(store, path, multiPart); }
@StoreType("store") @RequestMapping(value = BASE_MAPPING, method = RequestMethod.POST, headers = "content-type=multipart/form-data") @ResponseBody public void postMultipartContent(HttpServletRequest request, HttpServletResponse response, @PathVariable String store, @RequestParam("file") MultipartFile multiPart) throws IOException, HttpRequestMethodNotSupportedException, InstantiationException, IllegalAccessException { String path = new UrlPathHelper().getPathWithinApplication(request); handleMultipart(store, path, multiPart); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = asHttp(request); HttpServletResponse httpResponse = asHttp(response); Optional<String> username = Optional.fromNullable(httpRequest.getParameter("username")); Optional<String> password = Optional.fromNullable(httpRequest.getParameter("password")); Optional<String> token = Optional.fromNullable(httpRequest.getHeader("Authorization")); String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try { if (postToAuthenticate(httpRequest, resourcePath)) { logger.debug("Trying to authenticate user {} by Username method", username); processUsernamePasswordAuthentication(httpResponse, username, password); return; } if (token.isPresent()) { logger.debug("Trying to authenticate user by Token method. Token: {}", token); processTokenAuthentication(token); } logger.debug("AuthenticationFilter is passing request down the filter chain"); addSessionContextToLogging(); chain.doFilter(request, response); } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) { SecurityContextHolder.clearContext(); logger.error("Internal authentication service exception", internalAuthenticationServiceException); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } finally { MDC.remove(TOKEN_SESSION_KEY); MDC.remove(USER_SESSION_KEY); } }
/** * 获得当的访问路径 * * HttpServletRequest.getRequestURL+"?"+HttpServletRequest.getQueryString * * @param request * @return */ public static String getLocation(HttpServletRequest request) { UrlPathHelper helper = new UrlPathHelper(); StringBuffer buff = request.getRequestURL(); String uri = request.getRequestURI(); String origUri = helper.getOriginatingRequestUri(request); buff.replace(buff.length() - uri.length(), buff.length(), origUri); String queryString = helper.getOriginatingQueryString(request); if (queryString != null) { buff.append("?").append(queryString); } return buff.toString(); }
public static String getURI(HttpServletRequest request) { UrlPathHelper helper = new UrlPathHelper(); String uri = helper.getOriginatingRequestUri(request); String ctx = helper.getOriginatingContextPath(request); if (!StringUtils.isBlank(ctx)) { return uri.substring(ctx.length()); } else { return uri; } }
/** * 获得翻页信息 * * @param request * @return */ public static PageInfo getPageInfo(HttpServletRequest request) { UrlPathHelper helper = new UrlPathHelper(); String uri = helper.getOriginatingRequestUri(request); String queryString = helper.getOriginatingQueryString(request); return getPageInfo(uri, queryString); }
public CmsLog loginSuccess(HttpServletRequest request, CmsUser user) { String ip = RequestUtils.getIpAddr(request); UrlPathHelper helper = new UrlPathHelper(); String uri = helper.getOriginatingRequestUri(request); Date date = new Date(); CmsLog log = save(CmsLog.LOGIN_SUCCESS, null, user, uri, ip, date,CmsLog.LOGIN_SUCCESS_TITLE, null); return log; }
public CmsLog loginFailure(HttpServletRequest request,String content) { String ip = RequestUtils.getIpAddr(request); UrlPathHelper helper = new UrlPathHelper(); String uri = helper.getOriginatingRequestUri(request); Date date = new Date(); CmsLog log = save(CmsLog.LOGIN_FAILURE, null, null, uri, ip, date,CmsLog.LOGIN_FAILURE_TITLE, content); return log; }