/
ExtDirectSpringUtil.java
256 lines (220 loc) · 8.87 KB
/
ExtDirectSpringUtil.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 the original author or authors.
*
* 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 ch.ralscha.extdirectspring.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.util.ReflectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ch.ralscha.extdirectspring.bean.ExtDirectRequest;
import ch.ralscha.extdirectspring.bean.api.PollingProvider;
import ch.ralscha.extdirectspring.bean.api.RemotingApi;
import ch.ralscha.extdirectspring.controller.ConfigurationService;
/**
* Utility class
*/
public final class ExtDirectSpringUtil {
public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private ExtDirectSpringUtil() {
// singleton
}
/**
* Checks if two objects are equal. Returns true if both objects are null
* @param a object one
* @param b object two
* @return true if objects are equal
*/
public static boolean equal(Object a, Object b) {
return a == b || a != null && a.equals(b);
}
/**
* Checks if the request is a multipart request
* @param request the HTTP servlet request
* @return true if request is a Multipart request (file upload)
*/
public static boolean isMultipart(HttpServletRequest request) {
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return contentType != null && contentType.toLowerCase().startsWith("multipart/");
}
/**
* Invokes a method on a Spring managed bean.
* @param context a Spring application context
* @param beanName the name of the bean
* @param methodInfo the methodInfo object
* @param params the parameters
* @return the result of the method invocation
* @throws IllegalArgumentException if there is no bean in the context
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Object invoke(ApplicationContext context, String beanName, MethodInfo methodInfo,
final Object[] params) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Object bean = context.getBean(beanName);
Method handlerMethod = methodInfo.getMethod();
ReflectionUtils.makeAccessible(handlerMethod);
Object result = handlerMethod.invoke(bean, params);
if (result != null && result instanceof Optional) {
return ((Optional<?>) result).orElse(null);
}
return result;
}
public static Object invoke(HttpServletRequest request, HttpServletResponse response, Locale locale,
ApplicationContext context, ExtDirectRequest directRequest, ParametersResolver parametersResolver,
MethodInfoCache cache) throws Exception {
MethodInfo methodInfo = cache.get(directRequest.getAction(), directRequest.getMethod());
Object[] resolvedParams = parametersResolver.resolveParameters(request, response, locale, directRequest,
methodInfo);
return invoke(context, directRequest.getAction(), methodInfo, resolvedParams);
}
/**
* Converts a stacktrace into a String
* @param t a Throwable
* @return the whole stacktrace in a String
*/
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
private final static long secondsInAMonth = 30L * 24L * 60L * 60L;
/**
* Adds Expires, ETag and Cache-Control response headers.
* @param response the HTTP servlet response
* @param etag the calculated etag (md5) of the response
* @param month number of months the response can be cached. Added to the Expires and
* Cache-Control header. If null defaults to 6 months.
*/
public static void addCacheHeaders(HttpServletResponse response, String etag, Integer month) {
Assert.notNull(etag, "ETag must not be null");
long seconds;
if (month != null) {
seconds = month * secondsInAMonth;
}
else {
seconds = 6L * secondsInAMonth;
}
response.setDateHeader("Expires", System.currentTimeMillis() + seconds * 1000L);
response.setHeader("ETag", etag);
response.setHeader("Cache-Control", "public, max-age=" + seconds);
}
/**
* Checks etag and sends back HTTP status 304 if not modified. If modified sets
* content type and content length, adds cache headers (
* {@link #addCacheHeaders(HttpServletResponse, String, Integer)}), writes the data
* into the {@link HttpServletResponse#getOutputStream()} and flushes it.
* @param request the HTTP servlet request
* @param response the HTTP servlet response
* @param data the response data
* @param contentType the content type of the data (i.e.
* "application/javascript;charset=utf-8")
* @throws IOException
*/
public static void handleCacheableResponse(HttpServletRequest request, HttpServletResponse response, byte[] data,
String contentType) throws IOException {
String ifNoneMatch = request.getHeader("If-None-Match");
String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\"";
addCacheHeaders(response, etag, 6);
if (etag.equals(ifNoneMatch)) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
response.setContentType(contentType);
response.setContentLength(data.length);
@SuppressWarnings("resource")
ServletOutputStream out = response.getOutputStream();
out.write(data);
out.flush();
}
/**
* Returns the api configuration as a String. Uses "REMOTING_API" and "POLLING_URLS"
* for the variable names
* @param ctx The spring applicationcontext
* @return the api configuration
* @throws JsonProcessingException
*/
public static String generateApiString(ApplicationContext ctx) throws JsonProcessingException {
return generateApiString(ctx, "REMOTING_API", "POLLING_URLS");
}
/**
* Returns the api configuration as a String
* @param ctx The spring applicationcontext
* @param remotingVarName name of the variable for the remoting configuration (e.g.
* REMOTING_API)
* @param pollingApiVarName name of the variable for the polling configuration (e.g.
* POLLING_URLS)
* @return the api configuration
* @throws JsonProcessingException
*/
public static String generateApiString(ApplicationContext ctx, String remotingVarName, String pollingApiVarName)
throws JsonProcessingException {
RemotingApi remotingApi = new RemotingApi(
ctx.getBean(ConfigurationService.class).getConfiguration().getProviderType(), "router", null);
for (Map.Entry<MethodInfoCache.Key, MethodInfo> entry : ctx.getBean(MethodInfoCache.class)) {
MethodInfo methodInfo = entry.getValue();
if (methodInfo.getAction() != null) {
remotingApi.addAction(entry.getKey().getBeanName(), methodInfo.getAction());
}
else if (methodInfo.getPollingProvider() != null) {
remotingApi.addPollingProvider(methodInfo.getPollingProvider());
}
}
remotingApi.sort();
StringBuilder extDirectConfig = new StringBuilder(100);
extDirectConfig.append("var ").append(remotingVarName).append(" = ");
extDirectConfig.append(new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(remotingApi));
extDirectConfig.append(";");
List<PollingProvider> pollingProviders = remotingApi.getPollingProviders();
if (!pollingProviders.isEmpty()) {
extDirectConfig.append("\n\nvar ").append(pollingApiVarName).append(" = {\n");
for (int i = 0; i < pollingProviders.size(); i++) {
extDirectConfig.append(" \"");
extDirectConfig.append(pollingProviders.get(i).getEvent());
extDirectConfig.append("\" : \"poll/");
extDirectConfig.append(pollingProviders.get(i).getBeanName());
extDirectConfig.append("/");
extDirectConfig.append(pollingProviders.get(i).getMethod());
extDirectConfig.append("/");
extDirectConfig.append(pollingProviders.get(i).getEvent());
extDirectConfig.append("\"");
if (i < pollingProviders.size() - 1) {
extDirectConfig.append(",\n");
}
}
extDirectConfig.append("\n};");
}
return extDirectConfig.toString();
}
}