/
SearchEngineApiManager.java
244 lines (221 loc) · 10.8 KB
/
SearchEngineApiManager.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
/*
* Copyright 2012-2024 CodeLibs Project and the Others.
*
* 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 org.codelibs.fess.api.engine;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codelibs.core.io.CopyUtil;
import org.codelibs.core.lang.StringUtil;
import org.codelibs.curl.Curl.Method;
import org.codelibs.curl.CurlRequest;
import org.codelibs.curl.CurlResponse;
import org.codelibs.fess.Constants;
import org.codelibs.fess.api.BaseApiManager;
import org.codelibs.fess.exception.FessSystemException;
import org.codelibs.fess.exception.WebApiException;
import org.codelibs.fess.mylasta.action.FessUserBean;
import org.codelibs.fess.util.ComponentUtil;
import org.codelibs.fess.util.ResourceUtil;
import org.lastaflute.web.servlet.request.RequestManager;
import org.lastaflute.web.servlet.session.SessionManager;
public class SearchEngineApiManager extends BaseApiManager {
private static final String ADMIN_SERVER = "/admin/server_";
private static final Logger logger = LogManager.getLogger(SearchEngineApiManager.class);
protected String[] acceptedRoles = { "admin" };
public SearchEngineApiManager() {
setPathPrefix(ADMIN_SERVER);
}
@PostConstruct
public void register() {
if (logger.isInfoEnabled()) {
logger.info("Load {}", this.getClass().getSimpleName());
}
ComponentUtil.getWebApiManagerFactory().add(this);
}
@Override
public boolean matches(final HttpServletRequest request) {
final String servletPath = request.getServletPath();
return servletPath.startsWith(pathPrefix);
}
@Override
public void process(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final RequestManager requestManager = ComponentUtil.getRequestManager();
if (!requestManager.findUserBean(FessUserBean.class).map(user -> user.hasRoles(acceptedRoles)).orElse(Boolean.FALSE)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized access: " + request.getServletPath());
return;
}
try {
getSessionManager().getAttribute(Constants.SEARCH_ENGINE_API_ACCESS_TOKEN, String.class).ifPresent(token -> {
final String servletPath = request.getServletPath();
final String pathPrefix = ADMIN_SERVER + token;
if (!servletPath.startsWith(pathPrefix)) {
throw new WebApiException(HttpServletResponse.SC_FORBIDDEN, "Invalid access token.");
}
final String path;
final String value = servletPath.substring(pathPrefix.length());
if (!value.startsWith("/")) {
path = "/" + value;
} else {
path = value;
}
processRequest(request, response, path);
}).orElse(() -> {
throw new WebApiException(HttpServletResponse.SC_FORBIDDEN, "Invalid session.");
});
} catch (final WebApiException e) {
logger.debug("Failed to access to Web API.", e);
response.sendError(e.getStatusCode(), e.getMessage());
}
}
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final String path) {
if ("/_plugin".equals(path) || path.startsWith("/_plugin/")) {
processPluginRequest(request, response, path.replaceFirst("^/_plugin", StringUtil.EMPTY));
return;
}
final Method httpMethod = Method.valueOf(request.getMethod().toUpperCase(Locale.ROOT));
final CurlRequest curlRequest = ComponentUtil.getCurlHelper().request(httpMethod, path);
final String contentType = request.getHeader("Content-Type");
if (StringUtil.isNotEmpty(contentType)) {
curlRequest.header("Content-Type", contentType);
}
request.getParameterMap().entrySet().stream().forEach(entry -> {
if (entry.getValue().length > 1) {
curlRequest.param(entry.getKey(), String.join(",", entry.getValue()));
} else if (entry.getValue().length == 1) {
curlRequest.param(entry.getKey(), entry.getValue()[0]);
}
});
try (final CurlResponse curlResponse = curlRequest.onConnect((req, con) -> {
con.setDoOutput(true);
if (httpMethod != Method.GET && request.getContentLength() > 2) {
try (ServletInputStream in = request.getInputStream(); OutputStream out = con.getOutputStream()) {
CopyUtil.copy(in, out);
} catch (final IOException e) {
throw new WebApiException(HttpServletResponse.SC_BAD_REQUEST, e);
}
}
}).execute()) {
try (ServletOutputStream out = response.getOutputStream(); InputStream in = curlResponse.getContentAsStream()) {
response.setStatus(curlResponse.getHttpStatusCode());
writeHeaders(response);
final String responseContentType = curlResponse.getHeaderValue("Content-Type");
if (StringUtil.isBlank(responseContentType)) {
response.setHeader("Content-Type", "application/json");
} else {
response.setHeader("Content-Type", responseContentType);
}
CopyUtil.copy(in, out);
} catch (final ClientAbortException e) {
logger.debug("Client aborts this request.", e);
}
} catch (final Exception e) {
if (!(e.getCause() instanceof ClientAbortException)) {
throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
logger.debug("Client aborts this request.", e);
}
}
protected void processPluginRequest(final HttpServletRequest request, final HttpServletResponse response, final String path) {
if (StringUtil.isNotBlank(path)) {
final String lowerPath = path.toLowerCase(Locale.ROOT);
if (lowerPath.endsWith(".html")) {
response.setContentType("text/html;charset=utf-8");
} else if (lowerPath.endsWith(".css")) {
response.setContentType("text/css");
} else if (lowerPath.endsWith(".eot")) {
response.setContentType("application/vnd.ms-fontobject");
} else if (lowerPath.endsWith(".ico")) {
response.setContentType("image/vnd.microsoft.icon");
} else if (lowerPath.endsWith(".js")) {
response.setContentType("text/javascript");
} else if (lowerPath.endsWith(".json")) {
response.setContentType("application/json");
} else if (lowerPath.endsWith(".otf")) {
response.setContentType("font/otf");
} else if (lowerPath.endsWith(".svg")) {
response.setContentType("image/svg+xml");
} else if (lowerPath.endsWith(".ttf")) {
response.setContentType("font/ttf");
} else if (lowerPath.endsWith(".txt")) {
response.setContentType("text/plain");
} else if (lowerPath.endsWith(".woff")) {
response.setContentType("font/woff");
} else if (lowerPath.endsWith(".woff2")) {
response.setContentType("font/woff2");
} else if (lowerPath.endsWith("/")) {
response.setContentType("text/html;charset=utf-8");
}
}
Path filePath = ResourceUtil.getSitePath(path.replaceAll("\\.\\.+", StringUtil.EMPTY).replaceAll("/+", "/").split("/"));
if (Files.isDirectory(filePath)) {
filePath = filePath.resolve("index.html");
}
if (Files.exists(filePath)) {
try (InputStream in = Files.newInputStream(filePath); ServletOutputStream out = response.getOutputStream()) {
response.setStatus(HttpServletResponse.SC_OK);
writeHeaders(response);
CopyUtil.copy(in, out);
} catch (final ClientAbortException e) {
logger.debug("Client aborts this request.", e);
} catch (final IOException e) {
logger.error("Failed to read {} from {}", path, filePath);
throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
} else {
try {
writeHeaders(response);
response.sendError(HttpServletResponse.SC_NOT_FOUND, path + " is not found.");
} catch (final ClientAbortException e) {
logger.debug("Client aborts this request.", e);
} catch (final IOException e) {
logger.error("Failed to read {} from {}", path, filePath);
throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
}
}
public void setAcceptedRoles(final String[] acceptedRoles) {
this.acceptedRoles = acceptedRoles;
}
public String getServerPath() {
return getSessionManager().getAttribute(Constants.SEARCH_ENGINE_API_ACCESS_TOKEN, String.class).map(token -> ADMIN_SERVER + token)
.orElseThrow(() -> new FessSystemException("Cannot create an access token."));
}
public void saveToken() {
getSessionManager().setAttribute(Constants.SEARCH_ENGINE_API_ACCESS_TOKEN, UUID.randomUUID().toString().replace("-", ""));
}
private SessionManager getSessionManager() {
return ComponentUtil.getComponent(SessionManager.class);
}
@Override
protected void writeHeaders(final HttpServletResponse response) {
ComponentUtil.getFessConfig().getApiDashboardResponseHeaderList().forEach(e -> response.setHeader(e.getFirst(), e.getSecond()));
}
}