Java Code Examples for org.apache.commons.lang3.ClassUtils#getAllInterfaces()

The following examples show how to use org.apache.commons.lang3.ClassUtils#getAllInterfaces() . 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: AnnotationUtil.java    From vjtools with Apache License 2.0 6 votes vote down vote up
/**
 * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口.
 * 
 * 暂未支持Spring风格Annotation继承Annotation
 * 
 * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承.
 */
public static <T extends Annotation> Set<Method> getAnnotatedPublicMethods(Class<?> clazz, Class<T> annotation) {
	// 已递归到Objebt.class, 停止递归
	if (Object.class.equals(clazz)) {
		return Collections.emptySet();
	}

	List<Class<?>> ifcs = ClassUtils.getAllInterfaces(clazz);
	Set<Method> annotatedMethods = new HashSet<Method>();

	// 遍历当前类的所有公共方法
	Method[] methods = clazz.getMethods();

	for (Method method : methods) {
		// 如果当前方法有标注,或定义了该方法的所有接口有标注
		if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) {
			annotatedMethods.add(method);
		}
	}

	return annotatedMethods;
}
 
Example 2
Source File: AnnotationUtil.java    From vjtools with Apache License 2.0 6 votes vote down vote up
/**
 * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口.
 * 
 * 暂未支持Spring风格Annotation继承Annotation
 * 
 * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承.
 */
public static <T extends Annotation> Set<Method> getAnnotatedPublicMethods(Class<?> clazz, Class<T> annotation) {
	// 已递归到Objebt.class, 停止递归
	if (Object.class.equals(clazz)) {
		return Collections.emptySet();
	}

	List<Class<?>> ifcs = ClassUtils.getAllInterfaces(clazz);
	Set<Method> annotatedMethods = new HashSet<Method>();

	// 遍历当前类的所有公共方法
	Method[] methods = clazz.getMethods();

	for (Method method : methods) {
		// 如果当前方法有标注,或定义了该方法的所有接口有标注
		if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) {
			annotatedMethods.add(method);
		}
	}

	return annotatedMethods;
}
 
Example 3
Source File: NiFiRegistryFlowMapper.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<ControllerServiceAPI> mapControllerServiceApis(final ControllerServiceNode service) {
    final Class<?> serviceClass = service.getControllerServiceImplementation().getClass();

    final Set<Class<?>> serviceApiClasses = new HashSet<>();
    // get all of it's interfaces to determine the controller service api's it implements
    final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(serviceClass);
    for (final Class<?> i : interfaces) {
        // add all controller services that's not ControllerService itself
        if (ControllerService.class.isAssignableFrom(i) && !ControllerService.class.equals(i)) {
            serviceApiClasses.add(i);
        }
    }


    final List<ControllerServiceAPI> serviceApis = new ArrayList<>();
    for (final Class<?> serviceApiClass : serviceApiClasses) {
        final BundleCoordinate bundleCoordinate = extensionManager.getBundle(serviceApiClass.getClassLoader()).getBundleDetails().getCoordinate();

        final ControllerServiceAPI serviceApi = new ControllerServiceAPI();
        serviceApi.setType(serviceApiClass.getName());
        serviceApi.setBundle(mapBundle(bundleCoordinate));
        serviceApis.add(serviceApi);
    }
    return serviceApis;
}
 
Example 4
Source File: ClassUtil.java    From j360-dubbo-app-all with Apache License 2.0 6 votes vote down vote up
/**
 * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口.
 * 
 * 暂未支持Spring风格Annotation继承Annotation
 * 
 * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承.
 */
public static <T extends Annotation> Set<Method> getAnnotatedPublicMethods(Class<?> clazz, Class<T> annotation) {
	// 已递归到Objebt.class, 停止递归
	if (Object.class.equals(clazz)) {
		return Collections.emptySet();
	}

	List<Class<?>> ifcs = ClassUtils.getAllInterfaces(clazz);
	Set<Method> annotatedMethods = new HashSet<Method>();

	// 遍历当前类的所有公共方法
	Method[] methods = clazz.getMethods();

	for (Method method : methods) {
		// 如果当前方法有标注,或定义了该方法的所有接口有标注
		if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) {
			annotatedMethods.add(method);
		}
	}

	return annotatedMethods;
}
 
Example 5
Source File: MetaModelLoader.java    From cuba with Apache License 2.0 6 votes vote down vote up
private boolean propertyBelongsTo(Field field, MetaProperty metaProperty, List<Class> systemInterfaces) {
    String getterName = "get" + StringUtils.capitalize(metaProperty.getName());

    Class<?> aClass = field.getDeclaringClass();
    //noinspection unchecked
    List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(aClass);
    for (Class intf : allInterfaces) {
        Method[] methods = intf.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(getterName) && method.getParameterTypes().length == 0) {
                if (systemInterfaces.contains(intf))
                    return true;
            }
        }
    }
    return false;
}
 
Example 6
Source File: ControllerFacade.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the specified type implements the specified serviceType.
 *
 * @param serviceType type
 * @param type type
 * @return whether the specified type implements the specified serviceType
 */
private boolean implementsServiceType(final String serviceType, final Class type) {
    final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(type);
    for (final Class i : interfaces) {
        if (ControllerService.class.isAssignableFrom(i) && i.getName().equals(serviceType)) {
            return true;
        }
    }

    return false;
}
 
Example 7
Source File: StandardControllerServiceInvocationHandler.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Object proxy(final Object bareObject, final Class<?> declaredType) {
    if (bareObject == null) {
        return null;
    }

    // We only want to proxy the object if the object is defined by the method that
    // was invoked as being an interface. For example, if a method is expected to return a java.lang.String,
    // we do not want to instead return a proxy because the Proxy won't be a String.
    if (declaredType == null || !declaredType.isInterface()) {
        return bareObject;
    }

    // If the ClassLoader is null, we have a primitive type, which we can't proxy.
    if (bareObject.getClass().getClassLoader() == null) {
        return bareObject;
    }

    // The proxy that is to be returned needs to ensure that it implements all interfaces that are defined by the
    // object. We cannot simply implement the return that that is defined, because the code that receives the object
    // may perform further inspection. For example, consider that a javax.jms.Message is returned. If this method proxies
    // only that method, but the object itself is a javax.jms.BytesMessage, then code such as the following will result in `isBytes == false`
    // when it should be `true`:
    //
    // final javax.jms.Message myMessage = controllerService.getMessage();
    // final boolean isBytes = myMessage instanceof javax.jms.BytesMessage;
    final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(bareObject.getClass());
    if (interfaces == null || interfaces.isEmpty()) {
        return bareObject;
    }

    // Add the ControllerServiceProxyWrapper to the List of interfaces to implement. See javadocs for ControllerServiceProxyWrapper
    // to understand why this is needed.
    if (!interfaces.contains(ControllerServiceProxyWrapper.class)) {
        interfaces.add(ControllerServiceProxyWrapper.class);
    }

    final Class<?>[] interfaceTypes = interfaces.toArray(new Class<?>[0]);
    final InvocationHandler invocationHandler = new ProxiedReturnObjectInvocationHandler(bareObject);
    return Proxy.newProxyInstance(bareObject.getClass().getClassLoader(), interfaceTypes, invocationHandler);
}
 
Example 8
Source File: EntityValidationListener.java    From syncope with Apache License 2.0 5 votes vote down vote up
@PrePersist
@PreUpdate
public void validate(final Object object) {
    final Validator validator = ApplicationContextProvider.getBeanFactory().getBean(Validator.class);
    Set<ConstraintViolation<Object>> violations = validator.validate(object);
    if (!violations.isEmpty()) {
        LOG.warn("Bean validation errors found: {}", violations);

        Class<?> entityInt = null;
        for (Class<?> interf : ClassUtils.getAllInterfaces(object.getClass())) {
            if (!Entity.class.equals(interf)
                    && !ProvidedKeyEntity.class.equals(interf)
                    && !Schema.class.equals(interf)
                    && !Task.class.equals(interf)
                    && !Policy.class.equals(interf)
                    && !GroupableRelatable.class.equals(interf)
                    && !Any.class.equals(interf)
                    && !DynMembership.class.equals(interf)
                    && Entity.class.isAssignableFrom(interf)) {

                entityInt = interf;
            }
        }

        throw new InvalidEntityException(entityInt == null
                ? "Entity" : entityInt.getSimpleName(), violations);
    }
}
 
Example 9
Source File: ControllerFacade.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the specified type implements the specified serviceType.
 *
 * @param serviceType type
 * @param type type
 * @return whether the specified type implements the specified serviceType
 */
private boolean implementsServiceType(final Class serviceType, final Class type) {
    final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(type);
    for (final Class i : interfaces) {
        if (ControllerService.class.isAssignableFrom(i) && serviceType.isAssignableFrom(i)) {
            return true;
        }
    }

    return false;
}
 
Example 10
Source File: AuthorizerFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Decorates the base authorizer to ensure the nar context classloader is used when invoking the underlying methods.
 *
 * @param baseAuthorizer base authorizer
 * @return authorizer
 */
public static Authorizer withNarLoader(final Authorizer baseAuthorizer, final ClassLoader classLoader) {
    final AuthorizerInvocationHandler invocationHandler = new AuthorizerInvocationHandler(baseAuthorizer, classLoader);

    final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(baseAuthorizer.getClass());
    final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[interfaceList.size()]);

    return (Authorizer) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}
 
Example 11
Source File: UserGroupProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static UserGroupProvider withNarLoader(final UserGroupProvider baseUserGroupProvider, final ClassLoader classLoader) {
    final UserGroupProviderInvocationHandler invocationHandler = new UserGroupProviderInvocationHandler(baseUserGroupProvider, classLoader);

    // extract all interfaces... baseUserGroupProvider is non null so getAllInterfaces is non null
    final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(baseUserGroupProvider.getClass());
    final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[interfaceList.size()]);

    return (UserGroupProvider) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}
 
Example 12
Source File: AccessPolicyProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static AccessPolicyProvider withNarLoader(final AccessPolicyProvider baseAccessPolicyProvider, final ClassLoader classLoader) {
    final AccessPolicyProviderInvocationHandler invocationHandler = new AccessPolicyProviderInvocationHandler(baseAccessPolicyProvider, classLoader);

    // extract all interfaces... baseAccessPolicyProvider is non null so getAllInterfaces is non null
    final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(baseAccessPolicyProvider.getClass());
    final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[interfaceList.size()]);

    return (AccessPolicyProvider) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}
 
Example 13
Source File: ProxyUtils.java    From EclipseCodeFormatter with Apache License 2.0 4 votes vote down vote up
@NotNull
private static Class[] getInterfaces(CodeStyleManager manager) {
	List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(manager.getClass());
	LOG.debug("Proxy interfaces " + allInterfaces);
	return allInterfaces.toArray(new Class[0]);
}
 
Example 14
Source File: ExtensionBuilder.java    From nifi with Apache License 2.0 4 votes vote down vote up
private ControllerServiceNode createControllerServiceNode() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InitializationException {
    final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final Bundle bundle = extensionManager.getBundle(bundleCoordinate);
        if (bundle == null) {
            throw new IllegalStateException("Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate());
        }

        final ClassLoader detectedClassLoader = extensionManager.createInstanceClassLoader(type, identifier, bundle, classpathUrls == null ? Collections.emptySet() : classpathUrls);
        final Class<?> rawClass = Class.forName(type, true, detectedClassLoader);
        Thread.currentThread().setContextClassLoader(detectedClassLoader);

        final Class<? extends ControllerService> controllerServiceClass = rawClass.asSubclass(ControllerService.class);
        final ControllerService serviceImpl = controllerServiceClass.newInstance();
        final StandardControllerServiceInvocationHandler invocationHandler = new StandardControllerServiceInvocationHandler(extensionManager, serviceImpl);

        // extract all interfaces... controllerServiceClass is non null so getAllInterfaces is non null
        final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(controllerServiceClass);
        final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[0]);

        final ControllerService proxiedService;
        if (detectedClassLoader == null) {
            proxiedService = (ControllerService) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, invocationHandler);
        } else {
            proxiedService = (ControllerService) Proxy.newProxyInstance(detectedClassLoader, interfaces, invocationHandler);
        }

        logger.info("Created Controller Service of type {} with identifier {}", type, identifier);
        final ComponentLog serviceLogger = new SimpleProcessLogger(identifier, serviceImpl);
        final TerminationAwareLogger terminationAwareLogger = new TerminationAwareLogger(serviceLogger);

        final StateManager stateManager = stateManagerProvider.getStateManager(identifier);
        final ControllerServiceInitializationContext initContext = new StandardControllerServiceInitializationContext(identifier, terminationAwareLogger,
                serviceProvider, stateManager, kerberosConfig, nodeTypeProvider);
        serviceImpl.initialize(initContext);

        final LoggableComponent<ControllerService> originalLoggableComponent = new LoggableComponent<>(serviceImpl, bundleCoordinate, terminationAwareLogger);
        final LoggableComponent<ControllerService> proxiedLoggableComponent = new LoggableComponent<>(proxiedService, bundleCoordinate, terminationAwareLogger);

        final ComponentVariableRegistry componentVarRegistry = new StandardComponentVariableRegistry(this.variableRegistry);
        final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(serviceProvider, componentVarRegistry);
        final ControllerServiceNode serviceNode = new StandardControllerServiceNode(originalLoggableComponent, proxiedLoggableComponent, invocationHandler,
                identifier, validationContextFactory, serviceProvider, componentVarRegistry, reloadComponent, extensionManager, validationTrigger);
        serviceNode.setName(rawClass.getSimpleName());

        invocationHandler.setServiceNode(serviceNode);
        return serviceNode;
    } finally {
        if (ctxClassLoader != null) {
            Thread.currentThread().setContextClassLoader(ctxClassLoader);
        }
    }
}
 
Example 15
Source File: RemoteServicesBeanCreator.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public void postProcessBeanFactory(@Nonnull ConfigurableListableBeanFactory beanFactory) throws BeansException {
    log.info("Configuring remote services");

    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    ApplicationContext coreContext = context.getParent();
    if (coreContext == null) {
        throw new RuntimeException("Parent Spring context is null");
    }

    Map<String,Object> services = coreContext.getBeansWithAnnotation(Service.class);
    for (Map.Entry<String, Object> entry : services.entrySet()) {
        String serviceName = entry.getKey();
        Object service = entry.getValue();

        List<Class> serviceInterfaces = new ArrayList<>();
        List<Class<?>> interfaces = ClassUtils.getAllInterfaces(service.getClass());
        for (Class intf : interfaces) {
            if (intf.getName().endsWith("Service"))
                serviceInterfaces.add(intf);
        }
        String intfName = null;
        if (serviceInterfaces.size() == 0) {
            log.error("Bean " + serviceName + " has @Service annotation but no interfaces named '*Service'. Ignoring it.");
        } else if (serviceInterfaces.size() > 1) {
            intfName = findLowestSubclassName(serviceInterfaces);
            if (intfName == null)
                log.error("Bean " + serviceName + " has @Service annotation and more than one interface named '*Service', " +
                        "but these interfaces are not from the same hierarchy. Ignoring it.");
        } else {
            intfName = serviceInterfaces.get(0).getName();
        }
        if (intfName != null) {
            if (ServiceExportHelper.exposeServices()) {
                BeanDefinition definition = new RootBeanDefinition(HttpServiceExporter.class);
                MutablePropertyValues propertyValues = definition.getPropertyValues();
                propertyValues.add("service", service);
                propertyValues.add("serviceInterface", intfName);
                registry.registerBeanDefinition("/" + serviceName, definition);
                log.debug("Bean " + serviceName + " configured for export via HTTP");
            } else {
                ServiceExportHelper.registerLocal("/" + serviceName, service);
            }
        }
    }
}
 
Example 16
Source File: ClassUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 递归返回本类及所有基类继承的接口,及接口继承的接口,比Spring中的相同实现完整
 */
public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
	return ClassUtils.getAllInterfaces(cls);
}
 
Example 17
Source File: ClassUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 递归返回本类及所有基类继承的接口,及接口继承的接口,比Spring中的相同实现完整
 */
public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
	return ClassUtils.getAllInterfaces(cls);
}
 
Example 18
Source File: ClassUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 递归返回本类及所有基类继承的接口,及接口继承的接口,比Spring中的相同实现完整
 */
public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
	return ClassUtils.getAllInterfaces(cls);
}