use of java.lang.reflect.Parameter in project weicoder by wdcode.
the class BasicServlet method doPost.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long curr = System.currentTimeMillis();
// 获得客户端IP
String ip = RequestUtil.getIp(request);
// 获得callback
String callback = RequestUtil.getParameter(request, "callback");
Logs.debug("check ip request ip={},ips={}", ip, WebParams.IPS);
// 获得path
String path = request.getPathInfo();
Logs.debug("request ip={},path={},{}", ip, path, request.getQueryString());
if (!EmptyUtil.isEmpty(path)) {
// 分解提交action 去处开头的/ 并且按/或者_分解出数组
String actionName = StringUtil.subString(path, 1, path.length());
String[] actions = StringUtil.contains(actionName, StringConstants.BACKSLASH) ? StringUtil.split(actionName, StringConstants.BACKSLASH) : StringUtil.split(actionName, StringConstants.UNDERLINE);
if (EmptyUtil.isEmpty(actions)) {
Logs.debug("this path={}", path);
ResponseUtil.json(response, callback, "action is null path");
return;
}
// 获得Action
// String name = actions.length > 2 ? actions[actions.length - 2] : actions[actions.length - 1];
// Object action = WebCommons.ACTIONS.get(name);
String name = null;
Object action = null;
for (String n : actions) {
name = n;
action = WebCommons.ACTIONS.get(name);
if (action != null) {
break;
}
}
// action为空
if (action == null) {
// 如果使用action[_/]method模式 直接返回
if (actions.length == 2) {
Logs.debug("request ip={},path={},no action", ip, path);
ResponseUtil.json(response, callback, "no action");
return;
}
// 查找方法对应action
action = WebCommons.METHODS_ACTIONS.get(name);
}
// action为空
if (action == null) {
// 还是为空
Logs.warn("request ip={},path={},no action and method", ip, path);
ResponseUtil.json(response, callback, "no action and method");
return;
}
// 过滤IP
Action a = action.getClass().getAnnotation(Action.class);
if (a.ips() && !EmptyUtil.isEmpty(WebParams.IPS)) {
// 如果在允许列表继续 否则退出
if (!WebParams.IPS.contains(ip)) {
Logs.debug("this ip={}", ip);
ResponseUtil.json(response, callback, "not exist ip");
return;
}
}
// 验证token
if (a.token()) {
// 获得token
String token = RequestUtil.getParameter(request, "token");
if (!TokenEngine.decrypt(token).isLogin()) {
Logs.debug("this token={}", token);
ResponseUtil.json(response, callback, "token is no login");
return;
}
}
// 获得方法
Map<String, Method> methods = WebCommons.ACTIONS_METHODS.get(name);
if (EmptyUtil.isEmpty(methods)) {
methods = WebCommons.METHODS;
}
Method method = methods.get(actions[actions.length - 1]);
if (method == null) {
Logs.debug("request ip={},path={},no method", ip, path);
ResponseUtil.json(response, callback, "no method");
return;
}
Logs.debug("request ip={},name={}", ip, actionName);
// 设置参数
Parameter[] pars = method.getParameters();
Object[] params = null;
if (!EmptyUtil.isEmpty(pars)) {
// 参数不为空 设置参数
params = new Object[pars.length];
// 所有提交的参数
Map<String, String> ps = RequestUtil.getParameters(request);
// action全部参数下标
int i = 0;
for (; i < pars.length; i++) {
// 判断类型并设置
Parameter p = pars[i];
// 参数的类型
Class<?> cs = p.getType();
if (HttpServletRequest.class.equals(cs)) {
params[i] = request;
} else if (HttpServletResponse.class.equals(cs)) {
params[i] = response;
} else if (Map.class.equals(cs)) {
params[i] = ps;
} else if (ClassUtil.isBaseType(cs)) {
params[i] = Conversion.to(ps.get(p.getName()), cs);
// 判断参数为空并且参数名为ip
if (EmptyUtil.isEmpty(params[i]) && "ip".equals(p.getName())) {
// 赋值为调用客户端IP
params[i] = ip;
}
Logs.debug("request ip={},name={},params index={},name={},type={},value={}", ip, actionName, i, p.getName(), cs, params[i]);
} else {
params[i] = BeanUtil.copy(ps, cs);
Logs.debug("request ip={},name={},params={}", ip, actionName, params[i]);
}
}
}
// 调用方法
// try {
Object res = BeanUtil.invoke(action, method, params);
Logs.debug("invoke method={},params={},res={} end", method.getName(), params, res);
// 判断是否跳转url
if (method.isAnnotationPresent(Redirect.class) || action.getClass().isAnnotationPresent(Redirect.class)) {
String url = Conversion.toString(res);
if (EmptyUtil.isEmpty(url)) {
ResponseUtil.json(response, callback, "Redirect is null");
} else {
response.sendRedirect(url);
}
Logs.debug("redirect url:{}", url);
} else if (method.isAnnotationPresent(Forward.class) || action.getClass().isAnnotationPresent(Forward.class)) {
String url = Conversion.toString(res);
if (EmptyUtil.isEmpty(url)) {
ResponseUtil.json(response, callback, "Forward is null");
} else {
request.getRequestDispatcher(url).forward(request, response);
}
Logs.debug("forward url:{}", url);
} else if (method.isAnnotationPresent(State.class) || action.getClass().isAnnotationPresent(State.class)) {
// 状态码对象
State state = method.getAnnotation(State.class);
if (state == null) {
state = action.getClass().getAnnotation(State.class);
}
// 字段名
String status = state.state();
String success = state.success();
String error = state.error();
// 如果res为状态码
if (res == null) {
// 写空信息
ResponseUtil.json(response, callback, Maps.newMap(new String[] { status, error }, new Object[] { WebParams.STATE_ERROR_NULL, ErrorCodeParams.getMessage(WebParams.STATE_ERROR_NULL) }));
} else if (res instanceof Void) {
// 空返回
ResponseUtil.json(response, callback, Maps.newMap(new String[] { status, success }, new Object[] { WebParams.STATE_SUCCESS, WebParams.STATE_SUCCESS_MSG }));
} else if (res instanceof Integer) {
// 写错误信息
int errorcode = Conversion.toInt(res);
ResponseUtil.json(response, callback, Maps.newMap(new String[] { status, error }, new Object[] { errorcode, ErrorCodeParams.getMessage(errorcode) }));
} else {
ResponseUtil.json(response, callback, Maps.newMap(new String[] { status, success }, new Object[] { 0, res }));
}
Logs.debug("servlet state={} method={},params={},res={} end", state, method.getName(), params, res);
} else {
// 如果结果为空
if (res == null || res instanceof Void) {
// 结果设置为空map
res = Maps.emptyMap();
}
// 写到前端
ResponseUtil.json(response, callback, res);
Logs.debug("servlet method={},params={},res={} end", method.getName(), params, res);
}
Logs.info("request ip={},name={},time={},res={},params={} end", ip, actionName, System.currentTimeMillis() - curr, res, params);
}
}
use of java.lang.reflect.Parameter in project weicoder by wdcode.
the class Kafkas method init.
/**
* 初始化
*/
public static void init() {
List<Class<Consumer>> consumers = ClassUtil.getAnnotationClass(CommonParams.getPackages("kafka"), Consumer.class);
if (!EmptyUtil.isEmpty(consumers)) {
// 循环处理kafka类
for (Class<Consumer> c : consumers) {
// 执行对象
Object consumer = BeanUtil.newInstance(c);
String name = consumer.getClass().getAnnotation(Consumer.class).value();
// 如果KafkaConsumer列表里没有相对应的消费者 创建
if (!KAFKA_CONSUMERS.containsKey(name)) {
KAFKA_CONSUMERS.put(name, KafkaFactory.getConsumer(name));
}
// 获得topic列表
List<String> topics = Maps.getList(TOPICS, name, String.class);
// 处理所有方法
for (Method m : c.getMethods()) {
// 方法有执行时间注解
Topic topic = m.getAnnotation(Topic.class);
if (topic != null) {
String val = topic.value();
METHODS.put(val, m);
CONSUMERS.put(val, consumer);
topics.add(val);
Logs.info("add kafka Consumer={} topic={}", c.getSimpleName(), val);
}
}
}
Logs.info("add kafka Consumers size={}", consumers.size());
// 订阅相关消费数据
for (String key : TOPICS.keySet()) {
List<String> topics = TOPICS.get(key);
KAFKA_CONSUMERS.get(key).subscribe(topics);
Logs.info("Kafkas init Consumer={} subscribe topic={}", key, topics);
}
// 启动定时读取kafka消息
for (final KafkaConsumer<byte[], byte[]> consumer : KAFKA_CONSUMERS.values()) {
ScheduledUtil.delay(() -> {
// 日志使用
int time = DateUtil.getTime();
int n = 0;
// 获得消费数据
for (ConsumerRecord<byte[], byte[]> record : consumer.poll(1000)) {
// 获得消费对象类和方法
Logs.debug("kafka read consumer record={}", record);
String topic = record.topic();
Object obj = CONSUMERS.get(topic);
Method method = METHODS.get(topic);
// 获得所有参数
Parameter[] params = method.getParameters();
Object[] objs = new Object[params.length];
if (EmptyUtil.isEmpty(params)) {
// 参数为空直接执行方法
BeanUtil.invoke(obj, method);
} else {
// 有参数 现在只支持 1-2位的参数,1个参数表示value,2个参数表示key,value
if (params.length == 1) {
objs[0] = toParam(record.value(), params[0].getType());
} else {
objs[0] = toParam(record.key(), params[0].getType());
objs[1] = toParam(record.value(), params[1].getType());
}
// 执行方法
BeanUtil.invoke(obj, method, objs);
}
n++;
Logs.debug("kafka consumer method={} params={} args={}", method.getName(), params, objs);
}
// 数量不为空
if (n > 0) {
Logs.debug("kafka consumer end size={} time={}", n, DateUtil.getTime() - time);
}
}, 1);
}
}
}
use of java.lang.reflect.Parameter in project incubator-servicecomb-java-chassis by apache.
the class ProtobufSchemaUtils method getOrCreateArgsSchema.
public static WrapSchema getOrCreateArgsSchema(OperationMeta operationMeta) {
Method method = operationMeta.getMethod();
String type = "gen." + method.getDeclaringClass().getName() + "." + method.getName() + ".Args";
return getOrCreateSchema(type, () -> {
if (!isArgsNeedWrap(method)) {
// 可以直接使用
Class<?> cls = (Class<?>) method.getParameterTypes()[0];
Schema<?> schema = RuntimeSchema.createFrom(cls);
return WrapSchemaFactory.createSchema(schema, WrapType.ARGS_NOT_WRAP);
}
// 需要包装
WrapClassConfig config = new WrapClassConfig();
config.setType(WrapType.ARGS_WRAP);
config.setClassName(type);
Parameter[] params = method.getParameters();
for (int idx = 0; idx < params.length; idx++) {
Parameter param = params[idx];
String paramName = org.apache.servicecomb.swagger.generator.core.utils.ClassUtils.correctMethodParameterName(operationMeta.getParamName(idx));
config.addField(paramName, param.getParameterizedType());
}
JavassistUtils.genMultiWrapperInterface(config);
return createWrapSchema(config);
});
}
use of java.lang.reflect.Parameter in project junit5 by junit-team.
the class ParameterizedTestParameterResolver method resolveParameter.
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Object argument = arguments[parameterContext.getIndex()];
Parameter parameter = parameterContext.getParameter();
Optional<ConvertWith> annotation = AnnotationUtils.findAnnotation(parameter, ConvertWith.class);
// @formatter:off
ArgumentConverter argumentConverter = annotation.map(ConvertWith::value).map(clazz -> (ArgumentConverter) ReflectionUtils.newInstance(clazz)).map(converter -> AnnotationConsumerInitializer.initialize(parameter, converter)).orElse(DefaultArgumentConverter.INSTANCE);
// @formatter:on
try {
return argumentConverter.convert(argument, parameterContext);
} catch (Exception ex) {
throw new ParameterResolutionException("Error resolving parameter at index " + parameterContext.getIndex(), ex);
}
}
use of java.lang.reflect.Parameter in project junit5 by junit-team.
the class ExecutableInvoker method resolveParameter.
private Object resolveParameter(ParameterContext parameterContext, Executable executable, ExtensionContext extensionContext, ExtensionRegistry extensionRegistry) {
try {
// @formatter:off
List<ParameterResolver> matchingResolvers = extensionRegistry.stream(ParameterResolver.class).filter(resolver -> resolver.supportsParameter(parameterContext, extensionContext)).collect(toList());
if (matchingResolvers.isEmpty()) {
throw new ParameterResolutionException(String.format("No ParameterResolver registered for parameter [%s] in executable [%s].", parameterContext.getParameter(), executable.toGenericString()));
}
if (matchingResolvers.size() > 1) {
// @formatter:off
String resolverNames = matchingResolvers.stream().map(resolver -> resolver.getClass().getName()).collect(joining(", "));
// @formatter:on
throw new ParameterResolutionException(String.format("Discovered multiple competing ParameterResolvers for parameter [%s] in executable [%s]: %s", parameterContext.getParameter(), executable.toGenericString(), resolverNames));
}
ParameterResolver resolver = matchingResolvers.get(0);
Object value = resolver.resolveParameter(parameterContext, extensionContext);
validateResolvedType(parameterContext.getParameter(), value, executable, resolver);
logger.trace(() -> String.format("ParameterResolver [%s] resolved a value of type [%s] for parameter [%s] in executable [%s].", resolver.getClass().getName(), (value != null ? value.getClass().getName() : null), parameterContext.getParameter(), executable.toGenericString()));
return value;
} catch (ParameterResolutionException ex) {
throw ex;
} catch (Throwable ex) {
throw new ParameterResolutionException(String.format("Failed to resolve parameter [%s] in executable [%s]", parameterContext.getParameter(), executable.toGenericString()), ex);
}
}
Aggregations