Java Code Examples for org.springframework.util.ClassUtils

The following are top voted examples for showing how to use org.springframework.util.ClassUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-domain-events   File: PublicationTargetIdentifier.java   View source code 7 votes vote down vote up
/**
 * Creates a {@link PublicationTargetIdentifier} for the given {@link Method}.
 * 
 * @param method must not be {@literal null}.
 * @return
 */
public static PublicationTargetIdentifier forMethod(Method method) {

	String typeName = ClassUtils.getUserClass(method.getDeclaringClass()).getName();
	String methodName = method.getName();
	String parameterTypes = StringUtils.arrayToDelimitedString(method.getParameterTypes(), ", ");

	return PublicationTargetIdentifier.of(String.format("%s.%s(%s)", typeName, methodName, parameterTypes));
}
 
Example 2
Project: lams   File: ProxyFactoryBean.java   View source code 6 votes vote down vote up
/**
 * Return the singleton instance of this class's proxy object,
 * lazily creating it if it hasn't been created already.
 * @return the shared singleton proxy
 */
private synchronized Object getSingletonInstance() {
	if (this.singletonInstance == null) {
		this.targetSource = freshTargetSource();
		if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
			// Rely on AOP infrastructure to tell us what interfaces to proxy.
			Class<?> targetClass = getTargetClass();
			if (targetClass == null) {
				throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
			}
			setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
		}
		// Initialize the shared singleton instance.
		super.setFrozen(this.freezeProxy);
		this.singletonInstance = getProxy(createAopProxy());
	}
	return this.singletonInstance;
}
 
Example 3
Project: spring-data-jdbc   File: GeneratedValueUtil.java   View source code 6 votes vote down vote up
private static String getNumberConversionMethodName(Class<?> objectClass) {
    objectClass = ClassUtils.resolvePrimitiveIfNecessary(objectClass);
    if (Integer.class.isAssignableFrom(objectClass)) {
        return INT_VALUE;
    }
    if (Long.class.isAssignableFrom(objectClass)) {
        return LONG_VALUE;
    }
    if (Float.class.isAssignableFrom(objectClass)) {
        return FLOAT_VALUE;
    }
    if (Double.class.isAssignableFrom(objectClass)) {
        return DOUBLE_VALUE;
    }
    throw new IllegalArgumentException(
            "Cannot get conversion number for class " + objectClass);
}
 
Example 4
Project: bekit   File: FlowParser.java   View source code 6 votes vote down vote up
private static FlowExecutor.TargetMappingExecutor parseTargetMapping(Method method) {
    logger.debug("解析目标对象映射方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验入参
    Class[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "必须只能有一个入参");
    }
    // 校验返回参数
    if (method.getReturnType() != String.class) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "返回参数必须是String类型");
    }

    return new FlowExecutor.TargetMappingExecutor(method, parameterTypes[0]);
}
 
Example 5
Project: cas-5.1.0   File: CasCoreBootstrapStandaloneConfiguration.java   View source code 6 votes vote down vote up
@ConfigurationPropertiesBinding
@Bean
public Converter<String, List<Class<? extends Throwable>>> commaSeparatedStringToThrowablesCollection() {
    return new Converter<String, List<Class<? extends Throwable>>>() {
        @Override
        public List<Class<? extends Throwable>> convert(final String source) {
            try {
                final List<Class<? extends Throwable>> classes = new ArrayList<>();
                for (final String className : StringUtils.commaDelimitedListToStringArray(source)) {
                    classes.add((Class<? extends Throwable>) ClassUtils.forName(className.trim(), getClass().getClassLoader()));
                }
                return classes;
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    };
}
 
Example 6
Project: lams   File: ProxyFactoryBean.java   View source code 6 votes vote down vote up
/**
 * Create a new prototype instance of this class's created proxy object,
 * backed by an independent AdvisedSupport configuration.
 * @return a totally independent proxy, whose advice we may manipulate in isolation
 */
private synchronized Object newPrototypeInstance() {
	// In the case of a prototype, we need to give the proxy
	// an independent instance of the configuration.
	// In this case, no proxy will have an instance of this object's configuration,
	// but will have an independent copy.
	if (logger.isTraceEnabled()) {
		logger.trace("Creating copy of prototype ProxyFactoryBean config: " + this);
	}

	ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());
	// The copy needs a fresh advisor chain, and a fresh TargetSource.
	TargetSource targetSource = freshTargetSource();
	copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
	if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
		// Rely on AOP infrastructure to tell us what interfaces to proxy.
		copy.setInterfaces(
				ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), this.proxyClassLoader));
	}
	copy.setFrozen(this.freezeProxy);

	if (logger.isTraceEnabled()) {
		logger.trace("Using ProxyCreatorSupport copy: " + copy);
	}
	return getProxy(copy.createAopProxy());
}
 
Example 7
Project: xm-commons   File: LepServicesRegistrar.java   View source code 6 votes vote down vote up
private static String getBeanName(AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
    // name & value are aliases
    String beanName = (String) attributes.get("value");
    if (!StringUtils.isEmpty(beanName)) {
        return beanName;
    } else {
        // generate bean name from class name
        String shortName = ClassUtils.getShortName(annotationMetadata.getClassName());
        return StringUtils.uncapitalize(shortName);
    }
}
 
Example 8
Project: lams   File: ExtendedEntityManagerCreator.java   View source code 6 votes vote down vote up
/**
 * Actually create the EntityManager proxy.
 * @param rawEm raw EntityManager
 * @param emIfc the (potentially vendor-specific) EntityManager
 * interface to proxy, or {@code null} for default detection of all interfaces
 * @param cl the ClassLoader to use for proxy creation (maybe {@code null})
 * @param exceptionTranslator the PersistenceException translator to use
 * @param jta whether to create a JTA-aware EntityManager
 * (or {@code null} if not known in advance)
 * @param containerManaged whether to follow container-managed EntityManager
 * or application-managed EntityManager semantics
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @return the EntityManager proxy
 */
private static EntityManager createProxy(
		EntityManager rawEm, Class<? extends EntityManager> emIfc, ClassLoader cl,
		PersistenceExceptionTranslator exceptionTranslator, Boolean jta,
		boolean containerManaged, boolean synchronizedWithTransaction) {

	Assert.notNull(rawEm, "EntityManager must not be null");
	Set<Class<?>> ifcs = new LinkedHashSet<Class<?>>();
	if (emIfc != null) {
		ifcs.add(emIfc);
	}
	else {
		ifcs.addAll(ClassUtils.getAllInterfacesForClassAsSet(rawEm.getClass(), cl));
	}
	ifcs.add(EntityManagerProxy.class);
	return (EntityManager) Proxy.newProxyInstance(
			(cl != null ? cl : ExtendedEntityManagerCreator.class.getClassLoader()),
			ifcs.toArray(new Class<?>[ifcs.size()]),
			new ExtendedEntityManagerInvocationHandler(
					rawEm, exceptionTranslator, jta, containerManaged, synchronizedWithTransaction));
}
 
Example 9
Project: spring-data-documentdb   File: DocumentDbConfigurationSupport.java   View source code 6 votes vote down vote up
protected Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException {
    if (!StringUtils.hasText(basePackage)) {
        return Collections.emptySet();
    }

    final Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();

    if (StringUtils.hasText(basePackage)) {
        final ClassPathScanningCandidateComponentProvider componentProvider =
                new ClassPathScanningCandidateComponentProvider(false);
        componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));

        for (final BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {

            initialEntitySet
                    .add(ClassUtils.forName(candidate.getBeanClassName(),
                            DocumentDbConfigurationSupport.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}
 
Example 10
Project: wamp2spring   File: HandlerMethodService.java   View source code 6 votes vote down vote up
public HandlerMethodService(ConversionService conversionService,
		List<HandlerMethodArgumentResolver> customArgumentResolvers,
		ObjectMapper objectMapper, ApplicationContext applicationContext) {
	this.conversionService = conversionService;
	this.parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

	this.argumentResolvers = new HandlerMethodArgumentResolverComposite();

	ConfigurableBeanFactory beanFactory = ClassUtils.isAssignableValue(
			ConfigurableApplicationContext.class, applicationContext)
					? ((ConfigurableApplicationContext) applicationContext)
							.getBeanFactory()
					: null;

	this.argumentResolvers.addResolver(
			new HeaderMethodArgumentResolver(this.conversionService, beanFactory));
	this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver());
	this.argumentResolvers.addResolver(new WampMessageMethodArgumentResolver());
	this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver());
	this.argumentResolvers.addResolver(new WampSessionIdMethodArgumentResolver());
	this.argumentResolvers.addResolvers(customArgumentResolvers);

	this.objectMapper = objectMapper;
}
 
Example 11
Project: wamp2spring   File: InvocableHandlerMethod.java   View source code 6 votes vote down vote up
/**
 * Invoke the method after resolving its argument values in the context of the given
 * message.
 * <p>
 * Argument values are commonly resolved through
 * {@link HandlerMethodArgumentResolver}s. The {@code providedArgs} parameter however
 * may supply argument values to be used directly, i.e. without argument resolution.
 * @param message the current message being processed
 * @param arguments
 * @param argumentsKw
 * @return the raw value returned by the invoked method
 * @exception Exception raised if no suitable argument resolver can be found, or if
 * the method raised an exception
 */
@Nullable
public Object invoke(WampMessage message, List<Object> arguments,
		Map<String, Object> argumentsKw) throws Exception {
	Object[] args = getMethodArgumentValues(message, arguments, argumentsKw);
	if (this.logger.isTraceEnabled()) {
		this.logger.trace("Invoking '"
				+ ClassUtils.getQualifiedMethodName(getMethod(), getBeanType())
				+ "' with arguments " + Arrays.toString(args));
	}
	Object returnValue = doInvoke(args);
	if (this.logger.isTraceEnabled()) {
		this.logger.trace("Method ["
				+ ClassUtils.getQualifiedMethodName(getMethod(), getBeanType())
				+ "] returned [" + returnValue + "]");
	}
	return returnValue;
}
 
Example 12
Project: leafer   File: CachingAnnotationsAspect.java   View source code 6 votes vote down vote up
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	// The method may be on an interface, but we need attributes from the
	// target class. If the target class is null, the method will be
	// unchanged.
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
	if (targetClass == null && pjp.getTarget() != null) {
		targetClass = pjp.getTarget().getClass();
	}
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the
	// original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	return specificMethod;
}
 
Example 13
Project: tasfe-framework   File: BaseEntity.java   View source code 6 votes vote down vote up
@Override
public boolean equals(Object obj) {

    if (null == obj) {
        return false;
    }

    if (this == obj) {
        return true;
    }

    if (!getClass().equals(ClassUtils.getUserClass(obj))) {
        return false;
    }

    AbstractPersistable<?> that = (AbstractPersistable<?>) obj;

    return null != this.getId() && this.getId().equals(that.getId());
}
 
Example 14
Project: tasfe-framework   File: NettyEmbeddedServletContainerFactory.java   View source code 6 votes vote down vote up
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
    ClassLoader parentClassLoader = resourceLoader != null ? resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader();
    Package nettyPackage = Bootstrap.class.getPackage();
    String title = nettyPackage.getImplementationTitle();
    String version = nettyPackage.getImplementationVersion();
    logger.info("Running with " + title + " " + version);
    NettyEmbeddedContext context = new NettyEmbeddedContext(getContextPath(), new URLClassLoader(new URL[]{}, parentClassLoader), SERVER_INFO);
    if (isRegisterDefaultServlet()) {
        logger.warn("This container does not support a default servlet");
    }
    /*if (isRegisterJspServlet()) {
        logger.warn("This container does not support a JSP servlet");
    }*/
    for (ServletContextInitializer initializer : initializers) {
        try {
            initializer.onStartup(context);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
    int port = getPort() > 0 ? getPort() : new Random().nextInt(65535 - 1024) + 1024;
    InetSocketAddress address = new InetSocketAddress(port);
    logger.info("Server initialized with port: " + port);
    return new NettyEmbeddedServletContainer(address, context);
}
 
Example 15
Project: tasfe-framework   File: ResourcesUtil.java   View source code 6 votes vote down vote up
public static URL getURL(String resourceLocation)
        throws FileNotFoundException {
    Assert.notNull(resourceLocation, "Resource location must not be null");
    if (resourceLocation.startsWith("classpath:")) {
        String path = resourceLocation.substring("classpath:".length());
        ClassLoader cl = ClassUtils.getDefaultClassLoader();
        URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
        if (url == null) {
            String description = "class path resource [" + path + "]";
            throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist");
        }

        return url;
    }
    try {
        return new URL(resourceLocation);
    } catch (MalformedURLException ex) {
        try {
            return new File(resourceLocation).toURI().toURL();
        } catch (MalformedURLException ex2) {
        }
    }
    throw new FileNotFoundException("Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path");
}
 
Example 16
Project: bekit   File: FlowTxParser.java   View source code 6 votes vote down vote up
/**
 * 解析流程事务
 *
 * @param flowTx             流程事务
 * @param transactionManager 事务管理器
 * @return 流程事务执行器
 */
public static FlowTxExecutor parseFlowTx(Object flowTx, PlatformTransactionManager transactionManager) {
    // 获取目标class(应对AOP代理情况)
    Class<?> flowTxClass = AopUtils.getTargetClass(flowTx);
    logger.debug("解析流程事务:{}", ClassUtils.getQualifiedName(flowTxClass));
    FlowTx flowTxAnnotation = flowTxClass.getAnnotation(FlowTx.class);
    // 创建流程事务执行器
    FlowTxExecutor flowTxExecutor = new FlowTxExecutor(flowTxAnnotation.flow(), flowTx, transactionManager);
    for (Method method : flowTxClass.getDeclaredMethods()) {
        for (Class clazz : FlowTxExecutor.FLOW_TX_OPERATE_ANNOTATIONS) {
            if (method.isAnnotationPresent(clazz)) {
                // 设置流程事务操作执行器
                flowTxExecutor.setOperateExecutor(clazz, parseFlowTxOperate(method));
                break;
            }
        }
    }
    flowTxExecutor.validate();

    return flowTxExecutor;
}
 
Example 17
Project: lams   File: AspectJAwareAdvisorAutoProxyCreator.java   View source code 6 votes vote down vote up
@Override
public String toString() {
	StringBuilder sb = new StringBuilder();
	Advice advice = this.advisor.getAdvice();
	sb.append(ClassUtils.getShortName(advice.getClass()));
	sb.append(": ");
	if (this.advisor instanceof Ordered) {
		sb.append("order ").append(((Ordered) this.advisor).getOrder()).append(", ");
	}
	if (advice instanceof AbstractAspectJAdvice) {
		AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice;
		sb.append(ajAdvice.getAspectName());
		sb.append(", declaration order ");
		sb.append(ajAdvice.getDeclarationOrder());
	}
	return sb.toString();
}
 
Example 18
Project: spring-boot-starter-dao   File: AbstractDataBaseBean.java   View source code 6 votes vote down vote up
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage,
		String typeAliasesPackage, Dialect dialect, Configuration configuration) {
	configuration.setDatabaseId(dataSourceName);
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class);
	bdb.addPropertyValue("configuration", configuration);
	bdb.addPropertyValue("failFast", true);
	bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage));
	bdb.addPropertyReference("dataSource", dataSourceName);
	bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) });
	if (!StringUtils.isEmpty(mapperPackage)) {
		try {
			mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage);
			String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage);
			String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml";
			Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath);
			bdb.addPropertyValue("mapperLocations", resources);
		} catch (Exception e) {
			log.error("初始化失败", e);
			throw new RuntimeException( String.format("SqlSessionFactory 初始化失败  mapperPackage=%s", mapperPackage + ""));
		}
	}
	return bdb.getBeanDefinition();
}
 
Example 19
Project: jwx   File: ClasspathPackageScanner.java   View source code 6 votes vote down vote up
/**
 * 将符合条件的Bean以Class集合的形式返回
 * 
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Set<Class<?>> getClassSet() throws IOException, ClassNotFoundException {
	this.classSet.clear();
	if (!this.packagesList.isEmpty()) {
		for (String pkg : this.packagesList) {
			String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
					+ ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
			Resource[] resources = this.resourcePatternResolver.getResources(pattern);
			MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					MetadataReader reader = readerFactory.getMetadataReader(resource);
					String className = reader.getClassMetadata().getClassName();
					if (matchesEntityTypeFilter(reader, readerFactory)) {
						this.classSet.add(Class.forName(className));
					}
				}
			}
		}
	}
	return this.classSet;
}
 
Example 20
Project: parabuild-ci   File: SpringContainer.java   View source code 6 votes vote down vote up
public void addParameter(Object askFor, Object valueParam)
throws InstantiationException, IllegalAccessException {
    try {
        Class clz = ClassUtils.forName((String)askFor);
        if (log.isDebugEnabled()) {
            log.debug("trying to resolve the following class from the Spring bean container: " + clz.getName());
        }

        Map beansOfType = ((ListableBeanFactory)beanFactory).getBeansOfType(clz);
        if (log.isDebugEnabled()) {
            log.debug("beans: " + beansOfType + " - " + beansOfType.size());
        }
        if (beansOfType.size() == 0) {
            log.debug("adding parameter the normal way");
            super.addParameter(askFor, valueParam);
        } else if (beansOfType.size() > 1) {
            // TODO: handle multiple declarations
            throw new InstantiationException("multiple beans of type '" + clz.getName() + "' were found in the spring configuration");
        } else {
            this.beans.put(askFor, beansOfType.values().iterator().next());
        }
    } catch (ClassNotFoundException e) {
        super.addParameter(askFor, valueParam);
    }
}
 
Example 21
Project: bekit   File: ListenerParser.java   View source code 6 votes vote down vote up
private static ListenExecutor parseListen(Listen listenAnnotation, Method method) {
    logger.debug("解析监听方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("监听方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验返回类型
    if (method.getReturnType() != void.class) {
        throw new IllegalArgumentException("监听方法" + ClassUtils.getQualifiedMethodName(method) + "的返回必须是void");
    }
    // 创建监听解决器
    ListenResolver resolver = (ListenResolver) ReflectUtils.newInstance(listenAnnotation.resolver());
    resolver.init(method);

    return new ListenExecutor(resolver, listenAnnotation.priorityAsc(), method);
}
 
Example 22
Project: spring-data-tarantool   File: MappingTarantoolConverter.java   View source code 6 votes vote down vote up
public Object toTarantoolNativeType(Object value, Class<?> targetType) {
    if (value instanceof Boolean ||
        value instanceof Number ||
        value instanceof String ||
        value instanceof byte[]
    ) {
        return value;
    }

    if (ClassUtils.isAssignable(Boolean.class, targetType)) {
        return conversionService.convert(value, Boolean.class);
    } else if (ClassUtils.isAssignable(Number.class, targetType)) {
        return conversionService.convert(value, Number.class);
    } else if (ClassUtils.isAssignable(String.class, targetType)) {
        return conversionService.convert(value, String.class);
    } else if (ClassUtils.isAssignable(byte[].class, targetType)) {
        return conversionService.convert(value, byte[].class);
    } else {
        throw new IllegalStateException("Unknown targetType: " + targetType);
    }
}
 
Example 23
Project: configcenter   File: ListenConfigModifiedResolver.java   View source code 6 votes vote down vote up
@Override
public void init(Method listenMethod) {
    ConfigListener configListenerAnnotation = AnnotatedElementUtils.findMergedAnnotation(listenMethod.getDeclaringClass(), ConfigListener.class);
    if (configListenerAnnotation == null) {
        throw new IllegalArgumentException("@ListenConfigModified只能标注在配置监听器(@ConfigListener)的方法上");
    }
    // 校验入参
    Class[] parameterTypes = listenMethod.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)");
    }
    if (parameterTypes[0] != List.class) {
        throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)");
    }
    ResolvableType resolvableType = ResolvableType.forMethodParameter(listenMethod, 0);
    if (resolvableType.getGeneric(0).resolve(Object.class) != ModifiedProperty.class) {
        throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)");
    }
    // 设置事件类型
    ListenConfigModified listenConfigModifiedAnnotation = AnnotatedElementUtils.findMergedAnnotation(listenMethod, ListenConfigModified.class);
    eventType = new ConfigModifiedEventType(configListenerAnnotation.configContextName(), listenConfigModifiedAnnotation.prefix());
}
 
Example 24
Project: bekit   File: ProcessorParser.java   View source code 6 votes vote down vote up
/**
 * 解析处理器
 *
 * @param processor 处理器
 * @return 处理器执行器
 */
public static ProcessorExecutor parseProcessor(Object processor) {
    // 获取目标class(应对AOP代理情况)
    Class<?> processorClass = AopUtils.getTargetClass(processor);
    logger.debug("解析处理器:{}", ClassUtils.getQualifiedName(processorClass));
    // 获取处理器名称
    String processorName = processorClass.getAnnotation(Processor.class).name();
    if (StringUtils.isEmpty(processorName)) {
        processorName = ClassUtils.getShortNameAsProperty(processorClass);
    }
    // 创建处理器执行器
    ProcessorExecutor processorExecutor = new ProcessorExecutor(processorName, processor);
    for (Method method : processorClass.getDeclaredMethods()) {
        for (Class clazz : ProcessorExecutor.PROCESSOR_METHOD_ANNOTATIONS) {
            if (method.isAnnotationPresent(clazz)) {
                // 设置处理器方法执行器
                processorExecutor.setMethodExecutor(clazz, parseProcessorMethod(clazz, method));
                break;
            }
        }
    }
    processorExecutor.validate();

    return processorExecutor;
}
 
Example 25
Project: lams   File: ReflectiveLoadTimeWeaver.java   View source code 6 votes vote down vote up
/**
 * Create a new SimpleLoadTimeWeaver for the given class loader.
 * @param classLoader the {@code ClassLoader} to delegate to for
 * weaving (<i>must</i> support the required weaving methods).
 * @throws IllegalStateException if the supplied {@code ClassLoader}
 * does not support the required weaving methods
 */
public ReflectiveLoadTimeWeaver(ClassLoader classLoader) {
	Assert.notNull(classLoader, "ClassLoader must not be null");
	this.classLoader = classLoader;
	this.addTransformerMethod = ClassUtils.getMethodIfAvailable(
			this.classLoader.getClass(), ADD_TRANSFORMER_METHOD_NAME,
			new Class<?>[] {ClassFileTransformer.class});
	if (this.addTransformerMethod == null) {
		throw new IllegalStateException(
				"ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide an " +
				"'addTransformer(ClassFileTransformer)' method.");
	}
	this.getThrowawayClassLoaderMethod = ClassUtils.getMethodIfAvailable(
			this.classLoader.getClass(), GET_THROWAWAY_CLASS_LOADER_METHOD_NAME, new Class<?>[0]);
	// getThrowawayClassLoader method is optional
	if (this.getThrowawayClassLoaderMethod == null) {
		if (logger.isInfoEnabled()) {
			logger.info("The ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide a " +
					"'getThrowawayClassLoader()' method; SimpleThrowawayClassLoader will be used instead.");
		}
	}
}
 
Example 26
Project: juiser   File: JuiserSpringSecurityCondition.java   View source code 6 votes vote down vote up
private boolean isSpringSecurityEnabled(ConditionContext ctx) {

        boolean enabled = true;

        Environment env = ctx.getEnvironment();

        for (String propName : props) {
            if (env.containsProperty(propName)) {
                if (!Boolean.parseBoolean(env.getProperty(propName))) {
                    enabled = false;
                    break;
                }
            }
        }

        if (enabled) {
            enabled = ClassUtils.isPresent(SPRING_SEC_CLASS_NAME, ctx.getClassLoader());
        }

        return enabled;
    }
 
Example 27
Project: lams   File: Projection.java   View source code 6 votes vote down vote up
private Class<?> determineCommonType(Class<?> oldType, Class<?> newType) {
	if (oldType == null) {
		return newType;
	}
	if (oldType.isAssignableFrom(newType)) {
		return oldType;
	}
	Class<?> nextType = newType;
	while (nextType != Object.class) {
		if (nextType.isAssignableFrom(oldType)) {
			return nextType;
		}
		nextType = nextType.getSuperclass();
	}
	Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(newType);
	for (Class<?> nextInterface : interfaces) {
		if (nextInterface.isAssignableFrom(oldType)) {
			return nextInterface;
		}
	}
	return Object.class;
}
 
Example 28
Project: lams   File: AbstractWebArgumentResolverAdapter.java   View source code 6 votes vote down vote up
/**
 * Delegate to the {@link WebArgumentResolver} instance.
 * @exception IllegalStateException if the resolved value is not assignable
 * to the method parameter.
 */
@Override
public Object resolveArgument(
		MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
		throws Exception {

	Class<?> paramType = parameter.getParameterType();
	Object result = this.adaptee.resolveArgument(parameter, webRequest);
	if (result == WebArgumentResolver.UNRESOLVED || !ClassUtils.isAssignableValue(paramType, result)) {
		throw new IllegalStateException(
				"Standard argument type [" + paramType.getName() + "] in method " + parameter.getMethod() +
				"resolved to incompatible value of type [" + (result != null ? result.getClass() : null) +
				"]. Consider declaring the argument type in a less specific fashion.");
	}
	return result;
}
 
Example 29
Project: bekit   File: ProcessorParser.java   View source code 6 votes vote down vote up
/**
 * 解析处理器方法
 */
private static ProcessorMethodExecutor parseProcessorMethod(Class clazz, Method method) {
    logger.debug("解析处理器方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验入参
    Class[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "入参必须是(TargetContext)");
    }
    if (parameterTypes[0] != TargetContext.class) {
        throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "入参必须是(TargetContext)");
    }
    // 校验返回类型
    if (clazz != ProcessorExecute.class && method.getReturnType() != void.class) {
        throw new IllegalArgumentException("非@ProcessorExecute类型的处理器方法" + ClassUtils.getQualifiedMethodName(method) + "的返回类型必须是void");
    }
    // 获取目标对象类型
    ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0);
    Class classOfTarget = resolvableType.getGeneric(0).resolve(Object.class);

    return new ProcessorMethodExecutor(method, classOfTarget);
}
 
Example 30
Project: lams   File: NameMatchTransactionAttributeSource.java   View source code 6 votes vote down vote up
@Override
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
	if (!ClassUtils.isUserLevelMethod(method)) {
		return null;
	}

	// Look for direct name match.
	String methodName = method.getName();
	TransactionAttribute attr = this.nameMap.get(methodName);

	if (attr == null) {
		// Look for most specific name match.
		String bestNameMatch = null;
		for (String mappedName : this.nameMap.keySet()) {
			if (isMatch(methodName, mappedName) &&
					(bestNameMatch == null || bestNameMatch.length() <= mappedName.length())) {
				attr = this.nameMap.get(mappedName);
				bestNameMatch = mappedName;
			}
		}
	}

	return attr;
}
 
Example 31
Project: lams   File: AutowireUtils.java   View source code 5 votes vote down vote up
/**
 * Determine whether the given bean property is excluded from dependency checks.
 * <p>This implementation excludes properties defined by CGLIB.
 * @param pd the PropertyDescriptor of the bean property
 * @return whether the bean property is excluded
 */
public static boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
	Method wm = pd.getWriteMethod();
	if (wm == null) {
		return false;
	}
	if (!wm.getDeclaringClass().getName().contains("$$")) {
		// Not a CGLIB method so it's OK.
		return false;
	}
	// It was declared by CGLIB, but we might still want to autowire it
	// if it was actually declared by the superclass.
	Class<?> superclass = wm.getDeclaringClass().getSuperclass();
	return !ClassUtils.hasMethod(superclass, wm.getName(), wm.getParameterTypes());
}
 
Example 32
Project: Learning-Spring-Boot-2.0-Second-Edition   File: WebDriverAutoConfigurationTests.java   View source code 5 votes vote down vote up
@Test
public void testWithMockedChrome() {
	load(new Class[]{},
		"com.greglturnquist.webdriver.firefox.enabled:false",
		"com.greglturnquist.webdriver.safari.enabled:false");
	WebDriver driver = context.getBean(WebDriver.class);
	assertThat(ClassUtils.isAssignable(TakesScreenshot.class,
		driver.getClass())).isTrue();
	assertThat(ClassUtils.isAssignable(ChromeDriver.class,
		driver.getClass())).isTrue();
}
 
Example 33
Project: lams   File: RemoteInvocationTraceInterceptor.java   View source code 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	Method method = invocation.getMethod();
	if (logger.isDebugEnabled()) {
		logger.debug("Incoming " + this.exporterNameClause + "remote call: " +
				ClassUtils.getQualifiedMethodName(method));
	}
	try {
		Object retVal = invocation.proceed();
		if (logger.isDebugEnabled()) {
			logger.debug("Finished processing of " + this.exporterNameClause + "remote call: " +
					ClassUtils.getQualifiedMethodName(method));
		}
		return retVal;
	}
	catch (Throwable ex) {
		if (ex instanceof RuntimeException || ex instanceof Error) {
			if (logger.isWarnEnabled()) {
				logger.warn("Processing of " + this.exporterNameClause + "remote call resulted in fatal exception: " +
						ClassUtils.getQualifiedMethodName(method), ex);
			}
		}
		else {
			if (logger.isInfoEnabled()) {
				logger.info("Processing of " + this.exporterNameClause + "remote call resulted in exception: " +
						ClassUtils.getQualifiedMethodName(method), ex);
			}
		}
		throw ex;
	}
}
 
Example 34
Project: lams   File: ClassArrayEditor.java   View source code 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (StringUtils.hasText(text)) {
		String[] classNames = StringUtils.commaDelimitedListToStringArray(text);
		Class<?>[] classes = new Class<?>[classNames.length];
		for (int i = 0; i < classNames.length; i++) {
			String className = classNames[i].trim();
			classes[i] = ClassUtils.resolveClassName(className, this.classLoader);
		}
		setValue(classes);
	}
	else {
		setValue(null);
	}
}
 
Example 35
Project: incubator-servicecomb-java-chassis   File: JavassistUtils.java   View source code 5 votes vote down vote up
public static String getNameForGenerateCode(JavaType javaType) {
  if (byte[].class.equals(javaType.getRawClass())) {
    return "byte[]";
  }

  if (!javaType.isArrayType()) {
    Class<?> rawClass = ClassUtils.resolvePrimitiveIfNecessary(javaType.getRawClass());
    return rawClass.getTypeName();
  }

  return javaType.getContentType().getRawClass().getName() + "[]";
}
 
Example 36
Project: incubator-servicecomb-java-chassis   File: ProtobufSchemaUtils.java   View source code 5 votes vote down vote up
private static boolean isNeedWrap(Class<?> cls) {
  // protobuf不支持原子类型、enum、string、数组、collection等等作为msg
  // 只有pojo类型才可以
  // java.lang.Object也不可以,因为这可以是任意类型,结果不确定
  return ClassUtils.isPrimitiveOrWrapper(cls) || cls.isArray() || cls.isEnum()
      || String.class.isAssignableFrom(cls)
      || Collection.class.isAssignableFrom(cls)
      || Map.class.isAssignableFrom(cls)
      || Date.class.isAssignableFrom(cls)
      || Object.class.equals(cls);
}
 
Example 37
Project: mybatis-plus-mini   File: PackageHelper.java   View source code 5 votes vote down vote up
/**
   * <p>
   * 别名通配符设置
   * </p>
   * <p>
   * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/>
   * </p>
   *
   * @param typeAliasesPackage 类别名包路径
   * @return
   */
  public static String[] convertTypeAliasesPackage(String typeAliasesPackage) {
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
      String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
              + ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/*.class";

/*
       * 将加载多个绝对匹配的所有Resource
 * 将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分,然后进行遍历模式匹配,排除重复包路径
 */
      try {
          Set<String> set = new HashSet<>();
          Resource[] resources = resolver.getResources(pkg);
          if (resources != null && resources.length > 0) {
              MetadataReader metadataReader;
              for (Resource resource : resources) {
                  if (resource.isReadable()) {
                      metadataReader = metadataReaderFactory.getMetadataReader(resource);
                      set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                  }
              }
          }
          if (!set.isEmpty()) {
              return set.toArray(new String[]{});
          } else {
              throw new MybatisPlusException("not find typeAliasesPackage:" + pkg);
          }
      } catch (Exception e) {
          throw new MybatisPlusException("not find typeAliasesPackage:" + pkg, e);
      }
  }
 
Example 38
Project: framework   File: ThriftUtil.java   View source code 5 votes vote down vote up
public static TProcessor buildProcessor(Class<?> svcInterface, Object service) throws Exception {
	Class<TProcessor> processorClass = (Class<TProcessor>) getThriftServiceInnerClassOrNull(svcInterface.getEnclosingClass(), PROCESSOR_NAME, false);
	if (processorClass == null) {
		throw new ThriftRuntimeException("the processor is null");
	}

	Constructor<TProcessor> constructor = ClassUtils.getConstructorIfAvailable(processorClass, svcInterface);
	if (constructor == null) {
		throw new ThriftRuntimeException("the processor constructor is null");
	}

	return constructor.newInstance(service);
}
 
Example 39
Project: bekit   File: ListenerHolder.java   View source code 5 votes vote down vote up
/**
 * 获取指定类型的监听器执行器
 *
 * @param type 监听器类型
 * @throws IllegalArgumentException 如果不存在该类型的监听器执行器
 */
public List<ListenerExecutor> getRequiredListenerExecutors(Class type) {
    if (!listenerExecutorsMap.containsKey(type)) {
        throw new IllegalArgumentException("不存在" + ClassUtils.getShortName(type) + "类型的监听器");
    }
    return listenerExecutorsMap.get(type);
}
 
Example 40
Project: bekit   File: ServiceExecutor.java   View source code 5 votes vote down vote up
/**
 * 设置服务阶段执行器
 *
 * @param clazz         服务阶段注解的class
 * @param phaseExecutor 服务阶段执行器
 * @throws IllegalArgumentException 如果入参class不是服务阶段注解
 * @throws IllegalStateException    如果已存在该类型的服务阶段执行器
 */
public void setPhaseExecutor(Class clazz, ServicePhaseExecutor phaseExecutor) {
    if (!Arrays.asList(SERVICE_PHASE_ANNOTATIONS).contains(clazz)) {
        throw new IllegalArgumentException(ClassUtils.getShortName(clazz) + "不是服务阶段注解");
    }
    if (phaseExecutorMap.containsKey(clazz)) {
        throw new IllegalStateException("服务" + serviceName + "存在多个@" + ClassUtils.getShortName(clazz) + "类型方法");
    }
    phaseExecutorMap.put(clazz, phaseExecutor);
}