org.springframework.util.ClassUtils Java Examples

The following examples show how to use org.springframework.util.ClassUtils. 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: CosmosConfigurationSupport.java    From spring-data-cosmosdb with MIT License 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<>();

    if (StringUtils.hasText(basePackage)) {
        final ClassPathScanningCandidateComponentProvider componentProvider =
                new ClassPathScanningCandidateComponentProvider(false);

        componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));

        for (final BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
            final String className = candidate.getBeanClassName();
            Assert.notNull(className, "Bean class name is null.");

            initialEntitySet
                    .add(ClassUtils.forName(className, CosmosConfigurationSupport.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}
 
Example #2
Source File: LoggingEnvironmentApplicationListener.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
/**
 * deducing groupId, artifactId
 *
 * @param event
 */
private void onApplicationStartingEvent(ApplicationStartingEvent event) {
    if (ClassUtils.isPresent("ch.qos.logback.core.Appender",
            event.getSpringApplication().getClassLoader())) {
        // base package
        Class<?> mainClass = event.getSpringApplication().getMainApplicationClass();
        if (mainClass != null) {
            String basePackage = mainClass.getPackage().getName();
            System.setProperty("BASE_PACKAGE", basePackage);
        } else {
            System.setProperty("BASE_PACKAGE", "");
            logger.warn("can not set BASE_PACKAGE correctly");
        }

        // set logging system impl
        System.setProperty(LoggingSystem.SYSTEM_PROPERTY, FormulaLogbackSystem.class.getName());
    }
}
 
Example #3
Source File: ClassPathResource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation returns a description that includes the class path location.
 */
@Override
public String getDescription() {
	StringBuilder builder = new StringBuilder("class path resource [");
	String pathToUse = this.path;
	if (this.clazz != null && !pathToUse.startsWith("/")) {
		builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
		builder.append('/');
	}
	if (pathToUse.startsWith("/")) {
		pathToUse = pathToUse.substring(1);
	}
	builder.append(pathToUse);
	builder.append(']');
	return builder.toString();
}
 
Example #4
Source File: ExtendedEntityManagerCreator.java    From spring-analysis-note with MIT License 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, @Nullable Class<? extends EntityManager> emIfc, @Nullable ClassLoader cl,
		@Nullable PersistenceExceptionTranslator exceptionTranslator, @Nullable Boolean jta,
		boolean containerManaged, boolean synchronizedWithTransaction) {

	Assert.notNull(rawEm, "EntityManager must not be null");
	Set<Class<?>> ifcs = new LinkedHashSet<>();
	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()),
			ClassUtils.toClassArray(ifcs),
			new ExtendedEntityManagerInvocationHandler(
					rawEm, exceptionTranslator, jta, containerManaged, synchronizedWithTransaction));
}
 
Example #5
Source File: MockServerContainerContextCustomizerFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	if (webSocketPresent && isAnnotatedWithWebAppConfiguration(testClass)) {
		try {
			Class<?> clazz = ClassUtils.forName(MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME,
					getClass().getClassLoader());
			return (ContextCustomizer) BeanUtils.instantiateClass(clazz);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Failed to enable WebSocket test support; could not load class: " +
					MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME, ex);
		}
	}

	// Else, nothing to customize
	return null;
}
 
Example #6
Source File: CacheKeyGenerator.java    From computoser with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Object generate(Object target, Method method, Object... params) {
    StringBuilder key = new StringBuilder();
    key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");

    if (params.length == 0) {
        key.append(NO_PARAM_KEY).toString();
    }

    for (Object param : params) {
        if (param == null) {
            key.append(NULL_PARAM_KEY);
        } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
            key.append(param);
        } else if (param instanceof CacheKey) {
            key.append(((CacheKey) param).getCacheKey());
        } else {
            logger.warn("Using object " + param + " as cache key. Either use key='..' or implement CacheKey. Method is " + target.getClass() + "#" + method.getName());
            key.append(param.hashCode());
        }
    }

    return  key.toString();
}
 
Example #7
Source File: ConstructorArgumentValues.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Look for the next generic argument value that matches the given type,
 * ignoring argument values that have already been used in the current
 * resolution process.
 * @param requiredType the type to match (can be {@code null} to find
 * an arbitrary next generic argument value)
 * @param requiredName the name to match (can be {@code null} to not
 * match argument values by name, or empty String to match any name)
 * @param usedValueHolders a Set of ValueHolder objects that have already been used
 * in the current resolution process and should therefore not be returned again
 * @return the ValueHolder for the argument, or {@code null} if none found
 */
@Nullable
public ValueHolder getGenericArgumentValue(@Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) {
	for (ValueHolder valueHolder : this.genericArgumentValues) {
		if (usedValueHolders != null && usedValueHolders.contains(valueHolder)) {
			continue;
		}
		if (valueHolder.getName() != null && !"".equals(requiredName) &&
				(requiredName == null || !valueHolder.getName().equals(requiredName))) {
			continue;
		}
		if (valueHolder.getType() != null &&
				(requiredType == null || !ClassUtils.matchesTypeName(requiredType, valueHolder.getType()))) {
			continue;
		}
		if (requiredType != null && valueHolder.getType() == null && valueHolder.getName() == null &&
				!ClassUtils.isAssignableValue(requiredType, valueHolder.getValue())) {
			continue;
		}
		return valueHolder;
	}
	return null;
}
 
Example #8
Source File: AnnotationDrivenBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
	ManagedList<Object> result = new ManagedList<Object>();
	for (Object object : list) {
		if (object instanceof BeanDefinitionHolder) {
			BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
			String className = beanDef.getBeanDefinition().getBeanClassName();
			Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());
			if (WebArgumentResolver.class.isAssignableFrom(clazz)) {
				RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class);
				adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef);
				result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter"));
				continue;
			}
		}
		result.add(object);
	}
	return result;
}
 
Example #9
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
	markBeanAsCreated(beanName);
	BeanDefinition mbd = getMergedBeanDefinition(beanName);
	RootBeanDefinition bd = null;
	if (mbd instanceof RootBeanDefinition) {
		RootBeanDefinition rbd = (RootBeanDefinition) mbd;
		bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
	}
	if (bd == null) {
		bd = new RootBeanDefinition(mbd);
	}
	if (!bd.isPrototype()) {
		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
	}
	BeanWrapper bw = new BeanWrapperImpl(existingBean);
	initBeanWrapper(bw);
	populateBean(beanName, bd, bw);
	return initializeBean(beanName, existingBean, bd);
}
 
Example #10
Source File: MessageMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
	Class<?> paramType = parameter.getParameterType();
	if (!paramType.isAssignableFrom(message.getClass())) {
			throw new MethodArgumentTypeMismatchException(message, parameter,
					"The actual message type [" + ClassUtils.getQualifiedName(message.getClass()) + "] " +
					"does not match the expected type [" + ClassUtils.getQualifiedName(paramType) + "]");
	}

	Class<?> expectedPayloadType = getPayloadType(parameter);
	Object payload = message.getPayload();
	if (payload != null && expectedPayloadType != null && !expectedPayloadType.isInstance(payload)) {
		throw new MethodArgumentTypeMismatchException(message, parameter,
				"The expected Message<?> payload type [" + ClassUtils.getQualifiedName(expectedPayloadType) +
				"] does not match the actual payload type [" + ClassUtils.getQualifiedName(payload.getClass()) + "]");
	}

	return message;
}
 
Example #11
Source File: ContextFunctionCatalogAutoConfigurationTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Test
public void componentScanJarFunction() {
	try {
		create("greeter.jar", ComponentScanJarConfiguration.class);
		assertThat(this.context.getBean("greeter")).isInstanceOf(Function.class);
		assertThat((Function<?, ?>) this.catalog.lookup(Function.class, "greeter"))
				.isInstanceOf(Function.class);
		assertThat(this.inspector
				.getInputType(this.catalog.lookup(Function.class, "greeter")))
						.isAssignableFrom(String.class);
		assertThat(this.inspector
				.getInputWrapper(this.catalog.lookup(Function.class, "greeter")))
						.isAssignableFrom(String.class);
	}
	finally {
		ClassUtils.overrideThreadContextClassLoader(getClass().getClassLoader());
	}
}
 
Example #12
Source File: RpcExporterRegister.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                    BeanDefinitionRegistry registry) {
    Map<Class, String> serviceExporterMap = new HashMap<>();
    AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
    Collection<BeanDefinition> candidates = getCandidates(resourceLoader);
    for (BeanDefinition candidate : candidates) {
        Class<?> clazz = getClass(candidate.getBeanClassName());
        Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(clazz);
        if (interfaces.length != 1) {
            throw new BeanInitializationException("bean interface num must equal 1, " + clazz.getName());
        }
        String serviceBeanName = beanNameGenerator.generateBeanName(candidate, registry);
        String old = serviceExporterMap.putIfAbsent(interfaces[0], serviceBeanName);
        if (old != null) {
            throw new RuntimeException("interface already be exported by bean name:" + old);
        }
        registry.registerBeanDefinition(serviceBeanName, candidate);
    }
}
 
Example #13
Source File: SecurityAspect.java    From mcspring-boot with MIT License 6 votes vote down vote up
@Order(1)
@Before("within(@(@dev.alangomes.springspigot.security.Audit *) *) " +
        "|| execution(@(@dev.alangomes.springspigot.security.Audit *) * *(..)) " +
        "|| @within(dev.alangomes.springspigot.security.Audit)" +
        "|| execution(@dev.alangomes.springspigot.security.Audit * *(..))")
public void auditCall(JoinPoint joinPoint) {
    val sender = context.getSender();
    val method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    val signature = ClassUtils.getUserClass(method.getDeclaringClass()).getName() + "." + method.getName();
    val arguments = Arrays.stream(joinPoint.getArgs()).map(String::valueOf).collect(Collectors.joining(", "));

    AopAnnotationUtils.getAppliableAnnotations(method, Audit.class).stream()
            .filter(audit -> sender != null || !audit.senderOnly())
            .limit(1)
            .forEach(audit -> {
                if (sender != null) {
                    log.info(String.format("Player %s invoked %s(%s)", sender.getName(), signature, arguments));
                } else {
                    log.info(String.format("Server invoked %s(%s)", signature, arguments));
                }
            });
}
 
Example #14
Source File: ProxyExchange.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
	Object body = body();
	MethodParameter output = new MethodParameter(
			ClassUtils.getMethod(BodySender.class, "body"), -1);
	ServletOutputToInputConverter response = new ServletOutputToInputConverter(
			this.response);
	ServletWebRequest webRequest = new ServletWebRequest(this.request, response);
	try {
		delegate.handleReturnValue(body, output, mavContainer, webRequest);
	}
	catch (HttpMessageNotWritableException
			| HttpMediaTypeNotAcceptableException e) {
		throw new IllegalStateException("Cannot convert body", e);
	}
	return response.getInputStream();
}
 
Example #15
Source File: SmartMessageMethodArgumentResolver.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
private Object convertPayload(Message<?> message, MethodParameter parameter,
		Class<?> targetPayloadType) {
	Object result = null;
	if (this.messageConverter instanceof SmartMessageConverter) {
		SmartMessageConverter smartConverter = (SmartMessageConverter) this.messageConverter;
		result = smartConverter.fromMessage(message, targetPayloadType, parameter);
	}
	else if (this.messageConverter != null) {
		result = this.messageConverter.fromMessage(message, targetPayloadType);
	}

	if (result == null) {
		throw new MessageConversionException(message,
				"No converter found from actual payload type '"
						+ ClassUtils.getDescriptiveType(message.getPayload())
						+ "' to expected payload type '"
						+ ClassUtils.getQualifiedName(targetPayloadType) + "'");
	}
	return result;
}
 
Example #16
Source File: StartupApplicationListener.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> sources(ApplicationReadyEvent event) {
	Method method = ReflectionUtils.findMethod(SpringApplication.class, "getAllSources");
	if (method == null) {
		method = ReflectionUtils.findMethod(SpringApplication.class, "getSources");
	}
	ReflectionUtils.makeAccessible(method);
	@SuppressWarnings("unchecked")
	Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method, event.getSpringApplication());
	Set<Class<?>> result = new LinkedHashSet<>();
	for (Object object : objects) {
		if (object instanceof String) {
			object = ClassUtils.resolveClassName((String) object, null);
		}
		result.add((Class<?>) object);
	}
	return result;
}
 
Example #17
Source File: NameMatchTransactionAttributeSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public TransactionAttribute getTransactionAttribute(Method method, @Nullable 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 #18
Source File: XmlBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * @since 3.2.8 and 4.0.2
 * @see <a href="https://jira.spring.io/browse/SPR-10785">SPR-10785</a> and <a
 *      href="https://jira.spring.io/browse/SPR-11420">SPR-11420</a>
 */
@Test
public void methodInjectedBeanMustBeOfSameEnhancedCglibSubclassTypeAcrossBeanFactories() {
	Class<?> firstClass = null;

	for (int i = 0; i < 10; i++) {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		new XmlBeanDefinitionReader(bf).loadBeanDefinitions(OVERRIDES_CONTEXT);

		final Class<?> currentClass = bf.getBean("overrideOneMethod").getClass();
		assertTrue("Method injected bean class [" + currentClass + "] must be a CGLIB enhanced subclass.",
			ClassUtils.isCglibProxyClass(currentClass));

		if (firstClass == null) {
			firstClass = currentClass;
		}
		else {
			assertEquals(firstClass, currentClass);
		}
	}
}
 
Example #19
Source File: MapperLoader.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
public Resource[] getResource(String basePackage, String pattern) throws IOException {
	String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
			+ ClassUtils.convertClassNameToResourcePath(context.getEnvironment().resolveRequiredPlaceholders(
					basePackage)) + "/" + pattern;
	Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
	return resources;
}
 
Example #20
Source File: SqlScriptsTestExecutionListener.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
					prefixedResourcePath, elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
				"%s does not exist. Either declare statements or scripts via @Sql or make the " +
				"default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example #21
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Override
public String apply(@Nullable Entry<String, StandardUsernameCredentials> entry) {
    if (entry == null)
        return null;
    String mavenServerId = entry.getKey();
    StandardUsernameCredentials credentials = entry.getValue();
    return "[" +
            "mavenServerId: '" + mavenServerId + "', " +
            "jenkinsCredentials: '" + credentials.getId() + "', " +
            "username: '" + credentials.getUsername() + "', " +
            "type: '" + ClassUtils.getShortName(credentials.getClass()) +
            "']";
}
 
Example #22
Source File: AnnotationMethodHandlerAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {

	Class<?> clazz = ClassUtils.getUserClass(handler);
	Boolean annotatedWithSessionAttributes = this.sessionAnnotatedClassesCache.get(clazz);
	if (annotatedWithSessionAttributes == null) {
		annotatedWithSessionAttributes = (AnnotationUtils.findAnnotation(clazz, SessionAttributes.class) != null);
		this.sessionAnnotatedClassesCache.put(clazz, annotatedWithSessionAttributes);
	}

	if (annotatedWithSessionAttributes) {
		checkAndPrepare(request, response, this.cacheSecondsForSessionAttributeHandlers, true);
	}
	else {
		checkAndPrepare(request, response, true);
	}

	// Execute invokeHandlerMethod in synchronized block if required.
	if (this.synchronizeOnSession) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				return invokeHandlerMethod(request, response, handler);
			}
		}
	}

	return invokeHandlerMethod(request, response, handler);
}
 
Example #23
Source File: HandshakeWebSocketService.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static RequestUpgradeStrategy initUpgradeStrategy() {
	String className;
	if (tomcatPresent) {
		className = "TomcatRequestUpgradeStrategy";
	}
	else if (jettyPresent) {
		className = "JettyRequestUpgradeStrategy";
	}
	else if (undertowPresent) {
		className = "UndertowRequestUpgradeStrategy";
	}
	else if (reactorNettyPresent) {
		// As late as possible (Reactor Netty commonly used for WebClient)
		className = "ReactorNettyRequestUpgradeStrategy";
	}
	else {
		throw new IllegalStateException("No suitable default RequestUpgradeStrategy found");
	}

	try {
		className = "org.springframework.web.reactive.socket.server.upgrade." + className;
		Class<?> clazz = ClassUtils.forName(className, HandshakeWebSocketService.class.getClassLoader());
		return (RequestUpgradeStrategy) ReflectionUtils.accessibleConstructor(clazz).newInstance();
	}
	catch (Throwable ex) {
		throw new IllegalStateException(
				"Failed to instantiate RequestUpgradeStrategy: " + className, ex);
	}
}
 
Example #24
Source File: ScopedProxyFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	if (!(beanFactory instanceof ConfigurableBeanFactory)) {
		throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
	}
	ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;

	this.scopedTargetSource.setBeanFactory(beanFactory);

	ProxyFactory pf = new ProxyFactory();
	pf.copyFrom(this);
	pf.setTargetSource(this.scopedTargetSource);

	Assert.notNull(this.targetBeanName, "Property 'targetBeanName' is required");
	Class<?> beanType = beanFactory.getType(this.targetBeanName);
	if (beanType == null) {
		throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName +
				"': Target type could not be determined at the time of proxy creation.");
	}
	if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) {
		pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader()));
	}

	// Add an introduction that implements only the methods on ScopedObject.
	ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
	pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));

	// Add the AopInfrastructureBean marker to indicate that the scoped proxy
	// itself is not subject to auto-proxying! Only its target bean is.
	pf.addInterface(AopInfrastructureBean.class);

	this.proxy = pf.getProxy(cbf.getBeanClassLoader());
}
 
Example #25
Source File: PropertySourcesPropertyResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Deprecated
public <T> Class<T> getPropertyAsClass(String key, Class<T> targetValueType) {
	if (this.propertySources != null) {
		for (PropertySource<?> propertySource : this.propertySources) {
			if (logger.isTraceEnabled()) {
				logger.trace(String.format("Searching for key '%s' in [%s]", key, propertySource.getName()));
			}
			Object value = propertySource.getProperty(key);
			if (value != null) {
				logKeyFound(key, propertySource, value);
				Class<?> clazz;
				if (value instanceof String) {
					try {
						clazz = ClassUtils.forName((String) value, null);
					}
					catch (Exception ex) {
						throw new ClassConversionException((String) value, targetValueType, ex);
					}
				}
				else if (value instanceof Class) {
					clazz = (Class<?>) value;
				}
				else {
					clazz = value.getClass();
				}
				if (!targetValueType.isAssignableFrom(clazz)) {
					throw new ClassConversionException(clazz, targetValueType);
				}
				@SuppressWarnings("unchecked")
				Class<T> targetClass = (Class<T>) clazz;
				return targetClass;
			}
		}
	}
	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Could not find key '%s' in any property source", key));
	}
	return null;
}
 
Example #26
Source File: AbstractApplicationEventMulticaster.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return a Collection of ApplicationListeners matching the given
 * event type. Non-matching listeners get excluded early.
 * @param event the event to be propagated. Allows for excluding
 * non-matching listeners early, based on cached matching information.
 * @param eventType the event type
 * @return a Collection of ApplicationListeners
 * @see org.springframework.context.ApplicationListener
 */
protected Collection<ApplicationListener<?>> getApplicationListeners(
		ApplicationEvent event, ResolvableType eventType) {

	Object source = event.getSource();
	Class<?> sourceType = (source != null ? source.getClass() : null);
	ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);

	// Quick check for existing entry on ConcurrentHashMap...
	ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
	if (retriever != null) {
		return retriever.getApplicationListeners();
	}

	if (this.beanClassLoader == null ||
			(ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) &&
					(sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) {
		// Fully synchronized building and caching of a ListenerRetriever
		synchronized (this.retrievalMutex) {
			retriever = this.retrieverCache.get(cacheKey);
			if (retriever != null) {
				return retriever.getApplicationListeners();
			}
			retriever = new ListenerRetriever(true);
			Collection<ApplicationListener<?>> listeners =
					retrieveApplicationListeners(eventType, sourceType, retriever);
			this.retrieverCache.put(cacheKey, retriever);
			return listeners;
		}
	}
	else {
		// No ListenerRetriever caching -> no synchronization necessary
		return retrieveApplicationListeners(eventType, sourceType, null);
	}
}
 
Example #27
Source File: BeanUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a method signature in the form {@code methodName[([arg_list])]},
 * where {@code arg_list} is an optional, comma-separated list of fully-qualified
 * type names, and attempts to resolve that signature against the supplied {@code Class}.
 * <p>When not supplying an argument list ({@code methodName}) the method whose name
 * matches and has the least number of parameters will be returned. When supplying an
 * argument type list, only the method whose name and argument types match will be returned.
 * <p>Note then that {@code methodName} and {@code methodName()} are <strong>not</strong>
 * resolved in the same way. The signature {@code methodName} means the method called
 * {@code methodName} with the least number of arguments, whereas {@code methodName()}
 * means the method called {@code methodName} with exactly 0 arguments.
 * <p>If no method can be found, then {@code null} is returned.
 * @param signature the method signature as String representation
 * @param clazz the class to resolve the method signature against
 * @return the resolved Method
 * @see #findMethod
 * @see #findMethodWithMinimalParameters
 */
public static Method resolveSignature(String signature, Class<?> clazz) {
	Assert.hasText(signature, "'signature' must not be empty");
	Assert.notNull(clazz, "Class must not be null");
	int firstParen = signature.indexOf("(");
	int lastParen = signature.indexOf(")");
	if (firstParen > -1 && lastParen == -1) {
		throw new IllegalArgumentException("Invalid method signature '" + signature +
				"': expected closing ')' for args list");
	}
	else if (lastParen > -1 && firstParen == -1) {
		throw new IllegalArgumentException("Invalid method signature '" + signature +
				"': expected opening '(' for args list");
	}
	else if (firstParen == -1 && lastParen == -1) {
		return findMethodWithMinimalParameters(clazz, signature);
	}
	else {
		String methodName = signature.substring(0, firstParen);
		String[] parameterTypeNames =
				StringUtils.commaDelimitedListToStringArray(signature.substring(firstParen + 1, lastParen));
		Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];
		for (int i = 0; i < parameterTypeNames.length; i++) {
			String parameterTypeName = parameterTypeNames[i].trim();
			try {
				parameterTypes[i] = ClassUtils.forName(parameterTypeName, clazz.getClassLoader());
			}
			catch (Throwable ex) {
				throw new IllegalArgumentException("Invalid method signature: unable to resolve type [" +
						parameterTypeName + "] for argument " + i + ". Root cause: " + ex);
			}
		}
		return findMethod(clazz, methodName, parameterTypes);
	}
}
 
Example #28
Source File: ClassMetadataReadingVisitor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(int version, int access, String name, String signature, String supername, String[] interfaces) {
	this.className = ClassUtils.convertResourcePathToClassName(name);
	this.isInterface = ((access & Opcodes.ACC_INTERFACE) != 0);
	this.isAnnotation = ((access & Opcodes.ACC_ANNOTATION) != 0);
	this.isAbstract = ((access & Opcodes.ACC_ABSTRACT) != 0);
	this.isFinal = ((access & Opcodes.ACC_FINAL) != 0);
	if (supername != null && !this.isInterface) {
		this.superClassName = ClassUtils.convertResourcePathToClassName(supername);
	}
	this.interfaces = new String[interfaces.length];
	for (int i = 0; i < interfaces.length; i++) {
		this.interfaces[i] = ClassUtils.convertResourcePathToClassName(interfaces[i]);
	}
}
 
Example #29
Source File: FailingBeforeAndAfterMethodsTestNGTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
public FailingBeforeAndAfterMethodsTestNGTests(String testClassName, int expectedTestStartCount,
		int expectedTestSuccessCount, int expectedFailureCount, int expectedFailedConfigurationsCount) throws Exception {

	this.clazz = ClassUtils.forName(getClass().getName() + "." + testClassName, getClass().getClassLoader());
	this.expectedTestStartCount = expectedTestStartCount;
	this.expectedTestSuccessCount = expectedTestSuccessCount;
	this.expectedFailureCount = expectedFailureCount;
	this.expectedFailedConfigurationsCount = expectedFailedConfigurationsCount;
}
 
Example #30
Source File: VaadinConnectController.java    From flow with Apache License 2.0 5 votes vote down vote up
void validateEndpointBean(EndpointNameChecker endpointNameChecker,
        String name, Object endpointBean) {
    // Check the bean type instead of the implementation type in
    // case of e.g. proxies
    Class<?> beanType = ClassUtils.getUserClass(endpointBean.getClass());

    String endpointName = Optional
            .ofNullable(beanType.getAnnotation(Endpoint.class))
            .map(Endpoint::value).filter(value -> !value.isEmpty())
            .orElse(beanType.getSimpleName());
    if (endpointName.isEmpty()) {
        throw new IllegalStateException(String.format(
                "A bean with name '%s' and type '%s' is annotated with '%s' "
                        + "annotation but is an anonymous class hence has no name. ",
                name, beanType, Endpoint.class)
                + String.format(
                        "Either modify the bean declaration so that it is not an "
                                + "anonymous class or specify an endpoint " +
                                "name in the '%s' annotation",
                        Endpoint.class));
    }
    String validationError = endpointNameChecker.check(endpointName);
    if (validationError != null) {
        throw new IllegalStateException(
                String.format("Endpoint name '%s' is invalid, reason: '%s'",
                        endpointName, validationError));
    }

    vaadinEndpoints.put(endpointName.toLowerCase(Locale.ENGLISH),
            new VaadinEndpointData(endpointBean, beanType.getMethods()));
}