/
StaticServlet.java
198 lines (169 loc) · 6.48 KB
/
StaticServlet.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
/*
* Copyright (C) 2020 ActiveJ LLC.
*
* 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
*
* http://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 io.activej.http;
import io.activej.async.function.AsyncSupplier;
import io.activej.bytebuf.ByteBuf;
import io.activej.http.loader.ResourceIsADirectoryException;
import io.activej.http.loader.ResourceNotFoundException;
import io.activej.http.loader.StaticLoader;
import io.activej.promise.Promise;
import io.activej.promise.Promises;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
import static io.activej.http.HttpHeaderValue.ofContentType;
import static io.activej.http.HttpHeaders.CONTENT_TYPE;
/**
* This servlet allows return HTTP responses by HTTP paths from some predefined storage, mainly the filesystem.
*/
public final class StaticServlet implements AsyncServlet {
public static final Charset DEFAULT_TXT_ENCODING = StandardCharsets.UTF_8;
private final StaticLoader resourceLoader;
private Function<String, ContentType> contentTypeResolver = StaticServlet::getContentType;
private Function<HttpRequest, @Nullable String> pathMapper = HttpRequest::getRelativePath;
private Supplier<HttpResponse> responseSupplier = HttpResponse::ok200;
private final Set<String> indexResources = new LinkedHashSet<>();
@Nullable
private String defaultResource;
private StaticServlet(StaticLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public static StaticServlet create(StaticLoader resourceLoader) {
return new StaticServlet(resourceLoader);
}
public static StaticServlet create(StaticLoader resourceLoader, String page) {
return create(resourceLoader).withMappingTo(page);
}
public static StaticServlet ofClassPath(Executor executor, String path) {
return new StaticServlet(StaticLoader.ofClassPath(executor, path));
}
public static StaticServlet ofPath(Executor executor, Path path) {
return new StaticServlet(StaticLoader.ofPath(executor, path));
}
@SuppressWarnings("UnusedReturnValue")
public StaticServlet withContentType(ContentType contentType) {
return withContentTypeResolver($ -> contentType);
}
public StaticServlet withContentTypeResolver(Function<String, ContentType> contentTypeResolver) {
this.contentTypeResolver = contentTypeResolver;
return this;
}
public StaticServlet withMapping(Function<HttpRequest, String> fn) {
pathMapper = fn;
return this;
}
public StaticServlet withMappingTo(String path) {
//noinspection RedundantCast - it does not compile without the cast
if (this.contentTypeResolver == (Function<String, ContentType>) StaticServlet::getContentType) {
withContentType(getContentType(path));
}
return withMapping($ -> path);
}
public StaticServlet withMappingNotFoundTo(String defaultResource) {
this.defaultResource = defaultResource;
return this;
}
public StaticServlet withIndexResources(String... indexResources) {
this.indexResources.addAll(Arrays.asList(indexResources));
return this;
}
public StaticServlet withIndexHtml() {
this.indexResources.add("index.html");
return this;
}
public StaticServlet withResponse(Supplier<HttpResponse> responseSupplier) {
this.responseSupplier = responseSupplier;
return this;
}
public static ContentType getContentType(String path) {
int pos = path.lastIndexOf('.');
if (pos == -1) {
return ContentType.of(MediaTypes.OCTET_STREAM);
}
String ext = path.substring(pos + 1);
MediaType mime = MediaTypes.getByExtension(ext);
if (mime == null) {
mime = MediaTypes.OCTET_STREAM;
}
ContentType type;
if (mime.isTextType()) {
type = ContentType.of(mime, DEFAULT_TXT_ENCODING);
} else {
type = ContentType.of(mime);
}
return type;
}
private HttpResponse createHttpResponse(ByteBuf buf, ContentType contentType) {
return responseSupplier.get()
.withBody(buf)
.withHeader(CONTENT_TYPE, ofContentType(contentType));
}
@NotNull
@Override
public final Promise<HttpResponse> serve(@NotNull HttpRequest request) {
String mappedPath = pathMapper.apply(request);
if (mappedPath == null) return Promise.ofException(HttpError.notFound404());
ContentType contentType = contentTypeResolver.apply(mappedPath);
return Promise.complete()
.then(() -> (mappedPath.endsWith("/") || mappedPath.isEmpty()) ?
tryLoadIndexResource(mappedPath) :
resourceLoader.load(mappedPath)
.map(byteBuf -> createHttpResponse(byteBuf, contentType))
.thenEx((value, e) -> {
if (e instanceof ResourceIsADirectoryException) {
return tryLoadIndexResource(mappedPath);
} else {
return Promise.of(value, e);
}
}))
.thenEx((response, e) -> {
if (e == null) {
return Promise.of(response);
} else if (e instanceof ResourceNotFoundException) {
return tryLoadDefaultResource();
} else {
return Promise.ofException(HttpError.ofCode(400, e));
}
});
}
@NotNull
private Promise<HttpResponse> tryLoadIndexResource(String mappedPath) {
String dirPath = mappedPath.endsWith("/") || mappedPath.isEmpty() ? mappedPath : (mappedPath + '/');
return Promises.first(
indexResources.stream()
.map(indexResource -> AsyncSupplier.of(() ->
resourceLoader.load(dirPath + indexResource)
.map(byteBuf -> createHttpResponse(byteBuf, contentTypeResolver.apply(indexResource))))))
.thenEx(((response, e) -> e == null ?
Promise.of(response) :
Promise.ofException(new ResourceNotFoundException("Could not find '" + mappedPath + '\'', e))));
}
@NotNull
private Promise<? extends HttpResponse> tryLoadDefaultResource() {
return defaultResource != null ?
resourceLoader.load(defaultResource)
.map(buf -> createHttpResponse(buf, contentTypeResolver.apply(defaultResource))) :
Promise.ofException(HttpError.notFound404());
}
}