forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssetHandler.java
More file actions
219 lines (194 loc) · 6.07 KB
/
AssetHandler.java
File metadata and controls
219 lines (194 loc) · 6.07 KB
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
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import javax.annotation.Nonnull;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
/**
* Handler for static resources represented by the {@link Asset} contract.
*
* It has built-in support for static-static as well as SPAs (single page applications).
*
* @author edgar
* @since 2.0.0
*/
public class AssetHandler implements Route.Handler {
private static final int ONE_SEC = 1000;
private final AssetSource[] sources;
private final CacheControl defaults = CacheControl.defaults();
private String filekey;
private String fallback;
private Function<String, CacheControl> cacheControl = path -> defaults;
/**
* Creates a new asset handler that fallback to the given fallback asset when the asset
* is not found. Instead of produces a <code>404</code> its fallback to the given asset.
*
* <pre>{@code
* {
* assets("/?*", new AssetHandler("index.html", AssetSource.create(Paths.get("...")));
* }
* }</pre>
*
* The fallback option makes the asset handler to work like a SPA (Single-Application-Page).
*
* @param fallback Fallback asset.
* @param sources Asset sources. At least one source is required.
*/
public AssetHandler(@Nonnull String fallback, AssetSource... sources) {
this.fallback = fallback;
this.sources = checkSource(sources);
}
/**
* Creates a new asset handler.
*
* @param sources Asset sources. At least one source is required.
*/
public AssetHandler(AssetSource... sources) {
this.sources = checkSource(sources);
}
@Nonnull @Override public Object apply(@Nonnull Context ctx) throws Exception {
final String resolvedPath;
String filepath = ctx.pathMap().getOrDefault(filekey, "index.html");
Asset asset = resolve(filepath);
if (asset == null) {
if (fallback != null) {
asset = resolve(fallback);
}
// Still null?
if (asset == null) {
ctx.send(StatusCode.NOT_FOUND);
return ctx;
} else {
resolvedPath = fallback;
}
} else {
resolvedPath = filepath;
}
CacheControl cacheParams = cacheControl.apply(resolvedPath);
// handle If-None-Match
if (cacheParams.isEtag()) {
String ifnm = ctx.header("If-None-Match").value((String) null);
if (ifnm != null && ifnm.equals(asset.getEtag())) {
ctx.send(StatusCode.NOT_MODIFIED);
asset.close();
return ctx;
} else {
ctx.setResponseHeader("ETag", asset.getEtag());
}
}
// Handle If-Modified-Since
if (cacheParams.isLastModified()) {
long lastModified = asset.getLastModified();
if (lastModified > 0) {
long ifms = ctx.header("If-Modified-Since").longValue(-1);
if (lastModified / ONE_SEC <= ifms / ONE_SEC) {
ctx.send(StatusCode.NOT_MODIFIED);
asset.close();
return ctx;
}
ctx.setResponseHeader("Last-Modified", Instant.ofEpochMilli(lastModified));
}
}
// cache control
if (cacheParams.getMaxAge() >= 0) {
ctx.setResponseHeader("Cache-Control", "max-age=" + cacheParams.getMaxAge());
} else if (cacheParams.getMaxAge() == CacheControl.NO_CACHE) {
ctx.setResponseHeader("Cache-Control", "no-store, must-revalidate");
}
long length = asset.getSize();
if (length != -1) {
ctx.setResponseLength(length);
}
ctx.setResponseType(asset.getContentType());
return ctx.send(asset.stream());
}
/**
* Turn on/off e-tag support.
*
* @param etag True for turning on.
* @return This handler.
*/
public AssetHandler setETag(boolean etag) {
defaults.setETag(etag);
return this;
}
/**
* Turn on/off handling of {@code If-Modified-Since} header.
*
* @param lastModified True for turning on. Default is: true.
* @return This handler.
*/
public AssetHandler setLastModified(boolean lastModified) {
defaults.setLastModified(lastModified);
return this;
}
/**
* Set cache-control header with the given max-age value. If max-age is greater than 0.
*
* @param maxAge Max-age value in seconds.
* @return This handler.
*/
public AssetHandler setMaxAge(long maxAge) {
defaults.setMaxAge(maxAge);
return this;
}
/**
* Set cache-control header with the given max-age value. If max-age is greater than 0.
*
* @param maxAge Max-age value in seconds.
* @return This handler.
*/
public AssetHandler setMaxAge(Duration maxAge) {
defaults.setMaxAge(maxAge);
return this;
}
/**
* Set cache-control header to {@code no-store, must-revalidate}, disables e-tag
* and {@code If-Modified-Since} header support.
*
* @return This handler.
*/
public AssetHandler setNoCache() {
defaults.setNoCache();
return this;
}
/**
* Sets a custom function that provides caching configuration for each individual
* asset response overriding the defaults set in {@link AssetHandler}.
*
* @param cacheControl a cache configuration provider function.
* @return this instance.
* @see CacheControl
*/
public AssetHandler cacheControl(@Nonnull Function<String, CacheControl> cacheControl) {
this.cacheControl = requireNonNull(cacheControl);
return this;
}
private Asset resolve(String filepath) {
for (AssetSource source : sources) {
Asset asset = source.resolve(filepath);
if (asset != null) {
return asset;
}
}
return null;
}
@Override public void setRoute(Route route) {
List<String> keys = route.getPathKeys();
this.filekey = keys.size() == 0 ? route.getPattern().substring(1) : keys.get(0);
// NOTE: It send an inputstream we don't need a renderer
route.setReturnType(Context.class);
}
private static AssetSource[] checkSource(AssetSource[] sources) {
if (sources.length == 0) {
throw new IllegalArgumentException("At least one source is required.");
}
return sources;
}
}