forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketConnectionHandler.java
More file actions
297 lines (272 loc) · 10 KB
/
WebSocketConnectionHandler.java
File metadata and controls
297 lines (272 loc) · 10 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package act.xio;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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.
* #L%
*/
import act.Act;
import act.app.ActionContext;
import act.app.App;
import act.controller.meta.ActionMethodMetaInfo;
import act.controller.meta.ControllerClassMetaInfo;
import act.controller.meta.HandlerParamMetaInfo;
import act.handler.RequestHandlerBase;
import act.inject.param.*;
import act.sys.Env;
import act.ws.WebSocketConnectionManager;
import act.ws.WebSocketContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.esotericsoftware.reflectasm.MethodAccess;
import org.osgl.$;
import org.osgl.inject.BeanSpec;
import org.osgl.mvc.annotation.WsAction;
import org.osgl.mvc.result.BadRequest;
import org.osgl.util.E;
import org.osgl.util.S;
import org.osgl.util.StringValueResolver;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
public abstract class WebSocketConnectionHandler extends RequestHandlerBase {
private static final Object[] DUMP_PARAMS = new Object[0];
protected boolean disabled;
protected ClassLoader cl;
protected WebSocketConnectionManager connectionManager;
protected ActionMethodMetaInfo handler;
protected ControllerClassMetaInfo controller;
protected Class<?> handlerClass;
protected Method method;
protected MethodAccess methodAccess;
private int methodIndex;
protected boolean isStatic;
private ParamValueLoaderService paramLoaderService;
private JsonDTOClassManager jsonDTOClassManager;
private int paramCount;
private int fieldsAndParamsCount;
private String singleJsonFieldName;
private List<BeanSpec> paramSpecs;
private Object host;
private boolean isWsHandler;
private Class[] paramTypes;
private boolean isSingleParam;
// used to compose connection only websocket handler
protected WebSocketConnectionHandler(WebSocketConnectionManager manager) {
this.connectionManager = manager;
this.isWsHandler = false;
this.disabled = true;
}
public WebSocketConnectionHandler(ActionMethodMetaInfo methodInfo, WebSocketConnectionManager manager) {
this.connectionManager = $.requireNotNull(manager);
if (null == methodInfo) {
this.isWsHandler = false;
this.disabled = true;
return;
}
App app = manager.app();
this.cl = app.classLoader();
this.handler = $.requireNotNull(methodInfo);
this.controller = handler.classInfo();
this.paramLoaderService = app.service(ParamValueLoaderManager.class).get(WebSocketContext.class);
this.jsonDTOClassManager = app.service(JsonDTOClassManager.class);
this.handlerClass = $.classForName(controller.className(), cl);
this.disabled = !Env.matches(handlerClass);
paramTypes = paramTypes(cl);
try {
this.method = handlerClass.getMethod(methodInfo.name(), paramTypes);
this.isWsHandler = null != this.method.getAnnotation(WsAction.class);
this.disabled = this.disabled || !Env.matches(method);
} catch (NoSuchMethodException e) {
throw E.unexpected(e);
}
if (!isWsHandler || disabled) {
return;
}
this.isStatic = methodInfo.isStatic();
if (!this.isStatic) {
//constructorAccess = ConstructorAccess.get(controllerClass);
methodAccess = MethodAccess.get(handlerClass);
methodIndex = methodAccess.getIndex(methodInfo.name(), paramTypes);
host = Act.getInstance(handlerClass);
} else {
method.setAccessible(true);
}
paramCount = handler.paramCount();
paramSpecs = jsonDTOClassManager.beanSpecs(handlerClass, method);
fieldsAndParamsCount = paramSpecs.size();
if (fieldsAndParamsCount == 1) {
singleJsonFieldName = paramSpecs.get(0).name();
}
// todo: do we want to allow inject Annotation type into web socket
// handler method param list?
ParamValueLoader[] loaders = paramLoaderService.methodParamLoaders(host, method, null);
if (loaders.length > 0) {
int realParamCnt = 0;
for (ParamValueLoader loader : loaders) {
if (loader instanceof ProvidedValueLoader) {
continue;
}
realParamCnt++;
}
isSingleParam = 1 == realParamCnt;
}
}
@Override
public String toString() {
return "websocket connection handler";
}
/**
* This method is used by {@link act.handler.builtin.controller.RequestHandlerProxy}
* to check if a handler is WS handler or GET handler
* @return `true` if this is a real WS handler
*/
public boolean isWsHandler() {
return isWsHandler;
}
@Override
public void prepareAuthentication(ActionContext context) {
}
protected void invoke(WebSocketContext context) {
if (disabled) {
return;
}
ensureJsonDTOGenerated(context);
Object[] params = params(context);
Object retVal;
if (this.isStatic) {
retVal = $.invokeStatic(method, params);
} else {
retVal = methodAccess.invoke(host, methodIndex, params);
}
if (null == retVal) {
return;
}
if (retVal instanceof String) {
context.sendToSelf((String) retVal);
} else {
context.sendJsonToSelf(retVal);
}
}
private Object[] params(WebSocketContext context) {
if (0 == paramCount) {
return DUMP_PARAMS;
}
Object[] params = paramLoaderService.loadMethodParams(host, method, context);
if (isSingleParam) {
for (int i = 0; i < paramCount; ++i) {
if (null == params[i]) {
String singleVal = context.stringMessage();
Class<?> paramType = paramTypes[i];
StringValueResolver resolver = context.app().resolverManager().resolver(paramType);
if (null != resolver) {
params[i] = resolver.apply(singleVal);
} else {
E.unexpected("Cannot determine string value resolver for param type: %s", paramType);
}
}
}
}
return params;
}
private Class[] paramTypes(ClassLoader cl) {
int sz = handler.paramCount();
Class[] ca = new Class[sz];
for (int i = 0; i < sz; ++i) {
HandlerParamMetaInfo param = handler.param(i);
ca[i] = $.classForName(param.type().getClassName(), cl);
}
return ca;
}
private void ensureJsonDTOGenerated(WebSocketContext context) {
if (0 == fieldsAndParamsCount || !context.isJson()) {
return;
}
Class<? extends JsonDTO> dtoClass = jsonDTOClassManager.get(handlerClass, method);
if (null == dtoClass) {
// there are neither fields nor params
return;
}
try {
JsonDTO dto = JSON.parseObject(patchedJsonBody(context), dtoClass);
context.attribute(JsonDTO.CTX_ATTR_KEY, dto);
} catch (JSONException e) {
if (e.getCause() != null) {
logger.warn(e.getCause(), "error parsing JSON data");
} else {
logger.warn(e, "error parsing JSON data");
}
throw new BadRequest(e.getCause());
}
}
/**
* Suppose method signature is: `public void foo(Foo foo)`, and a JSON content is
* not `{"foo": {foo-content}}`, then wrap it as `{"foo": body}`
*/
private String patchedJsonBody(WebSocketContext context) {
String body = context.stringMessage();
if (S.blank(body) || 1 < fieldsAndParamsCount) {
return body;
}
String theName = singleJsonFieldName(context);
int theNameLen = theName.length();
if (null == theName) {
return body;
}
body = body.trim();
boolean needPatch = body.charAt(0) == '[';
if (!needPatch) {
if (body.charAt(0) != '{') {
throw new IllegalArgumentException("Cannot parse JSON string: " + body);
}
boolean startCheckName = false;
int nameStart = -1;
for (int i = 1; i < body.length(); ++i) {
char c = body.charAt(i);
if (c == ' ') {
continue;
}
if (startCheckName) {
if (c == '"') {
break;
}
int id = i - nameStart - 1;
if (id >= theNameLen || theName.charAt(i - nameStart - 1) != c) {
needPatch = true;
break;
}
} else if (c == '"') {
startCheckName = true;
nameStart = i;
}
}
}
return needPatch ? S.fmt("{\"%s\": %s}", theName, body) : body;
}
private String singleJsonFieldName(WebSocketContext context) {
if (null != singleJsonFieldName) {
return singleJsonFieldName;
}
Set<String> set = context.paramKeys();
for (BeanSpec spec: paramSpecs) {
String name = spec.name();
if (!set.contains(name)) {
return name;
}
}
return null;
}
}