Search in sources :

Example 51 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project rxlib by RockyLOMO.

the class FeignInterceptor method onProcess.

@Override
protected Object onProcess(ProceedingJoinPoint joinPoint, StringBuilder msg) throws Throwable {
    Signature signature = joinPoint.getSignature();
    if (!(signature instanceof MethodSignature)) {
        return joinPoint.proceed();
    }
    Method method = ((MethodSignature) signature).getMethod();
    RequestMapping apiMapping = method.getAnnotation(RequestMapping.class);
    if (apiMapping == null) {
        return joinPoint.proceed();
    }
    String url = "";
    FeignClient feignClient = null;
    for (Class<?> pi : joinPoint.getTarget().getClass().getInterfaces()) {
        if ((feignClient = pi.getAnnotation(FeignClient.class)) != null) {
            break;
        }
    }
    if (feignClient != null) {
        url += feignClient.url();
    }
    RequestMapping baseMapping = method.getDeclaringClass().getAnnotation(RequestMapping.class);
    Function<RequestMapping, String> pf = p -> String.join(",", !ArrayUtils.isEmpty(p.value()) ? p.value() : p.path());
    if (baseMapping != null) {
        url += pf.apply(baseMapping);
    }
    url += pf.apply(apiMapping);
    String httpMethod = ArrayUtils.isEmpty(apiMapping.method()) ? "POST" : String.join(",", Arrays.stream(apiMapping.method()).map(p -> p.name()).collect(Collectors.toList()));
    msg.appendLine().appendLine("%s\t\t%s", httpMethod, resolveUrl(url, signature));
    return super.onProcess(joinPoint, msg);
}
Also used : Arrays(java.util.Arrays) Signature(org.aspectj.lang.Signature) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Tuple(org.rx.bean.Tuple) StringBuilder(org.rx.util.StringBuilder) FeignClient(org.springframework.cloud.netflix.feign.FeignClient) MethodSignature(org.aspectj.lang.reflect.MethodSignature) Method(java.lang.reflect.Method) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) LogInterceptor(org.rx.util.LogInterceptor) MethodSignature(org.aspectj.lang.reflect.MethodSignature) Signature(org.aspectj.lang.Signature) MethodSignature(org.aspectj.lang.reflect.MethodSignature) Method(java.lang.reflect.Method) FeignClient(org.springframework.cloud.netflix.feign.FeignClient) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 52 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project rxlib by RockyLOMO.

the class ValidateUtil method onProcess.

/**
 * Annotation expression只对method有效
 *
 * @param joinPoint
 * @param msg
 * @return
 * @throws Throwable
 */
@Override
protected Object onProcess(ProceedingJoinPoint joinPoint, StringBuilder msg) throws Throwable {
    Class targetType = joinPoint.getTarget().getClass();
    Signature signature = joinPoint.getSignature();
    Executable member;
    if (signature instanceof ConstructorSignature) {
        member = ((ConstructorSignature) signature).getConstructor();
    } else {
        member = ((MethodSignature) signature).getMethod();
    }
    msg.setPrefix(String.format("[Valid] %s.%s ", targetType.getSimpleName(), signature.getName()));
    EnableValid attr = member.getAnnotation(EnableValid.class);
    if (attr == null) {
        attr = (EnableValid) targetType.getAnnotation(EnableValid.class);
        if (attr == null) {
            msg.appendLine("skip validate..");
            return joinPoint.proceed();
        }
    }
    int flags = attr.value();
    boolean validateValues = hasFlags(flags, EnableValid.ParameterValues);
    if (hasFlags(flags, EnableValid.Method)) {
        if (signature instanceof ConstructorSignature) {
            ConstructorSignature cs = (ConstructorSignature) signature;
            validateConstructor(cs.getConstructor(), joinPoint.getArgs(), validateValues);
            return super.onProcess(joinPoint, msg);
        }
        MethodSignature ms = (MethodSignature) signature;
        return validateMethod(ms.getMethod(), joinPoint.getTarget(), joinPoint.getArgs(), validateValues, p -> super.onProcess(joinPoint, msg));
    }
    if (validateValues) {
        for (Object parameterValue : joinPoint.getArgs()) {
            validateBean(parameterValue);
        }
    }
    msg.appendLine("validate ok..").setPrefix(null);
    return super.onProcess(joinPoint, msg);
}
Also used : ConstructorSignature(org.aspectj.lang.reflect.ConstructorSignature) MethodSignature(org.aspectj.lang.reflect.MethodSignature) Signature(org.aspectj.lang.Signature) ConstructorSignature(org.aspectj.lang.reflect.ConstructorSignature) MethodSignature(org.aspectj.lang.reflect.MethodSignature) Executable(java.lang.reflect.Executable) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint)

Example 53 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project trafficController by amitkhosla.

the class AnnotationSupportImpl method runJoin.

/**
 * Handles Join operation.
 * Annotated method will be called with exactly same number of attributes for which non null data was returned by controlled methods.
 * If we have 4 methods defined and out of which 2 methods returned some value, join annotated method is expected to expect only these two methods in the same sequence as they would have called sequentially.
 * @param joinPoint Join point
 * @param join Join
 * @return This method will return null but will set output against its id in parallel map
 * @throws Throwable In case there is issue in processing
 */
@Around("execution(@org.ak.trafficController.annotations.api.Join * *(..)) && @annotation(join)")
public Object runJoin(ProceedingJoinPoint joinPoint, Join join) throws Throwable {
    int taskId = parallelJoinHelper.getObjectKeyForParalleldTask();
    int parallelTaskId = ParallelJoinHelper.getParallelId();
    AtomicReference<Object> output = new AtomicReference<Object>(null);
    Task joinerTask = parallelJoinHelper.getTask().then(() -> {
        List<Object> list = new ArrayList<>();
        addAllResultObjectsTillNowInList(list, parallelTaskId, taskId);
        if (!list.isEmpty()) {
            output.set(joinPoint.proceed(getObjectArrayFromList(list)));
        } else {
            output.set(joinPoint.proceed());
        }
        JoinResult jr = new JoinResult();
        jr.result = output.get();
        ParallelJoinHelper.map.get(parallelTaskId).put(taskId, jr);
    });
    joinerTask.setName("joiner ParallelId:" + parallelTaskId + " taskId : " + taskId + getTaskNameFromJoinPoint(joinPoint));
    parallelJoinHelper.setTask(joinerTask);
    setThreadingDetailsIfAny(joinerTask, join.threadDetailsDataExtractClass(), join.threadDetailsDataExtractMethodName(), join.threadDetailsProcessorClass(), join.threadDetailsProcessorMethodName(), join.threadDetailsCleanerClass(), join.threadDetailsCleanerMethodName());
    return null;
}
Also used : ParallelTask(org.ak.trafficController.ParallelTask) ParallelExecutingTask(org.ak.trafficController.ParallelExecutingTask) ExecutableTask(org.ak.trafficController.ExecutableTask) Task(org.ak.trafficController.Task) UnlinkedTask(org.ak.trafficController.UnlinkedTask) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) Around(org.aspectj.lang.annotation.Around)

Example 54 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project Hotchpotch by carryxyh.

the class Check method validator.

/**
 * 拦截所有使用Validator注解的接口,并进行参数合法有效性验证
 * @param joinPoint
 * @return
 * @throws Throwable
 */
@Around("@annotation(com.dfire.validator.annotation.Validator)")
public Object validator(ProceedingJoinPoint joinPoint) throws Throwable {
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    Object[] objects = joinPoint.getArgs();
    LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
    // 获得接口实现类的所有方法
    Method[] methods = joinPoint.getTarget().getClass().getDeclaredMethods();
    Map<String, Integer> paramMap = new HashMap<>();
    for (Method method1 : methods) {
        // 判断接口名与参数是否一致
        if (StringUtils.equals(method.getName(), method1.getName()) && method.getParameterTypes().length == method1.getParameterTypes().length && checkMethod(method, method1)) {
            String[] params = u.getParameterNames(method1);
            for (int i = 0; i < params.length; i++) {
                paramMap.put(params[i], i);
            }
            break;
        }
    }
    // 取得需要验证的注解对象
    Validator interfaceValidator = method.getAnnotation(Validator.class);
    // 取得明细验证规则
    Check[] params = interfaceValidator.value();
    int index = 0;
    for (int i = 0; i < params.length; i++) {
        Check p = params[i];
        Integer idx = paramMap.get(p.name());
        index = idx != null ? idx : i;
        // 如未指定验证参数名字,且当前规则所在索引大于参数个数时,报出异常
        if (index >= objects.length) {
            throw new Exception("未指定name或name错误 的注解索引已 大于 参数个数,请检查!注:name需与实现参数名一致!");
        }
        // 验证参数对象
        Object o = objects[index];
        Class<? extends ValidatorAdapter> vda = p.adapter();
        // 如未指定适配器,则默认使用oval验证对象
        if (vda.getName().equals(ValidatorAdapter.class.getName())) {
            if (o != null) {
                // 当验证对象不为null,使用oval验证框架验证
                net.sf.oval.Validator validator = new net.sf.oval.Validator();
                List<ConstraintViolation> ret = validator.validate(o);
                if (ret != null && ret.size() > 0) {
                    return processResult(p.name(), ret.get(0).getErrorCode(), ret.get(0).getMessage(), method.getReturnType());
                }
            }
        } else {
            ValidatorAdapter adapter = (ValidatorAdapter) Class.forName(vda.getName()).newInstance();
            // 根据注解相应设置的条件调用相应的验证方法
            if ((p.v().length == 0 && !adapter.validate(o)) || (p.v().length == 1 && !adapter.validate(o, p.v()[0])) || (p.v().length == 2 && !adapter.validate(o, p.v()[0], p.v()[1]))) {
                String message = StringUtils.isBlank(p.message()) ? adapter.getMessage() : p.message();
                return processResult(p.name(), p.errorCode(), message, method.getReturnType());
            }
        }
    }
    // 调用目标方法
    return joinPoint.proceed();
}
Also used : LocalVariableTableParameterNameDiscoverer(org.springframework.core.LocalVariableTableParameterNameDiscoverer) ValidatorAdapter(com.dfire.validator.validator.abstracts.ValidatorAdapter) MethodSignature(org.aspectj.lang.reflect.MethodSignature) HashMap(java.util.HashMap) Check(com.dfire.validator.annotation.Check) Method(java.lang.reflect.Method) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) ValidatorException(com.dfire.validator.exception.ValidatorException) ConstraintViolation(net.sf.oval.ConstraintViolation) Validator(com.dfire.validator.annotation.Validator) Around(org.aspectj.lang.annotation.Around)

Example 55 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project data-prep by Talend.

the class AnnotationGroupIdGenerator method getGroupId.

/**
 * @see GroupIdGenerator#getGroupId(ProceedingJoinPoint)
 */
@Override
public String getGroupId(ProceedingJoinPoint pjp) {
    // look for the @AsyncGroupId annotated parameter
    int idParameterIndex = AnnotationUtils.getAnnotatedParameterIndex(pjp, AsyncGroupId.class);
    // to get the @AsyncGroupId parameter value
    final String asyncGroupId;
    if (idParameterIndex >= 0) {
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        final Class groupIdParameterType = ms.getParameterTypes()[idParameterIndex];
        if (AsyncGroupKey.class.isAssignableFrom(groupIdParameterType)) {
            final AsyncGroupKey paramValue = (AsyncGroupKey) pjp.getArgs()[idParameterIndex];
            asyncGroupId = paramValue.getAsyncGroupKey();
        } else {
            asyncGroupId = String.valueOf(pjp.getArgs()[idParameterIndex]);
        }
    } else {
        asyncGroupId = null;
    }
    return asyncGroupId;
}
Also used : MethodSignature(org.aspectj.lang.reflect.MethodSignature) AsyncGroupKey(org.talend.dataprep.async.AsyncGroupKey) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint)

Aggregations

ProceedingJoinPoint (org.aspectj.lang.ProceedingJoinPoint)77 Around (org.aspectj.lang.annotation.Around)32 MethodSignature (org.aspectj.lang.reflect.MethodSignature)16 Method (java.lang.reflect.Method)14 Test (org.junit.Test)14 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)10 SimpleDateFormat (java.text.SimpleDateFormat)8 ArrayList (java.util.ArrayList)8 JoinPoint (org.aspectj.lang.JoinPoint)8 FaseDTO (com.tomasio.projects.trainning.dto.FaseDTO)7 OrganizacaoDTO (com.tomasio.projects.trainning.dto.OrganizacaoDTO)7 PessoaDTO (com.tomasio.projects.trainning.dto.PessoaDTO)7 MockProceedingJoinPoint (org.finra.herd.core.MockProceedingJoinPoint)7 Annotation (java.lang.annotation.Annotation)5 CancelamentoMatriculaDTO (com.tomasio.projects.trainning.dto.CancelamentoMatriculaDTO)4 MatriculaDTO (com.tomasio.projects.trainning.dto.MatriculaDTO)4 Date (java.util.Date)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Action (org.apache.nifi.action.Action)4 MessageHeader (org.finra.herd.model.dto.MessageHeader)4