Java Code Examples for java.lang.reflect.Method#getAnnotationsByType()

The following examples show how to use java.lang.reflect.Method#getAnnotationsByType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Minister.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 把定时任务检索出来
 */
private void checkSchedules(Class<?> clazz) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method m : methods) {
        if (m.getName().equals(DEFAULT_SCHEDULED_METHOD)) {
            continue;
        }
        Scheduled[] schedules = m.getAnnotationsByType(Scheduled.class);
        if (exist(schedules) && 0 < schedules.length) {
            m.setAccessible(true);
            List<ScheduledInfo> sis = new ArrayList<>(schedules.length);
            for (Scheduled s : schedules) {
                sis.add(new ScheduledInfo(s.cron(), s.fixedRate(), s.delay()));
            }
            if (!sis.isEmpty()) {
                ScheduledScope scheduledScope = m.getAnnotation(ScheduledScope.class);
                this.secretary.methods.add(new MethodInfo(m, null == scheduledScope ?
                        MethodScope.INSTANCE : scheduledScope.value(), sis));
            }
        }
    }
}
 
Example 2
Source File: AnnotatedGroupDefinitionBuilder.java    From cuba with Apache License 2.0 6 votes vote down vote up
public Map<String, Serializable> buildSessionAttributes(AccessGroupDefinition group) {
    Class<? extends AccessGroupDefinition> clazz = group.getClass();

    Map<String, Serializable> sessionAttributes = new HashMap<>();

    for (Method method : clazz.getDeclaredMethods()) {
        if (isSessionAttributesMethod(method)) {
            for (Class<? extends Annotation> annotationType : getAvailableAnnotationTypes()) {
                for (Annotation annotation : method.getAnnotationsByType(annotationType)) {
                    AnnotationProcessor<SessionAttributesContext> processor = findAnnotationProcessor(annotationType);
                    if (processor != null) {
                        processor.processAnnotation(new SessionAttributesContext(annotation, method, group, sessionAttributes));
                    }
                }
            }
        }
    }

    return sessionAttributes;
}
 
Example 3
Source File: LocalExecutableRegistryImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
/**
 * The <code>LocalExecutableRegistryImpl</code> stores registered tasks in a concurrent map structure
 * If the given entry is not in the map strucuture, this implementation looks for the given class and tries to retrieve
 * it from the guice injector.
 * @param taskIdentifier- String that identifies a task to be executed
 * @return The executable method that can be invoked - either one that is previously registered or one that is loaded dynamically in the JVM
 */
@Override
public Executable getTask(String taskIdentifier) {
    final Executable cachedExecutable = this.identifierToMethodMap.get(taskIdentifier);
    if (cachedExecutable == null) {
        try {
            //taskIdentifier would be of form methodIdentifier_version<no>, so removing _version<no> and passing the remaining string
            final MethodId methodId = MethodId.fromIdentifier(taskIdentifier.substring(0, taskIdentifier.lastIndexOf('_')));

            final Class<?> clazz = Class.forName(methodId.getClassName());
            final Object classInstance = this.injector.getInstance(clazz);
            final Method methodToInvoke = clazz.getDeclaredMethod(methodId.getMethodName(), methodId.getParameterTypes());
            final Task taskAnnotation = methodToInvoke.getAnnotationsByType(Task.class)[0];
            return new ExecutableImpl(classInstance, methodToInvoke, taskAnnotation.timeout());
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            throw new UnknownIdentifierException("Could not load method corresponding to the given task identifier:" + taskIdentifier);
        }
    }
    return cachedExecutable;
}
 
Example 4
Source File: TaskInterceptor.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    checkForBadSignatures(invocation);
    if (!localContext.isWorkflowInterception()) {
        return invocation.proceed();
    }
    final Method method = invocation.getMethod();
    final Task taskAnnotation = method.getAnnotationsByType(Task.class)[0];
    final String taskIdentifier = generateTaskIdentifier(method, taskAnnotation);
    final List<EventDefinition> dependencySet = generateDependencySet(invocation.getArguments(),method.getParameterAnnotations(),method.getParameterTypes());
    final Object proxyReturnObject = createProxyReturnObject(method);
    final EventDefinition outputEventDefintion = generateOutputEventDefintion(proxyReturnObject);

    //throw exception if state machine and state versions doesn't match
    if(localContext.getStateMachineDef() != null && localContext.getStateMachineDef().getVersion() != taskAnnotation.version()) {
        throw new VersionMismatchException("Mismatch between State machine and state versions for State: "+method.getDeclaringClass().getName()+"."
                +generateStateIdentifier(method)+". StateMachine version: "+localContext.getStateMachineDef().getVersion()+". State version: "+taskAnnotation.version());
    }
    /* Contribute to the ongoing state machine definition */
    localContext.registerNewState(taskAnnotation.version(), generateStateIdentifier(method), null, null, taskIdentifier, taskAnnotation.retries(), taskAnnotation.timeout(), dependencySet, outputEventDefintion);
    /* Register the task with the executable registry on this jvm */
    executableRegistry.registerTask(taskIdentifier, new ExecutableImpl(invocation.getThis(), invocation.getMethod(), taskAnnotation.timeout()));

    return proxyReturnObject;
}
 
Example 5
Source File: MethodInfo.java    From fastquery with Apache License 2.0 6 votes vote down vote up
public MethodInfo(Method method) { // NO_UCD
	this.method = method;
	this.modifying = method.getAnnotation(Modifying.class);
	this.queries = method.getAnnotationsByType(Query.class);
	this.parameters = method.getParameters();
	this.returnType = method.getReturnType();
	this.id = method.getAnnotation(Id.class);
	this.t = method.getAnnotation(Transactional.class);
	this.queryByNamed = method.getAnnotation(QueryByNamed.class);
	this.notCount = method.getAnnotation(NotCount.class);
	this.conditions = method.getAnnotationsByType(Condition.class);
	this.parameterAnnotations =  method.getParameterAnnotations();
	this.genericReturnType = method.getGenericReturnType();
	this.name = method.getName();
	this.query = method.getAnnotation(Query.class);
	this.sets = method.getAnnotationsByType(Set.class);
	this.containQueryBuilderParam = TypeUtil.hasType(QueryBuilder.class, this.parameters);
}
 
Example 6
Source File: WorkflowInterceptor.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
        final Method method = invocation.getMethod();
        final Workflow[] workFlowAnnotations = method.getAnnotationsByType(Workflow.class);
        checkForBadSignatures(invocation);
        final String correlationId = checkForCorrelationId(invocation.getArguments());
        Workflow workflow = workFlowAnnotations[0];
        localContext.registerNew(generateWorkflowIdentifier(method, workflow), workflow.version(),
                workflow.description(),correlationId, fluxClientConfigurationProvider.get().getClientElbId());
        registerEventsForArguments(invocation.getArguments());
        invocation.proceed();
        connectorProvider.get().submitNewWorkflow(localContext.getStateMachineDef());
        return null ; // TODO, return a proxy object
    }
    finally {
        this.localContext.reset();
    }
}
 
Example 7
Source File: StandardJaxrsActionProxy.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 获取方法的操作名称,首选AuditLog的value属性属性,如果没有,则选择JaxrsMethodDescribe的value属性
 * @param method
 * @param annotations_auditLog
 * @return
 */
private String getOperationName( Method method, Annotation[] annotations_auditLog ) {
    String operationName = ((AuditLog)annotations_auditLog[0]).operation();
    Annotation[] annotations_jaxrsMethodDescribe = null;
    if( StringUtils.isEmpty(operationName)){
        //取JaxrsMethodDescribe
        annotations_jaxrsMethodDescribe = method.getAnnotationsByType(JaxrsMethodDescribe.class);
        if( ArrayUtils.isNotEmpty( annotations_jaxrsMethodDescribe )){
            operationName = ((JaxrsMethodDescribe)annotations_auditLog[0]).value();
        }
    }
    return operationName;
}
 
Example 8
Source File: AnnotationActionModuleTypeHelper.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private List<Output> getOutputsFromMethod(Method method) {
    List<Output> outputs = new ArrayList<>();
    if (method.isAnnotationPresent(ActionOutputs.class)) {
        for (ActionOutput ruleActionOutput : method.getAnnotationsByType(ActionOutput.class)) {
            Output output = new Output(ruleActionOutput.name(), ruleActionOutput.type(), ruleActionOutput.label(),
                    ruleActionOutput.description(),
                    Arrays.stream(ruleActionOutput.tags()).collect(Collectors.toSet()),
                    ruleActionOutput.reference(), ruleActionOutput.defaultValue());

            outputs.add(output);
        }
    }
    return outputs;
}
 
Example 9
Source File: ApplicationSettings.java    From Open-LaTeX-Studio with MIT License 5 votes vote down vote up
public void registerSettingListeners(Object o) {
    for(Method m : o.getClass().getMethods()) {
        for(Annotation a : m.getAnnotationsByType( SettingListener.class )) {
            Setting s = ((SettingListener) a).setting();
            //TODO 20160323 Type validation
            settingListeners.get(s).add(Pair.of(o,m));
            try {
                m.invoke(o, s.getValue());
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                Exceptions.printStackTrace(ex);
            }
            break;
        }
    }
}
 
Example 10
Source File: ModifyingDependencyFilter.java    From fastquery with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(Method method) {
	Modifying m = method.getAnnotation(Modifying.class);
	int queryLen = method.getAnnotationsByType(Query.class).length;
	QueryByNamed queryByNamed = method.getAnnotation(QueryByNamed.class);
	Parameter[] parameters = method.getParameters();
	boolean hasQueryBuilder = TypeUtil.hasType(QueryBuilder.class, parameters);
	if (m != null && queryLen == 0 && queryByNamed == null && !hasQueryBuilder) {
		this.abortWith(method, "@Modifying 要么跟 @Query 组合, 要么跟@QueryByNamed组合, 要么跟QueryBuilder参数组合!");
	}
}
 
Example 11
Source File: OutFilter.java    From fastquery with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(Method method) {

	// 1). 不能同时标识@Query,@QueryByNamed
	if (method.getAnnotationsByType(Query.class).length > 0 && method.getAnnotation(QueryByNamed.class) != null) {
		this.abortWith(method, "该方法不能同时标识@Query和@QueryByNamed");
	}

}
 
Example 12
Source File: NotAllowedRepeat.java    From fastquery with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(Method method) {
	Query[] queries = method.getAnnotationsByType(Query.class);
	if (queries.length > 1) {
		this.abortWith(method, "@Query注解在这个方法上不能重复! 改操作的情形下@Query可以重复.");
	}
}
 
Example 13
Source File: HBaseClassTestRule.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that checks if the input method is a valid JUnit @Parameters method.
 * @param method Input method.
 * @return true if the method is a valid JUnit parameters method, false otherwise.
 */
private static boolean isParametersMethod(@NonNull Method method) {
  // A valid parameters method is public static and with @Parameters annotation.
  boolean methodPublicStatic = Modifier.isPublic(method.getModifiers()) &&
      Modifier.isStatic(method.getModifiers());
  Parameters[] params = method.getAnnotationsByType(Parameters.class);
  return methodPublicStatic && (params != null && params.length > 0);
}
 
Example 14
Source File: ApiDocTool.java    From nuls-v2 with MIT License 5 votes vote down vote up
public static List<ResultDes> buildParam(ApiType apiType, Method method) {
    Annotation annotation = method.getAnnotation(Parameters.class);
    List<Parameter> parameters;
    if (annotation != null) {
        parameters = Arrays.asList(((Parameters) annotation).value());
    } else {
        Parameter[] parameterAry = method.getAnnotationsByType(Parameter.class);
        parameters = Arrays.asList(parameterAry);
    }
    List<ResultDes> param = new ArrayList<>();
    parameters.stream().forEach(parameter -> {
        ResultDes res = new ResultDes();
        res.type = parameter.parameterType();
        res.name = parameter.parameterName();
        res.des = parameter.parameterDes();
        res.canNull = parameter.canNull();
        Class<?> requestType = parameter.requestType().value();
        if (baseType.contains(requestType)) {
            param.addAll(buildResultDes(parameter.requestType(), res.des, res.name, res.canNull));
        } else {
            if(ApiType.RESTFUL.equals(apiType)) {
                try {
                    res.formJsonOfRestful = JSONUtils.obj2PrettyJson(newInstance(requestType));
                } catch (Exception e) {
                    System.out.println(String.format("Form named [%s] has no non-args-constructor or other error [%s].", requestType.getSimpleName(), e.getMessage()));
                }
            }
            res.list = buildResultDes(parameter.requestType(), res.des, res.name, res.canNull);
            res.type = parameter.requestType().value().getSimpleName().toLowerCase();
            // pierre add at 20190910 for duplicate `List<String>`
            if(parameter.requestType().value() == List.class && baseType.contains(parameter.requestType().collectionElement())) {
                res.type = res.list.get(0).type;
                res.list = null;
            }
            param.add(res);
        }
    });
    return param;
}
 
Example 15
Source File: ControllerCall.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add custom binders assigned to the method
 * <p>
 * Custom binders assigned to the method will be added to the binding
 * manager instance.
 * </p>
 *
 * @param manager
 *            the manager to add binders to
 * @param method
 *            the method to evaluate for additional binders
 */
protected static void addMethodBinders ( final BindingManager manager, final Method method )
{
    final ControllerBinder[] binders = method.getAnnotationsByType ( ControllerBinder.class );

    if ( binders == null )
    {
        return;
    }

    for ( final ControllerBinder binder : binders )
    {
        try
        {
            final Binder binderImpl = binder.value ().newInstance ();
            if ( binderImpl instanceof ControllerBinderParametersAware )
            {
                ( (ControllerBinderParametersAware)binderImpl ).setParameters ( binder.parameters () );
            }
            manager.addBinder ( binderImpl );
        }
        catch ( InstantiationException | IllegalAccessException e )
        {
            manager.addBinder ( new ErrorBinder ( e ) );
        }
    }
}
 
Example 16
Source File: ModifyingReturnTypeFilter.java    From fastquery with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(Method method) {

	String errmsg = String.format(
			"为这个方法设置返回值错误!%n该方法允许的返回值类型如下: %n%s \t- 没有返回值;%n%s \t- 用来获取影响行数;%n%s \t- 保存的实体以Map封装后输出;%n%s \t- 保存的实体JSON格式;%n%s \t- 保存的实体Bean(注意:该bean必须有默认不带参数的构造方法);%n%s \t- 获取主键;%n%s \t - 操作是否正确.",
			"void",
			"int",
			"java.util.Map<String, Object>或java.util.Map<String, String>",
			"com.alibaba.fastjson.JSONObject",
			"Bean",
			Primarykey.class.getName(),
			boolean.class);
	
	String errmsg2 = " 该SQL的操作结果不能映射成Map格式";
	Type genericReturnType = method.getGenericReturnType();
	Class<?> returnType = method.getReturnType();

	Query[] queries = method.getAnnotationsByType(Query.class);
	for (Query query : queries) {
		// 如果当前方法没有标记 @Modifying 和 @ Query 是进入不了这个过滤器的. 过滤器已经分成了8类
		String sql = query.value();
		// 如果返回值是Map 并且 没有包含 "insert into" 或 "update"

		// sql中既不含insert又不含update,才会返回true
		boolean nothas = !TypeUtil.containsIgnoreCase(sql, "insert into") && !TypeUtil.containsIgnoreCase(sql, "update");
		if ((returnType == Map.class) && nothas) { // 1). 校验 SQL中存在"insert into" 才能允许其返回值为 Map<String,Object>
			this.abortWith(method, sql + errmsg2);
		} else if ((returnType == JSONObject.class) && nothas) { // 2). 校验:如果返回值是JSONObject,那么SQL必须是insert语句 或 "update"
			this.abortWith(method, sql + errmsg2);
		} else if ((TypeUtil.hasDefaultConstructor(returnType)) && nothas) { // 3). 校验:如果返回值是实体,那么SQL必须是insert 或 "update"
			this.abortWith(method, sql + errmsg2);
		} else if (TypeUtil.containsIgnoreCase(sql, "delete") && (returnType != void.class) && (returnType != int.class) && (returnType != int[].class) && (returnType != boolean.class)) { // 4). 校验:如果是删除操作,那么返回值只能是void 或是 int, 或者int[]
			this.abortWith(method, sql + "该SQL是删除操作,返回值只能是void,int,int[]或boolean类型.");
		} else if(returnType != void.class && 
			returnType != int.class &&
			returnType != int[].class &&
			returnType != boolean.class &&
			!TypeUtil.isMapSO(genericReturnType) &&
			returnType != JSONObject.class &&
			returnType != Primarykey.class &&
			!TypeUtil.hasDefaultConstructor(returnType) // 不是bean
	           ){ // 5). 校验返回值所允许的类型
			this.abortWith(method, errmsg);
           }
	}
}
 
Example 17
Source File: Properties.java    From es6draft with MIT License 4 votes vote down vote up
private static ObjectLayout createExternalObjectLayout(Class<?> holder, boolean staticMethods) {
    try {
        ObjectLayout layout = new ObjectLayout();
        Lookup lookup = MethodHandles.publicLookup();
        for (Method method : holder.getDeclaredMethods()) {
            if (Modifier.isStatic(method.getModifiers()) != staticMethods)
                continue;
            Function function = method.getAnnotation(Function.class);
            Accessor accessor = method.getAnnotation(Accessor.class);
            Value value = method.getAnnotation(Value.class);
            AliasFunction[] aliases = method.getAnnotationsByType(AliasFunction.class);
            if (aliases.length > 0 && function == null) {
                throw new IllegalArgumentException();
            }
            if (function != null) {
                if (accessor != null || value != null) {
                    throw new IllegalArgumentException();
                }
                if (layout.functions == null) {
                    layout.functions = new LinkedHashMap<>();
                }
                MethodHandle mh = lookup.unreflect(method);
                layout.functions.put(function, mh);
                for (AliasFunction alias : aliases) {
                    layout.functions.put(createFunctionFromAlias(function, alias), mh);
                }
            }
            if (accessor != null) {
                if (value != null) {
                    throw new IllegalArgumentException();
                }
                if (layout.accessors == null) {
                    layout.accessors = new LinkedHashMap<>();
                }
                layout.accessors.put(accessor, lookup.unreflect(method));
            }
            if (value != null) {
                if (layout.values == null) {
                    layout.values = new LinkedHashMap<>();
                }
                layout.values.put(value, lookup.unreflect(method));
            }
        }
        return layout;
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 18
Source File: SwaggerExtension.java    From Web-API with MIT License 4 votes vote down vote up
@Override
public void decorateOperation(Operation operation, Method method,
                              Iterator<io.swagger.jaxrs.ext.SwaggerExtension> chain) {
    // Automatically add query params
    operation.addParameter(new RefParameter("details"));
    operation.addParameter(new RefParameter("accept"));
    operation.addParameter(new RefParameter("pretty"));

    // Automatically add 500 as a possible response
    operation.addResponse("500", new RefResponse("500"));

    // Automatically add error codes depending on thrown exceptions
    for (Class<?> execClass : method.getExceptionTypes()) {
        if (BadRequestException.class.isAssignableFrom(execClass)) {
            operation.addResponse("400", new RefResponse("400"));
        }
        if (NotFoundException.class.isAssignableFrom(execClass)) {
            operation.addResponse("404", new RefResponse("404"));
        }
        if (NotImplementedException.class.isAssignableFrom(execClass)) {
            operation.addResponse("501", new RefResponse("501"));
        }
    }

    Permission[] perms = method.getAnnotationsByType(Permission.class);
    if (perms.length > 0) {
        // Automatically add 401 & 403 as a possible response
        operation.addResponse("401", new RefResponse("401"));
        operation.addResponse("403", new RefResponse("403"));

        // Automatically add required permission notes if we have a @Permission annotation
        Path path = method.getDeclaringClass().getAnnotation(Path.class);
        String prefix = path != null ? path.value() + "." : "";

        StringBuilder permStr = new StringBuilder("  \n\n **Required permissions:**  \n\n");
        for (Permission perm : perms) {
            permStr.append("- **").append(prefix).append(String.join(".", perm.value())).append("**  \n");
        }

        operation.setDescription(operation.getDescription() + permStr.toString());

        // Add security definitions
        operation.addSecurity("ApiKeyHeader", new ArrayList<>());
        operation.addSecurity("ApiKeyQuery", new ArrayList<>());
    }
    super.decorateOperation(operation, method, chain);
}
 
Example 19
Source File: DataProviderUtils.java    From at.info-knowledge-base with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@DataProvider(name = GENERIC_DP)
public static Iterator<Object[]> provideDBData(final Method testMethod) {
    if (testMethod == null) {
        throw new IllegalArgumentException("Test method cannot be null!");
    }

    final List<DataSet> dataSets = new ArrayList<>();
    final List<Object[]> outputData = new ArrayList<>();

    int outputDataSize = Integer.MAX_VALUE;

    for (Entity entity : testMethod.getAnnotationsByType(Entity.class)) {
        final DAO entityDAO = new GenericDAO<>(entity.entity(), entity.schema());
        final List<BaseEntity> retrievedFields = new ArrayList<>();

        int minInvocationCount = entity.ids().length;

        if (minInvocationCount > 0) {
            for (long id : entity.ids()) {
                retrievedFields.add(entityDAO.findById(id));
            }
        } else {
            retrievedFields.addAll(entityDAO.findAll());
            minInvocationCount = retrievedFields.size();
        }

        dataSets.add(new DataSet(retrievedFields).updateFieldsWith(entityDAO));

        final int currentDataSize = outputDataSize;
        outputDataSize = Optional.of(IntStream.of(entity.invocationCount(), minInvocationCount)
                .filter(value -> value > 0)
                .min()
                .getAsInt())
                .filter(value -> value < currentDataSize)
                .orElse(currentDataSize);
    }

    if (outputDataSize < Integer.MAX_VALUE) {
        for (int i = 0; i < outputDataSize; i++) {
            final Object[] dataSet = new Object[dataSets.size()];

            for (int j = 0; j < dataSets.size(); j++) {
                dataSet[j] = dataSets.get(j).getFields().get(i);
            }

            outputData.add(dataSet);
        }
    }

    return outputData.iterator();
}
 
Example 20
Source File: Functions.java    From JALSE with Apache License 2.0 3 votes vote down vote up
/**
    * Gets all the {@link EntityID} annotations and transforms into ID suppliers.
    *
    * @param m
    *            Method to check.
    * @return ID supplier set.
    *
    * @see #toIDSupplier(EntityID)
    */
   public static Set<Supplier<UUID>> getIDSuppliers(final Method m) {
final Set<Supplier<UUID>> idSuppliers = new HashSet<>();
for (final EntityID entityID : m.getAnnotationsByType(EntityID.class)) {
    idSuppliers.add(toIDSupplier(entityID));
}
return idSuppliers;
   }