code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
package cn.bugstack.springframework.beans.factory.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.DisposableBean; import cn.bugstack.springframework.beans.factory.config.BeanDefinition; import cn.hutool.core.util.StrUtil; import java.lang.reflect.Method; /** * Adapter that implements the {@link DisposableBean} and {@link Runnable} interfaces * performing various destruction steps on a given bean instance: * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class DisposableBeanAdapter implements DisposableBean { private final Object bean; private final String beanName; private String destroyMethodName; public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) { this.bean = bean; this.beanName = beanName; this.destroyMethodName = beanDefinition.getDestroyMethodName(); } @Override public void destroy() throws Exception { // 1. 实现接口 DisposableBean if (bean instanceof DisposableBean) { ((DisposableBean) bean).destroy(); } // 2. 注解配置 destroy-method {判断是为了避免二次执行销毁} if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) { Method destroyMethod = bean.getClass().getMethod(destroyMethodName); if (null == destroyMethod) { throw new BeansException("Couldn't find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'"); } destroyMethod.invoke(bean); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/DisposableBeanAdapter.java
Java
apache-2.0
1,940
package cn.bugstack.springframework.beans.factory.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.FactoryBean; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Support base class for singleton registries which need to handle * {@link cn.bugstack.springframework.beans.factory.FactoryBean} instances, * integrated with {@link DefaultSingletonBeanRegistry}'s singleton management. * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { /** * Cache of singleton objects created by FactoryBeans: FactoryBean name --> object */ private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>(); protected Object getCachedObjectForFactoryBean(String beanName) { Object object = this.factoryBeanObjectCache.get(beanName); return (object != NULL_OBJECT ? object : null); } protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName) { if (factory.isSingleton()) { Object object = this.factoryBeanObjectCache.get(beanName); if (object == null) { object = doGetObjectFromFactoryBean(factory, beanName); this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT)); } return (object != NULL_OBJECT ? object : null); } else { return doGetObjectFromFactoryBean(factory, beanName); } } private Object doGetObjectFromFactoryBean(final FactoryBean factory, final String beanName){ try { return factory.getObject(); } catch (Exception e) { throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation", e); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/FactoryBeanRegistrySupport.java
Java
apache-2.0
2,141
package cn.bugstack.springframework.beans.factory.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.config.BeanDefinition; import java.lang.reflect.Constructor; /** * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring * <p> * Bean 实例化策略 */ public interface InstantiationStrategy { Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/InstantiationStrategy.java
Java
apache-2.0
710
package cn.bugstack.springframework.beans.factory.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.config.BeanDefinition; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class SimpleInstantiationStrategy implements InstantiationStrategy { @Override public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException { Class clazz = beanDefinition.getBeanClass(); try { if (null != ctor) { return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args); } else { return clazz.getDeclaredConstructor().newInstance(); } } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/support/SimpleInstantiationStrategy.java
Java
apache-2.0
1,318
package cn.bugstack.springframework.beans.factory.xml; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.PropertyValue; import cn.bugstack.springframework.beans.factory.config.BeanDefinition; import cn.bugstack.springframework.beans.factory.config.BeanReference; import cn.bugstack.springframework.beans.factory.support.AbstractBeanDefinitionReader; import cn.bugstack.springframework.beans.factory.support.BeanDefinitionRegistry; import cn.bugstack.springframework.context.annotation.ClassPathBeanDefinitionScanner; import cn.bugstack.springframework.core.io.Resource; import cn.bugstack.springframework.core.io.ResourceLoader; import cn.hutool.core.util.StrUtil; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Bean definition reader for XML bean definitions. * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) { super(registry); } public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) { super(registry, resourceLoader); } @Override public void loadBeanDefinitions(Resource resource) throws BeansException { try { try (InputStream inputStream = resource.getInputStream()) { doLoadBeanDefinitions(inputStream); } } catch (IOException | ClassNotFoundException | DocumentException e) { throw new BeansException("IOException parsing XML document from " + resource, e); } } @Override public void loadBeanDefinitions(Resource... resources) throws BeansException { for (Resource resource : resources) { loadBeanDefinitions(resource); } } @Override public void loadBeanDefinitions(String location) throws BeansException { ResourceLoader resourceLoader = getResourceLoader(); Resource resource = resourceLoader.getResource(location); loadBeanDefinitions(resource); } @Override public void loadBeanDefinitions(String... locations) throws BeansException { for (String location : locations) { loadBeanDefinitions(location); } } protected void doLoadBeanDefinitions(InputStream inputStream) throws ClassNotFoundException, DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); Element root = document.getRootElement(); // 解析 context:component-scan 标签,扫描包中的类并提取相关信息,用于组装 BeanDefinition Element componentScan = root.element("component-scan"); if (null != componentScan) { String scanPath = componentScan.attributeValue("base-package"); if (StrUtil.isEmpty(scanPath)) { throw new BeansException("The value of base-package attribute can not be empty or null"); } scanPackage(scanPath); } List<Element> beanList = root.elements("bean"); for (Element bean : beanList) { String id = bean.attributeValue("id"); String name = bean.attributeValue("name"); String className = bean.attributeValue("class"); String initMethod = bean.attributeValue("init-method"); String destroyMethodName = bean.attributeValue("destroy-method"); String beanScope = bean.attributeValue("scope"); // 获取 Class,方便获取类中的名称 Class<?> clazz = Class.forName(className); // 优先级 id > name String beanName = StrUtil.isNotEmpty(id) ? id : name; if (StrUtil.isEmpty(beanName)) { beanName = StrUtil.lowerFirst(clazz.getSimpleName()); } // 定义Bean BeanDefinition beanDefinition = new BeanDefinition(clazz); beanDefinition.setInitMethodName(initMethod); beanDefinition.setDestroyMethodName(destroyMethodName); if (StrUtil.isNotEmpty(beanScope)) { beanDefinition.setScope(beanScope); } List<Element> propertyList = bean.elements("property"); // 读取属性并填充 for (Element property : propertyList) { // 解析标签:property String attrName = property.attributeValue("name"); String attrValue = property.attributeValue("value"); String attrRef = property.attributeValue("ref"); // 获取属性值:引入对象、值对象 Object value = StrUtil.isNotEmpty(attrRef) ? new BeanReference(attrRef) : attrValue; // 创建属性信息 PropertyValue propertyValue = new PropertyValue(attrName, value); beanDefinition.getPropertyValues().addPropertyValue(propertyValue); } if (getRegistry().containsBeanDefinition(beanName)) { throw new BeansException("Duplicate beanName[" + beanName + "] is not allowed"); } // 注册 BeanDefinition getRegistry().registerBeanDefinition(beanName, beanDefinition); } } private void scanPackage(String scanPath) { String[] basePackages = StrUtil.splitToArray(scanPath, ','); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(getRegistry()); scanner.doScan(basePackages); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/beans/factory/xml/XmlBeanDefinitionReader.java
Java
apache-2.0
5,964
package cn.bugstack.springframework.context; import cn.bugstack.springframework.beans.factory.HierarchicalBeanFactory; import cn.bugstack.springframework.beans.factory.ListableBeanFactory; import cn.bugstack.springframework.core.io.ResourceLoader; /** * Central interface to provide configuration for an application. * This is read-only while the application is running, but may be * reloaded if the implementation supports this. * <p> * 应用上下文 * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory, ResourceLoader, ApplicationEventPublisher { }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/ApplicationContext.java
Java
apache-2.0
878
package cn.bugstack.springframework.context; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.Aware; /** * Interface to be implemented by any object that wishes to be notified * of the {@link ApplicationContext} that it runs in. * * 实现此接口,既能感知到所属的 ApplicationContext * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ApplicationContextAware extends Aware { void setApplicationContext(ApplicationContext applicationContext) throws BeansException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/ApplicationContextAware.java
Java
apache-2.0
793
package cn.bugstack.springframework.context; import java.util.EventObject; /** * Class to be extended by all application events. Abstract as it * doesn't make sense for generic events to be published directly. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public abstract class ApplicationEvent extends EventObject { /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ public ApplicationEvent(Object source) { super(source); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/ApplicationEvent.java
Java
apache-2.0
823
package cn.bugstack.springframework.context; /** * Interface that encapsulates event publication functionality. * Serves as super-interface for ApplicationContext. * * 事件发布者接口 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ApplicationEventPublisher { /** * Notify all listeners registered with this application of an application * event. Events may be framework events (such as RequestHandledEvent) * or application-specific events. * @param event the event to publish */ void publishEvent(ApplicationEvent event); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/ApplicationEventPublisher.java
Java
apache-2.0
818
package cn.bugstack.springframework.context; import java.util.EventListener; /** * Interface to be implemented by application event listeners. * Based on the standard <code>java.util.EventListener</code> interface * for the Observer design pattern. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * Handle an application event. * @param event the event to respond to */ void onApplicationEvent(E event); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/ApplicationListener.java
Java
apache-2.0
758
package cn.bugstack.springframework.context; import cn.bugstack.springframework.beans.BeansException; /** * SPI interface to be implemented by most if not all application contexts. * Provides facilities to configure an application context in addition * to the application context client methods in the * {@link cn.bugstack.springframework.context.ApplicationContext} interface. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ConfigurableApplicationContext extends ApplicationContext { /** * 刷新容器 * * @throws BeansException */ void refresh() throws BeansException; void registerShutdownHook(); void close(); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/ConfigurableApplicationContext.java
Java
apache-2.0
910
package cn.bugstack.springframework.context.annotation; import cn.bugstack.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; import cn.bugstack.springframework.beans.factory.config.BeanDefinition; import cn.bugstack.springframework.beans.factory.support.BeanDefinitionRegistry; import cn.bugstack.springframework.stereotype.Component; import cn.hutool.core.util.StrUtil; import java.util.Set; /** * A bean definition scanner that detects bean candidates on the classpath, * registering corresponding bean definitions with a given registry ({@code BeanFactory} * or {@code ApplicationContext}). * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider { private BeanDefinitionRegistry registry; public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { this.registry = registry; } public void doScan(String... basePackages) { for (String basePackage : basePackages) { Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition beanDefinition : candidates) { // 解析 Bean 的作用域 singleton、prototype String beanScope = resolveBeanScope(beanDefinition); if (StrUtil.isNotEmpty(beanScope)) { beanDefinition.setScope(beanScope); } registry.registerBeanDefinition(determineBeanName(beanDefinition), beanDefinition); } } // 注册处理注解的 BeanPostProcessor(@Autowired、@Value) registry.registerBeanDefinition("cn.bugstack.springframework.context.annotation.internalAutowiredAnnotationProcessor", new BeanDefinition(AutowiredAnnotationBeanPostProcessor.class)); } private String resolveBeanScope(BeanDefinition beanDefinition) { Class<?> beanClass = beanDefinition.getBeanClass(); Scope scope = beanClass.getAnnotation(Scope.class); if (null != scope) return scope.value(); return StrUtil.EMPTY; } private String determineBeanName(BeanDefinition beanDefinition) { Class<?> beanClass = beanDefinition.getBeanClass(); Component component = beanClass.getAnnotation(Component.class); String value = component.value(); if (StrUtil.isEmpty(value)) { value = StrUtil.lowerFirst(beanClass.getSimpleName()); } return value; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/annotation/ClassPathBeanDefinitionScanner.java
Java
apache-2.0
2,745
package cn.bugstack.springframework.context.annotation; import cn.bugstack.springframework.beans.factory.config.BeanDefinition; import cn.bugstack.springframework.stereotype.Component; import cn.hutool.core.util.ClassUtil; import java.util.LinkedHashSet; import java.util.Set; /** * A component provider that scans the classpath from a base package. It then * applies exclude and include filters to the resulting classes to find candidates. * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ClassPathScanningCandidateComponentProvider { public Set<BeanDefinition> findCandidateComponents(String basePackage) { Set<BeanDefinition> candidates = new LinkedHashSet<>(); Set<Class<?>> classes = ClassUtil.scanPackageByAnnotation(basePackage, Component.class); for (Class<?> clazz : classes) { candidates.add(new BeanDefinition(clazz)); } return candidates; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java
Java
apache-2.0
1,167
package cn.bugstack.springframework.context.annotation; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Scope { String value() default "singleton"; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/annotation/Scope.java
Java
apache-2.0
255
package cn.bugstack.springframework.context.event; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.BeanFactory; import cn.bugstack.springframework.beans.factory.BeanFactoryAware; import cn.bugstack.springframework.context.ApplicationEvent; import cn.bugstack.springframework.context.ApplicationListener; import cn.bugstack.springframework.util.ClassUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; /** * Abstract implementation of the {@link ApplicationEventMulticaster} interface, * providing the basic listener registration facility. * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanFactoryAware { public final Set<ApplicationListener<ApplicationEvent>> applicationListeners = new LinkedHashSet<>(); private BeanFactory beanFactory; @Override public void addApplicationListener(ApplicationListener<?> listener) { applicationListeners.add((ApplicationListener<ApplicationEvent>) listener); } @Override public void removeApplicationListener(ApplicationListener<?> listener) { applicationListeners.remove(listener); } @Override public final void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * 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. * @return a Collection of ApplicationListeners * @see cn.bugstack.springframework.context.ApplicationListener */ protected Collection<ApplicationListener> getApplicationListeners(ApplicationEvent event) { LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>(); for (ApplicationListener<ApplicationEvent> listener : applicationListeners) { if (supportsEvent(listener, event)) allListeners.add(listener); } return allListeners; } /** * 监听器是否对该事件感兴趣 */ protected boolean supportsEvent(ApplicationListener<ApplicationEvent> applicationListener, ApplicationEvent event) { Class<? extends ApplicationListener> listenerClass = applicationListener.getClass(); // 按照 CglibSubclassingInstantiationStrategy、SimpleInstantiationStrategy 不同的实例化类型,需要判断后获取目标 class Class<?> targetClass = ClassUtils.isCglibProxyClass(listenerClass) ? listenerClass.getSuperclass() : listenerClass; Type genericInterface = targetClass.getGenericInterfaces()[0]; Type actualTypeArgument = ((ParameterizedType) genericInterface).getActualTypeArguments()[0]; String className = actualTypeArgument.getTypeName(); Class<?> eventClassName; try { eventClassName = Class.forName(className); } catch (ClassNotFoundException e) { throw new BeansException("wrong event class name: " + className); } // 判定此 eventClassName 对象所表示的类或接口与指定的 event.getClass() 参数所表示的类或接口是否相同,或是否是其超类或超接口。 // isAssignableFrom是用来判断子类和父类的关系的,或者接口的实现类和接口的关系的,默认所有的类的终极父类都是Object。如果A.isAssignableFrom(B)结果是true,证明B可以转换成为A,也就是A可以由B转换而来。 return eventClassName.isAssignableFrom(event.getClass()); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/event/AbstractApplicationEventMulticaster.java
Java
apache-2.0
4,090
package cn.bugstack.springframework.context.event; import cn.bugstack.springframework.context.ApplicationContext; import cn.bugstack.springframework.context.ApplicationEvent; /** * Base class for events raised for an <code>ApplicationContext</code>. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ApplicationContextEvent extends ApplicationEvent { /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ public ApplicationContextEvent(Object source) { super(source); } /** * Get the <code>ApplicationContext</code> that the event was raised for. */ public final ApplicationContext getApplicationContext() { return (ApplicationContext) getSource(); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/event/ApplicationContextEvent.java
Java
apache-2.0
1,084
package cn.bugstack.springframework.context.event; import cn.bugstack.springframework.context.ApplicationEvent; import cn.bugstack.springframework.context.ApplicationListener; /** * Interface to be implemented by objects that can manage a number of * {@link ApplicationListener} objects, and publish events to them. * * 事件广播器 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ApplicationEventMulticaster { /** * Add a listener to be notified of all events. * @param listener the listener to add */ void addApplicationListener(ApplicationListener<?> listener); /** * Remove a listener from the notification list. * @param listener the listener to remove */ void removeApplicationListener(ApplicationListener<?> listener); /** * Multicast the given application event to appropriate listeners. * @param event the event to multicast */ void multicastEvent(ApplicationEvent event); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/event/ApplicationEventMulticaster.java
Java
apache-2.0
1,212
package cn.bugstack.springframework.context.event; /** * Event raised when an <code>ApplicationContext</code> gets closed. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ContextClosedEvent extends ApplicationContextEvent{ /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ public ContextClosedEvent(Object source) { super(source); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/event/ContextClosedEvent.java
Java
apache-2.0
740
package cn.bugstack.springframework.context.event; /** * Event raised when an <code>ApplicationContext</code> gets initialized or refreshed. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ContextRefreshedEvent extends ApplicationContextEvent{ /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ public ContextRefreshedEvent(Object source) { super(source); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/event/ContextRefreshedEvent.java
Java
apache-2.0
763
package cn.bugstack.springframework.context.event; import cn.bugstack.springframework.beans.factory.BeanFactory; import cn.bugstack.springframework.context.ApplicationEvent; import cn.bugstack.springframework.context.ApplicationListener; /** * Simple implementation of the {@link ApplicationEventMulticaster} interface. * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { public SimpleApplicationEventMulticaster(BeanFactory beanFactory) { setBeanFactory(beanFactory); } @SuppressWarnings("unchecked") @Override public void multicastEvent(final ApplicationEvent event) { for (final ApplicationListener listener : getApplicationListeners(event)) { listener.onApplicationEvent(event); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/event/SimpleApplicationEventMulticaster.java
Java
apache-2.0
1,077
package cn.bugstack.springframework.context.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.ConfigurableListableBeanFactory; import cn.bugstack.springframework.beans.factory.config.BeanFactoryPostProcessor; import cn.bugstack.springframework.beans.factory.config.BeanPostProcessor; import cn.bugstack.springframework.context.ApplicationEvent; import cn.bugstack.springframework.context.ApplicationListener; import cn.bugstack.springframework.context.ConfigurableApplicationContext; import cn.bugstack.springframework.context.event.ApplicationEventMulticaster; import cn.bugstack.springframework.context.event.ContextClosedEvent; import cn.bugstack.springframework.context.event.ContextRefreshedEvent; import cn.bugstack.springframework.context.event.SimpleApplicationEventMulticaster; import cn.bugstack.springframework.core.convert.ConversionService; import cn.bugstack.springframework.core.io.DefaultResourceLoader; import java.util.Collection; import java.util.Map; /** * Abstract implementation of the {@link cn.bugstack.springframework.context.ApplicationContext} * interface. Doesn't mandate the type of storage used for configuration; simply * implements common context functionality. Uses the Template Method design pattern, * requiring concrete subclasses to implement abstract methods. * <p> * 抽象应用上下文 * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext { public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster"; private ApplicationEventMulticaster applicationEventMulticaster; @Override public void refresh() throws BeansException { // 1. 创建 BeanFactory,并加载 BeanDefinition refreshBeanFactory(); // 2. 获取 BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 3. 添加 ApplicationContextAwareProcessor,让继承自 ApplicationContextAware 的 Bean 对象都能感知所属的 ApplicationContext beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 4. 在 Bean 实例化之前,执行 BeanFactoryPostProcessor (Invoke factory processors registered as beans in the context.) invokeBeanFactoryPostProcessors(beanFactory); // 5. BeanPostProcessor 需要提前于其他 Bean 对象实例化之前执行注册操作 registerBeanPostProcessors(beanFactory); // 6. 初始化事件发布者 initApplicationEventMulticaster(); // 7. 注册事件监听器 registerListeners(); // 8. 设置类型转换器、提前实例化单例Bean对象 finishBeanFactoryInitialization(beanFactory); // 9. 发布容器刷新完成事件 finishRefresh(); } // 设置类型转换器、提前实例化单例Bean对象 protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // 设置类型转换器 if (beanFactory.containsBean("conversionService")) { Object conversionService = beanFactory.getBean("conversionService"); if (conversionService instanceof ConversionService) { beanFactory.setConversionService((ConversionService) conversionService); } } // 提前实例化单例Bean对象 beanFactory.preInstantiateSingletons(); } protected abstract void refreshBeanFactory() throws BeansException; protected abstract ConfigurableListableBeanFactory getBeanFactory(); private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessorMap = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class); for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessorMap.values()) { beanFactoryPostProcessor.postProcessBeanFactory(beanFactory); } } private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanPostProcessor.class); for (BeanPostProcessor beanPostProcessor : beanPostProcessorMap.values()) { beanFactory.addBeanPostProcessor(beanPostProcessor); } } private void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, applicationEventMulticaster); } private void registerListeners() { Collection<ApplicationListener> applicationListeners = getBeansOfType(ApplicationListener.class).values(); for (ApplicationListener listener : applicationListeners) { applicationEventMulticaster.addApplicationListener(listener); } } private void finishRefresh() { publishEvent(new ContextRefreshedEvent(this)); } @Override public void publishEvent(ApplicationEvent event) { applicationEventMulticaster.multicastEvent(event); } @Override public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException { return getBeanFactory().getBeansOfType(type); } @Override public String[] getBeanDefinitionNames() { return getBeanFactory().getBeanDefinitionNames(); } @Override public Object getBean(String name) throws BeansException { return getBeanFactory().getBean(name); } @Override public Object getBean(String name, Object... args) throws BeansException { return getBeanFactory().getBean(name, args); } @Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return getBeanFactory().getBean(name, requiredType); } @Override public <T> T getBean(Class<T> requiredType) throws BeansException { return getBeanFactory().getBean(requiredType); } @Override public boolean containsBean(String name) { return getBeanFactory().containsBean(name); } @Override public void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(this::close)); } @Override public void close() { // 发布容器关闭事件 publishEvent(new ContextClosedEvent(this)); // 执行销毁单例bean的销毁方法 getBeanFactory().destroySingletons(); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/support/AbstractApplicationContext.java
Java
apache-2.0
6,979
package cn.bugstack.springframework.context.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.ConfigurableListableBeanFactory; import cn.bugstack.springframework.beans.factory.support.DefaultListableBeanFactory; /** * Base class for {@link cn.bugstack.springframework.context.ApplicationContext} * implementations which are supposed to support multiple calls to {@link #refresh()}, * creating a new internal bean factory instance every time. * Typically (but not necessarily), such a context will be driven by * a set of config locations to load bean definitions from. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext { private DefaultListableBeanFactory beanFactory; @Override protected void refreshBeanFactory() throws BeansException { DefaultListableBeanFactory beanFactory = createBeanFactory(); loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } private DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory(); } protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory); @Override protected ConfigurableListableBeanFactory getBeanFactory() { return beanFactory; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/support/AbstractRefreshableApplicationContext.java
Java
apache-2.0
1,629
package cn.bugstack.springframework.context.support; import cn.bugstack.springframework.beans.factory.support.DefaultListableBeanFactory; import cn.bugstack.springframework.beans.factory.xml.XmlBeanDefinitionReader; /** * Convenient base class for {@link cn.bugstack.springframework.context.ApplicationContext} * implementations, drawing configuration from XML documents containing bean definitions * understood by an {@link cn.bugstack.springframework.beans.factory.xml.XmlBeanDefinitionReader}. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public abstract class AbstractXmlApplicationContext extends AbstractRefreshableApplicationContext { @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) { XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory, this); String[] configLocations = getConfigLocations(); if (null != configLocations){ beanDefinitionReader.loadBeanDefinitions(configLocations); } } protected abstract String[] getConfigLocations(); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/support/AbstractXmlApplicationContext.java
Java
apache-2.0
1,318
package cn.bugstack.springframework.context.support; import cn.bugstack.springframework.beans.BeansException; import cn.bugstack.springframework.beans.factory.config.BeanPostProcessor; import cn.bugstack.springframework.context.ApplicationContext; import cn.bugstack.springframework.context.ApplicationContextAware; /** * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ApplicationContextAwareProcessor implements BeanPostProcessor { private final ApplicationContext applicationContext; public ApplicationContextAwareProcessor(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ApplicationContextAware){ ((ApplicationContextAware) bean).setApplicationContext(applicationContext); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/support/ApplicationContextAwareProcessor.java
Java
apache-2.0
1,323
package cn.bugstack.springframework.context.support; import cn.bugstack.springframework.beans.BeansException; /** * Standalone XML application context, taking the context definition files * from the class path, interpreting plain paths as class path resource names * that include the package path (e.g. "mypackage/myresource.txt"). Useful for * test harnesses as well as for application contexts embedded within JARs. * <p> * XML 文件应用上下文 * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext { private String[] configLocations; public ClassPathXmlApplicationContext() { } /** * 从 XML 中加载 BeanDefinition,并刷新上下文 * * @param configLocations * @throws BeansException */ public ClassPathXmlApplicationContext(String configLocations) throws BeansException { this(new String[]{configLocations}); } /** * 从 XML 中加载 BeanDefinition,并刷新上下文 * @param configLocations * @throws BeansException */ public ClassPathXmlApplicationContext(String[] configLocations) throws BeansException { this.configLocations = configLocations; refresh(); } @Override protected String[] getConfigLocations() { return configLocations; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/support/ClassPathXmlApplicationContext.java
Java
apache-2.0
1,608
package cn.bugstack.springframework.context.support; import cn.bugstack.springframework.beans.factory.FactoryBean; import cn.bugstack.springframework.beans.factory.InitializingBean; import cn.bugstack.springframework.core.convert.ConversionService; import cn.bugstack.springframework.core.convert.converter.Converter; import cn.bugstack.springframework.core.convert.converter.ConverterFactory; import cn.bugstack.springframework.core.convert.converter.ConverterRegistry; import cn.bugstack.springframework.core.convert.converter.GenericConverter; import cn.bugstack.springframework.core.convert.support.DefaultConversionService; import cn.bugstack.springframework.core.convert.support.GenericConversionService; import org.jetbrains.annotations.Nullable; import java.util.Set; /** * A factory providing convenient access to a ConversionService configured with * converters appropriate for most environments. Set the * setConverters "converters" property to supplement the default converters. * * 提供创建 ConversionService 工厂 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean { @Nullable private Set<?> converters; @Nullable private GenericConversionService conversionService; @Override public ConversionService getObject() throws Exception { return conversionService; } @Override public Class<?> getObjectType() { return conversionService.getClass(); } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { this.conversionService = new DefaultConversionService(); registerConverters(converters, conversionService); } private void registerConverters(Set<?> converters, ConverterRegistry registry) { if (converters != null) { for (Object converter : converters) { if (converter instanceof GenericConverter) { registry.addConverter((GenericConverter) converter); } else if (converter instanceof Converter<?, ?>) { registry.addConverter((Converter<?, ?>) converter); } else if (converter instanceof ConverterFactory<?, ?>) { registry.addConverterFactory((ConverterFactory<?, ?>) converter); } else { throw new IllegalArgumentException("Each converter object must implement one of the " + "Converter, ConverterFactory, or GenericConverter interfaces"); } } } } public void setConverters(Set<?> converters) { this.converters = converters; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/context/support/ConversionServiceFactoryBean.java
Java
apache-2.0
3,012
package cn.bugstack.springframework.core; import cn.bugstack.springframework.util.ClassUtils; import cn.bugstack.springframework.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author zhangdd on 2022/2/27 */ public class BridgeMethodResolver { private BridgeMethodResolver() { } public static Method findBridgedMethod(Method bridgeMethod) { if (!bridgeMethod.isBridge()) { return bridgeMethod; } // Gather all methods with matching name and parameter size. List<Method> candidateMethods = new ArrayList<>(); Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass()); for (Method candidateMethod : methods) { if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) { candidateMethods.add(candidateMethod); } } // Now perform simple quick check. if (candidateMethods.size() == 1) { return candidateMethods.get(0); } // Search for candidate match. Method bridgedMethod = searchCandidates(candidateMethods, bridgeMethod); if (bridgedMethod != null) { // Bridged method found... return bridgedMethod; } else { // A bridge method was passed in but we couldn't find the bridged method. // Let's proceed with the passed-in method and hope for the best... return bridgeMethod; } } private static boolean isBridgedCandidateFor(Method candidateMethod, Method bridgeMethod) { return (!candidateMethod.isBridge() && !candidateMethod.equals(bridgeMethod) && candidateMethod.getName().equals(bridgeMethod.getName()) && candidateMethod.getParameterCount() == bridgeMethod.getParameterCount()); } private static Method searchCandidates(List<Method> candidateMethods, Method bridgeMethod) { if (candidateMethods.isEmpty()) { return null; } Method previousMethod = null; boolean sameSig = true; for (Method candidateMethod : candidateMethods) { if (isBridgeMethodFor(bridgeMethod, candidateMethod, bridgeMethod.getDeclaringClass())) { return candidateMethod; } else if (previousMethod != null) { sameSig = sameSig && Arrays.equals(candidateMethod.getGenericParameterTypes(), previousMethod.getGenericParameterTypes()); } previousMethod = candidateMethod; } return (sameSig ? candidateMethods.get(0) : null); } static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Class<?> declaringClass) { if (isResolvedTypeMatch(candidateMethod, bridgeMethod, declaringClass)) { return true; } Method method = findGenericDeclaration(bridgeMethod); return (method != null && isResolvedTypeMatch(method, candidateMethod, declaringClass)); } /** * Returns {@code true} if the {@link Type} signature of both the supplied * {@link Method#getGenericParameterTypes() generic Method} and concrete {@link Method} * are equal after resolving all types against the declaringType, otherwise * returns {@code false}. */ private static boolean isResolvedTypeMatch(Method genericMethod, Method candidateMethod, Class<?> declaringClass) { Type[] genericParameters = genericMethod.getGenericParameterTypes(); Class<?>[] candidateParameters = candidateMethod.getParameterTypes(); if (genericParameters.length != candidateParameters.length) { return false; } for (int i = 0; i < candidateParameters.length; i++) { ResolvableType genericParameter = ResolvableType.forMethodParameter(genericMethod, i, declaringClass); Class<?> candidateParameter = candidateParameters[i]; if (candidateParameter.isArray()) { // An array type: compare the component type. if (!candidateParameter.getComponentType().equals(genericParameter.getComponentType().toClass())) { return false; } } // A non-array type: compare the type itself. if (!candidateParameter.equals(genericParameter.toClass())) { return false; } } return true; } /** * Searches for the generic {@link Method} declaration whose erased signature * matches that of the supplied bridge method. * @throws IllegalStateException if the generic declaration cannot be found */ private static Method findGenericDeclaration(Method bridgeMethod) { // Search parent types for method that has same signature as bridge. Class<?> superclass = bridgeMethod.getDeclaringClass().getSuperclass(); while (superclass != null && Object.class != superclass) { Method method = searchForMatch(superclass, bridgeMethod); if (method != null && !method.isBridge()) { return method; } superclass = superclass.getSuperclass(); } Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(bridgeMethod.getDeclaringClass()); return searchInterfaces(interfaces, bridgeMethod); } private static Method searchInterfaces(Class<?>[] interfaces, Method bridgeMethod) { for (Class<?> ifc : interfaces) { Method method = searchForMatch(ifc, bridgeMethod); if (method != null && !method.isBridge()) { return method; } else { method = searchInterfaces(ifc.getInterfaces(), bridgeMethod); if (method != null) { return method; } } } return null; } /** * If the supplied {@link Class} has a declared {@link Method} whose signature matches * that of the supplied {@link Method}, then this matching {@link Method} is returned, * otherwise {@code null} is returned. */ private static Method searchForMatch(Class<?> type, Method bridgeMethod) { try { return type.getDeclaredMethod(bridgeMethod.getName(), bridgeMethod.getParameterTypes()); } catch (NoSuchMethodException ex) { return null; } } /** * Compare the signatures of the bridge method and the method which it bridges. If * the parameter and return types are the same, it is a 'visibility' bridge method * introduced in Java 6 to fix https://bugs.java.com/view_bug.do?bug_id=6342411. * See also https://stas-blogspot.blogspot.com/2010/03/java-bridge-methods-explained.html * @return whether signatures match as described */ public static boolean isVisibilityBridgeMethodPair(Method bridgeMethod, Method bridgedMethod) { if (bridgeMethod == bridgedMethod) { return true; } return (bridgeMethod.getReturnType().equals(bridgedMethod.getReturnType()) && Arrays.equals(bridgeMethod.getParameterTypes(), bridgedMethod.getParameterTypes())); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/BridgeMethodResolver.java
Java
apache-2.0
7,388
package cn.bugstack.springframework.core; /** * @author zhangdd on 2022/2/27 */ public abstract class GraalDetector { // See https://github.com/oracle/graal/blob/master/sdk/src/org.graalvm.nativeimage/src/org/graalvm/nativeimage/ImageInfo.java private static final boolean imageCode = (System.getProperty("org.graalvm.nativeimage.imagecode") != null); /** * Return whether this runtime environment lives within a native image. */ public static boolean inImageCode() { return imageCode; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/GraalDetector.java
Java
apache-2.0
535
package cn.bugstack.springframework.core; import cn.bugstack.springframework.core.util.ObjectUtils; import java.lang.reflect.Method; /** * @author zhangdd on 2022/2/26 */ public final class MethodClassKey implements Comparable<MethodClassKey>{ private final Method method; private final Class<?> targetClass; public MethodClassKey(Method method, Class<?> targetClass) { this.method = method; this.targetClass = targetClass; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof MethodClassKey)) { return false; } MethodClassKey otherKey = (MethodClassKey) other; return (this.method.equals(otherKey.method) && ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass)); } @Override public int hashCode() { return this.method.hashCode() + (this.targetClass != null ? this.targetClass.hashCode() * 29 : 0); } @Override public String toString() { return this.method + (this.targetClass != null ? " on " + this.targetClass : ""); } @Override public int compareTo(MethodClassKey other) { int result = this.method.getName().compareTo(other.method.getName()); if (result == 0) { result = this.method.toString().compareTo(other.method.toString()); if (result == 0 && this.targetClass != null && other.targetClass != null) { result = this.targetClass.getName().compareTo(other.targetClass.getName()); } } return result; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/MethodClassKey.java
Java
apache-2.0
1,660
package cn.bugstack.springframework.core; import cn.bugstack.springframework.util.ClassUtils; import cn.hutool.core.lang.Assert; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Map; /** * @author zhangdd on 2022/2/27 */ public class MethodParameter { private volatile Class<?> containingClass; private final Executable executable; private final int parameterIndex; private int nestingLevel = 1; private volatile Type genericParameterType; private volatile Class<?> parameterType; Map<Integer, Integer> typeIndexesPerLevel; public MethodParameter(Method method, int parameterIndex) { this(method, parameterIndex, 1); } public MethodParameter(Constructor<?> constructor, int parameterIndex) { this(constructor, parameterIndex, 1); } public MethodParameter(Constructor<?> constructor, int parameterIndex, int nestingLevel) { Assert.notNull(constructor, "Constructor must not be null"); this.executable = constructor; this.parameterIndex = validateIndex(constructor, parameterIndex); this.nestingLevel = nestingLevel; } public MethodParameter(Method method, int parameterIndex, int nestingLevel) { Assert.notNull(method, "Method must not be null"); this.executable = method; this.parameterIndex = validateIndex(method, parameterIndex); this.nestingLevel = nestingLevel; } void setContainingClass(Class<?> containingClass) { this.containingClass = containingClass; } private static int validateIndex(Executable executable, int parameterIndex) { int count = executable.getParameterCount(); if (parameterIndex<-1 || parameterIndex>=count){ throw new IllegalArgumentException("Parameter index needs to be between -1 and " + (count - 1)); } return parameterIndex; } public Class<?> getContainingClass() { Class<?> containingClass = this.containingClass; return (containingClass != null ? containingClass : getDeclaringClass()); } public Class<?> getDeclaringClass() { return this.executable.getDeclaringClass(); } public Method getMethod() { return (this.executable instanceof Method ? (Method) this.executable : null); } public Executable getExecutable() { return this.executable; } public int getParameterIndex() { return this.parameterIndex; } public int getNestingLevel() { return this.nestingLevel; } public Type getGenericParameterType() { Type paramType = this.genericParameterType; if (paramType == null) { if (this.parameterIndex < 0) { Method method = getMethod(); paramType = (method != null ? method.getGenericReturnType() : void.class); } else { Type[] genericParameterTypes = this.executable.getGenericParameterTypes(); int index = this.parameterIndex; if (this.executable instanceof Constructor && ClassUtils.isInnerClass(this.executable.getDeclaringClass()) && genericParameterTypes.length == this.executable.getParameterCount() - 1) { // Bug in javac: type array excludes enclosing instance parameter // for inner classes with at least one generic constructor parameter, // so access it with the actual parameter index lowered by 1 index = this.parameterIndex - 1; } paramType = (index >= 0 && index < genericParameterTypes.length ? genericParameterTypes[index] : getParameterType()); } this.genericParameterType = paramType; } return paramType; } public Class<?> getParameterType() { Class<?> paramType = this.parameterType; if (paramType == null) { if (this.parameterIndex < 0) { Method method = getMethod(); paramType = (method != null ? method.getReturnType() : void.class); } else { paramType = this.executable.getParameterTypes()[this.parameterIndex]; } this.parameterType = paramType; } return paramType; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/MethodParameter.java
Java
apache-2.0
4,483
package cn.bugstack.springframework.core; import cn.bugstack.springframework.core.util.ConcurrentReferenceHashMap; import cn.bugstack.springframework.core.util.ObjectUtils; import cn.bugstack.springframework.core.util.StringUtils; import cn.bugstack.springframework.util.ClassUtils; import cn.hutool.core.lang.Assert; import java.io.Serializable; import java.lang.reflect.*; import java.util.Arrays; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Map; /** * @author zhangdd on 2022/2/27 */ public class ResolvableType implements Serializable { /** * {@code ResolvableType} returned when no value is available. {@code NONE} is used * in preference to {@code null} so that multiple method calls can be safely chained. */ public static final ResolvableType NONE = new ResolvableType(EmptyType.INSTANCE, null, null, 0); private static final ResolvableType[] EMPTY_TYPES_ARRAY = new ResolvableType[0]; private static final ConcurrentReferenceHashMap<ResolvableType, ResolvableType> cache = new ConcurrentReferenceHashMap<>(256); /** * The underlying Java type being managed. */ private final Type type; /** * Optional provider for the type. */ private final SerializableTypeWrapper.TypeProvider typeProvider; /** * The {@code VariableResolver} to use or {@code null} if no resolver is available. */ private final VariableResolver variableResolver; /** * The component type for an array or {@code null} if the type should be deduced. */ private final ResolvableType componentType; private final Integer hash; private Class<?> resolved; private volatile ResolvableType superType; private volatile ResolvableType[] interfaces; private volatile ResolvableType[] generics; /** * Private constructor used to create a new {@link ResolvableType} for cache key purposes, * with no upfront resolution. */ private ResolvableType( Type type, SerializableTypeWrapper.TypeProvider typeProvider, VariableResolver variableResolver) { this.type = type; this.typeProvider = typeProvider; this.variableResolver = variableResolver; this.componentType = null; this.hash = calculateHashCode(); this.resolved = null; } /** * Private constructor used to create a new {@link ResolvableType} for cache value purposes, * with upfront resolution and a pre-calculated hash. * @since 4.2 */ private ResolvableType(Type type, SerializableTypeWrapper.TypeProvider typeProvider, VariableResolver variableResolver, Integer hash) { this.type = type; this.typeProvider = typeProvider; this.variableResolver = variableResolver; this.componentType = null; this.hash = hash; this.resolved = resolveClass(); } /** * Private constructor used to create a new {@link ResolvableType} for uncached purposes, * with upfront resolution but lazily calculated hash. */ private ResolvableType(Type type, SerializableTypeWrapper.TypeProvider typeProvider, VariableResolver variableResolver, ResolvableType componentType) { this.type = type; this.typeProvider = typeProvider; this.variableResolver = variableResolver; this.componentType = componentType; this.hash = null; this.resolved = resolveClass(); } /** * Private constructor used to create a new {@link ResolvableType} on a {@link Class} basis. * Avoids all {@code instanceof} checks in order to create a straight {@link Class} wrapper. * @since 4.2 */ private ResolvableType(Class<?> clazz) { this.resolved = (clazz != null ? clazz : Object.class); this.type = this.resolved; this.typeProvider = null; this.variableResolver = null; this.componentType = null; this.hash = null; } /** * Return the underling Java {@link Type} being managed. */ public Type getType() { return SerializableTypeWrapper.unwrap(this.type); } /** * Return the underlying Java {@link Class} being managed, if available; * otherwise {@code null}. */ public Class<?> getRawClass() { if (this.type == this.resolved) { return this.resolved; } Type rawType = this.type; if (rawType instanceof ParameterizedType) { rawType = ((ParameterizedType) rawType).getRawType(); } return (rawType instanceof Class ? (Class<?>) rawType : null); } /** * Return the underlying source of the resolvable type. Will return a {@link Field}, * {@link MethodParameter} or {@link Type} depending on how the {@link ResolvableType} * was constructed. With the exception of the {@link #NONE} constant, this method will * never return {@code null}. This method is primarily to provide access to additional * type information or meta-data that alternative JVM languages may provide. */ public Object getSource() { Object source = (this.typeProvider != null ? this.typeProvider.getSource() : null); return (source != null ? source : this.type); } /** * Return this type as a resolved {@code Class}, falling back to * {@link Object} if no specific class can be resolved. * @return the resolved {@link Class} or the {@code Object} fallback * @since 5.1 * @see #getRawClass() * @see #resolve(Class) */ public Class<?> toClass() { return resolve(Object.class); } /** * Determine whether the given object is an instance of this {@code ResolvableType}. * @param obj the object to check * @since 4.2 * @see #isAssignableFrom(Class) */ public boolean isInstance( Object obj) { return (obj != null && isAssignableFrom(obj.getClass())); } /** * Determine whether this {@code ResolvableType} is assignable from the * specified other type. * @param other the type to be checked against (as a {@code Class}) * @since 4.2 * @see #isAssignableFrom(ResolvableType) */ public boolean isAssignableFrom(Class<?> other) { return isAssignableFrom(forClass(other), null); } /** * Determine whether this {@code ResolvableType} is assignable from the * specified other type. * <p>Attempts to follow the same rules as the Java compiler, considering * whether both the {@link #resolve() resolved} {@code Class} is * {@link Class#isAssignableFrom(Class) assignable from} the given type * as well as whether all {@link #getGenerics() generics} are assignable. * @param other the type to be checked against (as a {@code ResolvableType}) * @return {@code true} if the specified other type can be assigned to this * {@code ResolvableType}; {@code false} otherwise */ public boolean isAssignableFrom(ResolvableType other) { return isAssignableFrom(other, null); } private boolean isAssignableFrom(ResolvableType other, Map<Type, Type> matchedBefore) { Assert.notNull(other, "ResolvableType must not be null"); // If we cannot resolve types, we are not assignable if (this == NONE || other == NONE) { return false; } // Deal with array by delegating to the component type if (isArray()) { return (other.isArray() && getComponentType().isAssignableFrom(other.getComponentType())); } if (matchedBefore != null && matchedBefore.get(this.type) == other.type) { return true; } // Deal with wildcard bounds WildcardBounds ourBounds = WildcardBounds.get(this); WildcardBounds typeBounds = WildcardBounds.get(other); // In the form X is assignable to <? extends Number> if (typeBounds != null) { return (ourBounds != null && ourBounds.isSameKind(typeBounds) && ourBounds.isAssignableFrom(typeBounds.getBounds())); } // In the form <? extends Number> is assignable to X... if (ourBounds != null) { return ourBounds.isAssignableFrom(other); } // Main assignability check about to follow boolean exactMatch = (matchedBefore != null); // We're checking nested generic variables now... boolean checkGenerics = true; Class<?> ourResolved = null; if (this.type instanceof TypeVariable) { TypeVariable<?> variable = (TypeVariable<?>) this.type; // Try default variable resolution if (this.variableResolver != null) { ResolvableType resolved = this.variableResolver.resolveVariable(variable); if (resolved != null) { ourResolved = resolved.resolve(); } } if (ourResolved == null) { // Try variable resolution against target type if (other.variableResolver != null) { ResolvableType resolved = other.variableResolver.resolveVariable(variable); if (resolved != null) { ourResolved = resolved.resolve(); checkGenerics = false; } } } if (ourResolved == null) { // Unresolved type variable, potentially nested -> never insist on exact match exactMatch = false; } } if (ourResolved == null) { ourResolved = resolve(Object.class); } Class<?> otherResolved = other.toClass(); // We need an exact type match for generics // List<CharSequence> is not assignable from List<String> if (exactMatch ? !ourResolved.equals(otherResolved) : !ClassUtils.isAssignable(ourResolved, otherResolved)) { return false; } if (checkGenerics) { // Recursively check each generic ResolvableType[] ourGenerics = getGenerics(); ResolvableType[] typeGenerics = other.as(ourResolved).getGenerics(); if (ourGenerics.length != typeGenerics.length) { return false; } if (matchedBefore == null) { matchedBefore = new IdentityHashMap<>(1); } matchedBefore.put(this.type, other.type); for (int i = 0; i < ourGenerics.length; i++) { if (!ourGenerics[i].isAssignableFrom(typeGenerics[i], matchedBefore)) { return false; } } } return true; } /** * Return {@code true} if this type resolves to a Class that represents an array. * @see #getComponentType() */ public boolean isArray() { if (this == NONE) { return false; } return ((this.type instanceof Class && ((Class<?>) this.type).isArray()) || this.type instanceof GenericArrayType || resolveType().isArray()); } /** * Return the ResolvableType representing the component type of the array or * {@link #NONE} if this type does not represent an array. * @see #isArray() */ public ResolvableType getComponentType() { if (this == NONE) { return NONE; } if (this.componentType != null) { return this.componentType; } if (this.type instanceof Class) { Class<?> componentType = ((Class<?>) this.type).getComponentType(); return forType(componentType, this.variableResolver); } if (this.type instanceof GenericArrayType) { return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver); } return resolveType().getComponentType(); } /** * Convenience method to return this type as a resolvable {@link Collection} type. * Returns {@link #NONE} if this type does not implement or extend * {@link Collection}. * @see #as(Class) * @see #asMap() */ public ResolvableType asCollection() { return as(Collection.class); } /** * Convenience method to return this type as a resolvable {@link Map} type. * Returns {@link #NONE} if this type does not implement or extend * {@link Map}. * @see #as(Class) * @see #asCollection() */ public ResolvableType asMap() { return as(Map.class); } /** * Return this type as a {@link ResolvableType} of the specified class. Searches * {@link #getSuperType() supertype} and {@link #getInterfaces() interface} * hierarchies to find a match, returning {@link #NONE} if this type does not * implement or extend the specified class. * @param type the required type (typically narrowed) * @return a {@link ResolvableType} representing this object as the specified * type, or {@link #NONE} if not resolvable as that type * @see #asCollection() * @see #asMap() * @see #getSuperType() * @see #getInterfaces() */ public ResolvableType as(Class<?> type) { if (this == NONE) { return NONE; } Class<?> resolved = resolve(); if (resolved == null || resolved == type) { return this; } for (ResolvableType interfaceType : getInterfaces()) { ResolvableType interfaceAsType = interfaceType.as(type); if (interfaceAsType != NONE) { return interfaceAsType; } } return getSuperType().as(type); } /** * Return a {@link ResolvableType} representing the direct supertype of this type. * If no supertype is available this method returns {@link #NONE}. * <p>Note: The resulting {@link ResolvableType} instance may not be {@link Serializable}. * @see #getInterfaces() */ public ResolvableType getSuperType() { Class<?> resolved = resolve(); if (resolved == null || resolved.getGenericSuperclass() == null) { return NONE; } ResolvableType superType = this.superType; if (superType == null) { superType = forType(resolved.getGenericSuperclass(), this); this.superType = superType; } return superType; } /** * Return a {@link ResolvableType} array representing the direct interfaces * implemented by this type. If this type does not implement any interfaces an * empty array is returned. * <p>Note: The resulting {@link ResolvableType} instances may not be {@link Serializable}. * @see #getSuperType() */ public ResolvableType[] getInterfaces() { Class<?> resolved = resolve(); if (resolved == null) { return EMPTY_TYPES_ARRAY; } ResolvableType[] interfaces = this.interfaces; if (interfaces == null) { Type[] genericIfcs = resolved.getGenericInterfaces(); interfaces = new ResolvableType[genericIfcs.length]; for (int i = 0; i < genericIfcs.length; i++) { interfaces[i] = forType(genericIfcs[i], this); } this.interfaces = interfaces; } return interfaces; } /** * Return {@code true} if this type contains generic parameters. * @see #getGeneric(int...) * @see #getGenerics() */ public boolean hasGenerics() { return (getGenerics().length > 0); } /** * Return {@code true} if this type contains unresolvable generics only, * that is, no substitute for any of its declared type variables. */ boolean isEntirelyUnresolvable() { if (this == NONE) { return false; } ResolvableType[] generics = getGenerics(); for (ResolvableType generic : generics) { if (!generic.isUnresolvableTypeVariable() && !generic.isWildcardWithoutBounds()) { return false; } } return true; } /** * Determine whether the underlying type has any unresolvable generics: * either through an unresolvable type variable on the type itself * or through implementing a generic interface in a raw fashion, * i.e. without substituting that interface's type variables. * The result will be {@code true} only in those two scenarios. */ public boolean hasUnresolvableGenerics() { if (this == NONE) { return false; } ResolvableType[] generics = getGenerics(); for (ResolvableType generic : generics) { if (generic.isUnresolvableTypeVariable() || generic.isWildcardWithoutBounds()) { return true; } } Class<?> resolved = resolve(); if (resolved != null) { for (Type genericInterface : resolved.getGenericInterfaces()) { if (genericInterface instanceof Class) { if (forClass((Class<?>) genericInterface).hasGenerics()) { return true; } } } return getSuperType().hasUnresolvableGenerics(); } return false; } /** * Determine whether the underlying type is a type variable that * cannot be resolved through the associated variable resolver. */ private boolean isUnresolvableTypeVariable() { if (this.type instanceof TypeVariable) { if (this.variableResolver == null) { return true; } TypeVariable<?> variable = (TypeVariable<?>) this.type; ResolvableType resolved = this.variableResolver.resolveVariable(variable); if (resolved == null || resolved.isUnresolvableTypeVariable()) { return true; } } return false; } /** * Determine whether the underlying type represents a wildcard * without specific bounds (i.e., equal to {@code ? extends Object}). */ private boolean isWildcardWithoutBounds() { if (this.type instanceof WildcardType) { WildcardType wt = (WildcardType) this.type; if (wt.getLowerBounds().length == 0) { Type[] upperBounds = wt.getUpperBounds(); if (upperBounds.length == 0 || (upperBounds.length == 1 && Object.class == upperBounds[0])) { return true; } } } return false; } /** * Return a {@link ResolvableType} for the specified nesting level. * See {@link #getNested(int, Map)} for details. * @param nestingLevel the nesting level * @return the {@link ResolvableType} type, or {@code #NONE} */ public ResolvableType getNested(int nestingLevel) { return getNested(nestingLevel, null); } /** * Return a {@link ResolvableType} for the specified nesting level. * <p>The nesting level refers to the specific generic parameter that should be returned. * A nesting level of 1 indicates this type; 2 indicates the first nested generic; * 3 the second; and so on. For example, given {@code List<Set<Integer>>} level 1 refers * to the {@code List}, level 2 the {@code Set}, and level 3 the {@code Integer}. * <p>The {@code typeIndexesPerLevel} map can be used to reference a specific generic * for the given level. For example, an index of 0 would refer to a {@code Map} key; * whereas, 1 would refer to the value. If the map does not contain a value for a * specific level the last generic will be used (e.g. a {@code Map} value). * <p>Nesting levels may also apply to array types; for example given * {@code String[]}, a nesting level of 2 refers to {@code String}. * <p>If a type does not {@link #hasGenerics() contain} generics the * {@link #getSuperType() supertype} hierarchy will be considered. * @param nestingLevel the required nesting level, indexed from 1 for the * current type, 2 for the first nested generic, 3 for the second and so on * @param typeIndexesPerLevel a map containing the generic index for a given * nesting level (may be {@code null}) * @return a {@link ResolvableType} for the nested level, or {@link #NONE} */ public ResolvableType getNested(int nestingLevel, Map<Integer, Integer> typeIndexesPerLevel) { ResolvableType result = this; for (int i = 2; i <= nestingLevel; i++) { if (result.isArray()) { result = result.getComponentType(); } else { // Handle derived types while (result != ResolvableType.NONE && !result.hasGenerics()) { result = result.getSuperType(); } Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null); index = (index == null ? result.getGenerics().length - 1 : index); result = result.getGeneric(index); } } return result; } /** * Return a {@link ResolvableType} representing the generic parameter for the * given indexes. Indexes are zero based; for example given the type * {@code Map<Integer, List<String>>}, {@code getGeneric(0)} will access the * {@code Integer}. Nested generics can be accessed by specifying multiple indexes; * for example {@code getGeneric(1, 0)} will access the {@code String} from the * nested {@code List}. For convenience, if no indexes are specified the first * generic is returned. * <p>If no generic is available at the specified indexes {@link #NONE} is returned. * @param indexes the indexes that refer to the generic parameter * (may be omitted to return the first generic) * @return a {@link ResolvableType} for the specified generic, or {@link #NONE} * @see #hasGenerics() * @see #getGenerics() * @see #resolveGeneric(int...) * @see #resolveGenerics() */ public ResolvableType getGeneric( int... indexes) { ResolvableType[] generics = getGenerics(); if (indexes == null || indexes.length == 0) { return (generics.length == 0 ? NONE : generics[0]); } ResolvableType generic = this; for (int index : indexes) { generics = generic.getGenerics(); if (index < 0 || index >= generics.length) { return NONE; } generic = generics[index]; } return generic; } /** * Return an array of {@link ResolvableType ResolvableTypes} representing the generic parameters of * this type. If no generics are available an empty array is returned. If you need to * access a specific generic consider using the {@link #getGeneric(int...)} method as * it allows access to nested generics and protects against * {@code IndexOutOfBoundsExceptions}. * @return an array of {@link ResolvableType ResolvableTypes} representing the generic parameters * (never {@code null}) * @see #hasGenerics() * @see #getGeneric(int...) * @see #resolveGeneric(int...) * @see #resolveGenerics() */ public ResolvableType[] getGenerics() { if (this == NONE) { return EMPTY_TYPES_ARRAY; } ResolvableType[] generics = this.generics; if (generics == null) { if (this.type instanceof Class) { Type[] typeParams = ((Class<?>) this.type).getTypeParameters(); generics = new ResolvableType[typeParams.length]; for (int i = 0; i < generics.length; i++) { generics[i] = ResolvableType.forType(typeParams[i], this); } } else if (this.type instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) this.type).getActualTypeArguments(); generics = new ResolvableType[actualTypeArguments.length]; for (int i = 0; i < actualTypeArguments.length; i++) { generics[i] = forType(actualTypeArguments[i], this.variableResolver); } } else { generics = resolveType().getGenerics(); } this.generics = generics; } return generics; } /** * Convenience method that will {@link #getGenerics() get} and * {@link #resolve() resolve} generic parameters. * @return an array of resolved generic parameters (the resulting array * will never be {@code null}, but it may contain {@code null} elements}) * @see #getGenerics() * @see #resolve() */ public Class<?>[] resolveGenerics() { ResolvableType[] generics = getGenerics(); Class<?>[] resolvedGenerics = new Class<?>[generics.length]; for (int i = 0; i < generics.length; i++) { resolvedGenerics[i] = generics[i].resolve(); } return resolvedGenerics; } /** * Convenience method that will {@link #getGenerics() get} and {@link #resolve() * resolve} generic parameters, using the specified {@code fallback} if any type * cannot be resolved. * @param fallback the fallback class to use if resolution fails * @return an array of resolved generic parameters * @see #getGenerics() * @see #resolve() */ public Class<?>[] resolveGenerics(Class<?> fallback) { ResolvableType[] generics = getGenerics(); Class<?>[] resolvedGenerics = new Class<?>[generics.length]; for (int i = 0; i < generics.length; i++) { resolvedGenerics[i] = generics[i].resolve(fallback); } return resolvedGenerics; } /** * Convenience method that will {@link #getGeneric(int...) get} and * {@link #resolve() resolve} a specific generic parameters. * @param indexes the indexes that refer to the generic parameter * (may be omitted to return the first generic) * @return a resolved {@link Class} or {@code null} * @see #getGeneric(int...) * @see #resolve() */ public Class<?> resolveGeneric(int... indexes) { return getGeneric(indexes).resolve(); } /** * Resolve this type to a {@link Class}, returning {@code null} * if the type cannot be resolved. This method will consider bounds of * {@link TypeVariable TypeVariables} and {@link WildcardType WildcardTypes} if * direct resolution fails; however, bounds of {@code Object.class} will be ignored. * <p>If this method returns a non-null {@code Class} and {@link #hasGenerics()} * returns {@code false}, the given type effectively wraps a plain {@code Class}, * allowing for plain {@code Class} processing if desirable. * @return the resolved {@link Class}, or {@code null} if not resolvable * @see #resolve(Class) * @see #resolveGeneric(int...) * @see #resolveGenerics() */ public Class<?> resolve() { return this.resolved; } /** * Resolve this type to a {@link Class}, returning the specified * {@code fallback} if the type cannot be resolved. This method will consider bounds * of {@link TypeVariable TypeVariables} and {@link WildcardType WildcardTypes} if * direct resolution fails; however, bounds of {@code Object.class} will be ignored. * @param fallback the fallback class to use if resolution fails * @return the resolved {@link Class} or the {@code fallback} * @see #resolve() * @see #resolveGeneric(int...) * @see #resolveGenerics() */ public Class<?> resolve(Class<?> fallback) { return (this.resolved != null ? this.resolved : fallback); } private Class<?> resolveClass() { if (this.type == EmptyType.INSTANCE) { return null; } if (this.type instanceof Class) { return (Class<?>) this.type; } if (this.type instanceof GenericArrayType) { Class<?> resolvedComponent = getComponentType().resolve(); return (resolvedComponent != null ? Array.newInstance(resolvedComponent, 0).getClass() : null); } return resolveType().resolve(); } /** * Resolve this type by a single level, returning the resolved value or {@link #NONE}. * <p>Note: The returned {@link ResolvableType} should only be used as an intermediary * as it cannot be serialized. */ ResolvableType resolveType() { if (this.type instanceof ParameterizedType) { return forType(((ParameterizedType) this.type).getRawType(), this.variableResolver); } if (this.type instanceof WildcardType) { Type resolved = resolveBounds(((WildcardType) this.type).getUpperBounds()); if (resolved == null) { resolved = resolveBounds(((WildcardType) this.type).getLowerBounds()); } return forType(resolved, this.variableResolver); } if (this.type instanceof TypeVariable) { TypeVariable<?> variable = (TypeVariable<?>) this.type; // Try default variable resolution if (this.variableResolver != null) { ResolvableType resolved = this.variableResolver.resolveVariable(variable); if (resolved != null) { return resolved; } } // Fallback to bounds return forType(resolveBounds(variable.getBounds()), this.variableResolver); } return NONE; } private Type resolveBounds(Type[] bounds) { if (bounds.length == 0 || bounds[0] == Object.class) { return null; } return bounds[0]; } private ResolvableType resolveVariable(TypeVariable<?> variable) { if (this.type instanceof TypeVariable) { return resolveType().resolveVariable(variable); } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Class<?> resolved = resolve(); if (resolved == null) { return null; } TypeVariable<?>[] variables = resolved.getTypeParameters(); for (int i = 0; i < variables.length; i++) { if (ObjectUtils.nullSafeEquals(variables[i].getName(), variable.getName())) { Type actualType = parameterizedType.getActualTypeArguments()[i]; return forType(actualType, this.variableResolver); } } Type ownerType = parameterizedType.getOwnerType(); if (ownerType != null) { return forType(ownerType, this.variableResolver).resolveVariable(variable); } } if (this.variableResolver != null) { return this.variableResolver.resolveVariable(variable); } return null; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof ResolvableType)) { return false; } ResolvableType otherType = (ResolvableType) other; if (!ObjectUtils.nullSafeEquals(this.type, otherType.type)) { return false; } if (this.typeProvider != otherType.typeProvider && (this.typeProvider == null || otherType.typeProvider == null || !ObjectUtils.nullSafeEquals(this.typeProvider.getType(), otherType.typeProvider.getType()))) { return false; } if (this.variableResolver != otherType.variableResolver && (this.variableResolver == null || otherType.variableResolver == null || !ObjectUtils.nullSafeEquals(this.variableResolver.getSource(), otherType.variableResolver.getSource()))) { return false; } if (!ObjectUtils.nullSafeEquals(this.componentType, otherType.componentType)) { return false; } return true; } @Override public int hashCode() { return (this.hash != null ? this.hash : calculateHashCode()); } private int calculateHashCode() { int hashCode = ObjectUtils.nullSafeHashCode(this.type); if (this.typeProvider != null) { hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.typeProvider.getType()); } if (this.variableResolver != null) { hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.variableResolver.getSource()); } if (this.componentType != null) { hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.componentType); } return hashCode; } /** * Adapts this {@link ResolvableType} to a {@link VariableResolver}. */ VariableResolver asVariableResolver() { if (this == NONE) { return null; } return new DefaultVariableResolver(); } /** * Custom serialization support for {@link #NONE}. */ private Object readResolve() { return (this.type == EmptyType.INSTANCE ? NONE : this); } /** * Return a String representation of this type in its fully resolved form * (including any generic parameters). */ @Override public String toString() { if (isArray()) { return getComponentType() + "[]"; } if (this.resolved == null) { return "?"; } if (this.type instanceof TypeVariable) { TypeVariable<?> variable = (TypeVariable<?>) this.type; if (this.variableResolver == null || this.variableResolver.resolveVariable(variable) == null) { // Don't bother with variable boundaries for toString()... // Can cause infinite recursions in case of self-references return "?"; } } StringBuilder result = new StringBuilder(this.resolved.getName()); if (hasGenerics()) { result.append('<'); result.append(StringUtils.arrayToDelimitedString(getGenerics(), ", ")); result.append('>'); } return result.toString(); } // Factory methods /** * Return a {@link ResolvableType} for the specified {@link Class}, * using the full generic type information for assignability checks. * For example: {@code ResolvableType.forClass(MyArrayList.class)}. * @param clazz the class to introspect ({@code null} is semantically * equivalent to {@code Object.class} for typical use cases here} * @return a {@link ResolvableType} for the specified class * @see #forClass(Class, Class) * @see #forClassWithGenerics(Class, Class...) */ public static ResolvableType forClass( Class<?> clazz) { return new ResolvableType(clazz); } /** * Return a {@link ResolvableType} for the specified {@link Class}, * doing assignability checks against the raw class only (analogous to * {@link Class#isAssignableFrom}, which this serves as a wrapper for. * For example: {@code ResolvableType.forRawClass(List.class)}. * @param clazz the class to introspect ({@code null} is semantically * equivalent to {@code Object.class} for typical use cases here} * @return a {@link ResolvableType} for the specified class * @since 4.2 * @see #forClass(Class) * @see #getRawClass() */ public static ResolvableType forRawClass( Class<?> clazz) { return new ResolvableType(clazz) { @Override public ResolvableType[] getGenerics() { return EMPTY_TYPES_ARRAY; } @Override public boolean isAssignableFrom(Class<?> other) { return (clazz == null || ClassUtils.isAssignable(clazz, other)); } @Override public boolean isAssignableFrom(ResolvableType other) { Class<?> otherClass = other.getRawClass(); return (otherClass != null && (clazz == null || ClassUtils.isAssignable(clazz, otherClass))); } }; } /** * Return a {@link ResolvableType} for the specified base type * (interface or base class) with a given implementation class. * For example: {@code ResolvableType.forClass(List.class, MyArrayList.class)}. * @param baseType the base type (must not be {@code null}) * @param implementationClass the implementation class * @return a {@link ResolvableType} for the specified base type backed by the * given implementation class * @see #forClass(Class) * @see #forClassWithGenerics(Class, Class...) */ public static ResolvableType forClass(Class<?> baseType, Class<?> implementationClass) { Assert.notNull(baseType, "Base type must not be null"); ResolvableType asType = forType(implementationClass).as(baseType); return (asType == NONE ? forType(baseType) : asType); } /** * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared generics. * @param clazz the class (or interface) to introspect * @param generics the generics of the class * @return a {@link ResolvableType} for the specific class and generics * @see #forClassWithGenerics(Class, ResolvableType...) */ public static ResolvableType forClassWithGenerics(Class<?> clazz, Class<?>... generics) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(generics, "Generics array must not be null"); ResolvableType[] resolvableGenerics = new ResolvableType[generics.length]; for (int i = 0; i < generics.length; i++) { resolvableGenerics[i] = forClass(generics[i]); } return forClassWithGenerics(clazz, resolvableGenerics); } /** * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared generics. * @param clazz the class (or interface) to introspect * @param generics the generics of the class * @return a {@link ResolvableType} for the specific class and generics * @see #forClassWithGenerics(Class, Class...) */ public static ResolvableType forClassWithGenerics(Class<?> clazz, ResolvableType... generics) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(generics, "Generics array must not be null"); TypeVariable<?>[] variables = clazz.getTypeParameters(); Assert.isTrue(variables.length == generics.length, "Mismatched number of generics specified"); Type[] arguments = new Type[generics.length]; for (int i = 0; i < generics.length; i++) { ResolvableType generic = generics[i]; Type argument = (generic != null ? generic.getType() : null); arguments[i] = (argument != null && !(argument instanceof TypeVariable) ? argument : variables[i]); } ParameterizedType syntheticType = new SyntheticParameterizedType(clazz, arguments); return forType(syntheticType, new TypeVariablesVariableResolver(variables, generics)); } // public static ResolvableType forInstance(Object instance) { // Assert.notNull(instance, "Instance must not be null"); // if (instance instanceof ResolvableTypeProvider) { // ResolvableType type = ((ResolvableTypeProvider) instance).getResolvableType(); // if (type != null) { // return type; // } // } // return ResolvableType.forClass(instance.getClass()); // } // /** // * Return a {@link ResolvableType} for the specified {@link Field}. // * @param field the source field // * @return a {@link ResolvableType} for the specified field // * @see #forField(Field, Class) // */ // public static ResolvableType forField(Field field) { // Assert.notNull(field, "Field must not be null"); // return forType(null, new FieldTypeProvider(field), null); // } // /** // * Return a {@link ResolvableType} for the specified {@link Field} with a given // * implementation. // * <p>Use this variant when the class that declares the field includes generic // * parameter variables that are satisfied by the implementation class. // * @param field the source field // * @param implementationClass the implementation class // * @return a {@link ResolvableType} for the specified field // * @see #forField(Field) // */ // public static ResolvableType forField(Field field, Class<?> implementationClass) { // Assert.notNull(field, "Field must not be null"); // ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass()); // return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()); // } // /** // * Return a {@link ResolvableType} for the specified {@link Field} with a given // * implementation. // * <p>Use this variant when the class that declares the field includes generic // * parameter variables that are satisfied by the implementation type. // * @param field the source field // * @param implementationType the implementation type // * @return a {@link ResolvableType} for the specified field // * @see #forField(Field) // */ // public static ResolvableType forField(Field field, ResolvableType implementationType) { // Assert.notNull(field, "Field must not be null"); // ResolvableType owner = (implementationType != null ? implementationType : NONE); // owner = owner.as(field.getDeclaringClass()); // return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()); // } // /** // * Return a {@link ResolvableType} for the specified {@link Field} with the // * given nesting level. // * @param field the source field // * @param nestingLevel the nesting level (1 for the outer level; 2 for a nested // * generic type; etc) // * @see #forField(Field) // */ // public static ResolvableType forField(Field field, int nestingLevel) { // Assert.notNull(field, "Field must not be null"); // return forType(null, new FieldTypeProvider(field), null).getNested(nestingLevel); // } // /** // * Return a {@link ResolvableType} for the specified {@link Field} with a given // * implementation and the given nesting level. // * <p>Use this variant when the class that declares the field includes generic // * parameter variables that are satisfied by the implementation class. // * @param field the source field // * @param nestingLevel the nesting level (1 for the outer level; 2 for a nested // * generic type; etc) // * @param implementationClass the implementation class // * @return a {@link ResolvableType} for the specified field // * @see #forField(Field) // */ // public static ResolvableType forField(Field field, int nestingLevel, Class<?> implementationClass) { // Assert.notNull(field, "Field must not be null"); // ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass()); // return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()).getNested(nestingLevel); // } /** * Return a {@link ResolvableType} for the specified {@link Constructor} parameter. * @param constructor the source constructor (must not be {@code null}) * @param parameterIndex the parameter index * @return a {@link ResolvableType} for the specified constructor parameter * @see #forConstructorParameter(Constructor, int, Class) */ public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex) { Assert.notNull(constructor, "Constructor must not be null"); return forMethodParameter(new MethodParameter(constructor, parameterIndex)); } /** * Return a {@link ResolvableType} for the specified {@link Constructor} parameter * with a given implementation. Use this variant when the class that declares the * constructor includes generic parameter variables that are satisfied by the * implementation class. * @param constructor the source constructor (must not be {@code null}) * @param parameterIndex the parameter index * @param implementationClass the implementation class * @return a {@link ResolvableType} for the specified constructor parameter * @see #forConstructorParameter(Constructor, int) */ public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex, Class<?> implementationClass) { Assert.notNull(constructor, "Constructor must not be null"); MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex); methodParameter.setContainingClass(implementationClass); return forMethodParameter(methodParameter); } /** * Return a {@link ResolvableType} for the specified {@link Method} return type. * @param method the source for the method return type * @return a {@link ResolvableType} for the specified method return * @see #forMethodReturnType(Method, Class) */ public static ResolvableType forMethodReturnType(Method method) { Assert.notNull(method, "Method must not be null"); return forMethodParameter(new MethodParameter(method, -1)); } /** * Return a {@link ResolvableType} for the specified {@link Method} return type. * Use this variant when the class that declares the method includes generic * parameter variables that are satisfied by the implementation class. * @param method the source for the method return type * @param implementationClass the implementation class * @return a {@link ResolvableType} for the specified method return * @see #forMethodReturnType(Method) */ public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) { Assert.notNull(method, "Method must not be null"); MethodParameter methodParameter = new MethodParameter(method, -1); methodParameter.setContainingClass(implementationClass); return forMethodParameter(methodParameter); } /** * Return a {@link ResolvableType} for the specified {@link Method} parameter. * @param method the source method (must not be {@code null}) * @param parameterIndex the parameter index * @return a {@link ResolvableType} for the specified method parameter * @see #forMethodParameter(Method, int, Class) * @see #forMethodParameter(MethodParameter) */ public static ResolvableType forMethodParameter(Method method, int parameterIndex) { Assert.notNull(method, "Method must not be null"); return forMethodParameter(new MethodParameter(method, parameterIndex)); } /** * Return a {@link ResolvableType} for the specified {@link Method} parameter with a * given implementation. Use this variant when the class that declares the method * includes generic parameter variables that are satisfied by the implementation class. * @param method the source method (must not be {@code null}) * @param parameterIndex the parameter index * @param implementationClass the implementation class * @return a {@link ResolvableType} for the specified method parameter * @see #forMethodParameter(Method, int, Class) * @see #forMethodParameter(MethodParameter) */ public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class<?> implementationClass) { Assert.notNull(method, "Method must not be null"); MethodParameter methodParameter = new MethodParameter(method, parameterIndex); methodParameter.setContainingClass(implementationClass); return forMethodParameter(methodParameter); } /** * Return a {@link ResolvableType} for the specified {@link MethodParameter}. * @param methodParameter the source method parameter (must not be {@code null}) * @return a {@link ResolvableType} for the specified method parameter * @see #forMethodParameter(Method, int) */ public static ResolvableType forMethodParameter(MethodParameter methodParameter) { return forMethodParameter(methodParameter, (Type) null); } // /** // * Return a {@link ResolvableType} for the specified {@link MethodParameter} with a // * given implementation type. Use this variant when the class that declares the method // * includes generic parameter variables that are satisfied by the implementation type. // * @param methodParameter the source method parameter (must not be {@code null}) // * @param implementationType the implementation type // * @return a {@link ResolvableType} for the specified method parameter // * @see #forMethodParameter(MethodParameter) // */ // public static ResolvableType forMethodParameter(MethodParameter methodParameter, // ResolvableType implementationType) { // // Assert.notNull(methodParameter, "MethodParameter must not be null"); // implementationType = (implementationType != null ? implementationType : // forType(methodParameter.getContainingClass())); // ResolvableType owner = implementationType.as(methodParameter.getDeclaringClass()); // return forType(null, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). // getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); // } /** * Return a {@link ResolvableType} for the specified {@link MethodParameter}, * overriding the target type to resolve with a specific given type. * @param methodParameter the source method parameter (must not be {@code null}) * @param targetType the type to resolve (a part of the method parameter's type) * @return a {@link ResolvableType} for the specified method parameter * @see #forMethodParameter(Method, int) */ public static ResolvableType forMethodParameter(MethodParameter methodParameter, Type targetType) { Assert.notNull(methodParameter, "MethodParameter must not be null"); ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); return forType(targetType, new SerializableTypeWrapper.MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); } // static void resolveMethodParameter(MethodParameter methodParameter) { // Assert.notNull(methodParameter, "MethodParameter must not be null"); // ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); // methodParameter.setParameterType( // forType(null, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).resolve()); // } /** * Return a {@link ResolvableType} as a array of the specified {@code componentType}. * @param componentType the component type * @return a {@link ResolvableType} as an array of the specified component type */ public static ResolvableType forArrayComponent(ResolvableType componentType) { Assert.notNull(componentType, "Component type must not be null"); Class<?> arrayClass = Array.newInstance(componentType.resolve(), 0).getClass(); return new ResolvableType(arrayClass, null, null, componentType); } /** * Return a {@link ResolvableType} for the specified {@link Type}. * <p>Note: The resulting {@link ResolvableType} instance may not be {@link Serializable}. * @param type the source type (potentially {@code null}) * @return a {@link ResolvableType} for the specified {@link Type} * @see #forType(Type, ResolvableType) */ public static ResolvableType forType( Type type) { return forType(type, null, null); } /** * Return a {@link ResolvableType} for the specified {@link Type} backed by the given * owner type. * <p>Note: The resulting {@link ResolvableType} instance may not be {@link Serializable}. * @param type the source type or {@code null} * @param owner the owner type used to resolve variables * @return a {@link ResolvableType} for the specified {@link Type} and owner * @see #forType(Type) */ public static ResolvableType forType( Type type, ResolvableType owner) { VariableResolver variableResolver = null; if (owner != null) { variableResolver = owner.asVariableResolver(); } return forType(type, variableResolver); } // public static ResolvableType forType(ParameterizedTypeReference<?> typeReference) { // return forType(typeReference.getType(), null, null); // } /** * Return a {@link ResolvableType} for the specified {@link Type} backed by a given * {@link VariableResolver}. * @param type the source type or {@code null} * @param variableResolver the variable resolver or {@code null} * @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver} */ static ResolvableType forType( Type type, VariableResolver variableResolver) { return forType(type, null, variableResolver); } /** * Return a {@link ResolvableType} for the specified {@link Type} backed by a given * {@link VariableResolver}. * @param type the source type or {@code null} * @param typeProvider the type provider or {@code null} * @param variableResolver the variable resolver or {@code null} * @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver} */ static ResolvableType forType( Type type, SerializableTypeWrapper.TypeProvider typeProvider, VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } /** * Clear the internal {@code ResolvableType}/{@code SerializableTypeWrapper} cache. * @since 4.2 */ public static void clearCache() { cache.clear(); SerializableTypeWrapper.cache.clear(); } /** * Strategy interface used to resolve {@link TypeVariable TypeVariables}. */ interface VariableResolver extends Serializable { /** * Return the source of the resolver (used for hashCode and equals). */ Object getSource(); /** * Resolve the specified variable. * @param variable the variable to resolve * @return the resolved variable, or {@code null} if not found */ ResolvableType resolveVariable(TypeVariable<?> variable); } @SuppressWarnings("serial") private class DefaultVariableResolver implements VariableResolver { @Override public ResolvableType resolveVariable(TypeVariable<?> variable) { return ResolvableType.this.resolveVariable(variable); } @Override public Object getSource() { return ResolvableType.this; } } @SuppressWarnings("serial") private static class TypeVariablesVariableResolver implements VariableResolver { private final TypeVariable<?>[] variables; private final ResolvableType[] generics; public TypeVariablesVariableResolver(TypeVariable<?>[] variables, ResolvableType[] generics) { this.variables = variables; this.generics = generics; } @Override public ResolvableType resolveVariable(TypeVariable<?> variable) { for (int i = 0; i < this.variables.length; i++) { TypeVariable<?> v1 = SerializableTypeWrapper.unwrap(this.variables[i]); TypeVariable<?> v2 = SerializableTypeWrapper.unwrap(variable); if (ObjectUtils.nullSafeEquals(v1, v2)) { return this.generics[i]; } } return null; } @Override public Object getSource() { return this.generics; } } private static final class SyntheticParameterizedType implements ParameterizedType, Serializable { private final Type rawType; private final Type[] typeArguments; public SyntheticParameterizedType(Type rawType, Type[] typeArguments) { this.rawType = rawType; this.typeArguments = typeArguments; } @Override public String getTypeName() { StringBuilder result = new StringBuilder(this.rawType.getTypeName()); if (this.typeArguments.length > 0) { result.append('<'); for (int i = 0; i < this.typeArguments.length; i++) { if (i > 0) { result.append(", "); } result.append(this.typeArguments[i].getTypeName()); } result.append('>'); } return result.toString(); } @Override public Type getOwnerType() { return null; } @Override public Type getRawType() { return this.rawType; } @Override public Type[] getActualTypeArguments() { return this.typeArguments; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof ParameterizedType)) { return false; } ParameterizedType otherType = (ParameterizedType) other; return (otherType.getOwnerType() == null && this.rawType.equals(otherType.getRawType()) && Arrays.equals(this.typeArguments, otherType.getActualTypeArguments())); } @Override public int hashCode() { return (this.rawType.hashCode() * 31 + Arrays.hashCode(this.typeArguments)); } @Override public String toString() { return getTypeName(); } } /** * Internal helper to handle bounds from {@link WildcardType WildcardTypes}. */ private static class WildcardBounds { private final Kind kind; private final ResolvableType[] bounds; /** * Internal constructor to create a new {@link WildcardBounds} instance. * @param kind the kind of bounds * @param bounds the bounds * @see #get(ResolvableType) */ public WildcardBounds(Kind kind, ResolvableType[] bounds) { this.kind = kind; this.bounds = bounds; } /** * Return {@code true} if this bounds is the same kind as the specified bounds. */ public boolean isSameKind(WildcardBounds bounds) { return this.kind == bounds.kind; } /** * Return {@code true} if this bounds is assignable to all the specified types. * @param types the types to test against * @return {@code true} if this bounds is assignable to all types */ public boolean isAssignableFrom(ResolvableType... types) { for (ResolvableType bound : this.bounds) { for (ResolvableType type : types) { if (!isAssignable(bound, type)) { return false; } } } return true; } private boolean isAssignable(ResolvableType source, ResolvableType from) { return (this.kind == Kind.UPPER ? source.isAssignableFrom(from) : from.isAssignableFrom(source)); } /** * Return the underlying bounds. */ public ResolvableType[] getBounds() { return this.bounds; } /** * Get a {@link WildcardBounds} instance for the specified type, returning * {@code null} if the specified type cannot be resolved to a {@link WildcardType}. * @param type the source type * @return a {@link WildcardBounds} instance or {@code null} */ public static WildcardBounds get(ResolvableType type) { ResolvableType resolveToWildcard = type; while (!(resolveToWildcard.getType() instanceof WildcardType)) { if (resolveToWildcard == NONE) { return null; } resolveToWildcard = resolveToWildcard.resolveType(); } WildcardType wildcardType = (WildcardType) resolveToWildcard.type; Kind boundsType = (wildcardType.getLowerBounds().length > 0 ? Kind.LOWER : Kind.UPPER); Type[] bounds = (boundsType == Kind.UPPER ? wildcardType.getUpperBounds() : wildcardType.getLowerBounds()); ResolvableType[] resolvableBounds = new ResolvableType[bounds.length]; for (int i = 0; i < bounds.length; i++) { resolvableBounds[i] = ResolvableType.forType(bounds[i], type.variableResolver); } return new WildcardBounds(boundsType, resolvableBounds); } /** * The various kinds of bounds. */ enum Kind {UPPER, LOWER} } /** * Internal {@link Type} used to represent an empty value. */ @SuppressWarnings("serial") static class EmptyType implements Type, Serializable { static final Type INSTANCE = new EmptyType(); Object readResolve() { return INSTANCE; } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/ResolvableType.java
Java
apache-2.0
63,624
package cn.bugstack.springframework.core; import cn.bugstack.springframework.core.util.ObjectUtils; import cn.bugstack.springframework.util.ReflectionUtils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.lang.reflect.*; import java.util.concurrent.ConcurrentHashMap; /** * @author zhangdd on 2022/2/27 */ public final class SerializableTypeWrapper { private static final Class<?>[] SUPPORTED_SERIALIZABLE_TYPES = { GenericArrayType.class, ParameterizedType.class, TypeVariable.class, WildcardType.class}; static final ConcurrentHashMap<Type, Type> cache = new ConcurrentHashMap<>(256); static Type forTypeProvider(TypeProvider provider) { Type providedType = provider.getType(); if (providedType == null || providedType instanceof Serializable) { // No serializable type wrapping necessary (e.g. for java.lang.Class) return providedType; } if (GraalDetector.inImageCode() || !Serializable.class.isAssignableFrom(Class.class)) { // Let's skip any wrapping attempts if types are generally not serializable in // the current runtime environment (even java.lang.Class itself, e.g. on Graal) return providedType; } // Obtain a serializable type proxy for the given provider... Type cached = cache.get(providedType); if (cached != null) { return cached; } for (Class<?> type : SUPPORTED_SERIALIZABLE_TYPES) { if (type.isInstance(providedType)) { ClassLoader classLoader = provider.getClass().getClassLoader(); Class<?>[] interfaces = new Class<?>[] {type, SerializableTypeProxy.class, Serializable.class}; InvocationHandler handler = new TypeProxyInvocationHandler(provider); cached = (Type) Proxy.newProxyInstance(classLoader, interfaces, handler); cache.put(providedType, cached); return cached; } } throw new IllegalArgumentException("Unsupported Type class: " + providedType.getClass().getName()); } public static <T extends Type> T unwrap(T type) { Type unwrapped = type; while (unwrapped instanceof SerializableTypeProxy) { unwrapped = ((SerializableTypeProxy) type).getTypeProvider().getType(); } return (unwrapped != null ? (T) unwrapped : type); } interface TypeProvider extends Serializable { /** * Return the (possibly non {@link Serializable}) {@link Type}. */ Type getType(); /** * Return the source of the type, or {@code null} if not known. * <p>The default implementations returns {@code null}. */ default Object getSource() { return null; } } static class MethodParameterTypeProvider implements TypeProvider { private final String methodName; private final Class<?>[] parameterTypes; private final Class<?> declaringClass; private final int parameterIndex; private transient MethodParameter methodParameter; public MethodParameterTypeProvider(MethodParameter methodParameter) { this.methodName = (methodParameter.getMethod() != null ? methodParameter.getMethod().getName() : null); this.parameterTypes = methodParameter.getExecutable().getParameterTypes(); this.declaringClass = methodParameter.getDeclaringClass(); this.parameterIndex = methodParameter.getParameterIndex(); this.methodParameter = methodParameter; } @Override public Type getType() { return this.methodParameter.getGenericParameterType(); } @Override public Object getSource() { return this.methodParameter; } private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { inputStream.defaultReadObject(); try { if (this.methodName != null) { this.methodParameter = new MethodParameter( this.declaringClass.getDeclaredMethod(this.methodName, this.parameterTypes), this.parameterIndex); } else { this.methodParameter = new MethodParameter( this.declaringClass.getDeclaredConstructor(this.parameterTypes), this.parameterIndex); } } catch (Throwable ex) { throw new IllegalStateException("Could not find original class structure", ex); } } } interface SerializableTypeProxy { /** * Return the underlying type provider. */ TypeProvider getTypeProvider(); } private static class TypeProxyInvocationHandler implements InvocationHandler, Serializable { private final TypeProvider provider; public TypeProxyInvocationHandler(TypeProvider provider) { this.provider = provider; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("equals") && args != null) { Object other = args[0]; // Unwrap proxies for speed if (other instanceof Type) { other = unwrap((Type) other); } return ObjectUtils.nullSafeEquals(this.provider.getType(), other); } else if (method.getName().equals("hashCode")) { return ObjectUtils.nullSafeHashCode(this.provider.getType()); } else if (method.getName().equals("getTypeProvider")) { return this.provider; } if (Type.class == method.getReturnType() && args == null) { return forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, -1)); } else if (Type[].class == method.getReturnType() && args == null) { Type[] result = new Type[((Type[]) method.invoke(this.provider.getType())).length]; for (int i = 0; i < result.length; i++) { result[i] = forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, i)); } return result; } try { return method.invoke(this.provider.getType(), args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } static class MethodInvokeTypeProvider implements TypeProvider { private final TypeProvider provider; private final String methodName; private final Class<?> declaringClass; private final int index; private transient Method method; private transient volatile Object result; public MethodInvokeTypeProvider(TypeProvider provider, Method method, int index) { this.provider = provider; this.methodName = method.getName(); this.declaringClass = method.getDeclaringClass(); this.index = index; this.method = method; } @Override public Type getType() { Object result = this.result; if (result == null) { // Lazy invocation of the target method on the provided type result = ReflectionUtils.invokeMethod(this.method, this.provider.getType()); // Cache the result for further calls to getType() this.result = result; } return (result instanceof Type[] ? ((Type[]) result)[this.index] : (Type) result); } @Override public Object getSource() { return null; } private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { inputStream.defaultReadObject(); Method method = ReflectionUtils.findMethod(this.declaringClass, this.methodName); if (method == null) { throw new IllegalStateException("Cannot find method on deserialization: " + this.methodName); } if (method.getReturnType() != Type.class && method.getReturnType() != Type[].class) { throw new IllegalStateException( "Invalid return type on deserialized method - needs to be Type or Type[]: " + method); } this.method = method; } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/SerializableTypeWrapper.java
Java
apache-2.0
8,735
package cn.bugstack.springframework.core.annotation; import cn.bugstack.springframework.core.util.ObjectUtils; import cn.hutool.core.lang.Assert; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.List; import java.util.Map; /** * @author zhangdd on 2022/2/27 */ abstract class AbstractAliasAwareAnnotationAttributeExtractor<S> implements AnnotationAttributeExtractor<S> { private final Class<? extends Annotation> annotationType; private final Object annotatedElement; private final S source; private final Map<String, List<String>> attributeAliasMap; /** * Construct a new {@code AbstractAliasAwareAnnotationAttributeExtractor}. * @param annotationType the annotation type to synthesize; never {@code null} * @param annotatedElement the element that is annotated with the annotation * of the supplied type; may be {@code null} if unknown * @param source the underlying source of annotation attributes; never {@code null} */ AbstractAliasAwareAnnotationAttributeExtractor( Class<? extends Annotation> annotationType, Object annotatedElement, S source) { Assert.notNull(annotationType, "annotationType must not be null"); Assert.notNull(source, "source must not be null"); this.annotationType = annotationType; this.annotatedElement = annotatedElement; this.source = source; this.attributeAliasMap = AnnotationUtils.getAttributeAliasMap(annotationType); } @Override public final Class<? extends Annotation> getAnnotationType() { return this.annotationType; } @Override public final Object getAnnotatedElement() { return this.annotatedElement; } @Override public final S getSource() { return this.source; } @Override public final Object getAttributeValue(Method attributeMethod) { String attributeName = attributeMethod.getName(); Object attributeValue = getRawAttributeValue(attributeMethod); List<String> aliasNames = this.attributeAliasMap.get(attributeName); if (aliasNames != null) { Object defaultValue = AnnotationUtils.getDefaultValue(this.annotationType, attributeName); for (String aliasName : aliasNames) { Object aliasValue = getRawAttributeValue(aliasName); if (!ObjectUtils.nullSafeEquals(attributeValue, aliasValue) && !ObjectUtils.nullSafeEquals(attributeValue, defaultValue) && !ObjectUtils.nullSafeEquals(aliasValue, defaultValue)) { String elementName = (this.annotatedElement != null ? this.annotatedElement.toString() : "unknown element"); throw new AnnotationConfigurationException(String.format( "In annotation [%s] declared on %s and synthesized from [%s], attribute '%s' and its " + "alias '%s' are present with values of [%s] and [%s], but only one is permitted.", this.annotationType.getName(), elementName, this.source, attributeName, aliasName, ObjectUtils.nullSafeToString(attributeValue), ObjectUtils.nullSafeToString(aliasValue))); } // If the user didn't declare the annotation with an explicit value, // use the value of the alias instead. if (ObjectUtils.nullSafeEquals(attributeValue, defaultValue)) { attributeValue = aliasValue; } } } return attributeValue; } /** * Get the raw, unmodified attribute value from the underlying * {@linkplain #getSource source} that corresponds to the supplied * attribute method. */ protected abstract Object getRawAttributeValue(Method attributeMethod); /** * Get the raw, unmodified attribute value from the underlying * {@linkplain #getSource source} that corresponds to the supplied * attribute name. */ protected abstract Object getRawAttributeValue(String attributeName); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AbstractAliasAwareAnnotationAttributeExtractor.java
Java
apache-2.0
4,185
package cn.bugstack.springframework.core.annotation; import java.lang.annotation.*; /** * @author zhangdd on 2022/2/27 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AliasFor { /** * Alias for {@link #attribute}. * <p>Intended to be used instead of {@link #attribute} when {@link #annotation} * is not declared &mdash; for example: {@code @AliasFor("value")} instead of * {@code @AliasFor(attribute = "value")}. */ @AliasFor("attribute") String value() default ""; /** * The name of the attribute that <em>this</em> attribute is an alias for. * @see #value */ @AliasFor("value") String attribute() default ""; /** * The type of annotation in which the aliased {@link #attribute} is declared. * <p>Defaults to {@link Annotation}, implying that the aliased attribute is * declared in the same annotation as <em>this</em> attribute. */ Class<? extends Annotation> annotation() default Annotation.class; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AliasFor.java
Java
apache-2.0
1,040
package cn.bugstack.springframework.core.annotation; import cn.bugstack.springframework.core.BridgeMethodResolver; import cn.hutool.core.collection.CollUtil; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.*; /** * @author zhangdd on 2022/2/26 */ public class AnnotatedElementUtils { private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; public static AnnotationAttributes findMergedAnnotationAttributes(AnnotatedElement element, Class<? extends Annotation> annotationType, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { return searchWithFindSemantics(element, annotationType, null, new MergedAnnotationAttributesProcessor(classValuesAsString, nestedAnnotationsAsMap)); } private static <T> T searchWithFindSemantics(AnnotatedElement element, Class<? extends Annotation> annotationType, String annotationName, Processor<T> processor) { return searchWithFindSemantics(element, (null != annotationType ? Collections.singleton(annotationType) : Collections.emptySet()), annotationName, null, processor); } private static <T> T searchWithFindSemantics(AnnotatedElement element, Set<Class<? extends Annotation>> annotationType, String annotationName, Class<? extends Annotation> containerType, Processor<T> processor) { if (containerType != null && !processor.aggregates()) { throw new IllegalArgumentException("Search for repeatable annotations must supply an aggregating Processor"); } return searchWithFindSemantics(element, annotationType, annotationName, containerType, processor, new HashSet<>(), 0); } private static <T> T searchWithFindSemantics(AnnotatedElement element, Set<Class<? extends Annotation>> annotationTypes, String annotationName, Class<? extends Annotation> containerType, Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth) { if (visited.add(element)) { try { // Locally declared annotations (ignoring @Inherited) Annotation[] annotations = AnnotationUtils.getDeclaredAnnotations(element); if (annotations.length > 0) { List<T> aggregatedResults = (processor.aggregates() ? new ArrayList<>() : null); // Search in local annotations for (Annotation annotation : annotations) { Class<? extends Annotation> currentAnnotationType = annotation.annotationType(); if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) { if (annotationTypes.contains(currentAnnotationType) || currentAnnotationType.getName().equals(annotationName) || processor.alwaysProcesses()) { T result = processor.process(element, annotation, metaDepth); if (result != null) { if (aggregatedResults != null && metaDepth == 0) { aggregatedResults.add(result); } else { return result; } } } // Repeatable annotations in container? else if (currentAnnotationType == containerType) { for (Annotation contained : getRawAnnotationsFromContainer(element, annotation)) { T result = processor.process(element, contained, metaDepth); if (aggregatedResults != null && result != null) { // No need to post-process since repeatable annotations within a // container cannot be composed annotations. aggregatedResults.add(result); } } } } } // Recursively search in meta-annotations for (Annotation annotation : annotations) { Class<? extends Annotation> currentAnnotationType = annotation.annotationType(); if (!AnnotationUtils.hasPlainJavaAnnotationsOnly(currentAnnotationType)) { T result = searchWithFindSemantics(currentAnnotationType, annotationTypes, annotationName, containerType, processor, visited, metaDepth + 1); if (result != null) { processor.postProcess(currentAnnotationType, annotation, result); if (aggregatedResults != null && metaDepth == 0) { aggregatedResults.add(result); } else { return result; } } } } if (!CollUtil.isEmpty(aggregatedResults)) { // Prepend to support top-down ordering within class hierarchies processor.getAggregatedResults().addAll(0, aggregatedResults); } } if (element instanceof Method) { Method method = (Method) element; T result; // Search on possibly bridged method Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method); if (resolvedMethod != method) { result = searchWithFindSemantics(resolvedMethod, annotationTypes, annotationName, containerType, processor, visited, metaDepth); if (result != null) { return result; } } // Search on methods in interfaces declared locally Class<?>[] ifcs = method.getDeclaringClass().getInterfaces(); if (ifcs.length > 0) { result = searchOnInterfaces(method, annotationTypes, annotationName, containerType, processor, visited, metaDepth, ifcs); if (result != null) { return result; } } // Search on methods in class hierarchy and interface hierarchy Class<?> clazz = method.getDeclaringClass(); while (true) { clazz = clazz.getSuperclass(); if (clazz == null || clazz == Object.class) { break; } Set<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethodsInBaseType(clazz); if (!annotatedMethods.isEmpty()) { for (Method annotatedMethod : annotatedMethods) { if (AnnotationUtils.isOverride(method, annotatedMethod)) { Method resolvedSuperMethod = BridgeMethodResolver.findBridgedMethod(annotatedMethod); result = searchWithFindSemantics(resolvedSuperMethod, annotationTypes, annotationName, containerType, processor, visited, metaDepth); if (result != null) { return result; } } } } // Search on interfaces declared on superclass result = searchOnInterfaces(method, annotationTypes, annotationName, containerType, processor, visited, metaDepth, clazz.getInterfaces()); if (result != null) { return result; } } } else if (element instanceof Class) { Class<?> clazz = (Class<?>) element; if (!Annotation.class.isAssignableFrom(clazz)) { // Search on interfaces for (Class<?> ifc : clazz.getInterfaces()) { T result = searchWithFindSemantics(ifc, annotationTypes, annotationName, containerType, processor, visited, metaDepth); if (result != null) { return result; } } // Search on superclass Class<?> superclass = clazz.getSuperclass(); if (superclass != null && superclass != Object.class) { T result = searchWithFindSemantics(superclass, annotationTypes, annotationName, containerType, processor, visited, metaDepth); if (result != null) { return result; } } } } } catch (Throwable ex) { AnnotationUtils.handleIntrospectionFailure(element, ex); } } return null; } private static <T> T searchOnInterfaces(Method method, Set<Class<? extends Annotation>> annotationTypes, String annotationName, Class<? extends Annotation> containerType, Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth, Class<?>[] ifcs) { for (Class<?> ifc : ifcs) { Set<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethodsInBaseType(ifc); if (!annotatedMethods.isEmpty()) { for (Method annotatedMethod : annotatedMethods) { if (AnnotationUtils.isOverride(method, annotatedMethod)) { T result = searchWithFindSemantics(annotatedMethod, annotationTypes, annotationName, containerType, processor, visited, metaDepth); if (result != null) { return result; } } } } } return null; } private static <A extends Annotation> A[] getRawAnnotationsFromContainer(AnnotatedElement element, Annotation container) { try { A[] value = (A[]) AnnotationUtils.getValue(container); if (value != null) { return value; } } catch (Throwable ex) { AnnotationUtils.handleIntrospectionFailure(element, ex); } // Unable to read value from repeating annotation container -> ignore it. return (A[]) EMPTY_ANNOTATION_ARRAY; } public static AnnotatedElement forAnnotations(final Annotation... annotations) { return new AnnotatedElement() { @Override public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { for (Annotation annotation : annotations) { if (annotation.annotationType() == annotationClass) { return (T) annotation; } } return null; } @Override public Annotation[] getAnnotations() { return annotations; } @Override public Annotation[] getDeclaredAnnotations() { return annotations; } }; } private static class MergedAnnotationAttributesProcessor implements Processor<AnnotationAttributes> { private final boolean classValuesAsString; private final boolean nestedAnnotationsAsMap; private final boolean aggregates; private final List<AnnotationAttributes> aggregatedResults; MergedAnnotationAttributesProcessor() { this(false, false, false); } MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap) { this(classValuesAsString, nestedAnnotationsAsMap, false); } MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap, boolean aggregates) { this.classValuesAsString = classValuesAsString; this.nestedAnnotationsAsMap = nestedAnnotationsAsMap; this.aggregates = aggregates; this.aggregatedResults = (aggregates ? new ArrayList<>() : Collections.emptyList()); } @Override public boolean alwaysProcesses() { return false; } @Override public boolean aggregates() { return this.aggregates; } @Override public List<AnnotationAttributes> getAggregatedResults() { return this.aggregatedResults; } @Override public AnnotationAttributes process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) { return AnnotationUtils.retrieveAnnotationAttributes(annotatedElement, annotation, this.classValuesAsString, this.nestedAnnotationsAsMap); } @Override public void postProcess(AnnotatedElement element, Annotation annotation, AnnotationAttributes attributes) { annotation = AnnotationUtils.synthesizeAnnotation(annotation, element); Class<? extends Annotation> targetAnnotationType = attributes.annotationType(); // Track which attribute values have already been replaced so that we can short // circuit the search algorithms. Set<String> valuesAlreadyReplaced = new HashSet<>(); for (Method attributeMethod : AnnotationUtils.getAttributeMethods(annotation.annotationType())) { String attributeName = attributeMethod.getName(); String attributeOverrideName = AnnotationUtils.getAttributeOverrideName(attributeMethod, targetAnnotationType); // Explicit annotation attribute override declared via @AliasFor if (attributeOverrideName != null) { if (valuesAlreadyReplaced.contains(attributeOverrideName)) { continue; } List<String> targetAttributeNames = new ArrayList<>(); targetAttributeNames.add(attributeOverrideName); valuesAlreadyReplaced.add(attributeOverrideName); // Ensure all aliased attributes in the target annotation are overridden. (SPR-14069) List<String> aliases = AnnotationUtils.getAttributeAliasMap(targetAnnotationType).get(attributeOverrideName); if (aliases != null) { for (String alias : aliases) { if (!valuesAlreadyReplaced.contains(alias)) { targetAttributeNames.add(alias); valuesAlreadyReplaced.add(alias); } } } overrideAttributes(element, annotation, attributes, attributeName, targetAttributeNames); } // Implicit annotation attribute override based on convention else if (!AnnotationUtils.VALUE.equals(attributeName) && attributes.containsKey(attributeName)) { overrideAttribute(element, annotation, attributes, attributeName, attributeName); } } } private void overrideAttributes(AnnotatedElement element, Annotation annotation, AnnotationAttributes attributes, String sourceAttributeName, List<String> targetAttributeNames) { Object adaptedValue = getAdaptedValue(element, annotation, sourceAttributeName); for (String targetAttributeName : targetAttributeNames) { attributes.put(targetAttributeName, adaptedValue); } } private void overrideAttribute(AnnotatedElement element, Annotation annotation, AnnotationAttributes attributes, String sourceAttributeName, String targetAttributeName) { attributes.put(targetAttributeName, getAdaptedValue(element, annotation, sourceAttributeName)); } private Object getAdaptedValue( AnnotatedElement element, Annotation annotation, String sourceAttributeName) { Object value = AnnotationUtils.getValue(annotation, sourceAttributeName); return AnnotationUtils.adaptValue(element, value, this.classValuesAsString, this.nestedAnnotationsAsMap); } } private interface Processor<T> { T process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth); void postProcess(AnnotatedElement annotatedElement, Annotation annotation, T result); boolean alwaysProcesses(); boolean aggregates(); List<T> getAggregatedResults(); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AnnotatedElementUtils.java
Java
apache-2.0
18,371
package cn.bugstack.springframework.core.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * @author zhangdd on 2022/2/27 */ public interface AnnotationAttributeExtractor<S> { /** * Get the type of annotation that this extractor extracts attribute * values for. */ Class<? extends Annotation> getAnnotationType(); /** * Get the element that is annotated with an annotation of the annotation * type supported by this extractor. * @return the annotated element, or {@code null} if unknown */ Object getAnnotatedElement(); /** * Get the underlying source of annotation attributes. */ S getSource(); /** * Get the attribute value from the underlying {@linkplain #getSource source} * that corresponds to the supplied attribute method. * @param attributeMethod an attribute method from the annotation type * supported by this extractor * @return the value of the annotation attribute */ Object getAttributeValue(Method attributeMethod); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AnnotationAttributeExtractor.java
Java
apache-2.0
1,088
package cn.bugstack.springframework.core.annotation; import cn.hutool.core.lang.Assert; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.util.LinkedHashMap; /** * @author zhangdd on 2022/2/26 */ public class AnnotationAttributes extends LinkedHashMap<String, Object> { private final Class<? extends Annotation> annotationType; boolean validated = false; final String displayName; public AnnotationAttributes(Class<? extends Annotation> annotationType) { Assert.notNull(annotationType, "'annotationType' must not be null"); this.annotationType = annotationType; this.displayName = annotationType.getName(); } public Class<?>[] getClassArray(String attributeName) { return getRequiredAttribute(attributeName, Class[].class); } private <T> T getRequiredAttribute(String attributeName, Class<T> expectedType) { Object value = get(attributeName); if (!expectedType.isInstance(value) && expectedType.isArray() && expectedType.getComponentType().isInstance(value)) { Object array = Array.newInstance(expectedType.getComponentType(), 1); Array.set(array,0,value); value=array; } return (T) value; } public Class<? extends Annotation> annotationType() { return this.annotationType; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AnnotationAttributes.java
Java
apache-2.0
1,395
package cn.bugstack.springframework.core.annotation; /** * @author zhangdd on 2022/2/27 */ public class AnnotationConfigurationException extends RuntimeException{ public AnnotationConfigurationException(String message) { super(message); } public AnnotationConfigurationException(String message, Throwable cause) { super(message, cause); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AnnotationConfigurationException.java
Java
apache-2.0
377
package cn.bugstack.springframework.core.annotation; import cn.bugstack.springframework.core.ResolvableType; import cn.bugstack.springframework.core.util.ConcurrentReferenceHashMap; import cn.bugstack.springframework.core.util.ObjectUtils; import cn.bugstack.springframework.core.util.StringUtils; import cn.bugstack.springframework.util.ClassUtils; import cn.bugstack.springframework.util.ReflectionUtils; import cn.hutool.core.lang.Assert; import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.reflect.*; import java.util.*; /** * @author zhangdd on 2022/2/27 */ public class AnnotationUtils { /** * The attribute name for annotations with a single element. */ public static final String VALUE = "value"; private static final Map<AnnotationCacheKey, Annotation> findAnnotationCache = new ConcurrentReferenceHashMap<>(256); private static final Map<AnnotationCacheKey, Boolean> metaPresentCache = new ConcurrentReferenceHashMap<>(256); private static final Map<AnnotatedElement, Annotation[]> declaredAnnotationsCache = new ConcurrentReferenceHashMap<>(256); private static final Map<Class<?>, Set<Method>> annotatedBaseTypeCache = new ConcurrentReferenceHashMap<>(256); @SuppressWarnings("unused") @Deprecated // just here for older tool versions trying to reflectively clear the cache private static final Map<Class<?>, ?> annotatedInterfaceCache = annotatedBaseTypeCache; private static final Map<Class<? extends Annotation>, Boolean> synthesizableCache = new ConcurrentReferenceHashMap<>(256); private static final Map<Class<? extends Annotation>, Map<String, List<String>>> attributeAliasesCache = new ConcurrentReferenceHashMap<>(256); private static final Map<Class<? extends Annotation>, List<Method>> attributeMethodsCache = new ConcurrentReferenceHashMap<>(256); private static final Map<Method, AliasDescriptor> aliasDescriptorCache = new ConcurrentReferenceHashMap<>(256); // @SuppressWarnings("unchecked") // public static <A extends Annotation> A getAnnotation(Annotation annotation, Class<A> annotationType) { // if (annotationType.isInstance(annotation)) { // return synthesizeAnnotation((A) annotation); // } // Class<? extends Annotation> annotatedElement = annotation.annotationType(); // try { // A metaAnn = annotatedElement.getAnnotation(annotationType); // return (metaAnn != null ? synthesizeAnnotation(metaAnn, annotatedElement) : null); // } // catch (Throwable ex) { // handleIntrospectionFailure(annotatedElement, ex); // return null; // } // } // // public static <A extends Annotation> A getAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) { try { A annotation = annotatedElement.getAnnotation(annotationType); if (annotation == null) { for (Annotation metaAnn : annotatedElement.getAnnotations()) { annotation = metaAnn.annotationType().getAnnotation(annotationType); if (annotation != null) { break; } } } return (annotation != null ? synthesizeAnnotation(annotation, annotatedElement) : null); } catch (Throwable ex) { handleIntrospectionFailure(annotatedElement, ex); return null; } } // public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) { // Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method); // return getAnnotation((AnnotatedElement) resolvedMethod, annotationType); // } // public static Annotation[] getAnnotations(AnnotatedElement annotatedElement) { // try { // return synthesizeAnnotationArray(annotatedElement.getAnnotations(), annotatedElement); // } // catch (Throwable ex) { // handleIntrospectionFailure(annotatedElement, ex); // return null; // } // } // // public static Annotation[] getAnnotations(Method method) { // try { // return synthesizeAnnotationArray(BridgeMethodResolver.findBridgedMethod(method).getAnnotations(), method); // } // catch (Throwable ex) { // handleIntrospectionFailure(method, ex); // return null; // } // } // public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedElement annotatedElement, // Class<A> annotationType) { // // return getRepeatableAnnotations(annotatedElement, annotationType, null); // } // public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedElement annotatedElement, // Class<A> annotationType, Class<? extends Annotation> containerAnnotationType) { // // Set<A> annotations = getDeclaredRepeatableAnnotations(annotatedElement, annotationType, containerAnnotationType); // if (annotations.isEmpty() && annotatedElement instanceof Class) { // Class<?> superclass = ((Class<?>) annotatedElement).getSuperclass(); // if (superclass != null && superclass != Object.class) { // return getRepeatableAnnotations(superclass, annotationType, containerAnnotationType); // } // } // return annotations; // } // public static <A extends Annotation> Set<A> getDeclaredRepeatableAnnotations(AnnotatedElement annotatedElement, // Class<A> annotationType) { // // return getDeclaredRepeatableAnnotations(annotatedElement, annotationType, null); // } // public static <A extends Annotation> Set<A> getDeclaredRepeatableAnnotations(AnnotatedElement annotatedElement, // Class<A> annotationType, Class<? extends Annotation> containerAnnotationType) { // // try { // if (annotatedElement instanceof Method) { // annotatedElement = BridgeMethodResolver.findBridgedMethod((Method) annotatedElement); // } // return new AnnotationCollector<>(annotationType, containerAnnotationType).getResult(annotatedElement); // } // catch (Throwable ex) { // handleIntrospectionFailure(annotatedElement, ex); // return Collections.emptySet(); // } // } // // public static <A extends Annotation> A findAnnotation( // AnnotatedElement annotatedElement, Class<A> annotationType) { // // if (annotationType == null) { // return null; // } // // // Do NOT store result in the findAnnotationCache since doing so could break // // findAnnotation(Class, Class) and findAnnotation(Method, Class). // A ann = findAnnotation(annotatedElement, annotationType, new HashSet<>()); // return (ann != null ? synthesizeAnnotation(ann, annotatedElement) : null); // } // private static <A extends Annotation> A findAnnotation( // AnnotatedElement annotatedElement, Class<A> annotationType, Set<Annotation> visited) { // try { // A annotation = annotatedElement.getDeclaredAnnotation(annotationType); // if (annotation != null) { // return annotation; // } // for (Annotation declaredAnn : getDeclaredAnnotations(annotatedElement)) { // Class<? extends Annotation> declaredType = declaredAnn.annotationType(); // if (!isInJavaLangAnnotationPackage(declaredType) && visited.add(declaredAnn)) { // annotation = findAnnotation((AnnotatedElement) declaredType, annotationType, visited); // if (annotation != null) { // return annotation; // } // } // } // } // catch (Throwable ex) { // handleIntrospectionFailure(annotatedElement, ex); // } // return null; // } // public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) { // Assert.notNull(method, "Method must not be null"); // if (annotationType == null) { // return null; // } // // AnnotationCacheKey cacheKey = new AnnotationCacheKey(method, annotationType); // A result = (A) findAnnotationCache.get(cacheKey); // // if (result == null) { // Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method); // result = findAnnotation((AnnotatedElement) resolvedMethod, annotationType); // if (result == null) { // result = searchOnInterfaces(method, annotationType, method.getDeclaringClass().getInterfaces()); // } // // Class<?> clazz = method.getDeclaringClass(); // while (result == null) { // clazz = clazz.getSuperclass(); // if (clazz == null || clazz == Object.class) { // break; // } // Set<Method> annotatedMethods = getAnnotatedMethodsInBaseType(clazz); // if (!annotatedMethods.isEmpty()) { // for (Method annotatedMethod : annotatedMethods) { // if (isOverride(method, annotatedMethod)) { // Method resolvedSuperMethod = BridgeMethodResolver.findBridgedMethod(annotatedMethod); // result = findAnnotation((AnnotatedElement) resolvedSuperMethod, annotationType); // if (result != null) { // break; // } // } // } // } // if (result == null) { // result = searchOnInterfaces(method, annotationType, clazz.getInterfaces()); // } // } // // if (result != null) { // result = synthesizeAnnotation(result, method); // findAnnotationCache.put(cacheKey, result); // } // } // // return result; // } // private static <A extends Annotation> A searchOnInterfaces(Method method, Class<A> annotationType, Class<?>... ifcs) { // for (Class<?> ifc : ifcs) { // Set<Method> annotatedMethods = getAnnotatedMethodsInBaseType(ifc); // if (!annotatedMethods.isEmpty()) { // for (Method annotatedMethod : annotatedMethods) { // if (isOverride(method, annotatedMethod)) { // A annotation = getAnnotation(annotatedMethod, annotationType); // if (annotation != null) { // return annotation; // } // } // } // } // } // return null; // } static boolean isOverride(Method method, Method candidate) { if (!candidate.getName().equals(method.getName()) || candidate.getParameterCount() != method.getParameterCount()) { return false; } Class<?>[] paramTypes = method.getParameterTypes(); if (Arrays.equals(candidate.getParameterTypes(), paramTypes)) { return true; } for (int i = 0; i < paramTypes.length; i++) { if (paramTypes[i] != ResolvableType.forMethodParameter(candidate, i, method.getDeclaringClass()).resolve()) { return false; } } return true; } static Set<Method> getAnnotatedMethodsInBaseType(Class<?> baseType) { boolean ifcCheck = baseType.isInterface(); if (ifcCheck && ClassUtils.isJavaLanguageInterface(baseType)) { return Collections.emptySet(); } Set<Method> annotatedMethods = annotatedBaseTypeCache.get(baseType); if (annotatedMethods != null) { return annotatedMethods; } Method[] methods = (ifcCheck ? baseType.getMethods() : baseType.getDeclaredMethods()); for (Method baseMethod : methods) { try { // Public methods on interfaces (including interface hierarchy), // non-private (and therefore overridable) methods on base classes if ((ifcCheck || !Modifier.isPrivate(baseMethod.getModifiers())) && hasSearchableAnnotations(baseMethod)) { if (annotatedMethods == null) { annotatedMethods = new HashSet<>(); } annotatedMethods.add(baseMethod); } } catch (Throwable ex) { handleIntrospectionFailure(baseMethod, ex); } } if (annotatedMethods == null) { annotatedMethods = Collections.emptySet(); } annotatedBaseTypeCache.put(baseType, annotatedMethods); return annotatedMethods; } private static boolean hasSearchableAnnotations(Method ifcMethod) { Annotation[] anns = getDeclaredAnnotations(ifcMethod); if (anns.length == 0) { return false; } for (Annotation ann : anns) { String name = ann.annotationType().getName(); if (!name.startsWith("java.lang.") && !name.startsWith("org.springframework.lang.")) { return true; } } return false; } /** * Retrieve a potentially cached array of declared annotations for the * given element. * @param element the annotated element to introspect * @return a potentially cached array of declared annotations * (only for internal iteration purposes, not for external exposure) * @since 5.1 */ static Annotation[] getDeclaredAnnotations(AnnotatedElement element) { if (element instanceof Class || element instanceof Member) { // Class/Field/Method/Constructor returns a defensively cloned array from getDeclaredAnnotations. // Since we use our result for internal iteration purposes only, it's safe to use a shared copy. return declaredAnnotationsCache.computeIfAbsent(element, AnnotatedElement::getDeclaredAnnotations); } return element.getDeclaredAnnotations(); } // public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) { // return findAnnotation(clazz, annotationType, true); // } @SuppressWarnings("unchecked") private static <A extends Annotation> A findAnnotation( Class<?> clazz, Class<A> annotationType, boolean synthesize) { Assert.notNull(clazz, "Class must not be null"); if (annotationType == null) { return null; } AnnotationCacheKey cacheKey = new AnnotationCacheKey(clazz, annotationType); A result = (A) findAnnotationCache.get(cacheKey); if (result == null) { result = findAnnotation(clazz, annotationType, new HashSet<>()); if (result != null && synthesize) { result = synthesizeAnnotation(result, clazz); findAnnotationCache.put(cacheKey, result); } } return result; } private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, Set<Annotation> visited) { try { A annotation = clazz.getDeclaredAnnotation(annotationType); if (annotation != null) { return annotation; } for (Annotation declaredAnn : getDeclaredAnnotations(clazz)) { Class<? extends Annotation> declaredType = declaredAnn.annotationType(); if (!isInJavaLangAnnotationPackage(declaredType) && visited.add(declaredAnn)) { annotation = findAnnotation(declaredType, annotationType, visited); if (annotation != null) { return annotation; } } } } catch (Throwable ex) { handleIntrospectionFailure(clazz, ex); return null; } for (Class<?> ifc : clazz.getInterfaces()) { A annotation = findAnnotation(ifc, annotationType, visited); if (annotation != null) { return annotation; } } Class<?> superclass = clazz.getSuperclass(); if (superclass == null || superclass == Object.class) { return null; } return findAnnotation(superclass, annotationType, visited); } // // public static Class<?> findAnnotationDeclaringClass(Class<? extends Annotation> annotationType, Class<?> clazz) { // if (clazz == null || clazz == Object.class) { // return null; // } // if (isAnnotationDeclaredLocally(annotationType, clazz)) { // return clazz; // } // return findAnnotationDeclaringClass(annotationType, clazz.getSuperclass()); // } // // // public static Class<?> findAnnotationDeclaringClassForTypes( // List<Class<? extends Annotation>> annotationTypes, Class<?> clazz) { // // if (clazz == null || clazz == Object.class) { // return null; // } // for (Class<? extends Annotation> annotationType : annotationTypes) { // if (isAnnotationDeclaredLocally(annotationType, clazz)) { // return clazz; // } // } // return findAnnotationDeclaringClassForTypes(annotationTypes, clazz.getSuperclass()); // } // // public static boolean isAnnotationDeclaredLocally(Class<? extends Annotation> annotationType, Class<?> clazz) { // try { // return (clazz.getDeclaredAnnotation(annotationType) != null); // } // catch (Throwable ex) { // handleIntrospectionFailure(clazz, ex); // return false; // } // } // // public static boolean isAnnotationInherited(Class<? extends Annotation> annotationType, Class<?> clazz) { // return (clazz.isAnnotationPresent(annotationType) && !isAnnotationDeclaredLocally(annotationType, clazz)); // } public static boolean isAnnotationMetaPresent(Class<? extends Annotation> annotationType, Class<? extends Annotation> metaAnnotationType) { Assert.notNull(annotationType, "Annotation type must not be null"); if (metaAnnotationType == null) { return false; } AnnotationCacheKey cacheKey = new AnnotationCacheKey(annotationType, metaAnnotationType); Boolean metaPresent = metaPresentCache.get(cacheKey); if (metaPresent != null) { return metaPresent; } metaPresent = Boolean.FALSE; if (findAnnotation(annotationType, metaAnnotationType, false) != null) { metaPresent = Boolean.TRUE; } metaPresentCache.put(cacheKey, metaPresent); return metaPresent; } static boolean hasPlainJavaAnnotationsOnly( Object annotatedElement) { Class<?> clazz; if (annotatedElement instanceof Class) { clazz = (Class<?>) annotatedElement; } else if (annotatedElement instanceof Member) { clazz = ((Member) annotatedElement).getDeclaringClass(); } else { return false; } String name = clazz.getName(); return (name.startsWith("java") || name.startsWith("org.springframework.lang.")); } // // public static boolean isInJavaLangAnnotationPackage( Annotation annotation) { // return (annotation != null && isInJavaLangAnnotationPackage(annotation.annotationType())); // } static boolean isInJavaLangAnnotationPackage( Class<? extends Annotation> annotationType) { return (annotationType != null && isInJavaLangAnnotationPackage(annotationType.getName())); } public static boolean isInJavaLangAnnotationPackage( String annotationType) { return (annotationType != null && annotationType.startsWith("java.lang.annotation")); } // // public static void validateAnnotation(Annotation annotation) { // for (Method method : getAttributeMethods(annotation.annotationType())) { // Class<?> returnType = method.getReturnType(); // if (returnType == Class.class || returnType == Class[].class) { // try { // method.invoke(annotation); // } // catch (Throwable ex) { // throw new IllegalStateException("Could not obtain annotation attribute value for " + method, ex); // } // } // } // } // // public static Map<String, Object> getAnnotationAttributes(Annotation annotation) { // return getAnnotationAttributes(null, annotation); // } // // public static Map<String, Object> getAnnotationAttributes( // Annotation annotation, boolean classValuesAsString) { // // return getAnnotationAttributes(annotation, classValuesAsString, false); // } // public static AnnotationAttributes getAnnotationAttributes( // Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { // // return getAnnotationAttributes(null, annotation, classValuesAsString, nestedAnnotationsAsMap); // } // public static AnnotationAttributes getAnnotationAttributes( // AnnotatedElement annotatedElement, Annotation annotation) { // // return getAnnotationAttributes(annotatedElement, annotation, false, false); // } // public static AnnotationAttributes getAnnotationAttributes( AnnotatedElement annotatedElement, // Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { // // return getAnnotationAttributes( // (Object) annotatedElement, annotation, classValuesAsString, nestedAnnotationsAsMap); // } private static AnnotationAttributes getAnnotationAttributes( Object annotatedElement, Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { AnnotationAttributes attributes = retrieveAnnotationAttributes(annotatedElement, annotation, classValuesAsString, nestedAnnotationsAsMap); postProcessAnnotationAttributes(annotatedElement, attributes, classValuesAsString, nestedAnnotationsAsMap); return attributes; } static AnnotationAttributes retrieveAnnotationAttributes( Object annotatedElement, Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { Class<? extends Annotation> annotationType = annotation.annotationType(); AnnotationAttributes attributes = new AnnotationAttributes(annotationType); for (Method method : getAttributeMethods(annotationType)) { try { Object attributeValue = method.invoke(annotation); Object defaultValue = method.getDefaultValue(); if (defaultValue != null && ObjectUtils.nullSafeEquals(attributeValue, defaultValue)) { attributeValue = new DefaultValueHolder(defaultValue); } attributes.put(method.getName(), adaptValue(annotatedElement, attributeValue, classValuesAsString, nestedAnnotationsAsMap)); } catch (Throwable ex) { if (ex instanceof InvocationTargetException) { Throwable targetException = ((InvocationTargetException) ex).getTargetException(); rethrowAnnotationConfigurationException(targetException); } throw new IllegalStateException("Could not obtain annotation attribute value for " + method, ex); } } return attributes; } static Object adaptValue( Object annotatedElement, Object value, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { if (classValuesAsString) { if (value instanceof Class) { return ((Class<?>) value).getName(); } else if (value instanceof Class[]) { Class<?>[] clazzArray = (Class<?>[]) value; String[] classNames = new String[clazzArray.length]; for (int i = 0; i < clazzArray.length; i++) { classNames[i] = clazzArray[i].getName(); } return classNames; } } if (value instanceof Annotation) { Annotation annotation = (Annotation) value; if (nestedAnnotationsAsMap) { return getAnnotationAttributes(annotatedElement, annotation, classValuesAsString, true); } else { return synthesizeAnnotation(annotation, annotatedElement); } } if (value instanceof Annotation[]) { Annotation[] annotations = (Annotation[]) value; if (nestedAnnotationsAsMap) { AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[annotations.length]; for (int i = 0; i < annotations.length; i++) { mappedAnnotations[i] = getAnnotationAttributes(annotatedElement, annotations[i], classValuesAsString, true); } return mappedAnnotations; } else { return synthesizeAnnotationArray(annotations, annotatedElement); } } // Fallback return value; } // // public static void registerDefaultValues(AnnotationAttributes attributes) { // // Only do defaults scanning for public annotations; we'd run into // // IllegalAccessExceptions otherwise, and we don't want to mess with // // accessibility in a SecurityManager environment. // Class<? extends Annotation> annotationType = attributes.annotationType(); // if (annotationType != null && Modifier.isPublic(annotationType.getModifiers())) { // // Check declared default values of attributes in the annotation type. // for (Method annotationAttribute : getAttributeMethods(annotationType)) { // String attributeName = annotationAttribute.getName(); // Object defaultValue = annotationAttribute.getDefaultValue(); // if (defaultValue != null && !attributes.containsKey(attributeName)) { // if (defaultValue instanceof Annotation) { // defaultValue = getAnnotationAttributes((Annotation) defaultValue, false, true); // } // else if (defaultValue instanceof Annotation[]) { // Annotation[] realAnnotations = (Annotation[]) defaultValue; // AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length]; // for (int i = 0; i < realAnnotations.length; i++) { // mappedAnnotations[i] = getAnnotationAttributes(realAnnotations[i], false, true); // } // defaultValue = mappedAnnotations; // } // attributes.put(attributeName, new DefaultValueHolder(defaultValue)); // } // } // } // } // public static void postProcessAnnotationAttributes( Object annotatedElement, // AnnotationAttributes attributes, boolean classValuesAsString) { // // postProcessAnnotationAttributes(annotatedElement, attributes, classValuesAsString, false); // } static void postProcessAnnotationAttributes( Object annotatedElement, AnnotationAttributes attributes, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { if (attributes == null) { return; } Class<? extends Annotation> annotationType = attributes.annotationType(); // Track which attribute values have already been replaced so that we can short // circuit the search algorithms. Set<String> valuesAlreadyReplaced = new HashSet<>(); if (!attributes.validated) { // Validate @AliasFor configuration Map<String, List<String>> aliasMap = getAttributeAliasMap(annotationType); aliasMap.forEach((attributeName, aliasedAttributeNames) -> { if (valuesAlreadyReplaced.contains(attributeName)) { return; } Object value = attributes.get(attributeName); boolean valuePresent = (value != null && !(value instanceof DefaultValueHolder)); for (String aliasedAttributeName : aliasedAttributeNames) { if (valuesAlreadyReplaced.contains(aliasedAttributeName)) { continue; } Object aliasedValue = attributes.get(aliasedAttributeName); boolean aliasPresent = (aliasedValue != null && !(aliasedValue instanceof DefaultValueHolder)); // Something to validate or replace with an alias? if (valuePresent || aliasPresent) { if (valuePresent && aliasPresent) { // Since annotation attributes can be arrays, we must use ObjectUtils.nullSafeEquals(). if (!ObjectUtils.nullSafeEquals(value, aliasedValue)) { String elementAsString = (annotatedElement != null ? annotatedElement.toString() : "unknown element"); throw new AnnotationConfigurationException(String.format( "In AnnotationAttributes for annotation [%s] declared on %s, " + "attribute '%s' and its alias '%s' are declared with values of [%s] and [%s], " + "but only one is permitted.", attributes.displayName, elementAsString, attributeName, aliasedAttributeName, ObjectUtils.nullSafeToString(value), ObjectUtils.nullSafeToString(aliasedValue))); } } else if (aliasPresent) { // Replace value with aliasedValue attributes.put(attributeName, adaptValue(annotatedElement, aliasedValue, classValuesAsString, nestedAnnotationsAsMap)); valuesAlreadyReplaced.add(attributeName); } else { // Replace aliasedValue with value attributes.put(aliasedAttributeName, adaptValue(annotatedElement, value, classValuesAsString, nestedAnnotationsAsMap)); valuesAlreadyReplaced.add(aliasedAttributeName); } } } }); attributes.validated = true; } // Replace any remaining placeholders with actual default values for (Map.Entry<String, Object> attributeEntry : attributes.entrySet()) { String attributeName = attributeEntry.getKey(); if (valuesAlreadyReplaced.contains(attributeName)) { continue; } Object value = attributeEntry.getValue(); if (value instanceof DefaultValueHolder) { value = ((DefaultValueHolder) value).defaultValue; attributes.put(attributeName, adaptValue(annotatedElement, value, classValuesAsString, nestedAnnotationsAsMap)); } } } public static Object getValue(Annotation annotation) { return getValue(annotation, VALUE); } public static Object getValue( Annotation annotation, String attributeName) { if (annotation == null || !StringUtils.hasText(attributeName)) { return null; } try { Method method = annotation.annotationType().getDeclaredMethod(attributeName); ReflectionUtils.makeAccessible(method); return method.invoke(annotation); } catch (NoSuchMethodException ex) { return null; } catch (InvocationTargetException ex) { rethrowAnnotationConfigurationException(ex.getTargetException()); throw new IllegalStateException("Could not obtain value for annotation attribute '" + attributeName + "' in " + annotation, ex); } catch (Throwable ex) { handleIntrospectionFailure(annotation.getClass(), ex); return null; } } // // public static Object getDefaultValue(Annotation annotation) { // return getDefaultValue(annotation, VALUE); // } public static Object getDefaultValue( Annotation annotation, String attributeName) { return (annotation != null ? getDefaultValue(annotation.annotationType(), attributeName) : null); } // public static Object getDefaultValue(Class<? extends Annotation> annotationType) { // return getDefaultValue(annotationType, VALUE); // } public static Object getDefaultValue( Class<? extends Annotation> annotationType, String attributeName) { if (annotationType == null || !StringUtils.hasText(attributeName)) { return null; } try { return annotationType.getDeclaredMethod(attributeName).getDefaultValue(); } catch (Throwable ex) { handleIntrospectionFailure(annotationType, ex); return null; } } // static <A extends Annotation> A synthesizeAnnotation(A annotation) { // return synthesizeAnnotation(annotation, null); // } public static <A extends Annotation> A synthesizeAnnotation( A annotation, AnnotatedElement annotatedElement) { return synthesizeAnnotation(annotation, (Object) annotatedElement); } @SuppressWarnings("unchecked") static <A extends Annotation> A synthesizeAnnotation(A annotation, Object annotatedElement) { if (annotation instanceof SynthesizedAnnotation || hasPlainJavaAnnotationsOnly(annotatedElement)) { return annotation; } Class<? extends Annotation> annotationType = annotation.annotationType(); if (!isSynthesizable(annotationType)) { return annotation; } DefaultAnnotationAttributeExtractor attributeExtractor = new DefaultAnnotationAttributeExtractor(annotation, annotatedElement); InvocationHandler handler = new SynthesizedAnnotationInvocationHandler(attributeExtractor); // Can always expose Spring's SynthesizedAnnotation marker since we explicitly check for a // synthesizable annotation before (which needs to declare @AliasFor from the same package) Class<?>[] exposedInterfaces = new Class<?>[] {annotationType, SynthesizedAnnotation.class}; return (A) Proxy.newProxyInstance(annotation.getClass().getClassLoader(), exposedInterfaces, handler); } @SuppressWarnings("unchecked") // public static <A extends Annotation> A synthesizeAnnotation(Map<String, Object> attributes, // Class<A> annotationType, AnnotatedElement annotatedElement) { // // MapAnnotationAttributeExtractor attributeExtractor = // new MapAnnotationAttributeExtractor(attributes, annotationType, annotatedElement); // InvocationHandler handler = new SynthesizedAnnotationInvocationHandler(attributeExtractor); // Class<?>[] exposedInterfaces = (canExposeSynthesizedMarker(annotationType) ? // new Class<?>[] {annotationType, SynthesizedAnnotation.class} : new Class<?>[] {annotationType}); // return (A) Proxy.newProxyInstance(annotationType.getClassLoader(), exposedInterfaces, handler); // } // public static <A extends Annotation> A synthesizeAnnotation(Class<A> annotationType) { // return synthesizeAnnotation(Collections.emptyMap(), annotationType, null); // } static Annotation[] synthesizeAnnotationArray(Annotation[] annotations, Object annotatedElement) { if (hasPlainJavaAnnotationsOnly(annotatedElement)) { return annotations; } Annotation[] synthesized = (Annotation[]) Array.newInstance( annotations.getClass().getComponentType(), annotations.length); for (int i = 0; i < annotations.length; i++) { synthesized[i] = synthesizeAnnotation(annotations[i], annotatedElement); } return synthesized; } // static <A extends Annotation> A[] synthesizeAnnotationArray( // Map<String, Object>[] maps, Class<A> annotationType) { // // if (maps == null) { // return null; // } // // A[] synthesized = (A[]) Array.newInstance(annotationType, maps.length); // for (int i = 0; i < maps.length; i++) { // synthesized[i] = synthesizeAnnotation(maps[i], annotationType, null); // } // return synthesized; // } static Map<String, List<String>> getAttributeAliasMap( Class<? extends Annotation> annotationType) { if (annotationType == null) { return Collections.emptyMap(); } Map<String, List<String>> map = attributeAliasesCache.get(annotationType); if (map != null) { return map; } map = new LinkedHashMap<>(); for (Method attribute : getAttributeMethods(annotationType)) { List<String> aliasNames = getAttributeAliasNames(attribute); if (!aliasNames.isEmpty()) { map.put(attribute.getName(), aliasNames); } } attributeAliasesCache.put(annotationType, map); return map; } // private static boolean canExposeSynthesizedMarker(Class<? extends Annotation> annotationType) { // try { // return (Class.forName(SynthesizedAnnotation.class.getName(), false, annotationType.getClassLoader()) == // SynthesizedAnnotation.class); // } // catch (ClassNotFoundException ex) { // return false; // } // } @SuppressWarnings("unchecked") private static boolean isSynthesizable(Class<? extends Annotation> annotationType) { if (hasPlainJavaAnnotationsOnly(annotationType)) { return false; } Boolean synthesizable = synthesizableCache.get(annotationType); if (synthesizable != null) { return synthesizable; } synthesizable = Boolean.FALSE; for (Method attribute : getAttributeMethods(annotationType)) { if (!getAttributeAliasNames(attribute).isEmpty()) { synthesizable = Boolean.TRUE; break; } Class<?> returnType = attribute.getReturnType(); if (Annotation[].class.isAssignableFrom(returnType)) { Class<? extends Annotation> nestedAnnotationType = (Class<? extends Annotation>) returnType.getComponentType(); if (isSynthesizable(nestedAnnotationType)) { synthesizable = Boolean.TRUE; break; } } else if (Annotation.class.isAssignableFrom(returnType)) { Class<? extends Annotation> nestedAnnotationType = (Class<? extends Annotation>) returnType; if (isSynthesizable(nestedAnnotationType)) { synthesizable = Boolean.TRUE; break; } } } synthesizableCache.put(annotationType, synthesizable); return synthesizable; } static List<String> getAttributeAliasNames(Method attribute) { AliasDescriptor descriptor = AliasDescriptor.from(attribute); return (descriptor != null ? descriptor.getAttributeAliasNames() : Collections.emptyList()); } static String getAttributeOverrideName(Method attribute, Class<? extends Annotation> metaAnnotationType) { AliasDescriptor descriptor = AliasDescriptor.from(attribute); return (descriptor != null && metaAnnotationType != null ? descriptor.getAttributeOverrideName(metaAnnotationType) : null); } static List<Method> getAttributeMethods(Class<? extends Annotation> annotationType) { List<Method> methods = attributeMethodsCache.get(annotationType); if (methods != null) { return methods; } methods = new ArrayList<>(); for (Method method : annotationType.getDeclaredMethods()) { if (isAttributeMethod(method)) { ReflectionUtils.makeAccessible(method); methods.add(method); } } attributeMethodsCache.put(annotationType, methods); return methods; } // static Annotation getAnnotation(AnnotatedElement element, String annotationName) { // for (Annotation annotation : element.getAnnotations()) { // if (annotation.annotationType().getName().equals(annotationName)) { // return annotation; // } // } // return null; // } static boolean isAttributeMethod( Method method) { return (method != null && method.getParameterCount() == 0 && method.getReturnType() != void.class); } static boolean isAnnotationTypeMethod( Method method) { return (method != null && method.getName().equals("annotationType") && method.getParameterCount() == 0); } static Class<? extends Annotation> resolveContainerAnnotationType(Class<? extends Annotation> annotationType) { Repeatable repeatable = getAnnotation(annotationType, Repeatable.class); return (repeatable != null ? repeatable.value() : null); } static void rethrowAnnotationConfigurationException(Throwable ex) { if (ex instanceof AnnotationConfigurationException) { throw (AnnotationConfigurationException) ex; } } static void handleIntrospectionFailure( AnnotatedElement element, Throwable ex) { rethrowAnnotationConfigurationException(ex); } // public static void clearCache() { // findAnnotationCache.clear(); // metaPresentCache.clear(); // declaredAnnotationsCache.clear(); // annotatedBaseTypeCache.clear(); // synthesizableCache.clear(); // attributeAliasesCache.clear(); // attributeMethodsCache.clear(); // aliasDescriptorCache.clear(); // } /** * Cache key for the AnnotatedElement cache. */ private static final class AnnotationCacheKey implements Comparable<AnnotationCacheKey> { private final AnnotatedElement element; private final Class<? extends Annotation> annotationType; public AnnotationCacheKey(AnnotatedElement element, Class<? extends Annotation> annotationType) { this.element = element; this.annotationType = annotationType; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof AnnotationCacheKey)) { return false; } AnnotationCacheKey otherKey = (AnnotationCacheKey) other; return (this.element.equals(otherKey.element) && this.annotationType.equals(otherKey.annotationType)); } @Override public int hashCode() { return (this.element.hashCode() * 29 + this.annotationType.hashCode()); } @Override public String toString() { return "@" + this.annotationType + " on " + this.element; } @Override public int compareTo(AnnotationCacheKey other) { int result = this.element.toString().compareTo(other.element.toString()); if (result == 0) { result = this.annotationType.getName().compareTo(other.annotationType.getName()); } return result; } } // private static class AnnotationCollector<A extends Annotation> { // // private final Class<A> annotationType; // // // private final Class<? extends Annotation> containerAnnotationType; // // private final Set<AnnotatedElement> visited = new HashSet<>(); // // private final Set<A> result = new LinkedHashSet<>(); // // AnnotationCollector(Class<A> annotationType, Class<? extends Annotation> containerAnnotationType) { // this.annotationType = annotationType; // this.containerAnnotationType = (containerAnnotationType != null ? containerAnnotationType : // resolveContainerAnnotationType(annotationType)); // } // // Set<A> getResult(AnnotatedElement element) { // process(element); // return Collections.unmodifiableSet(this.result); // } // // @SuppressWarnings("unchecked") // private void process(AnnotatedElement element) { // if (this.visited.add(element)) { // try { // Annotation[] annotations = getDeclaredAnnotations(element); // for (Annotation ann : annotations) { // Class<? extends Annotation> currentAnnotationType = ann.annotationType(); // if (ObjectUtils.nullSafeEquals(this.annotationType, currentAnnotationType)) { // this.result.add(synthesizeAnnotation((A) ann, element)); // } // else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, currentAnnotationType)) { // this.result.addAll(getValue(element, ann)); // } // else if (!isInJavaLangAnnotationPackage(currentAnnotationType)) { // process(currentAnnotationType); // } // } // } // catch (Throwable ex) { // handleIntrospectionFailure(element, ex); // } // } // } // // @SuppressWarnings("unchecked") // private List<A> getValue(AnnotatedElement element, Annotation annotation) { // try { // List<A> synthesizedAnnotations = new ArrayList<>(); // A[] value = (A[]) AnnotationUtils.getValue(annotation); // if (value != null) { // for (A anno : value) { // synthesizedAnnotations.add(synthesizeAnnotation(anno, element)); // } // } // return synthesizedAnnotations; // } // catch (Throwable ex) { // handleIntrospectionFailure(element, ex); // } // // Unable to read value from repeating annotation container -> ignore it. // return Collections.emptyList(); // } // } /** * {@code AliasDescriptor} encapsulates the declaration of {@code @AliasFor} * on a given annotation attribute and includes support for validating * the configuration of aliases (both explicit and implicit). * @since 4.2.1 * @see #from * @see #getAttributeAliasNames * @see #getAttributeOverrideName */ private static final class AliasDescriptor { private final Method sourceAttribute; private final Class<? extends Annotation> sourceAnnotationType; private final String sourceAttributeName; private final Method aliasedAttribute; private final Class<? extends Annotation> aliasedAnnotationType; private final String aliasedAttributeName; private final boolean isAliasPair; /** * Create an {@code AliasDescriptor} <em>from</em> the declaration * of {@code @AliasFor} on the supplied annotation attribute and * validate the configuration of {@code @AliasFor}. * @param attribute the annotation attribute that is annotated with * {@code @AliasFor} * @return an alias descriptor, or {@code null} if the attribute * is not annotated with {@code @AliasFor} * @see #validateAgainst */ public static AliasDescriptor from(Method attribute) { AliasDescriptor descriptor = aliasDescriptorCache.get(attribute); if (descriptor != null) { return descriptor; } AliasFor aliasFor = attribute.getAnnotation(AliasFor.class); if (aliasFor == null) { return null; } descriptor = new AliasDescriptor(attribute, aliasFor); descriptor.validate(); aliasDescriptorCache.put(attribute, descriptor); return descriptor; } @SuppressWarnings("unchecked") private AliasDescriptor(Method sourceAttribute, AliasFor aliasFor) { Class<?> declaringClass = sourceAttribute.getDeclaringClass(); this.sourceAttribute = sourceAttribute; this.sourceAnnotationType = (Class<? extends Annotation>) declaringClass; this.sourceAttributeName = sourceAttribute.getName(); this.aliasedAnnotationType = (Annotation.class == aliasFor.annotation() ? this.sourceAnnotationType : aliasFor.annotation()); this.aliasedAttributeName = getAliasedAttributeName(aliasFor, sourceAttribute); if (this.aliasedAnnotationType == this.sourceAnnotationType && this.aliasedAttributeName.equals(this.sourceAttributeName)) { String msg = String.format("@AliasFor declaration on attribute '%s' in annotation [%s] points to " + "itself. Specify 'annotation' to point to a same-named attribute on a meta-annotation.", sourceAttribute.getName(), declaringClass.getName()); throw new AnnotationConfigurationException(msg); } try { this.aliasedAttribute = this.aliasedAnnotationType.getDeclaredMethod(this.aliasedAttributeName); } catch (NoSuchMethodException ex) { String msg = String.format( "Attribute '%s' in annotation [%s] is declared as an @AliasFor nonexistent attribute '%s' in annotation [%s].", this.sourceAttributeName, this.sourceAnnotationType.getName(), this.aliasedAttributeName, this.aliasedAnnotationType.getName()); throw new AnnotationConfigurationException(msg, ex); } this.isAliasPair = (this.sourceAnnotationType == this.aliasedAnnotationType); } private void validate() { // Target annotation is not meta-present? if (!this.isAliasPair && !isAnnotationMetaPresent(this.sourceAnnotationType, this.aliasedAnnotationType)) { String msg = String.format("@AliasFor declaration on attribute '%s' in annotation [%s] declares " + "an alias for attribute '%s' in meta-annotation [%s] which is not meta-present.", this.sourceAttributeName, this.sourceAnnotationType.getName(), this.aliasedAttributeName, this.aliasedAnnotationType.getName()); throw new AnnotationConfigurationException(msg); } if (this.isAliasPair) { AliasFor mirrorAliasFor = this.aliasedAttribute.getAnnotation(AliasFor.class); if (mirrorAliasFor == null) { String msg = String.format("Attribute '%s' in annotation [%s] must be declared as an @AliasFor [%s].", this.aliasedAttributeName, this.sourceAnnotationType.getName(), this.sourceAttributeName); throw new AnnotationConfigurationException(msg); } String mirrorAliasedAttributeName = getAliasedAttributeName(mirrorAliasFor, this.aliasedAttribute); if (!this.sourceAttributeName.equals(mirrorAliasedAttributeName)) { String msg = String.format("Attribute '%s' in annotation [%s] must be declared as an @AliasFor [%s], not [%s].", this.aliasedAttributeName, this.sourceAnnotationType.getName(), this.sourceAttributeName, mirrorAliasedAttributeName); throw new AnnotationConfigurationException(msg); } } Class<?> returnType = this.sourceAttribute.getReturnType(); Class<?> aliasedReturnType = this.aliasedAttribute.getReturnType(); if (returnType != aliasedReturnType && (!aliasedReturnType.isArray() || returnType != aliasedReturnType.getComponentType())) { String msg = String.format("Misconfigured aliases: attribute '%s' in annotation [%s] " + "and attribute '%s' in annotation [%s] must declare the same return type.", this.sourceAttributeName, this.sourceAnnotationType.getName(), this.aliasedAttributeName, this.aliasedAnnotationType.getName()); throw new AnnotationConfigurationException(msg); } if (this.isAliasPair) { validateDefaultValueConfiguration(this.aliasedAttribute); } } private void validateDefaultValueConfiguration(Method aliasedAttribute) { Object defaultValue = this.sourceAttribute.getDefaultValue(); Object aliasedDefaultValue = aliasedAttribute.getDefaultValue(); if (defaultValue == null || aliasedDefaultValue == null) { String msg = String.format("Misconfigured aliases: attribute '%s' in annotation [%s] " + "and attribute '%s' in annotation [%s] must declare default values.", this.sourceAttributeName, this.sourceAnnotationType.getName(), aliasedAttribute.getName(), aliasedAttribute.getDeclaringClass().getName()); throw new AnnotationConfigurationException(msg); } if (!ObjectUtils.nullSafeEquals(defaultValue, aliasedDefaultValue)) { String msg = String.format("Misconfigured aliases: attribute '%s' in annotation [%s] " + "and attribute '%s' in annotation [%s] must declare the same default value.", this.sourceAttributeName, this.sourceAnnotationType.getName(), aliasedAttribute.getName(), aliasedAttribute.getDeclaringClass().getName()); throw new AnnotationConfigurationException(msg); } } /** * Validate this descriptor against the supplied descriptor. * <p>This method only validates the configuration of default values * for the two descriptors, since other aspects of the descriptors * are validated when they are created. */ private void validateAgainst(AliasDescriptor otherDescriptor) { validateDefaultValueConfiguration(otherDescriptor.sourceAttribute); } /** * Determine if this descriptor represents an explicit override for * an attribute in the supplied {@code metaAnnotationType}. * @see #isAliasFor */ private boolean isOverrideFor(Class<? extends Annotation> metaAnnotationType) { return (this.aliasedAnnotationType == metaAnnotationType); } /** * Determine if this descriptor and the supplied descriptor both * effectively represent aliases for the same attribute in the same * target annotation, either explicitly or implicitly. * <p>This method searches the attribute override hierarchy, beginning * with this descriptor, in order to detect implicit and transitively * implicit aliases. * @return {@code true} if this descriptor and the supplied descriptor * effectively alias the same annotation attribute * @see #isOverrideFor */ private boolean isAliasFor(AliasDescriptor otherDescriptor) { for (AliasDescriptor lhs = this; lhs != null; lhs = lhs.getAttributeOverrideDescriptor()) { for (AliasDescriptor rhs = otherDescriptor; rhs != null; rhs = rhs.getAttributeOverrideDescriptor()) { if (lhs.aliasedAttribute.equals(rhs.aliasedAttribute)) { return true; } } } return false; } public List<String> getAttributeAliasNames() { // Explicit alias pair? if (this.isAliasPair) { return Collections.singletonList(this.aliasedAttributeName); } // Else: search for implicit aliases List<String> aliases = new ArrayList<>(); for (AliasDescriptor otherDescriptor : getOtherDescriptors()) { if (this.isAliasFor(otherDescriptor)) { this.validateAgainst(otherDescriptor); aliases.add(otherDescriptor.sourceAttributeName); } } return aliases; } private List<AliasDescriptor> getOtherDescriptors() { List<AliasDescriptor> otherDescriptors = new ArrayList<>(); for (Method currentAttribute : getAttributeMethods(this.sourceAnnotationType)) { if (!this.sourceAttribute.equals(currentAttribute)) { AliasDescriptor otherDescriptor = AliasDescriptor.from(currentAttribute); if (otherDescriptor != null) { otherDescriptors.add(otherDescriptor); } } } return otherDescriptors; } public String getAttributeOverrideName(Class<? extends Annotation> metaAnnotationType) { // Search the attribute override hierarchy, starting with the current attribute for (AliasDescriptor desc = this; desc != null; desc = desc.getAttributeOverrideDescriptor()) { if (desc.isOverrideFor(metaAnnotationType)) { return desc.aliasedAttributeName; } } // Else: explicit attribute override for a different meta-annotation return null; } private AliasDescriptor getAttributeOverrideDescriptor() { if (this.isAliasPair) { return null; } return AliasDescriptor.from(this.aliasedAttribute); } private String getAliasedAttributeName(AliasFor aliasFor, Method attribute) { String attributeName = aliasFor.attribute(); String value = aliasFor.value(); boolean attributeDeclared = StringUtils.hasText(attributeName); boolean valueDeclared = StringUtils.hasText(value); // Ensure user did not declare both 'value' and 'attribute' in @AliasFor if (attributeDeclared && valueDeclared) { String msg = String.format("In @AliasFor declared on attribute '%s' in annotation [%s], attribute 'attribute' " + "and its alias 'value' are present with values of [%s] and [%s], but only one is permitted.", attribute.getName(), attribute.getDeclaringClass().getName(), attributeName, value); throw new AnnotationConfigurationException(msg); } // Either explicit attribute name or pointing to same-named attribute by default attributeName = (attributeDeclared ? attributeName : value); return (StringUtils.hasText(attributeName) ? attributeName.trim() : attribute.getName()); } @Override public String toString() { return String.format("%s: @%s(%s) is an alias for @%s(%s)", getClass().getSimpleName(), this.sourceAnnotationType.getSimpleName(), this.sourceAttributeName, this.aliasedAnnotationType.getSimpleName(), this.aliasedAttributeName); } } private static class DefaultValueHolder { final Object defaultValue; public DefaultValueHolder(Object defaultValue) { this.defaultValue = defaultValue; } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/AnnotationUtils.java
Java
apache-2.0
62,026
package cn.bugstack.springframework.core.annotation; import cn.bugstack.springframework.util.ReflectionUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * @author zhangdd on 2022/2/27 */ class DefaultAnnotationAttributeExtractor extends AbstractAliasAwareAnnotationAttributeExtractor<Annotation> { /** * Construct a new {@code DefaultAnnotationAttributeExtractor}. * @param annotation the annotation to synthesize; never {@code null} * @param annotatedElement the element that is annotated with the supplied * annotation; may be {@code null} if unknown */ DefaultAnnotationAttributeExtractor(Annotation annotation, Object annotatedElement) { super(annotation.annotationType(), annotatedElement, annotation); } @Override protected Object getRawAttributeValue(Method attributeMethod) { ReflectionUtils.makeAccessible(attributeMethod); return ReflectionUtils.invokeMethod(attributeMethod, getSource()); } @Override protected Object getRawAttributeValue(String attributeName) { Method attributeMethod = ReflectionUtils.findMethod(getAnnotationType(), attributeName); return (attributeMethod != null ? getRawAttributeValue(attributeMethod) : null); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/DefaultAnnotationAttributeExtractor.java
Java
apache-2.0
1,304
package cn.bugstack.springframework.core.annotation; /** * @author zhangdd on 2022/2/27 */ public @interface SynthesizedAnnotation { }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/SynthesizedAnnotation.java
Java
apache-2.0
138
package cn.bugstack.springframework.core.annotation; import cn.bugstack.springframework.core.util.ObjectUtils; import cn.bugstack.springframework.core.util.StringUtils; import cn.bugstack.springframework.util.ReflectionUtils; import cn.hutool.core.lang.Assert; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author zhangdd on 2022/2/27 */ class SynthesizedAnnotationInvocationHandler implements InvocationHandler { private final AnnotationAttributeExtractor<?> attributeExtractor; private final Map<String, Object> valueCache = new ConcurrentHashMap<>(8); /** * Construct a new {@code SynthesizedAnnotationInvocationHandler} for * the supplied {@link AnnotationAttributeExtractor}. * @param attributeExtractor the extractor to delegate to */ SynthesizedAnnotationInvocationHandler(AnnotationAttributeExtractor<?> attributeExtractor) { Assert.notNull(attributeExtractor, "AnnotationAttributeExtractor must not be null"); this.attributeExtractor = attributeExtractor; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (ReflectionUtils.isEqualsMethod(method)) { return annotationEquals(args[0]); } if (ReflectionUtils.isHashCodeMethod(method)) { return annotationHashCode(); } if (ReflectionUtils.isToStringMethod(method)) { return annotationToString(); } if (AnnotationUtils.isAnnotationTypeMethod(method)) { return annotationType(); } if (!AnnotationUtils.isAttributeMethod(method)) { throw new AnnotationConfigurationException(String.format( "Method [%s] is unsupported for synthesized annotation type [%s]", method, annotationType())); } return getAttributeValue(method); } private Class<? extends Annotation> annotationType() { return this.attributeExtractor.getAnnotationType(); } private Object getAttributeValue(Method attributeMethod) { String attributeName = attributeMethod.getName(); Object value = this.valueCache.get(attributeName); if (value == null) { value = this.attributeExtractor.getAttributeValue(attributeMethod); if (value == null) { String msg = String.format("%s returned null for attribute name [%s] from attribute source [%s]", this.attributeExtractor.getClass().getName(), attributeName, this.attributeExtractor.getSource()); throw new IllegalStateException(msg); } // Synthesize nested annotations before returning them. if (value instanceof Annotation) { value = AnnotationUtils.synthesizeAnnotation((Annotation) value, this.attributeExtractor.getAnnotatedElement()); } else if (value instanceof Annotation[]) { value = AnnotationUtils.synthesizeAnnotationArray((Annotation[]) value, this.attributeExtractor.getAnnotatedElement()); } this.valueCache.put(attributeName, value); } // Clone arrays so that users cannot alter the contents of values in our cache. if (value.getClass().isArray()) { value = cloneArray(value); } return value; } /** * Clone the provided array, ensuring that original component type is * retained. * @param array the array to clone */ private Object cloneArray(Object array) { if (array instanceof boolean[]) { return ((boolean[]) array).clone(); } if (array instanceof byte[]) { return ((byte[]) array).clone(); } if (array instanceof char[]) { return ((char[]) array).clone(); } if (array instanceof double[]) { return ((double[]) array).clone(); } if (array instanceof float[]) { return ((float[]) array).clone(); } if (array instanceof int[]) { return ((int[]) array).clone(); } if (array instanceof long[]) { return ((long[]) array).clone(); } if (array instanceof short[]) { return ((short[]) array).clone(); } // else return ((Object[]) array).clone(); } /** * See {@link Annotation#equals(Object)} for a definition of the required algorithm. * @param other the other object to compare against */ private boolean annotationEquals(Object other) { if (this == other) { return true; } if (!annotationType().isInstance(other)) { return false; } for (Method attributeMethod : AnnotationUtils.getAttributeMethods(annotationType())) { Object thisValue = getAttributeValue(attributeMethod); Object otherValue = ReflectionUtils.invokeMethod(attributeMethod, other); if (!ObjectUtils.nullSafeEquals(thisValue, otherValue)) { return false; } } return true; } /** * See {@link Annotation#hashCode()} for a definition of the required algorithm. */ private int annotationHashCode() { int result = 0; for (Method attributeMethod : AnnotationUtils.getAttributeMethods(annotationType())) { Object value = getAttributeValue(attributeMethod); int hashCode; if (value.getClass().isArray()) { hashCode = hashCodeForArray(value); } else { hashCode = value.hashCode(); } result += (127 * attributeMethod.getName().hashCode()) ^ hashCode; } return result; } private int hashCodeForArray(Object array) { if (array instanceof boolean[]) { return Arrays.hashCode((boolean[]) array); } if (array instanceof byte[]) { return Arrays.hashCode((byte[]) array); } if (array instanceof char[]) { return Arrays.hashCode((char[]) array); } if (array instanceof double[]) { return Arrays.hashCode((double[]) array); } if (array instanceof float[]) { return Arrays.hashCode((float[]) array); } if (array instanceof int[]) { return Arrays.hashCode((int[]) array); } if (array instanceof long[]) { return Arrays.hashCode((long[]) array); } if (array instanceof short[]) { return Arrays.hashCode((short[]) array); } // else return Arrays.hashCode((Object[]) array); } /** * See {@link Annotation#toString()} for guidelines on the recommended format. */ private String annotationToString() { StringBuilder sb = new StringBuilder("@").append(annotationType().getName()).append("("); Iterator<Method> iterator = AnnotationUtils.getAttributeMethods(annotationType()).iterator(); while (iterator.hasNext()) { Method attributeMethod = iterator.next(); sb.append(attributeMethod.getName()); sb.append('='); sb.append(attributeValueToString(getAttributeValue(attributeMethod))); sb.append(iterator.hasNext() ? ", " : ""); } return sb.append(")").toString(); } private String attributeValueToString(Object value) { if (value instanceof Object[]) { return "[" + StringUtils.arrayToDelimitedString((Object[]) value, ", ") + "]"; } return String.valueOf(value); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/annotation/SynthesizedAnnotationInvocationHandler.java
Java
apache-2.0
7,911
package cn.bugstack.springframework.core.convert; import org.jetbrains.annotations.Nullable; /** * A service interface for type conversion. This is the entry point into the convert system. * Call {@link #convert(Object, Class)} to perform a thread-safe type conversion using this system. * * 类型转换抽象接口 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ConversionService { /** Return {@code true} if objects of {@code sourceType} can be converted to the {@code targetType}. */ boolean canConvert(@Nullable Class<?> sourceType, Class<?> targetType); /** Convert the given {@code source} to the specified {@code targetType}. */ <T> T convert(Object source, Class<T> targetType); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/ConversionService.java
Java
apache-2.0
963
package cn.bugstack.springframework.core.convert.converter; /** * A converter converts a source object of type {@code S} to a target of type {@code T}. * * 类型转换处理接口 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface Converter<S, T> { /** Convert the source object of type {@code S} to target type {@code T}. */ T convert(S source); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/converter/Converter.java
Java
apache-2.0
608
package cn.bugstack.springframework.core.convert.converter; /** * A factory for "ranged" converters that can convert objects from S to subtypes of R. * * 类型转换工厂 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ConverterFactory<S, R>{ /** * Get the converter to convert from S to target type T, where T is also an instance of R. * @param <T> the target type * @param targetType the target type to convert to * @return a converter from S to T */ <T extends R> Converter<S, T> getConverter(Class<T> targetType); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/converter/ConverterFactory.java
Java
apache-2.0
807
package cn.bugstack.springframework.core.convert.converter; /** * For registering converters with a type conversion system. * * 类型转换注册接口 * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface ConverterRegistry { /** * Add a plain converter to this registry. * The convertible source/target type pair is derived from the Converter's parameterized types. * @throws IllegalArgumentException if the parameterized types could not be resolved */ void addConverter(Converter<?, ?> converter); /** * Add a generic converter to this registry. */ void addConverter(GenericConverter converter); /** * Add a ranged converter factory to this registry. * The convertible source/target type pair is derived from the ConverterFactory's parameterized types. * @throws IllegalArgumentException if the parameterized types could not be resolved */ void addConverterFactory(ConverterFactory<?, ?> converterFactory); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/converter/ConverterRegistry.java
Java
apache-2.0
1,234
package cn.bugstack.springframework.core.convert.converter; import cn.hutool.core.lang.Assert; import java.util.Set; /** * Generic converter interface for converting between two or more types. * <p> * 通用的转换接口 * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public interface GenericConverter { /** * Return the source and target types that this converter can convert between. */ Set<ConvertiblePair> getConvertibleTypes(); /** * Convert the source object to the targetType described by the {@code TypeDescriptor}. * @param source the source object to convert (may be {@code null}) * @param sourceType the type descriptor of the field we are converting from * @param targetType the type descriptor of the field we are converting to * @return the converted object */ Object convert(Object source, Class sourceType, Class targetType); /** * Holder for a source-to-target class pair. */ final class ConvertiblePair { private final Class<?> sourceType; private final Class<?> targetType; public ConvertiblePair(Class<?> sourceType, Class<?> targetType) { Assert.notNull(sourceType, "Source type must not be null"); Assert.notNull(targetType, "Target type must not be null"); this.sourceType = sourceType; this.targetType = targetType; } public Class<?> getSourceType() { return this.sourceType; } public Class<?> getTargetType() { return this.targetType; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != ConvertiblePair.class) { return false; } ConvertiblePair other = (ConvertiblePair) obj; return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType); } @Override public int hashCode() { return this.sourceType.hashCode() * 31 + this.targetType.hashCode(); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/converter/GenericConverter.java
Java
apache-2.0
2,402
package cn.bugstack.springframework.core.convert.support; import cn.bugstack.springframework.core.convert.converter.ConverterRegistry; /** * A specialization of {@link GenericConversionService} configured by default * with converters appropriate for most environments. * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class DefaultConversionService extends GenericConversionService{ public DefaultConversionService() { addDefaultConverters(this); } public static void addDefaultConverters(ConverterRegistry converterRegistry) { // 添加各类类型转换工厂 converterRegistry.addConverterFactory(new StringToNumberConverterFactory()); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/support/DefaultConversionService.java
Java
apache-2.0
925
package cn.bugstack.springframework.core.convert.support; import cn.bugstack.springframework.core.convert.ConversionService; import cn.bugstack.springframework.core.convert.converter.Converter; import cn.bugstack.springframework.core.convert.converter.ConverterFactory; import cn.bugstack.springframework.core.convert.converter.ConverterRegistry; import cn.bugstack.springframework.core.convert.converter.GenericConverter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; /** * Base ConversionService implementation suitable for use in most environments. * Indirectly implements ConverterRegistry as registration API through the * ConfigurableConversionService interface. * * * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class GenericConversionService implements ConversionService, ConverterRegistry { private Map<GenericConverter.ConvertiblePair, GenericConverter> converters = new HashMap<>(); @Override public boolean canConvert(Class<?> sourceType, Class<?> targetType) { GenericConverter converter = getConverter(sourceType, targetType); return converter != null; } @Override public <T> T convert(Object source, Class<T> targetType) { Class<?> sourceType = source.getClass(); GenericConverter converter = getConverter(sourceType, targetType); return (T) converter.convert(source, sourceType, targetType); } @Override public void addConverter(Converter<?, ?> converter) { GenericConverter.ConvertiblePair typeInfo = getRequiredTypeInfo(converter); ConverterAdapter converterAdapter = new ConverterAdapter(typeInfo, converter); for (GenericConverter.ConvertiblePair convertibleType : converterAdapter.getConvertibleTypes()) { converters.put(convertibleType, converterAdapter); } } @Override public void addConverterFactory(ConverterFactory<?, ?> converterFactory) { GenericConverter.ConvertiblePair typeInfo = getRequiredTypeInfo(converterFactory); ConverterFactoryAdapter converterFactoryAdapter = new ConverterFactoryAdapter(typeInfo, converterFactory); for (GenericConverter.ConvertiblePair convertibleType : converterFactoryAdapter.getConvertibleTypes()) { converters.put(convertibleType, converterFactoryAdapter); } } @Override public void addConverter(GenericConverter converter) { for (GenericConverter.ConvertiblePair convertibleType : converter.getConvertibleTypes()) { converters.put(convertibleType, converter); } } private GenericConverter.ConvertiblePair getRequiredTypeInfo(Object object) { Type[] types = object.getClass().getGenericInterfaces(); ParameterizedType parameterized = (ParameterizedType) types[0]; Type[] actualTypeArguments = parameterized.getActualTypeArguments(); Class sourceType = (Class) actualTypeArguments[0]; Class targetType = (Class) actualTypeArguments[1]; return new GenericConverter.ConvertiblePair(sourceType, targetType); } protected GenericConverter getConverter(Class<?> sourceType, Class<?> targetType) { List<Class<?>> sourceCandidates = getClassHierarchy(sourceType); List<Class<?>> targetCandidates = getClassHierarchy(targetType); for (Class<?> sourceCandidate : sourceCandidates) { for (Class<?> targetCandidate : targetCandidates) { GenericConverter.ConvertiblePair convertiblePair = new GenericConverter.ConvertiblePair(sourceCandidate, targetCandidate); GenericConverter converter = converters.get(convertiblePair); if (converter != null) { return converter; } } } return null; } private List<Class<?>> getClassHierarchy(Class<?> clazz) { List<Class<?>> hierarchy = new ArrayList<>(); while (clazz != null) { hierarchy.add(clazz); clazz = clazz.getSuperclass(); } return hierarchy; } private final class ConverterAdapter implements GenericConverter { private final ConvertiblePair typeInfo; private final Converter<Object, Object> converter; public ConverterAdapter(ConvertiblePair typeInfo, Converter<?, ?> converter) { this.typeInfo = typeInfo; this.converter = (Converter<Object, Object>) converter; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(typeInfo); } @Override public Object convert(Object source, Class sourceType, Class targetType) { return converter.convert(source); } } private final class ConverterFactoryAdapter implements GenericConverter { private final ConvertiblePair typeInfo; private final ConverterFactory<Object, Object> converterFactory; public ConverterFactoryAdapter(ConvertiblePair typeInfo, ConverterFactory<?, ?> converterFactory) { this.typeInfo = typeInfo; this.converterFactory = (ConverterFactory<Object, Object>) converterFactory; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(typeInfo); } @Override public Object convert(Object source, Class sourceType, Class targetType) { return converterFactory.getConverter(targetType).convert(source); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/support/GenericConversionService.java
Java
apache-2.0
5,815
package cn.bugstack.springframework.core.convert.support; import cn.bugstack.springframework.core.convert.converter.Converter; import cn.bugstack.springframework.core.convert.converter.ConverterFactory; import cn.bugstack.springframework.util.NumberUtils; import org.jetbrains.annotations.Nullable; /** * Converts from a String any JDK-standard Number implementation. * <p> * 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! * 公众号:bugstack虫洞栈 * Create by 小傅哥(fustack) * * 来自于对开源项目的学习; * 作者:DerekYRC https://github.com/DerekYRC/mini-spring */ public class StringToNumberConverterFactory implements ConverterFactory<String, Number> { @Override public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) { return new StringToNumber<>(targetType); } private static final class StringToNumber<T extends Number> implements Converter<String, T> { private final Class<T> targetType; public StringToNumber(Class<T> targetType) { this.targetType = targetType; } @Override @Nullable public T convert(String source) { if (source.isEmpty()) { return null; } return NumberUtils.parseNumber(source, this.targetType); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/convert/support/StringToNumberConverterFactory.java
Java
apache-2.0
1,394
package cn.bugstack.springframework.core.io; import cn.bugstack.springframework.util.ClassUtils; import cn.hutool.core.lang.Assert; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class ClassPathResource implements Resource { private final String path; private ClassLoader classLoader; public ClassPathResource(String path) { this(path, (ClassLoader) null); } public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); this.path = path; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } @Override public InputStream getInputStream() throws IOException { InputStream is = classLoader.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException( this.path + " cannot be opened because it does not exist"); } return is; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/io/ClassPathResource.java
Java
apache-2.0
1,029
package cn.bugstack.springframework.core.io; import cn.hutool.core.lang.Assert; import java.net.MalformedURLException; import java.net.URL; public class DefaultResourceLoader implements ResourceLoader { @Override public Resource getResource(String location) { Assert.notNull(location, "Location must not be null"); if (location.startsWith(CLASSPATH_URL_PREFIX)) { return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length())); } else { try { URL url = new URL(location); return new UrlResource(url); } catch (MalformedURLException e) { return new FileSystemResource(location); } } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/io/DefaultResourceLoader.java
Java
apache-2.0
756
package cn.bugstack.springframework.core.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class FileSystemResource implements Resource { private final File file; private final String path; public FileSystemResource(File file) { this.file = file; this.path = file.getPath(); } public FileSystemResource(String path) { this.file = new File(path); this.path = path; } @Override public InputStream getInputStream() throws IOException { return new FileInputStream(this.file); } public final String getPath() { return this.path; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/io/FileSystemResource.java
Java
apache-2.0
699
package cn.bugstack.springframework.core.io; import java.io.IOException; import java.io.InputStream; public interface Resource { InputStream getInputStream() throws IOException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/io/Resource.java
Java
apache-2.0
188
package cn.bugstack.springframework.core.io; public interface ResourceLoader { /** * Pseudo URL prefix for loading from the class path: "classpath:" */ String CLASSPATH_URL_PREFIX = "classpath:"; Resource getResource(String location); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/io/ResourceLoader.java
Java
apache-2.0
263
package cn.bugstack.springframework.core.io; import cn.hutool.core.lang.Assert; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class UrlResource implements Resource{ private final URL url; public UrlResource(URL url) { Assert.notNull(url,"URL must not be null"); this.url = url; } @Override public InputStream getInputStream() throws IOException { URLConnection con = this.url.openConnection(); try { return con.getInputStream(); } catch (IOException ex){ if (con instanceof HttpURLConnection){ ((HttpURLConnection) con).disconnect(); } throw ex; } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/io/UrlResource.java
Java
apache-2.0
807
package cn.bugstack.springframework.core.util; import cn.hutool.core.lang.Assert; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; /** * @author zhangdd on 2022/2/27 */ public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> { private static final int DEFAULT_INITIAL_CAPACITY = 16; private static final float DEFAULT_LOAD_FACTOR = 0.75f; private static final int DEFAULT_CONCURRENCY_LEVEL = 16; private static final ReferenceType DEFAULT_REFERENCE_TYPE = ReferenceType.SOFT; private static final int MAXIMUM_CONCURRENCY_LEVEL = 1 << 16; private static final int MAXIMUM_SEGMENT_SIZE = 1 << 30; /** * Array of segments indexed using the high order bits from the hash. */ private final Segment[] segments; /** * When the average number of references per table exceeds this value resize will be attempted. */ private final float loadFactor; /** * The reference type: SOFT or WEAK. */ private final ReferenceType referenceType; /** * The shift value used to calculate the size of the segments array and an index from the hash. */ private final int shift; /** * Late binding entry set. */ private volatile Set<Map.Entry<K, V>> entrySet; /** * Create a new {@code ConcurrentReferenceHashMap} instance. */ public ConcurrentReferenceHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_REFERENCE_TYPE); } /** * Create a new {@code ConcurrentReferenceHashMap} instance. * @param initialCapacity the initial capacity of the map */ public ConcurrentReferenceHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_REFERENCE_TYPE); } /** * Create a new {@code ConcurrentReferenceHashMap} instance. * @param initialCapacity the initial capacity of the map * @param loadFactor the load factor. When the average number of references per table * exceeds this value resize will be attempted */ public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_REFERENCE_TYPE); } /** * Create a new {@code ConcurrentReferenceHashMap} instance. * @param initialCapacity the initial capacity of the map * @param concurrencyLevel the expected number of threads that will concurrently * write to the map */ public ConcurrentReferenceHashMap(int initialCapacity, int concurrencyLevel) { this(initialCapacity, DEFAULT_LOAD_FACTOR, concurrencyLevel, DEFAULT_REFERENCE_TYPE); } /** * Create a new {@code ConcurrentReferenceHashMap} instance. * @param initialCapacity the initial capacity of the map * @param referenceType the reference type used for entries (soft or weak) */ public ConcurrentReferenceHashMap(int initialCapacity, ReferenceType referenceType) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, referenceType); } /** * Create a new {@code ConcurrentReferenceHashMap} instance. * @param initialCapacity the initial capacity of the map * @param loadFactor the load factor. When the average number of references per * table exceeds this value, resize will be attempted. * @param concurrencyLevel the expected number of threads that will concurrently * write to the map */ public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { this(initialCapacity, loadFactor, concurrencyLevel, DEFAULT_REFERENCE_TYPE); } /** * Create a new {@code ConcurrentReferenceHashMap} instance. * @param initialCapacity the initial capacity of the map * @param loadFactor the load factor. When the average number of references per * table exceeds this value, resize will be attempted. * @param concurrencyLevel the expected number of threads that will concurrently * write to the map * @param referenceType the reference type used for entries (soft or weak) */ @SuppressWarnings("unchecked") public ConcurrentReferenceHashMap( int initialCapacity, float loadFactor, int concurrencyLevel, ReferenceType referenceType) { Assert.isTrue(initialCapacity >= 0, "Initial capacity must not be negative"); Assert.isTrue(loadFactor > 0f, "Load factor must be positive"); Assert.isTrue(concurrencyLevel > 0, "Concurrency level must be positive"); Assert.notNull(referenceType, "Reference type must not be null"); this.loadFactor = loadFactor; this.shift = calculateShift(concurrencyLevel, MAXIMUM_CONCURRENCY_LEVEL); int size = 1 << this.shift; this.referenceType = referenceType; int roundedUpSegmentCapacity = (int) ((initialCapacity + size - 1L) / size); int initialSize = 1 << calculateShift(roundedUpSegmentCapacity, MAXIMUM_SEGMENT_SIZE); Segment[] segments = (Segment[]) Array.newInstance(Segment.class, size); int resizeThreshold = (int) (initialSize * getLoadFactor()); for (int i = 0; i < segments.length; i++) { segments[i] = new Segment(initialSize, resizeThreshold); } this.segments = segments; } protected final float getLoadFactor() { return this.loadFactor; } protected final int getSegmentsSize() { return this.segments.length; } protected final Segment getSegment(int index) { return this.segments[index]; } /** * Factory method that returns the {@link ReferenceManager}. * This method will be called once for each {@link Segment}. * @return a new reference manager */ protected ReferenceManager createReferenceManager() { return new ReferenceManager(); } /** * Get the hash for a given object, apply an additional hash function to reduce * collisions. This implementation uses the same Wang/Jenkins algorithm as * {@link ConcurrentHashMap}. Subclasses can override to provide alternative hashing. * @param o the object to hash (may be null) * @return the resulting hash code */ protected int getHash( Object o) { int hash = (o != null ? o.hashCode() : 0); hash += (hash << 15) ^ 0xffffcd7d; hash ^= (hash >>> 10); hash += (hash << 3); hash ^= (hash >>> 6); hash += (hash << 2) + (hash << 14); hash ^= (hash >>> 16); return hash; } @Override public V get( Object key) { Entry<K, V> entry = getEntryIfAvailable(key); return (entry != null ? entry.getValue() : null); } @Override public V getOrDefault( Object key, V defaultValue) { Entry<K, V> entry = getEntryIfAvailable(key); return (entry != null ? entry.getValue() : defaultValue); } @Override public boolean containsKey( Object key) { Entry<K, V> entry = getEntryIfAvailable(key); return (entry != null && ObjectUtils.nullSafeEquals(entry.getKey(), key)); } private Entry<K, V> getEntryIfAvailable( Object key) { Reference<K, V> ref = getReference(key, Restructure.WHEN_NECESSARY); return (ref != null ? ref.get() : null); } /** * Return a {@link Reference} to the {@link Entry} for the specified {@code key}, * or {@code null} if not found. * @param key the key (can be {@code null}) * @param restructure types of restructure allowed during this call * @return the reference, or {@code null} if not found */ protected final Reference<K, V> getReference( Object key, Restructure restructure) { int hash = getHash(key); return getSegmentForHash(hash).getReference(key, hash, restructure); } @Override public V put( K key, V value) { return put(key, value, true); } @Override public V putIfAbsent( K key, V value) { return put(key, value, false); } private V put( final K key, final V value, final boolean overwriteExisting) { return doTask(key, new Task<V>(TaskOption.RESTRUCTURE_BEFORE, TaskOption.RESIZE) { @Override protected V execute( Reference<K, V> ref, Entry<K, V> entry, Entries entries) { if (entry != null) { V oldValue = entry.getValue(); if (overwriteExisting) { entry.setValue(value); } return oldValue; } Assert.state(entries != null, "No entries segment"); entries.add(value); return null; } }); } @Override public V remove(Object key) { return doTask(key, new Task<V>(TaskOption.RESTRUCTURE_AFTER, TaskOption.SKIP_IF_EMPTY) { @Override protected V execute( Reference<K, V> ref, Entry<K, V> entry) { if (entry != null) { if (ref != null) { ref.release(); } return entry.value; } return null; } }); } @Override public boolean remove(Object key, final Object value) { Boolean result = doTask(key, new Task<Boolean>(TaskOption.RESTRUCTURE_AFTER, TaskOption.SKIP_IF_EMPTY) { @Override protected Boolean execute( Reference<K, V> ref, Entry<K, V> entry) { if (entry != null && ObjectUtils.nullSafeEquals(entry.getValue(), value)) { if (ref != null) { ref.release(); } return true; } return false; } }); return (result == Boolean.TRUE); } @Override public boolean replace(K key, final V oldValue, final V newValue) { Boolean result = doTask(key, new Task<Boolean>(TaskOption.RESTRUCTURE_BEFORE, TaskOption.SKIP_IF_EMPTY) { @Override protected Boolean execute( Reference<K, V> ref, Entry<K, V> entry) { if (entry != null && ObjectUtils.nullSafeEquals(entry.getValue(), oldValue)) { entry.setValue(newValue); return true; } return false; } }); return (result == Boolean.TRUE); } @Override public V replace(K key, final V value) { return doTask(key, new Task<V>(TaskOption.RESTRUCTURE_BEFORE, TaskOption.SKIP_IF_EMPTY) { @Override protected V execute( Reference<K, V> ref, Entry<K, V> entry) { if (entry != null) { V oldValue = entry.getValue(); entry.setValue(value); return oldValue; } return null; } }); } @Override public void clear() { for (Segment segment : this.segments) { segment.clear(); } } /** * Remove any entries that have been garbage collected and are no longer referenced. * Under normal circumstances garbage collected entries are automatically purged as * items are added or removed from the Map. This method can be used to force a purge, * and is useful when the Map is read frequently but updated less often. */ public void purgeUnreferencedEntries() { for (Segment segment : this.segments) { segment.restructureIfNecessary(false); } } @Override public int size() { int size = 0; for (Segment segment : this.segments) { size += segment.getCount(); } return size; } @Override public boolean isEmpty() { for (Segment segment : this.segments) { if (segment.getCount() > 0) { return false; } } return true; } @Override public Set<Map.Entry<K, V>> entrySet() { Set<Map.Entry<K, V>> entrySet = this.entrySet; if (entrySet == null) { entrySet = new EntrySet(); this.entrySet = entrySet; } return entrySet; } private <T> T doTask( Object key, Task<T> task) { int hash = getHash(key); return getSegmentForHash(hash).doTask(hash, key, task); } private Segment getSegmentForHash(int hash) { return this.segments[(hash >>> (32 - this.shift)) & (this.segments.length - 1)]; } /** * Calculate a shift value that can be used to create a power-of-two value between * the specified maximum and minimum values. * @param minimumValue the minimum value * @param maximumValue the maximum value * @return the calculated shift (use {@code 1 << shift} to obtain a value) */ protected static int calculateShift(int minimumValue, int maximumValue) { int shift = 0; int value = 1; while (value < minimumValue && value < maximumValue) { value <<= 1; shift++; } return shift; } /** * Various reference types supported by this map. */ public enum ReferenceType { /** Use {@link SoftReference SoftReferences}. */ SOFT, /** Use {@link WeakReference WeakReferences}. */ WEAK } /** * A single segment used to divide the map to allow better concurrent performance. */ @SuppressWarnings("serial") protected final class Segment extends ReentrantLock { private final ReferenceManager referenceManager; private final int initialSize; /** * Array of references indexed using the low order bits from the hash. * This property should only be set along with {@code resizeThreshold}. */ private volatile Reference<K, V>[] references; /** * The total number of references contained in this segment. This includes chained * references and references that have been garbage collected but not purged. */ private volatile int count = 0; /** * The threshold when resizing of the references should occur. When {@code count} * exceeds this value references will be resized. */ private int resizeThreshold; public Segment(int initialSize, int resizeThreshold) { this.referenceManager = createReferenceManager(); this.initialSize = initialSize; this.references = createReferenceArray(initialSize); this.resizeThreshold = resizeThreshold; } public Reference<K, V> getReference( Object key, int hash, Restructure restructure) { if (restructure == Restructure.WHEN_NECESSARY) { restructureIfNecessary(false); } if (this.count == 0) { return null; } // Use a local copy to protect against other threads writing Reference<K, V>[] references = this.references; int index = getIndex(hash, references); Reference<K, V> head = references[index]; return findInChain(head, key, hash); } /** * Apply an update operation to this segment. * The segment will be locked during the update. * @param hash the hash of the key * @param key the key * @param task the update operation * @return the result of the operation */ public <T> T doTask(final int hash, final Object key, final Task<T> task) { boolean resize = task.hasOption(TaskOption.RESIZE); if (task.hasOption(TaskOption.RESTRUCTURE_BEFORE)) { restructureIfNecessary(resize); } if (task.hasOption(TaskOption.SKIP_IF_EMPTY) && this.count == 0) { return task.execute(null, null, null); } lock(); try { final int index = getIndex(hash, this.references); final Reference<K, V> head = this.references[index]; Reference<K, V> ref = findInChain(head, key, hash); Entry<K, V> entry = (ref != null ? ref.get() : null); Entries entries = new Entries() { @Override public void add( V value) { @SuppressWarnings("unchecked") Entry<K, V> newEntry = new Entry<>((K) key, value); Reference<K, V> newReference = Segment.this.referenceManager.createReference(newEntry, hash, head); Segment.this.references[index] = newReference; Segment.this.count++; } }; return task.execute(ref, entry, entries); } finally { unlock(); if (task.hasOption(TaskOption.RESTRUCTURE_AFTER)) { restructureIfNecessary(resize); } } } /** * Clear all items from this segment. */ public void clear() { if (this.count == 0) { return; } lock(); try { this.references = createReferenceArray(this.initialSize); this.resizeThreshold = (int) (this.references.length * getLoadFactor()); this.count = 0; } finally { unlock(); } } /** * Restructure the underlying data structure when it becomes necessary. This * method can increase the size of the references table as well as purge any * references that have been garbage collected. * @param allowResize if resizing is permitted */ protected final void restructureIfNecessary(boolean allowResize) { int currCount = this.count; boolean needsResize = (currCount > 0 && currCount >= this.resizeThreshold); Reference<K, V> ref = this.referenceManager.pollForPurge(); if (ref != null || (needsResize && allowResize)) { lock(); try { int countAfterRestructure = this.count; Set<Reference<K, V>> toPurge = Collections.emptySet(); if (ref != null) { toPurge = new HashSet<>(); while (ref != null) { toPurge.add(ref); ref = this.referenceManager.pollForPurge(); } } countAfterRestructure -= toPurge.size(); // Recalculate taking into account count inside lock and items that // will be purged needsResize = (countAfterRestructure > 0 && countAfterRestructure >= this.resizeThreshold); boolean resizing = false; int restructureSize = this.references.length; if (allowResize && needsResize && restructureSize < MAXIMUM_SEGMENT_SIZE) { restructureSize <<= 1; resizing = true; } // Either create a new table or reuse the existing one Reference<K, V>[] restructured = (resizing ? createReferenceArray(restructureSize) : this.references); // Restructure for (int i = 0; i < this.references.length; i++) { ref = this.references[i]; if (!resizing) { restructured[i] = null; } while (ref != null) { if (!toPurge.contains(ref)) { Entry<K, V> entry = ref.get(); if (entry != null) { int index = getIndex(ref.getHash(), restructured); restructured[index] = this.referenceManager.createReference( entry, ref.getHash(), restructured[index]); } } ref = ref.getNext(); } } // Replace volatile members if (resizing) { this.references = restructured; this.resizeThreshold = (int) (this.references.length * getLoadFactor()); } this.count = Math.max(countAfterRestructure, 0); } finally { unlock(); } } } private Reference<K, V> findInChain(Reference<K, V> ref, Object key, int hash) { Reference<K, V> currRef = ref; while (currRef != null) { if (currRef.getHash() == hash) { Entry<K, V> entry = currRef.get(); if (entry != null) { K entryKey = entry.getKey(); if (ObjectUtils.nullSafeEquals(entryKey, key)) { return currRef; } } } currRef = currRef.getNext(); } return null; } @SuppressWarnings({"rawtypes", "unchecked"}) private Reference<K, V>[] createReferenceArray(int size) { return new Reference[size]; } private int getIndex(int hash, Reference<K, V>[] references) { return (hash & (references.length - 1)); } /** * Return the size of the current references array. */ public final int getSize() { return this.references.length; } /** * Return the total number of references in this segment. */ public final int getCount() { return this.count; } } /** * A reference to an {@link Entry} contained in the map. Implementations are usually * wrappers around specific Java reference implementations (e.g., {@link SoftReference}). * @param <K> the key type * @param <V> the value type */ protected interface Reference<K, V> { /** * Return the referenced entry, or {@code null} if the entry is no longer available. */ Entry<K, V> get(); /** * Return the hash for the reference. */ int getHash(); /** * Return the next reference in the chain, or {@code null} if none. */ Reference<K, V> getNext(); /** * Release this entry and ensure that it will be returned from * {@code ReferenceManager#pollForPurge()}. */ void release(); } /** * A single map entry. * @param <K> the key type * @param <V> the value type */ protected static final class Entry<K, V> implements Map.Entry<K, V> { private final K key; private volatile V value; public Entry( K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return this.key; } @Override public V getValue() { return this.value; } @Override public V setValue( V value) { V previous = this.value; this.value = value; return previous; } @Override public String toString() { return (this.key + "=" + this.value); } @Override @SuppressWarnings("rawtypes") public final boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Map.Entry)) { return false; } Map.Entry otherEntry = (Map.Entry) other; return (ObjectUtils.nullSafeEquals(getKey(), otherEntry.getKey()) && ObjectUtils.nullSafeEquals(getValue(), otherEntry.getValue())); } @Override public final int hashCode() { return (ObjectUtils.nullSafeHashCode(this.key) ^ ObjectUtils.nullSafeHashCode(this.value)); } } /** * A task that can be {@link Segment#doTask run} against a {@link Segment}. */ private abstract class Task<T> { private final EnumSet<TaskOption> options; public Task(TaskOption... options) { this.options = (options.length == 0 ? EnumSet.noneOf(TaskOption.class) : EnumSet.of(options[0], options)); } public boolean hasOption(TaskOption option) { return this.options.contains(option); } /** * Execute the task. * @param ref the found reference (or {@code null}) * @param entry the found entry (or {@code null}) * @param entries access to the underlying entries * @return the result of the task * @see #execute(Reference, Entry) */ protected T execute( Reference<K, V> ref, Entry<K, V> entry, Entries entries) { return execute(ref, entry); } /** * Convenience method that can be used for tasks that do not need access to {@link Entries}. * @param ref the found reference (or {@code null}) * @param entry the found entry (or {@code null}) * @return the result of the task * @see #execute(Reference, Entry, Entries) */ protected T execute( Reference<K, V> ref, Entry<K, V> entry) { return null; } } /** * Various options supported by a {@code Task}. */ private enum TaskOption { RESTRUCTURE_BEFORE, RESTRUCTURE_AFTER, SKIP_IF_EMPTY, RESIZE } /** * Allows a task access to {@link Segment} entries. */ private abstract class Entries { /** * Add a new entry with the specified value. * @param value the value to add */ public abstract void add( V value); } /** * Internal entry-set implementation. */ private class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(); } @Override public boolean contains( Object o) { if (o instanceof Map.Entry<?, ?>) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; Reference<K, V> ref = ConcurrentReferenceHashMap.this.getReference(entry.getKey(), Restructure.NEVER); Entry<K, V> otherEntry = (ref != null ? ref.get() : null); if (otherEntry != null) { return ObjectUtils.nullSafeEquals(otherEntry.getValue(), otherEntry.getValue()); } } return false; } @Override public boolean remove(Object o) { if (o instanceof Map.Entry<?, ?>) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return ConcurrentReferenceHashMap.this.remove(entry.getKey(), entry.getValue()); } return false; } @Override public int size() { return ConcurrentReferenceHashMap.this.size(); } @Override public void clear() { ConcurrentReferenceHashMap.this.clear(); } } /** * Internal entry iterator implementation. */ private class EntryIterator implements Iterator<Map.Entry<K, V>> { private int segmentIndex; private int referenceIndex; private Reference<K, V>[] references; private Reference<K, V> reference; private Entry<K, V> next; private Entry<K, V> last; public EntryIterator() { moveToNextSegment(); } @Override public boolean hasNext() { getNextIfNecessary(); return (this.next != null); } @Override public Entry<K, V> next() { getNextIfNecessary(); if (this.next == null) { throw new NoSuchElementException(); } this.last = this.next; this.next = null; return this.last; } private void getNextIfNecessary() { while (this.next == null) { moveToNextReference(); if (this.reference == null) { return; } this.next = this.reference.get(); } } private void moveToNextReference() { if (this.reference != null) { this.reference = this.reference.getNext(); } while (this.reference == null && this.references != null) { if (this.referenceIndex >= this.references.length) { moveToNextSegment(); this.referenceIndex = 0; } else { this.reference = this.references[this.referenceIndex]; this.referenceIndex++; } } } private void moveToNextSegment() { this.reference = null; this.references = null; if (this.segmentIndex < ConcurrentReferenceHashMap.this.segments.length) { this.references = ConcurrentReferenceHashMap.this.segments[this.segmentIndex].references; this.segmentIndex++; } } @Override public void remove() { Assert.state(this.last != null, "No element to remove"); ConcurrentReferenceHashMap.this.remove(this.last.getKey()); } } /** * The types of restructuring that can be performed. */ protected enum Restructure { WHEN_NECESSARY, NEVER } /** * Strategy class used to manage {@link Reference References}. This class can be overridden if * alternative reference types need to be supported. */ protected class ReferenceManager { private final ReferenceQueue<Entry<K, V>> queue = new ReferenceQueue<>(); /** * Factory method used to create a new {@link Reference}. * @param entry the entry contained in the reference * @param hash the hash * @param next the next reference in the chain, or {@code null} if none * @return a new {@link Reference} */ public Reference<K, V> createReference(Entry<K, V> entry, int hash, Reference<K, V> next) { if (ConcurrentReferenceHashMap.this.referenceType == ReferenceType.WEAK) { return new WeakEntryReference<>(entry, hash, next, this.queue); } return new SoftEntryReference<>(entry, hash, next, this.queue); } /** * Return any reference that has been garbage collected and can be purged from the * underlying structure or {@code null} if no references need purging. This * method must be thread safe and ideally should not block when returning * {@code null}. References should be returned once and only once. * @return a reference to purge or {@code null} */ @SuppressWarnings("unchecked") public Reference<K, V> pollForPurge() { return (Reference<K, V>) this.queue.poll(); } } /** * Internal {@link Reference} implementation for {@link SoftReference SoftReferences}. */ private static final class SoftEntryReference<K, V> extends SoftReference<Entry<K, V>> implements Reference<K, V> { private final int hash; private final Reference<K, V> nextReference; public SoftEntryReference(Entry<K, V> entry, int hash, Reference<K, V> next, ReferenceQueue<Entry<K, V>> queue) { super(entry, queue); this.hash = hash; this.nextReference = next; } @Override public int getHash() { return this.hash; } @Override public Reference<K, V> getNext() { return this.nextReference; } @Override public void release() { enqueue(); clear(); } } /** * Internal {@link Reference} implementation for {@link WeakReference WeakReferences}. */ private static final class WeakEntryReference<K, V> extends WeakReference<Entry<K, V>> implements Reference<K, V> { private final int hash; private final Reference<K, V> nextReference; public WeakEntryReference(Entry<K, V> entry, int hash, Reference<K, V> next, ReferenceQueue<Entry<K, V>> queue) { super(entry, queue); this.hash = hash; this.nextReference = next; } @Override public int getHash() { return this.hash; } @Override public Reference<K, V> getNext() { return this.nextReference; } @Override public void release() { enqueue(); clear(); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/util/ConcurrentReferenceHashMap.java
Java
apache-2.0
34,396
package cn.bugstack.springframework.core.util; import java.util.Arrays; /** * @author zhangdd on 2022/2/26 */ public class ObjectUtils { private static final String EMPTY_STRING = ""; private static final String NULL_STRING = "null"; public static boolean isEmpty( Object[] array) { return (array == null || array.length == 0); } public static String nullSafeToString( Object obj) { if (obj == null) { return NULL_STRING; } if (obj instanceof String) { return (String) obj; } if (obj instanceof Object[]) { return nullSafeToString((Object[]) obj); } if (obj instanceof boolean[]) { return nullSafeToString((boolean[]) obj); } if (obj instanceof byte[]) { return nullSafeToString((byte[]) obj); } if (obj instanceof char[]) { return nullSafeToString((char[]) obj); } if (obj instanceof double[]) { return nullSafeToString((double[]) obj); } if (obj instanceof float[]) { return nullSafeToString((float[]) obj); } if (obj instanceof int[]) { return nullSafeToString((int[]) obj); } if (obj instanceof long[]) { return nullSafeToString((long[]) obj); } if (obj instanceof short[]) { return nullSafeToString((short[]) obj); } String str = obj.toString(); return (str != null ? str : EMPTY_STRING); } public static boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { return arrayEquals(o1, o2); } return false; } private static boolean arrayEquals(Object o1, Object o2) { if (o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.equals((Object[]) o1, (Object[]) o2); } if (o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[]) o1, (boolean[]) o2); } if (o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[]) o1, (byte[]) o2); } if (o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[]) o1, (char[]) o2); } if (o1 instanceof double[] && o2 instanceof double[]) { return Arrays.equals((double[]) o1, (double[]) o2); } if (o1 instanceof float[] && o2 instanceof float[]) { return Arrays.equals((float[]) o1, (float[]) o2); } if (o1 instanceof int[] && o2 instanceof int[]) { return Arrays.equals((int[]) o1, (int[]) o2); } if (o1 instanceof long[] && o2 instanceof long[]) { return Arrays.equals((long[]) o1, (long[]) o2); } if (o1 instanceof short[] && o2 instanceof short[]) { return Arrays.equals((short[]) o1, (short[]) o2); } return false; } public static int nullSafeHashCode( Object obj) { if (obj == null) { return 0; } if (obj.getClass().isArray()) { if (obj instanceof Object[]) { return nullSafeHashCode((Object[]) obj); } if (obj instanceof boolean[]) { return nullSafeHashCode((boolean[]) obj); } if (obj instanceof byte[]) { return nullSafeHashCode((byte[]) obj); } if (obj instanceof char[]) { return nullSafeHashCode((char[]) obj); } if (obj instanceof double[]) { return nullSafeHashCode((double[]) obj); } if (obj instanceof float[]) { return nullSafeHashCode((float[]) obj); } if (obj instanceof int[]) { return nullSafeHashCode((int[]) obj); } if (obj instanceof long[]) { return nullSafeHashCode((long[]) obj); } if (obj instanceof short[]) { return nullSafeHashCode((short[]) obj); } } return obj.hashCode(); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/util/ObjectUtils.java
Java
apache-2.0
4,472
package cn.bugstack.springframework.core.util; /** * @author zhangdd on 2022/2/27 */ public class StringUtils { public static String arrayToDelimitedString( Object[] arr, String delim) { if (ObjectUtils.isEmpty(arr)) { return ""; } if (arr.length == 1) { return ObjectUtils.nullSafeToString(arr[0]); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } public static boolean hasText( String str) { return (str != null && !str.isEmpty() && containsText(str)); } private static boolean containsText(CharSequence str) { int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/core/util/StringUtils.java
Java
apache-2.0
1,017
package cn.bugstack.springframework.jdbc; import java.sql.SQLException; /** * @author zhangdd on 2022/2/9 */ public class CannotGetJdbcConnectionException extends RuntimeException { public CannotGetJdbcConnectionException(String message) { super(message); } public CannotGetJdbcConnectionException(String message, SQLException ex) { super(message, ex); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/CannotGetJdbcConnectionException.java
Java
apache-2.0
395
package cn.bugstack.springframework.jdbc; /** * @author zhangdd on 2022/2/10 */ public class IncorrectResultSetColumnCountException extends RuntimeException { private final int expectedCount; private final int actualCount; public IncorrectResultSetColumnCountException(int expectedCount, int actualCount) { super("Incorrect column count: expected " + expectedCount + ", actual " + actualCount); this.expectedCount = expectedCount; this.actualCount = actualCount; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/IncorrectResultSetColumnCountException.java
Java
apache-2.0
513
package cn.bugstack.springframework.jdbc; /** * @author zhangdd on 2022/2/9 */ public class UncategorizedSQLException extends RuntimeException{ public UncategorizedSQLException(String message) { super(message); } public UncategorizedSQLException(String task,String sql, Throwable cause) { super(sql, cause); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/UncategorizedSQLException.java
Java
apache-2.0
350
package cn.bugstack.springframework.jdbc.core; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author zhangdd on 2022/2/12 */ public class ArgumentPreparedStatementSetter implements PreparedStatementSetter { private final Object[] args; public ArgumentPreparedStatementSetter(Object[] args) { this.args = args; } @Override public void setValues(PreparedStatement ps) throws SQLException { if (null != args) { for (int i = 1; i <= args.length; i++) { ps.setObject(i, args[i - 1]); } } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/ArgumentPreparedStatementSetter.java
Java
apache-2.0
607
package cn.bugstack.springframework.jdbc.core; import cn.bugstack.springframework.jdbc.support.JdbcUtils; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; /** * 对sql的行数据 进行逐列获取放到map里 * * @author zhangdd on 2022/2/10 */ public class ColumnMapRowMapper implements RowMapper<Map<String, Object>> { @Override public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData rsMetaData = rs.getMetaData(); int columnCount = rsMetaData.getColumnCount(); Map<String, Object> mapOfColumnValues = createColumnMap(columnCount); for (int i = 1; i <= columnCount; i++) { String columnName = JdbcUtils.lookupColumnName(rsMetaData, i); mapOfColumnValues.putIfAbsent(getColumnKey(columnName), getColumnValue(rs, i)); } return mapOfColumnValues; } protected Map<String, Object> createColumnMap(int columnCount) { return new LinkedHashMap<>(columnCount); } protected String getColumnKey(String columnName) { return columnName; } protected Object getColumnValue(ResultSet rs, int index) throws SQLException { return JdbcUtils.getResultSetValue(rs, index); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/ColumnMapRowMapper.java
Java
apache-2.0
1,347
package cn.bugstack.springframework.jdbc.core; import java.util.List; import java.util.Map; /** * @author zhangdd on 2022/2/9 */ public interface JdbcOperations { <T> T execute(StatementCallback<T> action); void execute(String sql); //--------------------------------------------------------------------- // query //--------------------------------------------------------------------- <T> T query(String sql, ResultSetExtractor<T> res); <T> T query(String sql, Object[] args, ResultSetExtractor<T> rse); <T> List<T> query(String sql, RowMapper<T> rowMapper); <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); <T> T query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse); //--------------------------------------------------------------------- // queryForList //--------------------------------------------------------------------- List<Map<String, Object>> queryForList(String sql); /** * 查询数据库表中某一个字段 */ <T> List<T> queryForList(String sql, Class<T> elementType); <T> List<T> queryForList(String sql, Class<T> elementType, Object... args); List<Map<String, Object>> queryForList(String sql, Object... args); //--------------------------------------------------------------------- // queryForObject //--------------------------------------------------------------------- <T> T queryForObject(String sql, RowMapper<T> rowMapper); <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper); /** * 查询数据库表中 某一条记录的 某一个字段 */ <T> T queryForObject(String sql, Class<T> requiredType); //--------------------------------------------------------------------- // queryForMap //--------------------------------------------------------------------- Map<String, Object> queryForMap(String sql); Map<String, Object> queryForMap(String sql, Object... args); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/JdbcOperations.java
Java
apache-2.0
2,022
package cn.bugstack.springframework.jdbc.core; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author zhangdd on 2022/2/12 */ public interface PreparedStatementCallback<T> { T doInPreparedStatement(PreparedStatement ps) throws SQLException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/PreparedStatementCallback.java
Java
apache-2.0
276
package cn.bugstack.springframework.jdbc.core; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author zhangdd on 2022/2/12 */ public interface PreparedStatementCreator { PreparedStatement createPreparedStatement(Connection con) throws SQLException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/PreparedStatementCreator.java
Java
apache-2.0
312
package cn.bugstack.springframework.jdbc.core; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author zhangdd on 2022/2/12 */ public interface PreparedStatementSetter { void setValues(PreparedStatement ps) throws SQLException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/PreparedStatementSetter.java
Java
apache-2.0
262
package cn.bugstack.springframework.jdbc.core; import java.sql.ResultSet; import java.sql.SQLException; /** * @author zhangdd on 2022/2/10 */ public interface ResultSetExtractor<T> { T extractData(ResultSet rs) throws SQLException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/ResultSetExtractor.java
Java
apache-2.0
243
package cn.bugstack.springframework.jdbc.core; import java.sql.ResultSet; import java.sql.SQLException; /** * sql行转换 * * @author zhangdd on 2022/2/10 */ public interface RowMapper<T> { T mapRow(ResultSet rs, int rowNum) throws SQLException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/RowMapper.java
Java
apache-2.0
261
package cn.bugstack.springframework.jdbc.core; import cn.hutool.core.lang.Assert; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * 将查询结果的ResultSet逐行的进行转换提取,转换成map,放到list里 * * @author zhangdd on 2022/2/10 */ public class RowMapperResultSetExtractor<T> implements ResultSetExtractor<List<T>> { private final RowMapper<T> rowMapper; private final int rowsExpected; public RowMapperResultSetExtractor(RowMapper<T> rowMapper) { this(rowMapper, 0); } public RowMapperResultSetExtractor(RowMapper<T> rowMapper, int rowsExpected) { Assert.notNull(rowMapper, "RowMapper is required"); this.rowMapper = rowMapper; this.rowsExpected = rowsExpected; } @Override public List<T> extractData(ResultSet rs) throws SQLException { List<T> results = this.rowsExpected > 0 ? new ArrayList<>(this.rowsExpected) : new ArrayList<>(); int rowNum = 0; while (rs.next()) { results.add(this.rowMapper.mapRow(rs, rowNum++)); } return results; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/RowMapperResultSetExtractor.java
Java
apache-2.0
1,163
package cn.bugstack.springframework.jdbc.core; import cn.bugstack.springframework.jdbc.IncorrectResultSetColumnCountException; import cn.bugstack.springframework.jdbc.support.JdbcUtils; import cn.bugstack.springframework.util.NumberUtils; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * @author zhangdd on 2022/2/10 */ public class SingleColumnRowMapper<T> implements RowMapper<T> { private Class<?> requireType; public SingleColumnRowMapper() { } public SingleColumnRowMapper(Class<T> requireType) { this.requireType = requireType; } @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData rsMetaData = rs.getMetaData(); int columnCount = rsMetaData.getColumnCount(); if (columnCount != 1) { throw new IncorrectResultSetColumnCountException(1, columnCount); } Object result = getColumnValue(rs, 1, this.requireType); if (result != null && this.requireType != null && !this.requireType.isInstance(result)) { // Extracted value does not match already: try to convert it. try { return (T) convertValueToRequiredType(result, this.requireType); } catch (IllegalArgumentException ex) { } } return (T) result; } protected Object getColumnValue(ResultSet rs, int index, Class<?> requireType) throws SQLException { if (null != requireType) { return JdbcUtils.getResultSetValue(rs, index, requireType); } else { return getColumnValue(rs, index); } } protected Object getColumnValue(ResultSet rs, int index) throws SQLException { return JdbcUtils.getResultSetValue(rs, index); } protected Object convertValueToRequiredType(Object value, Class<?> requiredType) { if (String.class == requiredType) { return value.toString(); } else if (Number.class.isAssignableFrom(requiredType)) { if (value instanceof Number) { // Convert original Number to target Number class. return NumberUtils.convertNumberToTargetClass(((Number) value), (Class<Number>) requiredType); } else { // Convert stringified value to target Number class. return NumberUtils.parseNumber(value.toString(), (Class<Number>) requiredType); } } //这里暂时不添加spring-core里的类型转换处理 // else if (this.conversionService != null && this.conversionService.canConvert(value.getClass(), requiredType)) { // return this.conversionService.convert(value, requiredType); // } else { throw new IllegalArgumentException( "Value [" + value + "] is of type [" + value.getClass().getName() + "] and cannot be converted to required type [" + requiredType.getName() + "]"); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/SingleColumnRowMapper.java
Java
apache-2.0
3,040
package cn.bugstack.springframework.jdbc.core; /** * @author zhangdd on 2022/2/9 */ public interface SqlProvider { String getSql(); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/SqlProvider.java
Java
apache-2.0
142
package cn.bugstack.springframework.jdbc.core; import java.sql.SQLException; import java.sql.Statement; /** * @author zhangdd on 2022/2/9 */ public interface StatementCallback<T> { T doInStatement(Statement statement) throws SQLException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/core/StatementCallback.java
Java
apache-2.0
250
package cn.bugstack.springframework.jdbc.datasource; import java.sql.Connection; /** * @author zhangdd on 2022/2/9 */ public interface ConnectionHandler { Connection getConnection(); default void releaseConnection(Connection con) { } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/datasource/ConnectionHandler.java
Java
apache-2.0
256
package cn.bugstack.springframework.jdbc.datasource; import cn.hutool.core.lang.Assert; import java.sql.Connection; /** * @author zhangdd on 2022/2/9 */ public class ConnectionHolder { private ConnectionHandler connectionHandler; private Connection currentConnection; public ConnectionHolder(ConnectionHandler connectionHandler) { this.connectionHandler = connectionHandler; } public ConnectionHolder(Connection connection) { this.connectionHandler = new SimpleConnectionHandler(connection); } public ConnectionHandler getConnectionHandler() { return connectionHandler; } protected boolean hasConnection() { return this.connectionHandler != null; } protected void setConnection(Connection connection) { if (null != this.currentConnection) { if (null != this.connectionHandler) { this.connectionHandler.releaseConnection(this.currentConnection); } this.currentConnection = null; } if (null != connection) { this.connectionHandler = new SimpleConnectionHandler(connection); } else { this.connectionHandler = null; } } protected Connection getConnection() { Assert.notNull(this.connectionHandler, "Active connection is required."); if (null == this.currentConnection) { this.currentConnection = this.connectionHandler.getConnection(); } return this.currentConnection; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/datasource/ConnectionHolder.java
Java
apache-2.0
1,535
package cn.bugstack.springframework.jdbc.datasource; import cn.bugstack.springframework.beans.factory.InitializingBean; import cn.bugstack.springframework.tx.transaction.CannotCreateTransactionException; import cn.bugstack.springframework.tx.transaction.TransactionDefinition; import cn.bugstack.springframework.tx.transaction.TransactionException; import cn.bugstack.springframework.tx.transaction.support.AbstractPlatformTransactionManager; import cn.bugstack.springframework.tx.transaction.support.DefaultTransactionStatus; import cn.bugstack.springframework.tx.transaction.support.TransactionSynchronizationManager; import cn.hutool.core.lang.Assert; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * @author zhangdd on 2022/2/24 */ public class DataSourceTransactionManager extends AbstractPlatformTransactionManager implements InitializingBean { private DataSource dataSource; public DataSourceTransactionManager() { } public DataSourceTransactionManager(DataSource dataSource) { setDataSource(dataSource); afterPropertiesSet(); } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public DataSource getDataSource() { return dataSource; } protected DataSource obtainDataSource() { DataSource dataSource = getDataSource(); Assert.notNull(dataSource, "No DataSource set"); return dataSource; } @Override protected Object doGetTransaction() throws TransactionException { DataSourceTransactionObject txObject = new DataSourceTransactionObject(); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource()); txObject.setConnectionHolder(conHolder, false); return txObject; } @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException { DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction(); Connection con = txObject.getConnectionHolder().getConnection(); try { con.commit(); } catch (SQLException e) { throw new TransactionException("Could not commit JDBC transaction", e); } } @Override protected void doRollback(DefaultTransactionStatus status) throws TransactionException { DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction(); Connection con = txObject.getConnectionHolder().getConnection(); try { con.rollback(); } catch (SQLException e) { throw new TransactionException("Could not roll back JDBC transaction", e); } } @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; Connection con = null; try { Connection newCon = obtainDataSource().getConnection(); txObject.setConnectionHolder(new ConnectionHolder(newCon), true); con = txObject.getConnectionHolder().getConnection(); if (con.getAutoCommit()) { con.setAutoCommit(false); } prepareTransactionalConnection(con, definition); TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder()); } catch (SQLException e) { try { con.close(); } catch (SQLException ex) { ex.printStackTrace(); } txObject.setConnectionHolder(null, false); throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", e); } } @Override public void afterPropertiesSet() { if (null == getDataSource()) { throw new IllegalArgumentException("Property 'datasource' is required"); } } protected void prepareTransactionalConnection(Connection con, TransactionDefinition definition) throws SQLException { if (definition.isReadOnly()) { try (Statement stmt = con.createStatement()) { stmt.execute("set transaction read only"); } } } public static class DataSourceTransactionObject extends JdbcTransactionObjectSupport { private boolean newConnectionHolder; private boolean mustRestoreAutoCommit; public void setConnectionHolder(ConnectionHolder connectionHolder, boolean newConnectionHolder) { super.setConnectionHolder(connectionHolder); this.newConnectionHolder = newConnectionHolder; } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/datasource/DataSourceTransactionManager.java
Java
apache-2.0
4,847
package cn.bugstack.springframework.jdbc.datasource; import cn.bugstack.springframework.jdbc.CannotGetJdbcConnectionException; import cn.bugstack.springframework.tx.transaction.support.TransactionSynchronizationManager; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * @author zhangdd on 2022/2/9 */ public abstract class DataSourceUtils { public static Connection getConnection(DataSource dataSource) { try { return doGetConnection(dataSource); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", e); } } public static Connection doGetConnection(DataSource dataSource) throws SQLException { ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource); if (null != conHolder && conHolder.hasConnection()) { return conHolder.getConnection(); } return fetchConnection(dataSource); } private static Connection fetchConnection(DataSource dataSource) throws SQLException { Connection conn = dataSource.getConnection(); if (null == conn) { throw new IllegalArgumentException("DataSource return null from getConnection():" + dataSource); } return conn; } public static void releaseConnection(Connection con, DataSource dataSource) { try { doReleaseConnection(con, dataSource); } catch (SQLException ex) { // logger.debug("Could not close JDBC Connection", ex); } catch (Throwable ex) { // logger.debug("Unexpected exception on closing JDBC Connection", ex); } } public static void doReleaseConnection(Connection con, DataSource dataSource) throws SQLException { if (con == null) { return; } doCloseConnection(con, dataSource); } public static void doCloseConnection(Connection con, DataSource dataSource) throws SQLException { con.close(); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/datasource/DataSourceUtils.java
Java
apache-2.0
2,090
package cn.bugstack.springframework.jdbc.datasource; /** * @author zhangdd on 2022/2/25 */ public abstract class JdbcTransactionObjectSupport { private ConnectionHolder connectionHolder; public void setConnectionHolder(ConnectionHolder connectionHolder) { this.connectionHolder = connectionHolder; } public ConnectionHolder getConnectionHolder() { return connectionHolder; } public boolean hasConnectionHolder() { return null != this.connectionHolder; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/datasource/JdbcTransactionObjectSupport.java
Java
apache-2.0
520
package cn.bugstack.springframework.jdbc.datasource; import cn.hutool.core.lang.Assert; import java.sql.Connection; /** * @author zhangdd on 2022/2/9 */ public class SimpleConnectionHandler implements ConnectionHandler { private final Connection connection; public SimpleConnectionHandler(Connection connection) { Assert.notNull(connection, "Connection must not be null"); this.connection = connection; } @Override public Connection getConnection() { return this.connection; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/datasource/SimpleConnectionHandler.java
Java
apache-2.0
536
package cn.bugstack.springframework.jdbc.support; import cn.bugstack.springframework.beans.factory.InitializingBean; import javax.sql.DataSource; /** * @author zhangdd on 2022/2/9 */ public abstract class JdbcAccessor implements InitializingBean { private DataSource dataSource; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } protected DataSource obtainDataSource() { return getDataSource(); } @Override public void afterPropertiesSet() { if (null == getDataSource()) { throw new IllegalArgumentException("Property 'datasource' is required"); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/support/JdbcAccessor.java
Java
apache-2.0
746
package cn.bugstack.springframework.jdbc.support; import cn.bugstack.springframework.jdbc.UncategorizedSQLException; import cn.bugstack.springframework.jdbc.core.*; import cn.bugstack.springframework.jdbc.datasource.DataSourceUtils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.lang.Assert; import javax.sql.DataSource; import java.sql.*; import java.util.List; import java.util.Map; /** * @author zhangdd on 2022/2/9 */ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { private int fetchSize = -1; private int maxRows = -1; private int queryTimeout = -1; public JdbcTemplate() { } public JdbcTemplate(DataSource dataSource) { setDataSource(dataSource); afterPropertiesSet(); } public int getFetchSize() { return fetchSize; } public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } public int getMaxRows() { return maxRows; } public void setMaxRows(int maxRows) { this.maxRows = maxRows; } public int getQueryTimeout() { return queryTimeout; } public void setQueryTimeout(int queryTimeout) { this.queryTimeout = queryTimeout; } private <T> T execute(StatementCallback<T> action, boolean closeResources) { Connection con = DataSourceUtils.getConnection(obtainDataSource()); Statement stmt = null; try { stmt = con.createStatement(); applyStatementSettings(stmt); return action.doInStatement(stmt); } catch (SQLException e) { String sql = getSql(action); JdbcUtils.closeStatement(stmt); stmt = null; throw translateException("ConnectionCallback", sql, e); } finally { if (closeResources) { JdbcUtils.closeStatement(stmt); } } } private <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action, boolean closeResources) { Assert.notNull(psc, "PreparedStatementCreator must not be null"); Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(obtainDataSource()); PreparedStatement ps = null; try { ps = psc.createPreparedStatement(con); applyStatementSettings(ps); T result = action.doInPreparedStatement(ps); return result; } catch (SQLException ex) { String sql = getSql(psc); psc = null; JdbcUtils.closeStatement(ps); ps = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw translateException("PreparedStatementCallback", sql, ex); } finally { if (closeResources) { JdbcUtils.closeStatement(ps); DataSourceUtils.releaseConnection(con, getDataSource()); } } } public <T> T query( PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor<T> rse) { Assert.notNull(rse, "ResultSetExtractor must not be null"); return execute(psc, new PreparedStatementCallback<T>() { @Override public T doInPreparedStatement(PreparedStatement ps) throws SQLException { ResultSet rs = null; try { if (pss != null) { pss.setValues(ps); } rs = ps.executeQuery(); return rse.extractData(rs); } finally { JdbcUtils.closeResultSet(rs); } } }, true); } protected void applyStatementSettings(Statement stat) throws SQLException { int fetchSize = getFetchSize(); if (fetchSize != -1) { stat.setFetchSize(fetchSize); } int maxRows = getMaxRows(); if (maxRows != -1) { stat.setMaxRows(maxRows); } } protected UncategorizedSQLException translateException(String task, String sql, SQLException ex) { return new UncategorizedSQLException(task, sql, ex); } private static String getSql(Object sqlProvider) { if (sqlProvider instanceof SqlProvider) { return ((SqlProvider) sqlProvider).getSql(); } else { return null; } } @Override public <T> T execute(StatementCallback<T> action) { return execute(action, true); } @Override public void execute(String sql) { class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider { @Override public Object doInStatement(Statement statement) throws SQLException { statement.execute(sql); return null; } @Override public String getSql() { return sql; } } execute(new ExecuteStatementCallback(), true); } @Override public <T> T query(String sql, ResultSetExtractor<T> res) { Assert.notNull(sql, "SQL must not be null"); Assert.notNull(res, "ResultSetExtractor must be null"); class QueryStatementCallback implements StatementCallback<T>, SqlProvider { @Override public String getSql() { return sql; } @Override public T doInStatement(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery(sql); return res.extractData(rs); } } return execute(new QueryStatementCallback(), true); } @Override public <T> T query(String sql, Object[] args, ResultSetExtractor<T> rse) { return query(sql, newArgPreparedStatementSetter(args), rse); } @Override public <T> List<T> query(String sql, RowMapper<T> rowMapper) { return result(query(sql, new RowMapperResultSetExtractor<>(rowMapper))); } @Override public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) { return result(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper))); } @Override public <T> T query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse) { return query(new SimplePreparedStatementCreator(sql), pss, rse); } @Override public <T> T queryForObject(String sql, RowMapper<T> rowMapper) { List<T> results = query(sql, rowMapper); if (CollUtil.isEmpty(results)) { throw new RuntimeException("Incorrect result size: expected 1, actual 0"); } if (results.size() > 1) { throw new RuntimeException("Incorrect result size: expected 1, actual " + results.size()); } return results.iterator().next(); } @Override public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper) { List<T> results = query(sql, args, new RowMapperResultSetExtractor<>(rowMapper, 1)); if (CollUtil.isEmpty(results)) { throw new RuntimeException("Incorrect result size: expected 1, actual 0"); } if (results.size() > 1) { throw new RuntimeException("Incorrect result size: expected 1, actual " + results.size()); } return results.iterator().next(); } @Override public <T> T queryForObject(String sql, Class<T> requiredType) { return queryForObject(sql, getSingleColumnRowMapper(requiredType)); } @Override public Map<String, Object> queryForMap(String sql) { return result(queryForObject(sql, getColumnMapRowMapper())); } @Override public Map<String, Object> queryForMap(String sql, Object... args) { return result(queryForObject(sql, args, getColumnMapRowMapper())); } @Override public List<Map<String, Object>> queryForList(String sql) { return query(sql, getColumnMapRowMapper()); } @Override public <T> List<T> queryForList(String sql, Class<T> elementType) { return query(sql, getSingleColumnRowMapper(elementType)); } @Override public <T> List<T> queryForList(String sql, Class<T> elementType, Object... args) { return query(sql, args, getSingleColumnRowMapper(elementType)); } @Override public List<Map<String, Object>> queryForList(String sql, Object... args) { return query(sql, args, getColumnMapRowMapper()); } private static <T> T result(T result) { Assert.state(null != result, "No result"); return result; } protected RowMapper<Map<String, Object>> getColumnMapRowMapper() { return new ColumnMapRowMapper(); } protected <T> RowMapper<T> getSingleColumnRowMapper(Class<T> requiredType) { return new SingleColumnRowMapper<>(requiredType); } protected PreparedStatementSetter newArgPreparedStatementSetter(Object[] args) { return new ArgumentPreparedStatementSetter(args); } private static class SimplePreparedStatementCreator implements PreparedStatementCreator, SqlProvider { private final String sql; public SimplePreparedStatementCreator(String sql) { this.sql = sql; } @Override public String getSql() { return this.sql; } @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { return con.prepareStatement(this.sql); } } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/support/JdbcTemplate.java
Java
apache-2.0
9,707
package cn.bugstack.springframework.jdbc.support; //import com.sun.org.slf4j.internal.Logger; //import com.sun.org.slf4j.internal.LoggerFactory; import cn.bugstack.springframework.util.NumberUtils; import cn.hutool.core.util.StrUtil; import java.math.BigDecimal; import java.sql.*; /** * @author zhangdd on 2022/2/9 */ public class JdbcUtils { // private static final Logger logger = LoggerFactory.getLogger(JdbcUtils.class); public static void closeStatement(Statement stmt) { if (null != stmt) { try { stmt.close(); } catch (SQLException e) { // logger.trace("Could not close JDBC statement " + e); } } } public static void closeResultSet( ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException ex) { // logger.trace("Could not close JDBC ResultSet", ex); } catch (Throwable ex) { // We don't trust the JDBC driver: It might throw RuntimeException or Error. // logger.trace("Unexpected exception on closing JDBC ResultSet", ex); } } } public static String lookupColumnName(ResultSetMetaData resultSetMetaData, int columnIndex) throws SQLException { String name = resultSetMetaData.getColumnLabel(columnIndex); if (StrUtil.isEmpty(name)) { name = resultSetMetaData.getColumnName(columnIndex); } return name; } public static Object getResultSetValue(ResultSet rs, int index) throws SQLException { Object obj = rs.getObject(index); String className = null; if (null != obj) { className = obj.getClass().getName(); } if (obj instanceof Blob) { Blob blob = (Blob) obj; obj = blob.getBytes(1, (int) blob.length()); } else if (obj instanceof Clob) { Clob clob = (Clob) obj; obj = clob.getSubString(1, (int) clob.length()); } else if ("oracle.sql.TIMESTAMP".equals(className) || "oracle.sql.TIMESTAMPTZ".equals(className)) { obj = rs.getTimestamp(index); } else if (null != className && className.startsWith("oracle.sql.DATE")) { String metadataClassName = rs.getMetaData().getColumnClassName(index); if ("java.sql.Timestamp".equals(metadataClassName) || "oracle.sql.TIMESTAMP".equals(metadataClassName)) { obj = rs.getTimestamp(index); } else { obj = rs.getDate(index); } } else if (obj instanceof Date) { if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) { obj = rs.getDate(index); } } return obj; } public static Object getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException { if (null == requiredType) { return getResultSetValue(rs, index); } Object value; if (String.class == requiredType) { return rs.getString(index); } else if (boolean.class == requiredType || Boolean.class == requiredType) { value = rs.getBoolean(index); } else if (byte.class == requiredType || Byte.class == requiredType) { value = rs.getByte(index); } else if (short.class == requiredType || Short.class == requiredType) { value = rs.getShort(index); } else if (int.class == requiredType || Integer.class == requiredType) { value = rs.getInt(index); } else if (long.class == requiredType || Long.class == requiredType) { value = rs.getLong(index); } else if (float.class == requiredType || Float.class == requiredType) { value = rs.getFloat(index); } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) { value = rs.getDouble(index); } else if (BigDecimal.class == requiredType) { return rs.getBigDecimal(index); } else if (Date.class == requiredType) { return rs.getDate(index); } else if (Time.class == requiredType) { return rs.getTime(index); } else if (Timestamp.class == requiredType || java.util.Date.class == requiredType) { return rs.getTimestamp(index); } else if (byte[].class == requiredType) { return rs.getBytes(index); } else if (Blob.class == requiredType) { return rs.getBlob(index); } else if (Clob.class == requiredType) { return rs.getClob(index); } else if (requiredType.isEnum()) { Object obj = rs.getObject(index); if (obj instanceof String) { return obj; } else if (obj instanceof Number) { return NumberUtils.convertNumberToTargetClass(((Number) obj), Integer.class); } else { return rs.getString(index); } } else { return rs.getObject(index, requiredType); } return (rs.wasNull() ? null : value); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/jdbc/support/JdbcUtils.java
Java
apache-2.0
5,249
package cn.bugstack.springframework.stereotype; import java.lang.annotation.*; /** * Indicates that an annotated class is a "component". * Such classes are considered as candidates for auto-detection * when using annotation-based configuration and classpath scanning. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Component { String value() default ""; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/stereotype/Component.java
Java
apache-2.0
416
package cn.bugstack.springframework.tx.transaction; /** * @author zhangdd on 2022/2/22 */ public class CannotCreateTransactionException extends TransactionException{ public CannotCreateTransactionException(String message) { super(message); } public CannotCreateTransactionException(String message, Throwable cause) { super(message, cause); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/CannotCreateTransactionException.java
Java
apache-2.0
384
package cn.bugstack.springframework.tx.transaction; /** * @author zhangdd on 2022/2/22 */ public class NestedTransactionNotSupportedException extends CannotCreateTransactionException{ public NestedTransactionNotSupportedException(String message) { super(message); } public NestedTransactionNotSupportedException(String message, Throwable cause) { super(message, cause); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/NestedTransactionNotSupportedException.java
Java
apache-2.0
410
package cn.bugstack.springframework.tx.transaction; /** * @author zhangdd on 2022/2/21 */ public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/PlatformTransactionManager.java
Java
apache-2.0
389
package cn.bugstack.springframework.tx.transaction; /** * @author zhangdd on 2022/2/22 */ public interface SavepointManager { Object createSavepoint() throws TransactionException; void rollbackToSavepoint(Object savepoint) throws TransactionException; void releaseSavepoint(Object savepoint) throws TransactionException; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/SavepointManager.java
Java
apache-2.0
341
package cn.bugstack.springframework.tx.transaction; import java.sql.Connection; /** * @author zhangdd on 2022/2/21 */ public interface TransactionDefinition { /** * 这个是spring默认的事务传播行为 * 如果正处于一个事务中,则加入,否则创建一个新的事务 */ int PROPAGATION_REQUIRED = 0; /** * 如果正处于一个事务中,则加入,否则不使用事务 */ int PROPAGATION_SUPPORTS = 1; /** * 如果正处于一个事务中,则加入,否则抛出异常 */ int PROPAGATION_MANDATORY = 2; /** * 无论如何都会创建一个新事务, * 如果正处于一个事务中,则先挂起当前事务,然后创建 */ int PROPAGATION_REQUIRES_NEW = 3; /** * 不使用事务 * 如果正处于一个事务中,则挂起当前事务,不使用 */ int PROPAGATION_NOT_SUPPORTED = 4; /** * 不使用事务, * 如果正处于一个事务中,则抛出异常 */ int PROPAGATION_NEVER = 5; /** * 嵌套事务 * 如果正处于一个事务中,则创建一个事务嵌套其中(MySQL 采用 SAVEPOINT 保护点实现的),否则创建一个新事务 */ int PROPAGATION_NESTED = 6; /** * 使用默认的隔离级别 */ int ISOLATION_DEFAULT = -1; /** * 读未提交 */ int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED; /** * 读已提交 */ int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED; /** * 可重复读 */ int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ; /** * 串行化 */ int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE; /** * 默认超时时间 */ int TIMEOUT_DEFAULT = -1; /** * 获取传播行为 */ int getPropagationBehavior(); /** * 获取事务隔离级别 */ int getIsolationLevel(); /** * 获取事务超时时间 */ int getTimeout(); boolean isReadOnly(); String getName(); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/TransactionDefinition.java
Java
apache-2.0
2,161
package cn.bugstack.springframework.tx.transaction; /** * @author zhangdd on 2022/2/22 */ public class TransactionException extends RuntimeException{ public TransactionException(String message) { super(message); } public TransactionException(String message, Throwable cause) { super(message, cause); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/TransactionException.java
Java
apache-2.0
341
package cn.bugstack.springframework.tx.transaction; import java.io.Flushable; import java.io.IOException; /** * @author zhangdd on 2022/2/22 */ public interface TransactionStatus extends SavepointManager, Flushable { /** * 是否开启新的事务 */ boolean isNewTransaction(); boolean hasSavepoint(); void setRollbackOnly(); boolean isRollbackOnly(); @Override void flush() throws IOException; boolean isCompleted(); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/TransactionStatus.java
Java
apache-2.0
473
package cn.bugstack.springframework.tx.transaction.annotation; import cn.bugstack.springframework.tx.transaction.interceptor.AbstractFallbackTransactionAttributeSource; import cn.bugstack.springframework.tx.transaction.interceptor.TransactionAttribute; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Collections; import java.util.Set; /** * @author zhangdd on 2022/2/26 */ public class AnnotationTransactionAttributeSource extends AbstractFallbackTransactionAttributeSource implements Serializable { private final boolean publicMethodsOnly; private final Set<TransactionAnnotationParser> annotationParsers; public AnnotationTransactionAttributeSource() { this(true); } public AnnotationTransactionAttributeSource(boolean publicMethodsOnly) { this.publicMethodsOnly = publicMethodsOnly; this.annotationParsers = Collections.singleton(new SpringTransactionAnnotationParser()); } @Override protected TransactionAttribute findTransactionAttribute(Method method) { return determineTransactionAttribute(method); } @Override public TransactionAttribute findTransactionAttribute(Class<?> clazz) { return determineTransactionAttribute(clazz); } protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) { for (TransactionAnnotationParser annotationParser : this.annotationParsers) { TransactionAttribute attr = annotationParser.parseTransactionAnnotation(element); if (attr != null) { return attr; } } return null; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/annotation/AnnotationTransactionAttributeSource.java
Java
apache-2.0
1,708
package cn.bugstack.springframework.tx.transaction.annotation; import cn.bugstack.springframework.core.annotation.AnnotatedElementUtils; import cn.bugstack.springframework.core.annotation.AnnotationAttributes; import cn.bugstack.springframework.tx.transaction.interceptor.RollbackRuleAttribute; import cn.bugstack.springframework.tx.transaction.interceptor.RuleBasedTransactionAttribute; import cn.bugstack.springframework.tx.transaction.interceptor.TransactionAttribute; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; import java.util.ArrayList; import java.util.List; /** * @author zhangdd on 2022/2/26 */ public class SpringTransactionAnnotationParser implements TransactionAnnotationParser, Serializable { @Override public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) { AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes( element, Transactional.class, false, false); if (null != attributes) { return parseTransactionAnnotation(attributes); } else { return null; } } protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); List<RollbackRuleAttribute> rollbackRules = new ArrayList<>(); for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) { rollbackRules.add(new RollbackRuleAttribute(rbRule)); } rbta.setRollbackRules(rollbackRules); return rbta; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/annotation/SpringTransactionAnnotationParser.java
Java
apache-2.0
1,631
package cn.bugstack.springframework.tx.transaction.annotation; import cn.bugstack.springframework.tx.transaction.interceptor.TransactionAttribute; import java.lang.reflect.AnnotatedElement; /** * @author zhangdd on 2022/2/26 */ public interface TransactionAnnotationParser { /** * 解析 事务注解 */ TransactionAttribute parseTransactionAnnotation(AnnotatedElement element); }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/annotation/TransactionAnnotationParser.java
Java
apache-2.0
406
package cn.bugstack.springframework.tx.transaction.annotation; import java.lang.annotation.*; /** * @author zhangdd on 2022/2/26 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Transactional { Class<? extends Throwable>[] rollbackFor() default {}; }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/annotation/Transactional.java
Java
apache-2.0
339
package cn.bugstack.springframework.tx.transaction.interceptor; import cn.bugstack.springframework.core.MethodClassKey; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author zhangdd on 2022/2/26 */ public abstract class AbstractFallbackTransactionAttributeSource implements TransactionAttributeSource { private final Map<Object, TransactionAttribute> attributeCache = new ConcurrentHashMap<>(1024); private static final TransactionAttribute NULL_TRANSACTION_ATTRIBUTE = new DefaultTransactionAttribute() { @Override public String toString() { return "null"; } }; @Override public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) { if (method.getDeclaringClass() == Object.class) { return null; } Object cacheKey = getCacheKey(method, targetClass); TransactionAttribute cached = this.attributeCache.get(cacheKey); if (null != cached) { if (cached == NULL_TRANSACTION_ATTRIBUTE) { return null; } else { return cached; } } else { TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass); if (null == txAttr) { this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE); } else { this.attributeCache.put(cacheKey, txAttr); } return txAttr; } } protected Object getCacheKey(Method method, Class<?> targetClass) { return new MethodClassKey(method, targetClass); } protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) { if (!Modifier.isPublic(method.getModifiers())) { return null; } TransactionAttribute txAttr = findTransactionAttribute(method); if (null != txAttr) { return txAttr; } txAttr = findTransactionAttribute(method.getDeclaringClass()); if (null != txAttr) { return txAttr; } return null; } //--------------------------------------------------------------------- // Abstract methods to be implemented by subclasses start //--------------------------------------------------------------------- /** * 在方法上查找事务的相关属性 */ protected abstract TransactionAttribute findTransactionAttribute(Method method); protected abstract TransactionAttribute findTransactionAttribute(Class<?> clazz); //--------------------------------------------------------------------- // Abstract methods to be implemented by subclasses end //--------------------------------------------------------------------- }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
Java
apache-2.0
2,895
package cn.bugstack.springframework.tx.transaction.interceptor; import cn.bugstack.springframework.aop.ClassFilter; import cn.bugstack.springframework.aop.Pointcut; import cn.bugstack.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor; /** * @author zhangdd on 2022/2/27 */ public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor { private TransactionAttributeSource transactionAttributeSource; private final TransactionAttributeSourcePointcut pointcut=new TransactionAttributeSourcePointcut() { @Override protected TransactionAttributeSource getTransactionAttributeSource() { return transactionAttributeSource; } }; public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) { this.transactionAttributeSource = transactionAttributeSource; } public void setClassFilter(ClassFilter classFilter){ this.pointcut.setClassFilter(classFilter); } @Override public Pointcut getPointcut() { return pointcut; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/interceptor/BeanFactoryTransactionAttributeSourceAdvisor.java
Java
apache-2.0
1,108
package cn.bugstack.springframework.tx.transaction.interceptor; import cn.bugstack.springframework.tx.transaction.support.DefaultTransactionDefinition; /** * @author zhangdd on 2022/2/26 */ public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute { public DefaultTransactionAttribute() { super(); } @Override public boolean rollbackOn(Throwable ex) { return (ex instanceof RuntimeException || ex instanceof Error); } @Override public String toString() { return "DefaultTransactionAttribute{}"; } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/interceptor/DefaultTransactionAttribute.java
Java
apache-2.0
617
package cn.bugstack.springframework.tx.transaction.interceptor; import cn.bugstack.springframework.tx.transaction.support.DelegatingTransactionDefinition; import java.io.Serializable; /** * @author zhangdd on 2022/2/27 */ public abstract class DelegatingTransactionAttribute extends DelegatingTransactionDefinition implements TransactionAttribute, Serializable { private final TransactionAttribute targetAttribute; public DelegatingTransactionAttribute(TransactionAttribute targetAttribute) { super(targetAttribute); this.targetAttribute = targetAttribute; } @Override public boolean rollbackOn(Throwable ex) { return this.targetAttribute.rollbackOn(ex); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/interceptor/DelegatingTransactionAttribute.java
Java
apache-2.0
718
package cn.bugstack.springframework.tx.transaction.interceptor; import java.io.Serializable; /** * @author zhangdd on 2022/2/26 */ public class RollbackRuleAttribute implements Serializable { private final String exceptionName; public RollbackRuleAttribute(Class<?> clazz) { this.exceptionName = clazz.getName(); } }
2302_77879529/spring
small-spring-step-19/src/main/java/cn/bugstack/springframework/tx/transaction/interceptor/RollbackRuleAttribute.java
Java
apache-2.0
343