Merge branch 'release/5.45.0'
[cdmlib.git] / cdmlib-remote / src / main / java / eu / etaxonomy / cdm / remote / view / PatternViewResolver.java
1 /**
2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9 package eu.etaxonomy.cdm.remote.view;
10
11 import java.util.Arrays;
12 import java.util.HashSet;
13 import java.util.Locale;
14 import java.util.Set;
15
16 import org.springframework.beans.BeansException;
17 import org.springframework.beans.factory.BeanFactory;
18 import org.springframework.context.support.AbstractApplicationContext;
19 import org.springframework.util.AntPathMatcher;
20 import org.springframework.util.Assert;
21 import org.springframework.util.PathMatcher;
22 import org.springframework.web.servlet.View;
23 import org.springframework.web.servlet.view.XmlViewResolver;
24
25 /**
26 * Resolves views by using a {@link PathMatcher} to match the view name to the bean names.
27 *
28 * By default the {@link AntPathMatcher} is used which supports Ant-style path patterns.
29 * The mapping matches views using the following rules:
30 * <ul>
31 * <li>? matches one character
32 * <li>* matches zero or more characters
33 * <li>** matches zero or more 'directories' in a path
34 * </ul>
35 * @author ben.clark
36 */
37 public class PatternViewResolver extends XmlViewResolver {
38
39 private final Set<String> viewSet = new HashSet<>();
40
41 private PathMatcher pathMatcher = new AntPathMatcher();
42
43 public void setPathMatcher(PathMatcher pathMatcher) {
44 Assert.notNull(pathMatcher, "PathMatcher must not be null");
45 this.pathMatcher = pathMatcher;
46 }
47
48 public PathMatcher getPathMatcher() {
49 return this.pathMatcher;
50 }
51
52 @Override
53 public View resolveViewName(String viewName, Locale locale) throws Exception {
54 // Direct match?
55 if (this.viewSet.contains(viewName)) {
56 return super.resolveViewName(viewName, locale);
57 }
58 // Pattern match?
59 String bestPathMatch = null;
60 for (String registeredPath : this.viewSet) {
61 if (getPathMatcher().match(registeredPath, viewName) &&
62 (bestPathMatch == null || bestPathMatch.length() < registeredPath.length())) {
63 bestPathMatch = registeredPath;
64 }
65 }
66 if (bestPathMatch != null) {
67 return super.resolveViewName(bestPathMatch, locale);
68 }
69 // No view found...
70 return null;
71 }
72
73 @Override
74 protected synchronized BeanFactory initFactory() throws BeansException {
75 AbstractApplicationContext beanFactory = (AbstractApplicationContext)super.initFactory();
76 String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
77 for(String beanDefinitionName : beanDefinitionNames) {
78 viewSet.add(beanDefinitionName);
79 viewSet.addAll(Arrays.asList(beanFactory.getAliases(beanDefinitionName)));
80 }
81 return beanFactory;
82 }
83 }