@RequestMapping(value = "/{solution}/**", method = {RequestMethod.GET, RequestMethod.HEAD}) @ResponseBody public ResponseEntity<FileSystemResource> getFile(@PathVariable("solution") String solution, HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); AntPathMatcher apm = new AntPathMatcher(); path = apm.extractPathWithinPattern(bestMatchPattern, path); File file = fileService.getFile(solution, path); if (file.exists() && file.isFile()) { try { String detect = tika.detect(file); MediaType mediaType = MediaType.parseMediaType(detect); return ResponseEntity.ok() .contentLength(file.length()) .contentType(mediaType) .lastModified(file.lastModified()) .body(new FileSystemResource(file)); } catch (IOException e) { e.printStackTrace(); } } else { throw new ResourceNotFoundException(); } return null; }
@Test public void dotPathSeparator() { DotPathSeparatorController controller = new DotPathSeparatorController(); this.messageHandler.setPathMatcher(new AntPathMatcher(".")); this.messageHandler.registerHandler(controller); this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/")); Message<?> message = createMessage("/app1/pre.foo"); this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); assertEquals("handleFoo", controller.method); message = createMessage("/app2/pre.foo"); this.messageHandler.handleMessage(message); assertEquals("handleFoo", controller.method); }
/** * 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 PathMatcher} * under that well-known name, unless already registered. * @return a RuntimeBeanReference to this {@link PathMatcher} instance */ public static RuntimeBeanReference registerPathMatcher(RuntimeBeanReference pathMatcherRef, ParserContext parserContext, Object source) { if (pathMatcherRef != null) { if (parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME)) { parserContext.getRegistry().removeAlias(PATH_MATCHER_BEAN_NAME); } parserContext.getRegistry().registerAlias(pathMatcherRef.getBeanName(), PATH_MATCHER_BEAN_NAME); } else if (!parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME) && !parserContext.getRegistry().containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) { RootBeanDefinition pathMatcherDef = new RootBeanDefinition(AntPathMatcher.class); pathMatcherDef.setSource(source); pathMatcherDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); parserContext.getRegistry().registerBeanDefinition(PATH_MATCHER_BEAN_NAME, pathMatcherDef); parserContext.registerComponent(new BeanComponentDefinition(pathMatcherDef, PATH_MATCHER_BEAN_NAME)); } return new RuntimeBeanReference(PATH_MATCHER_BEAN_NAME); }
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) { PathMatcher pathMatcher = new AntPathMatcher(); List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>(); for (Object interceptor : this.registry.getInterceptors()) { if (interceptor instanceof MappedInterceptor) { MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor; if (mappedInterceptor.matches(lookupPath, pathMatcher)) { result.add(mappedInterceptor.getInterceptor()); } } else if (interceptor instanceof HandlerInterceptor) { result.add((HandlerInterceptor) interceptor); } else { fail("Unexpected interceptor type: " + interceptor.getClass().getName()); } } return result; }
@Override public List<Log> getLogs() throws IOException { final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); resolver.setPathMatcher(new AntPathMatcher()); final Resource[] resources = resolver.getResources("file:" + getPattern()); final ArrayList<Log> logs = new ArrayList<Log>(resources.length); // TODO Decouple direct file log association for (int i = 0; i < resources.length; i++) { if (resources[i].exists()) { if (resources[i].getFile().isFile()) { logs.add(new FileLog(resources[i].getFile())); } } else { logger.info("Ignore not existent file: {}", resources[i].getFile()); } } return logs; }
@Override public void configureMessageBroker(final MessageBrokerRegistry config) { // to support stomp over websockets natively... logger.warn(" ~~> issue #24 - not using the spring stomp broker relay until it supports reactor 3"); config.enableSimpleBroker("/topic"); // to use the stomp support built into RabbitMQ... // NOTE: not using this due to https://github.com/the-james-burton/the-turbine/issues/24 // config.enableStompBrokerRelay("/topic", "/queue") // .setRelayHost("localhost") // .setRelayPort(61613) // .setSystemLogin("guest") // .setSystemPasscode("guest"); // // .setVirtualHost("/"); config.setApplicationDestinationPrefixes("/app"); config.setPathMatcher(new AntPathMatcher(".")); }
private void initCache(List<Object> controllers){ if(null == mappingCache){ mappingCache = new HashMap<String, Action>(); } AntPathMatcher matcher = new AntPathMatcher(); for(Object bean : controllers){ Class<?> clazz = bean.getClass(); List<Method> methods = ReflectUtil.getPublicMethods(clazz); String mapping = getMapping(clazz); log.info(clazz.getName()); for(Method method : methods){ String returnType = method.getReturnType().getName(); if(!(void.class.getName().equals(returnType) || String.class.getName().equals(returnType))){ continue; } String resource = mapping + method.getName(); String[] argNames = ReflectUtil.getMethodArgNames(clazz.getName(), method.getName()); Action action = new Action(bean, method, method.getParameterTypes(), argNames, resource); action.setInterceptors(this.interceptorConfigBean.getInterceptors(resource, matcher)); mappingCache.put(resource, action); log.info(resource); } } }
@Before public void setup() { MockitoAnnotations.initMocks(this); when(this.clientOutboundChannel.send(any(WampMessage.class))).thenReturn(true); DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(); MethodParameterConverter paramConverter = new MethodParameterConverter( new ObjectMapper(), conversionService); this.messageHandler = new WampAnnotationMethodMessageHandler( this.clientInboundChannel, this.clientOutboundChannel, this.eventMessenger, conversionService, paramConverter, new AntPathMatcher(), WampMessageSelectors.ACCEPT_ALL, new GenericMessageConverter()); @SuppressWarnings("resource") StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerPrototype("annotatedTestService", AnnotatedTestService.class); applicationContext.refresh(); this.messageHandler.setApplicationContext(applicationContext); this.messageHandler.afterPropertiesSet(); this.messageHandler.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); } } }
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) { PathMatcher pathMatcher = new AntPathMatcher(); List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>(); for (Object i : registry.getInterceptors()) { if (i instanceof MappedInterceptor) { MappedInterceptor mappedInterceptor = (MappedInterceptor) i; if (mappedInterceptor.matches(lookupPath, pathMatcher)) { result.add(mappedInterceptor.getInterceptor()); } } else if (i instanceof HandlerInterceptor){ result.add((HandlerInterceptor) i); } else { fail("Unexpected interceptor type: " + i.getClass().getName()); } } return result; }
/** * Try to match a ant url pattern in url mapping and return the UI bean name * @param request vaadin request * @return the bean name for request, null if none. */ protected String getBeanNameFromRequest(VaadinRequest request) { String beanName = null; String pathInfo = request.getPathInfo(); if (this.pathMatcher == null) this.pathMatcher = new AntPathMatcher(); for (String pattern : this.urlMap.keySet()) { if (log.isDebugEnabled()) log.debug("Matching pattern [" + pattern + "] over path info [" + pathInfo + "]"); if (this.pathMatcher.match(pattern, request.getPathInfo())) { beanName = this.urlMap.get(pattern); if (log.isDebugEnabled()) log.debug("Matching success. Using bean name [" + beanName + "]"); break; } } if (beanName == null) beanName = request.getPathInfo(); return beanName; }
/** * Gets the registered service by id that would either match an ant or regex pattern. * * @param id the id * @return the registered service */ private AbstractRegisteredService getRegisteredService(@NotNull final String id) { if (RegexUtils.isValidRegex(id)) { return new RegexRegisteredService(); } if (new AntPathMatcher().isPattern(id)) { return new RegisteredServiceImpl(); } return null; }
/** * Determine service type by pattern. * * @param serviceId the service id * @return the abstract registered service */ private AbstractRegisteredService determineServiceTypeByPattern(final String serviceId) { try { Pattern.compile(serviceId); LOGGER.debug("Service id {} is a valid regex.", serviceId); return new RegexRegisteredService(); } catch (final PatternSyntaxException exception) { LOGGER.debug("Service id {} is not a valid regex. Checking ant patterns...", serviceId); if (new AntPathMatcher().isPattern(serviceId)) { LOGGER.debug("Service id {} is a valid ant pattern.", serviceId); return new RegisteredServiceImpl(); } } throw new RuntimeException("Service id " + serviceId + " cannot be resolve to a service type"); }
/** * Gets the registered service by id that would either match an ant or regex pattern. * * @param id the id * @return the registered service */ private AbstractRegisteredService getRegisteredService(@NotNull final String id) { if (isValidRegexPattern(id)) { return new RegexRegisteredService(); } if (new AntPathMatcher().isPattern(id)) { return new RegisteredServiceImpl(); } return null; }
private AbstractRegisteredService getRegisteredService(@NotNull final String id) { if (isValidRegexPattern(id)) { return new RegexRegisteredService(); } if (new AntPathMatcher().isPattern(id)) { return new RegisteredServiceImpl(); } return null; }
@Test public void test() { AntPathMatcher matcher = new AntPathMatcher(); String url = "/config/tenants/XM/entity/specs/xmentityspecs.yml"; String pattern = "/config/tenants/{tenantName}/entity/specs/xmentityspecs.yml"; System.out.println(matcher.match(pattern, url)); System.out.println(matcher.extractUriTemplateVariables(pattern, url).get("tenantName")); }
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(apiAuthInterceptor()) .addPathPatterns("/api/mars/**") .addPathPatterns("/do") .pathMatcher(new AntPathMatcher()); }
@Test public void prependSlashWithCustomPathSeparator() { DestinationPatternsMessageCondition c = new DestinationPatternsMessageCondition(new String[] {"foo"}, new AntPathMatcher(".")); assertEquals("Pre-pending should be disabled when not using '/' as path separator", "foo", c.getPatterns().iterator().next()); }
/** * Return a global {@link PathMatcher} 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 PathMatcher mvcPathMatcher() { if (getPathMatchConfigurer().getPathMatcher() != null) { return getPathMatchConfigurer().getPathMatcher(); } else { return new AntPathMatcher(); } }
@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()); }
/** * Determine service type by pattern. * * @param serviceId the service id * @return the abstract registered service */ private static AbstractRegisteredService determineServiceTypeByPattern(final String serviceId) { if (RegexUtils.isValidRegex(serviceId)) { LOGGER.debug("Service id {} is a valid regex.", serviceId); return new RegexRegisteredService(); } if (new AntPathMatcher().isPattern(serviceId)) { LOGGER.debug("Service id {} is a valid ant pattern.", serviceId); return new RegisteredServiceImpl(); } throw new RuntimeException("Service id " + serviceId + " cannot be resolve to a service type"); }
@Autowired public EventRouter(SimpMessagingTemplate simpMessagingTemplate, @Qualifier("clientOutboundChannel") MessageChannel clientChannel, @Qualifier(EventsUtils.BUS_ERRORS) Subscriptions<?> errorsSubs) { this.clientChannel = clientChannel; this.simpMessagingTemplate = simpMessagingTemplate; //default value this.pathMatcher = new AntPathMatcher(); this.acceptBus(errorsSubs); }
@Override public void configurePathMatch(PathMatchConfigurer configurer) { //This should make the url case insensitive AntPathMatcher matcher = new AntPathMatcher(); matcher.setCaseSensitive(false); configurer.setPathMatcher(matcher); }
public static Comparator<String> pathPatternComparator() { String path = (String)RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); if (StringUtils.isEmpty(path)) { throw new IllegalArgumentException("Path must not be empty"); } AntPathMatcher matcher = new AntPathMatcher(); return matcher.getPatternComparator(path); }
public static boolean matchesPathPattern(String pattern) { String path = (String)RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); // If They are both blank, then there is a default pattern if (StringUtils.isEmpty(path) && StringUtils.isEmpty(pattern)) { return true; } AntPathMatcher apm = new AntPathMatcher(); return apm.match(pattern, path); }
public static String getRequestPathVariable(String variableName) { String path = (String)RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); String bestMatchPattern = (String)RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); AntPathMatcher apm = new AntPathMatcher(); Map<String, String> variables = apm.extractUriTemplateVariables(bestMatchPattern, path); return variables.getOrDefault(variableName, null); }
public static Map<String, String> getRequestPathVariables() { String path = (String)RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); String bestMatchPattern = (String)RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); if (bestMatchPattern == null) { return new LinkedHashMap<>(); } AntPathMatcher apm = new AntPathMatcher(); Map<String, String> variables = apm.extractUriTemplateVariables(bestMatchPattern, path); return variables; }
/** * Set the included paths; an empty list will apply it to all paths except the ones specified by the 'excludePath' * * @param includePath A set of paths to apply this filter on */ @Value(value = "#{'${io.sprucehill.spring.filter.cors.path.include:}'.split(',')}") public void setIncludePath(Set<String> includePath) { if (1 == includePath.size() && includePath.stream().findFirst().get().isEmpty()) { this.includePath = new HashSet<>(); } else { this.includePath = includePath.stream().map(AntPathMatcher::new).collect(Collectors.toSet()); } }
/** * Set the excluded paths; excluded paths have precedence over included ones * * @param excludePath A set of paths to not apply this filter on */ @Value(value = "#{'${io.sprucehill.spring.filter.cors.path.exclude:}'.split(',')}") public void setExcludePath(Set<String> excludePath) { if (1 == excludePath.size() && excludePath.stream().findFirst().get().isEmpty()) { this.excludePath = new HashSet<>(); } else { this.excludePath = excludePath.stream().map(AntPathMatcher::new).collect(Collectors.toSet()); } }
@Test public void testAntMatcher(){ AntPathMatcher path = new AntPathMatcher(); boolean rs = path.match("/user.*", "/user.json?aaa=bbb&cc=ddd"); Assert.assertTrue(rs); //后缀的点号变成可选的写法? rs = path.match("/user.*", "/user"); Assert.assertFalse(rs); }
/** * getRoutingInfo: Returns the routing info for the given request and method. * @param requestUri * @param httpMethod * @return RoutingInfo The routing info for the matching route or <code>null</code> * if no match was found. */ public RoutingInfo getRoutingInfo(String requestUri, String httpMethod) { // create a new path matcher instance. AntPathMatcher matcher = new AntPathMatcher(); // define a map to hold parameter versions. Map<String, String> pathParams = null; // for each defined route for (IRoute route : _routes) { // extract the URI. String routeUri = route.getUri(); // if the defined route uses the given http method and the URIs match if (httpMethod.equals(route.getHttpMethod()) && matcher.match(routeUri, requestUri)) { // extract the template parameters from the uri. pathParams = matcher.extractUriTemplateVariables(routeUri, requestUri); // define a new routing info object RoutingInfo routingInfo = new RoutingInfo(); // set the values routingInfo.setRoute(route); routingInfo.setPathParameters(pathParams); // return the instance return routingInfo; } } // if we get here, no match. return null; }
private VersionEntry matchLatestByPattern(List<VersionEntry> results, String version) { AntPathMatcher matcher = new AntPathMatcher(); for (VersionEntry result : results) { if (matcher.match(version, result.getVersion())) { return result; } } return null; }
private void matchByPattern(ArtifactVersionsResult artifactVersions, String version) { List<VersionEntry> filteredResults = Lists.newArrayList(); AntPathMatcher matcher = new AntPathMatcher(); for (VersionEntry result : artifactVersions.getResults()) { if (matcher.match(version, result.getVersion())) { filteredResults.add(result); } } artifactVersions.setResults(filteredResults); }
public List<Interceptor> getInterceptors(String path, AntPathMatcher matcher) { List<Interceptor> interceptors = new ArrayList<Interceptor>(); for (InterceptorConfigHolder.InterceptorConfig interceptorConfig : interceptorConfigs) { if (matcher.match(interceptorConfig.getPath(), path)) { interceptors.add(SpringContainer.getBean(interceptorConfig.getClazz())); } } return interceptors; }