/
UnmappedResourceHandler.java
256 lines (218 loc) · 9.91 KB
/
UnmappedResourceHandler.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
* Copyright OmniFaces
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.omnifaces.resourcehandler;
import static jakarta.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static jakarta.servlet.http.HttpServletResponse.SC_NOT_MODIFIED;
import static java.util.logging.Level.FINE;
import static org.omnifaces.facesviews.FacesViews.isMultiViewsEnabled;
import static org.omnifaces.util.Faces.getMapping;
import static org.omnifaces.util.Faces.getRequestContextPath;
import static org.omnifaces.util.Faces.getServletContext;
import static org.omnifaces.util.Faces.isPrefixMapping;
import static org.omnifaces.util.FacesLocal.getRequestURI;
import static org.omnifaces.util.Utils.stream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.logging.Logger;
import jakarta.faces.application.Resource;
import jakarta.faces.application.ResourceHandler;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.faces.webapp.FacesServlet;
import org.omnifaces.util.FacesLocal;
import org.omnifaces.util.Hacks;
/**
* <p>
* This {@link ResourceHandler} implementation allows the developer to map Faces resources on an URL pattern of
* <code>/jakarta.faces.resource/*</code> (basically, the value of {@link ResourceHandler#RESOURCE_IDENTIFIER}) without
* the need for an additional {@link FacesServlet} prefix or suffix URL pattern in the default produced resource URLs,
* such as <code>/jakarta.faces.resource/faces/css/style.css</code> or
* <code>/jakarta.faces.resource/css/style.css.xhtml</code>. This resource handler will produce unmapped URLs like
* <code>/jakarta.faces.resource/css/style.css</code>. This has the major advantage that the developer don't need the
* <code>#{resource}</code> EL expression anymore in order to properly reference relative URLs to images in CSS files.
* <p>
* So, given the following folder structure,
* <pre>
* WebContent
* `-- resources
* `-- css
* |-- images
* | `-- background.png
* `-- style.css
* </pre>
* <p>And the following CSS file reference (note: the <code>library</code> is <strong>not</strong> supported by the
* <code>UnmappedResourceHandler</code>! this is a technical limitation, just exclusively use <code>name</code>):
* <pre>
* <h:outputStylesheet name="css/style.css" />
* </pre>
* <p>you can in <code>css/style.css</code> just use:
* <pre>
* body {
* background: url("images/background.png");
* }
* </pre>
* <p>instead of
* <pre>
* body {
* background: url("#{resource['css/images/background.png']}");
* }
* </pre>
* <p>
* This has in turn the advantage that you don't need to modify the background image or font face URLs in CSS files from
* 3rd party libraries such as Twitter Bootstrap, FontAwesome, etcetera.
*
* <h2>Installation</h2>
* <p>
* To get it to run, this handler needs be registered as follows in <code>faces-config.xml</code>:
* <pre>
* <application>
* <resource-handler>org.omnifaces.resourcehandler.UnmappedResourceHandler</resource-handler>
* </application>
* </pre>
* <p>
* And the {@link FacesServlet} needs to have an additional mapping <code>/jakarta.faces.resource/*</code> in
* <code>web.xml</code>. You can just add it as a new <code><url-pattern></code> entry to the existing mapping
* of the {@link FacesServlet}. For example, assuming that you've already a mapping on <code>*.xhtml</code>:
* <pre>
* <servlet-mapping>
* ...
* <url-pattern>*.xhtml</url-pattern>
* <url-pattern>/jakarta.faces.resource/*</url-pattern>
* </servlet-mapping>
* </pre>
*
* <h2>CombinedResourceHandler</h2>
* <p>
* If you're also using the {@link CombinedResourceHandler} or any other custom resource handler, then you need to
* ensure that this is in <code>faces-config.xml</code> declared <strong>before</strong> the
* <code>UnmappedResourceHandler</code>. Thus, like so:
* <pre>
* <application>
* <resource-handler>org.omnifaces.resourcehandler.CombinedResourceHandler</resource-handler>
* <resource-handler>org.omnifaces.resourcehandler.UnmappedResourceHandler</resource-handler>
* </application>
* </pre>
* <p>
* Otherwise the combined resource handler will still produce mapped URLs. In essence, the one which is later
* registered wraps the previously registered one.
*
* @author Bauke Scholtz
* @since 1.4
* @see RemappedResource
* @see DefaultResourceHandler
*/
public class UnmappedResourceHandler extends DefaultResourceHandler {
// Constants ------------------------------------------------------------------------------------------------------
private static final Logger logger = Logger.getLogger(UnmappedResourceHandler.class.getName());
// Constructors ---------------------------------------------------------------------------------------------------
/**
* Creates a new instance of this unmapped resource handler which wraps the given resource handler.
* @param wrapped The resource handler to be wrapped.
*/
public UnmappedResourceHandler(ResourceHandler wrapped) {
super(wrapped);
}
// Actions --------------------------------------------------------------------------------------------------------
/**
* If the given resource is not <code>null</code>, then decorate it as an unmapped resource.
*/
@Override
public Resource decorateResource(Resource resource) {
if (resource == null) {
return resource;
}
String path = fixMyFacesMultiViewsPrefixMappingIfNecessary(resource.getRequestPath());
return isResourceRequest(path) ? new RemappedResource(resource, unmapRequestPath(path)) : resource;
}
@Override
public boolean isResourceRequest(FacesContext context) {
return isResourceRequest(getRequestURI(context)) || super.isResourceRequest(context);
}
@Override
public void handleResourceRequest(FacesContext context) throws IOException {
Resource resource = createResource(context);
if (resource == null) {
super.handleResourceRequest(context);
return;
}
ExternalContext externalContext = context.getExternalContext();
if (!resource.userAgentNeedsUpdate(context)) {
externalContext.setResponseStatus(SC_NOT_MODIFIED);
return;
}
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
}
catch (Exception resourceNameIsProbablyInvalid) {
logger.log(FINE, "Ignoring thrown exception; this can only be caused by a spoofed request.", resourceNameIsProbablyInvalid);
}
if (inputStream == null) {
externalContext.setResponseStatus(SC_NOT_FOUND);
return;
}
externalContext.setResponseContentType(resource.getContentType());
for (Entry<String, String> header : resource.getResponseHeaders().entrySet()) {
externalContext.setResponseHeader(header.getKey(), header.getValue());
}
stream(inputStream, externalContext.getResponseOutputStream());
}
// Helpers --------------------------------------------------------------------------------------------------------
private static boolean isResourceRequest(String path) {
return path.startsWith(getRequestContextPath() + RESOURCE_IDENTIFIER);
}
private static String fixMyFacesMultiViewsPrefixMappingIfNecessary(String path) {
if (!(Hacks.isMyFacesUsed() && isMultiViewsEnabled(getServletContext()) && isPrefixMapping())) {
return path;
}
int resourceIdentifierIndex = path.indexOf(RESOURCE_IDENTIFIER);
if (resourceIdentifierIndex > -1) {
String contextPath = getRequestContextPath();
if (path.startsWith(contextPath)) {
String resourcePath = contextPath + RESOURCE_IDENTIFIER;
if (!path.startsWith(resourcePath)) {
return resourcePath + path.substring(resourceIdentifierIndex);
}
}
}
return path;
}
private static String unmapRequestPath(String path) {
String mapping = getMapping();
if (isPrefixMapping(mapping)) {
return path.replaceFirst(mapping, "");
}
else if (path.contains("?")) {
return path.replace(mapping + "?", "?");
}
else if (path.endsWith(mapping)) {
return path.substring(0, path.length() - mapping.length());
}
else {
return path;
}
}
private static Resource createResource(FacesContext context) {
if (Hacks.isPrimeFacesDynamicResourceRequest(context)) {
return null;
}
String pathInfo = context.getExternalContext().getRequestPathInfo();
String resourceName = (pathInfo != null) ? pathInfo.substring(1) : "";
if (resourceName.isEmpty()) {
return null;
}
String libraryName = context.getExternalContext().getRequestParameterMap().get("ln");
return FacesLocal.createResource(context, libraryName, resourceName);
}
}