forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCliContextParamLoader.java
More file actions
332 lines (303 loc) · 13.7 KB
/
CliContextParamLoader.java
File metadata and controls
332 lines (303 loc) · 13.7 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package act.inject.param;
/*-
* #%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.cli.CliContext;
import act.cli.Optional;
import act.cli.Required;
import act.cli.meta.CommandMethodMetaInfo;
import act.cli.util.CommandLineParser;
import act.util.ActContext;
import org.osgl.$;
import org.osgl.exception.UnexpectedException;
import org.osgl.http.H;
import org.osgl.inject.BeanSpec;
import org.osgl.inject.util.AnnotationUtil;
import org.osgl.mvc.annotation.Resolve;
import org.osgl.util.S;
import org.osgl.util.StringValueResolver;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Responsible for loading param value for {@link ActionContext}
*/
public class CliContextParamLoader extends ParamValueLoaderService {
private final static transient ThreadLocal<CommandMethodMetaInfo> methodMetaInfoHolder = new ThreadLocal<CommandMethodMetaInfo>();
private ConcurrentMap<Method, List<OptionLoader>> optionLoaderRegistry = new ConcurrentHashMap<Method, List<OptionLoader>>();
CliContextParamLoader(App app) {
super(app);
}
public CliContext.ParsingContext buildParsingContext(Class commander, Method method, CommandMethodMetaInfo methodMetaInfo) {
CliContext.ParsingContextBuilder.start();
ensureOptionLoaders(method, methodMetaInfo);
methodMetaInfoHolder.set(methodMetaInfo);
if (!Modifier.isStatic(method.getModifiers())) {
ParamValueLoader loader = findBeanLoader(commander);
classRegistry.putIfAbsent(commander, loader);
}
$.Var<Boolean> boolBag = $.var();
// create a pseudo ctx as we do not have one here
// the ctx is just a way to pass the method info
ActContext ctx = new ActContext.Base<ActContext.Base>(Act.app()) {
@Override
public Base accept(H.Format fmt) {
return null;
}
@Override
public H.Format accept() {
return null;
}
@Override
public String methodPath() {
return null;
}
@Override
public Set<String> paramKeys() {
return null;
}
@Override
public String paramVal(String key) {
return null;
}
@Override
public String[] paramVals(String key) {
return new String[0];
}
};
ctx.currentMethod(method);
ParamValueLoader[] loaders = findMethodParamLoaders(method, commander, ctx, boolBag);
methodRegistry.putIfAbsent(method, loaders);
methodValidationConstraintLookup.put(method, boolBag.get());
return CliContext.ParsingContextBuilder.finish();
}
public void preParseOptions(Method method, CommandMethodMetaInfo methodMetaInfo, CliContext context) {
List<OptionLoader> optionLoaders = ensureOptionLoaders(method, methodMetaInfo);
CommandLineParser commandLineParser = context.commandLine();
boolean argumentAsOption = false;
if (1 == optionLoaders.size()) {
OptionLoader loader = optionLoaders.get(0);
if (loader.required) {
String theOptionVal = commandLineParser.argumentAsOption();
if (null != theOptionVal) {
argumentAsOption = true;
context.parsingContext().foundRequired(loader.requiredGroup);
context.param(loader.bindName, theOptionVal);
}
}
}
if (!argumentAsOption) {
for (OptionLoader loader : optionLoaders) {
String bindName = loader.bindName;
String value = commandLineParser.getString(loader.lead1, loader.lead2);
if (S.notBlank(value)) {
if (loader.required) {
context.parsingContext().foundRequired(loader.requiredGroup);
}
context.param(bindName, value);
}
}
}
context.parsingContext().raiseExceptionIfThereAreMissingOptions(context);
}
@Override
protected ParamValueLoader findContextSpecificLoader(
String bindName,
BeanSpec spec
) {
boolean isArray = spec.isArray();
StringValueResolver resolver = findResolver(spec, isArray); //= isArray ? resolverManager.resolver(rawType.getComponentType(), spec) : resolverManager.resolver(rawType, spec);
Required required = spec.getAnnotation(Required.class);
Optional optional = null == required ? spec.getAnnotation(Optional.class) : null;
if (null != required) {
return new OptionLoader(bindName, required, resolver, spec);
} else if (null != optional) {
return new OptionLoader(bindName, optional, resolver, spec);
}
return isArray ? new CliVarArgumentLoader(spec.rawType().getComponentType(), resolver) : new CliArgumentLoader(resolver);
}
private StringValueResolver findResolver(BeanSpec spec, boolean isArray) {
StringValueResolver resolver = findAnnotatedResolver(spec);
return null == resolver ? findImplicitResolver(spec, isArray) : resolver;
}
private StringValueResolver findAnnotatedResolver(BeanSpec spec) {
StringValueResolver resolver = findDirectAnnotatedResolver(spec);
return null == resolver ? findIndirectAnnotatedResolver(spec) : resolver;
}
private StringValueResolver findDirectAnnotatedResolver(BeanSpec spec) {
Resolve resolve = spec.getAnnotation(Resolve.class);
Class<?> rawType = spec.rawType();
if (null != resolve) {
Class<? extends StringValueResolver>[] resolvers = resolve.value();
for (Class<? extends StringValueResolver> resolverClass : resolvers) {
StringValueResolver resolver = injector.get(resolverClass);
Class<?> targetType = resolver.targetType();
boolean matches = rawType.isAssignableFrom(targetType);
if (!matches) {
Class<?> rawType2 = $.wrapperClassOf(rawType);
if (rawType != rawType2) {
matches = rawType2.isAssignableFrom(targetType);
}
}
if (matches) {
return resolver;
}
}
}
return null;
}
private StringValueResolver findIndirectAnnotatedResolver(BeanSpec spec) {
Annotation[] aa = spec.allAnnotations();
Class<?> rawType = spec.rawType();
for (Annotation a : aa) {
Resolve resolve = AnnotationUtil.tagAnnotation(a, Resolve.class);
if (null != resolve) {
Class<? extends StringValueResolver>[] resolvers = resolve.value();
for (Class<? extends StringValueResolver> resolverClass : resolvers) {
StringValueResolver resolver = injector.get(resolverClass);
resolver.attributes($.evaluate(a));
Class<?> targetType = resolver.targetType();
boolean matches = rawType.isAssignableFrom(targetType);
if (!matches) {
Class<?> rawType2 = $.wrapperClassOf(rawType);
if (rawType != rawType2) {
matches = rawType2.isAssignableFrom(targetType);
}
}
if (matches) {
return resolver;
}
}
}
}
return null;
}
private StringValueResolver findImplicitResolver(final BeanSpec spec, boolean isArray) {
StringValueResolver resolver = resolverManager.resolver(spec.rawType(), spec);
if (null != resolver) {
return resolver;
} else if (isArray) {
final BeanSpec compSpec = spec.componentSpec();
final StringValueResolver<ArrayList> colResolver = resolverManager.collectionResolver(ArrayList.class, compSpec.rawType(), S.COMMON_SEP);
final boolean isPrimitive = $.isPrimitive(compSpec.rawType());
return new StringValueResolver() {
@Override
public Object resolve(String s) {
List list = colResolver.resolve(s);
int size = list.size();
final Class<?> compType = compSpec.rawType();
Object array = Array.newInstance(compType, size);
for (int i = 0; i < size; ++i) {
Object item = list.get(i);
if (isPrimitive) {
if (boolean.class == compType) {
Array.setBoolean(array, i, ((Boolean)item).booleanValue());
} else if (byte.class == compType) {
Array.setByte(array, i, ((Byte) item).byteValue());
} else if (char.class == compType) {
Array.setChar(array, i, ((Character) item).charValue());
} else if (double.class == compType) {
Array.setDouble(array, i, ((Double) item).doubleValue());
} else if (float.class == compType) {
Array.setFloat(array, i, ((Float) item).floatValue());
} else if (int.class == compType) {
Array.setInt(array, i, ((Integer) item).intValue());
} else if (long.class == compType) {
Array.setLong(array, i, ((Long) item).longValue());
} else if (short.class == compType) {
Array.setShort(array, i, ((Short) item).shortValue());
} else {
throw new UnexpectedException("Unknown primitive type");
}
} else {
Array.set(array, i, item);
}
}
return array;
}
};
} else {
return null;
}
}
@Override
protected String paramName(int i) {
return methodMetaInfoHolder.get().param(i).name();
}
private List<OptionLoader> ensureOptionLoaders(Method method, CommandMethodMetaInfo methodMetaInfo) {
List<OptionLoader> optionLoaders = optionLoaderRegistry.get(method);
if (null == optionLoaders) {
optionLoaders = findOptionLoaders(method, methodMetaInfo);
optionLoaderRegistry.put(method, optionLoaders);
}
return optionLoaders;
}
private List<OptionLoader> findOptionLoaders(Method method, CommandMethodMetaInfo methodMetaInfo) {
List<OptionLoader> optionLoaders = new ArrayList<OptionLoader>();
findParamOptionLoaders(method, methodMetaInfo, optionLoaders);
findFieldOptionLoaders(method.getDeclaringClass(), optionLoaders);
return optionLoaders;
}
private void findFieldOptionLoaders(Class c, List<OptionLoader> optionLoaders) {
if (injector.isProvided(c)) {
// No field injection for a provided host
return;
}
for (Field field : $.fieldsOf(c, true)) {
Type type = field.getGenericType();
Annotation[] annotations = field.getAnnotations();
String bindName = bindName(annotations, field.getName());
BeanSpec spec = BeanSpec.of(type, annotations, bindName, injector);
boolean provided = injector.isProvided(spec);
ParamValueLoader loader = provided ? ProvidedValueLoader.get(spec, injector) : findContextSpecificLoader(bindName, spec);
if (loader instanceof OptionLoader) {
optionLoaders.add((OptionLoader) loader);
}
}
}
private void findParamOptionLoaders(Method m, CommandMethodMetaInfo methodMetaInfo, List<OptionLoader> optionLoaders) {
Type[] types = m.getGenericParameterTypes();
int len = types.length;
if (len == 0) {
return;
}
Annotation[][] allAnnotations = m.getParameterAnnotations();
for (int i = len - 1; i >= 0; --i) {
Type type = types[i];
Annotation[] annotations = allAnnotations[i];
BeanSpec spec = BeanSpec.of(type, annotations, null, injector);
String bindName = tryFindBindName(annotations, spec.name());
if (null == bindName) {
bindName = methodMetaInfo.param(i).name();
}
ParamValueLoader loader = findContextSpecificLoader(bindName, spec);
if (loader instanceof OptionLoader) {
optionLoaders.add((OptionLoader) loader);
} else if (!$.isSimpleType(spec.rawType())) {
}
}
}
}