1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.virtualuri.mapping;
35
36 import info.magnolia.context.MgnlContext;
37 import info.magnolia.context.WebContext;
38
39 import java.net.URI;
40 import java.util.ArrayList;
41 import java.util.Collections;
42 import java.util.Comparator;
43 import java.util.List;
44 import java.util.Optional;
45
46 import org.apache.commons.lang3.StringUtils;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 public class HostBasedVirtualUriMapping extends DefaultVirtualUriMapping {
69 private static final Logger log = LoggerFactory.getLogger(HostBasedVirtualUriMapping.class);
70
71 private List<HostUriMapping> hostMappings = new ArrayList<>();
72
73 public List<HostUriMapping> getMappings() {
74 return Collections.unmodifiableList(hostMappings);
75 }
76
77 public void setMappings(List<HostUriMapping> hostMappings) {
78 this.hostMappings = hostMappings;
79 }
80
81
82
83
84
85
86 @Override
87 public Optional<Result> mapUri(URI uri) {
88 Optional<Result> fallbackResult = super.mapUri(uri);
89 if (!fallbackResult.isPresent()) {
90
91 return Optional.empty();
92 }
93
94 Optional<String> hostResult = tryToMapHost();
95 if (!hostResult.isPresent()) {
96 return fallbackResult;
97 }
98
99 return Optional.of(new Result(hostResult.get(), getPattern().getLength(), this));
100 }
101
102
103
104
105 protected Optional<String> tryToMapHost() {
106 if (hostMappings == null || hostMappings.isEmpty()) {
107 log.warn("No configured hosts to evaluate");
108 return Optional.empty();
109 }
110
111
112
113 String requestHost = ((WebContext) MgnlContext.getInstance()).getRequest().getServerName();
114 Comparator<HostUriMapping> hostLengthComparator = (hm1, hm2) -> Integer.compare(hm1.getHost().length(), hm2.getHost().length());
115
116 return hostMappings.stream()
117 .filter(hostMapping -> StringUtils.isNotEmpty(hostMapping.getToUri()) && StringUtils.isNotEmpty(hostMapping.getHost()) && requestHost.endsWith(hostMapping.getHost()))
118 .max(hostLengthComparator)
119 .map(HostUriMapping::getToUri);
120 }
121
122 @Override
123 public String toString() {
124 return "[" + super.toString() + "[hosts:" + hostMappings.toString() + "]]";
125 }
126
127
128
129
130 public static class HostUriMapping {
131 private String host;
132 private String toUri;
133
134 public String getHost() {
135 return host;
136 }
137
138 public void setHost(String host) {
139 this.host = host;
140 }
141
142 public String getToUri() {
143 return toUri;
144 }
145
146 public void setToUri(String toUri) {
147 this.toUri = toUri;
148 }
149
150 @Override
151 public String toString() {
152 return String.format("[%s --> %s]", host, toUri);
153 }
154 }
155 }