From 70097cade0b68a7ce574ebfdec5ea2693f04228c Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sat, 27 Nov 2021 13:10:52 +0800 Subject: [PATCH 01/37] =?UTF-8?q?=E4=BF=AE=E6=94=B9pom=E5=88=B03.0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- springboot-plugin-framework-extension/pom.xml | 2 +- .../springboot-plugin-framework-extension-log/pom.xml | 4 ++-- .../springboot-plugin-framework-extension-mybatis/pom.xml | 4 ++-- .../springboot-plugin-framework-extension-resources/pom.xml | 4 ++-- springboot-plugin-framework/pom.xml | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index c416713..e2f5a00 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.gitee.starblues springboot-plugin-framework-parent pom - 2.4.6-RELEASE + 3.0.0-RELEASE spring boot 插件开发集成包 diff --git a/springboot-plugin-framework-extension/pom.xml b/springboot-plugin-framework-extension/pom.xml index c206ec1..69f4f83 100644 --- a/springboot-plugin-framework-extension/pom.xml +++ b/springboot-plugin-framework-extension/pom.xml @@ -9,7 +9,7 @@ com.gitee.starblues springboot-plugin-framework-extension pom - 2.4.6-RELEASE + 3.0.0-RELEASE spring boot 插件式开发集成包--扩展模块 diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml index 31a1b6a..0d505c9 100644 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml @@ -12,7 +12,7 @@ com.gitee.starblues springboot-plugin-framework-extension-log - 2.4.6-RELEASE + 3.0.0-RELEASE 插件扩展-日志模块扩展 @@ -62,7 +62,7 @@ 3.1.0 1.6 - 2.4.6-RELEASE + 3.0.0-RELEASE 5.0.7.RELEASE 1.2.3 2.14.1 diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml index 8bbb501..ff2d825 100644 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml @@ -13,7 +13,7 @@ com.gitee.starblues springboot-plugin-framework-extension-mybatis - 2.4.6-RELEASE + 3.0.0-RELEASE jar 插件扩展-spring boot mybatis 集成扩展 @@ -64,7 +64,7 @@ 3.1.0 1.6 - 2.4.6-RELEASE + 3.0.0-RELEASE 2.0.1 3.4.1 2.1.5 diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml index 70af63f..d589dfb 100644 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml @@ -13,7 +13,7 @@ com.gitee.starblues springboot-plugin-framework-extension-resources - 2.4.6-RELEASE + 3.0.0-RELEASE jar 插件扩展-通过url读取插件中的静态资源 @@ -69,7 +69,7 @@ 5.0.7.RELEASE 4.0.1 - 2.4.6-RELEASE + 3.0.0-RELEASE 2.0.3.RELEASE 2.1.1.RELEASE diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index da29449..52efcb3 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -13,7 +13,7 @@ com.gitee.starblues springboot-plugin-framework jar - 2.4.6-RELEASE + 3.0.0-RELEASE spring boot 插件式开发集成包 -- Gitee From 5e80cc719b75d523928f50edcf0e092ef3770738 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sun, 28 Nov 2021 19:08:08 +0800 Subject: [PATCH 02/37] =?UTF-8?q?=E6=96=B0=E5=A2=9E3.0.0=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../starblues/core/DefaultPluginChecker.java | 42 + .../starblues/core/DefaultPluginManager.java | 244 +++++ .../core/DefaultRealizeProvider.java | 102 +++ .../gitee/starblues/core/PluginChecker.java | 26 + .../starblues/core/PluginConfiguration.java | 40 + .../gitee/starblues/core/PluginException.java | 34 + .../gitee/starblues/core/PluginManager.java | 92 ++ .../com/gitee/starblues/core/PluginState.java | 61 ++ .../gitee/starblues/core/RealizeProvider.java | 44 + .../com/gitee/starblues/core/RuntimeMode.java | 31 + .../AbstractPluginClassLoader.java | 11 + .../classloader/AbstractResourceLoader.java | 59 ++ .../core/classloader/ClassPathLoader.java | 73 ++ .../DefaultMainResourceDefiner.java | 99 ++ .../classloader/EmptyMainResourceDefiner.java | 25 + .../core/classloader/JarResourceLoader.java | 59 ++ .../core/classloader/MainResourceDefiner.java | 32 + .../core/classloader/PluginClassLoader.java | 173 ++++ .../starblues/core/classloader/Resource.java | 55 ++ .../classloader/ResourceLoaderFactory.java | 102 +++ .../AbstractPluginDescriptorLoader.java | 73 ++ .../descriptor/DefaultPluginDescriptor.java | 118 +++ .../descriptor/DevPluginDescriptorLoader.java | 35 + .../core/descriptor/PluginDependency.java | 30 + .../core/descriptor/PluginDescriptor.java | 79 ++ .../descriptor/PluginDescriptorLoader.java | 37 + .../ProdPluginDescriptorLoader.java | 31 + .../core/loader/DefaultPluginLoader.java | 137 +++ .../starblues/core/loader/PluginLoader.java | 22 + .../starblues/core/loader/PluginWrapper.java | 58 ++ .../core/loader/PluginWrapperFace.java | 56 ++ .../core/loader/PluginWrapperInside.java | 76 ++ .../gitee/starblues/core/package-info.java | 5 + .../core/scanner/BasePluginScanner.java | 60 ++ .../core/scanner/DevPathResolve.java | 39 + .../starblues/core/scanner/PathResolve.java | 20 + .../starblues/core/scanner/PluginScanner.java | 21 + .../core/scanner/ProdPathResolve.java | 41 + .../spring/BasePluginSpringApplication.java | 102 +++ .../core/spring/PluginApplicationContext.java | 31 + .../spring/PluginBeanDefinitionLoader.java | 281 ++++++ .../core/spring/PluginSpringApplication.java | 33 + .../environment/FilteredPropertySource.java | 50 + .../environment/LocalConfigFileLoader.java | 7 + .../PluginEnvironmentProcessor.java | 21 + .../PluginLocalConfigFileProcessor.java | 862 ++++++++++++++++++ .../core/version/SemverVersionInspector.java | 19 + .../core/version/VersionInspector.java | 19 + .../AutoIntegrationConfiguration.java | 22 +- .../integration/ConfigurationBuilder.java | 19 +- .../DefaultIntegrationConfiguration.java | 6 +- .../integration/IntegrationConfiguration.java | 13 +- .../application/DefaultPluginApplication.java | 51 +- .../manager/DefaultPluginManagerFactory.java | 33 + .../manager/PluginManagerFactory.java | 19 + .../operator/DefaultPluginOperator.java | 29 +- .../pf4j/ConfigPluginStatusProvider.java | 1 + .../integration/pf4j/DefaultPf4jFactory.java | 3 +- .../integration/pf4j/JarPluginLoader.java | 1 + .../integration/pf4j/Pf4jFactory.java | 1 + .../pf4j/SortDependencyResolver.java | 1 + .../DefaultPluginDescriptorExtend.java | 1 + .../ManifestPluginDescriptorFinderExtend.java | 1 + .../descriptor/PluginDescriptorExtend.java | 1 + ...solvePropertiesPluginDescriptorFinder.java | 1 + .../ResourcesPluginDescriptorFinder.java | 1 + .../com/gitee/starblues/utils/Assert.java | 72 ++ .../gitee/starblues/utils/CommonUtils.java | 4 +- .../gitee/starblues/utils/ObjectUtils.java | 377 ++++++++ .../starblues/utils/PluginFileUtils.java | 67 +- .../starblues/utils/ReflectionUtils.java | 84 ++ .../gitee/starblues/utils/ResourceUtils.java | 22 + 72 files changed, 4504 insertions(+), 93 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java new file mode 100644 index 0000000..18e0f9a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java @@ -0,0 +1,42 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.Assert; + +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginChecker implements PluginChecker{ + + + @Override + public void check(Path path) throws Exception { + if(path == null){ + throw new Exception("path 文件路径不能为空"); + } + if(Files.notExists(path)){ + throw new Exception("不存在文件: " + path.toString()); + } + } + + @Override + public void check(PluginDescriptor descriptor) throws Exception { + Assert.isNotNull(descriptor, "PluginDescriptor 不能为空"); + + Assert.isNotEmpty(descriptor.getPluginPath(), + "插件路径[pluginDescriptor->getPluginPath] 不能为空"); + + Assert.isNotNull(descriptor.getPluginId(), + "插件id[pluginDescriptor->getPluginId] 不能为空"); + + Assert.isNotNull(descriptor.getPluginClass(), + "插件id[pluginDescriptor->getPluginClass] 不能为空"); + + Assert.isNotNull(descriptor.getPluginVersion(), + "插件id[pluginDescriptor->getPluginVersion] 不能为空"); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java new file mode 100644 index 0000000..714e6b0 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -0,0 +1,244 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.core.loader.PluginWrapperFace; +import com.gitee.starblues.core.loader.PluginWrapperInside; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +/** + * 抽象的插件管理者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginManager implements PluginManager{ + + private final Logger log = LoggerFactory.getLogger(this.getClass()); + + private final RealizeProvider provider; + private final List pluginRootDirs; + + private PluginConfiguration configuration = new PluginConfiguration(); + + private final AtomicBoolean loaded = new AtomicBoolean(false); + + private final Map startedPlugins = new ConcurrentHashMap<>(); + private final Map resolvedPlugins = new ConcurrentHashMap<>(); + + public DefaultPluginManager(RealizeProvider realizeProvider, String ...pluginRootDirs) { + this(realizeProvider, pluginRootDirs == null ? null : Arrays.asList(pluginRootDirs)); + } + + public DefaultPluginManager(RealizeProvider realizeProvider, List pluginRootDirs) { + this.provider = Assert.isNotNull(realizeProvider, + "参数 realizeProvider 不能为空"); + this.pluginRootDirs = Assert.isNotEmpty(pluginRootDirs, "参数 pluginRootDirs 不能为空"); + } + + public void setConfiguration(PluginConfiguration configuration) { + this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); + } + + @Override + public List getPluginsRoot() { + return pluginRootDirs.stream() + .filter(Objects::nonNull) + .map(Paths::get) + .collect(Collectors.toList()); + } + + @Override + public synchronized List loadPlugins() { + if(loaded.get()){ + throw new RuntimeException("已经加载过了插件, 不能在重复调用: loadPlugins"); + } + try { + List scanPluginPaths = provider.getPluginScanner().scan(pluginRootDirs); + if(ObjectUtils.isEmpty(scanPluginPaths)){ + log.warn("没有发现插件!"); + return Collections.emptyList(); + } + List result = new ArrayList<>(scanPluginPaths.size()); + for (Path path : scanPluginPaths) { + try { + PluginDescriptor descriptor = load(path); + if(descriptor != null){ + result.add(descriptor); + } + } catch (PluginException e) { + log.error("从路径[{}]加载插件失败. {}", path, e.getMessage(), e); + } + } + return result; + } finally { + loaded.set(true); + } + } + + @Override + public PluginDescriptor load(String pluginPath) throws PluginException { + Path path = Paths.get(pluginPath); + return load(path); + } + + @Override + public void unLoad(String pluginId) { + resolvedPlugins.remove(pluginId); + } + + @Override + public PluginDescriptor install(String pluginPath) throws PluginException { + PluginDescriptor pluginDescriptor = load(pluginPath); + if(pluginDescriptor == null){ + throw new PluginException("安装[" + pluginPath + "]插件包失败."); + } + return start(pluginDescriptor); + } + + @Override + public synchronized void uninstall(String pluginId) throws PluginException { + PluginWrapper pluginWrapper = startedPlugins.get(pluginId); + PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); + if(pluginWrapper == null && pluginDescriptor == null){ + throw new PluginException("没有发现插件: " + pluginId); + } + if(pluginWrapper != null){ + stop(pluginWrapper); + startedPlugins.remove(pluginId); + } else { + resolvedPlugins.remove(pluginId); + } + } + + @Override + public void upgrade(String pluginPath) throws PluginException { + PluginDescriptor upgradePluginDescriptor = load(pluginPath); + if(upgradePluginDescriptor == null){ + throw new PluginException("解析[" + pluginPath + "]插件更新包失败."); + } + String pluginId = upgradePluginDescriptor.getPluginId(); + PluginWrapper pluginWrapper = startedPlugins.get(pluginId); + PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); + if(pluginWrapper == null && pluginDescriptor == null){ + throw new PluginException("没有发现插件: " + pluginId + ", 无法更新."); + } + String oldPluginVersion; + if(pluginDescriptor != null){ + oldPluginVersion = pluginDescriptor.getPluginVersion(); + } else { + oldPluginVersion = pluginWrapper.getPluginDescriptor().getPluginVersion(); + } + int compareVersion = provider.getVersionInspector().compareTo(oldPluginVersion, + upgradePluginDescriptor.getPluginVersion()); + if(compareVersion < 0){ + throw new PluginException("更新插件包[" + upgradePluginDescriptor.getPluginVersion() + "]版本不能小于等于:" + + oldPluginVersion); + } + if(pluginDescriptor != null){ + // 说明插件没有被启动 + resolvedPlugins.put(pluginId, upgradePluginDescriptor); + } else { + uninstall(pluginId); + } + start(upgradePluginDescriptor); + } + + @Override + public PluginDescriptor start(String pluginId) throws PluginException { + PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); + if(pluginDescriptor == null){ + throw new PluginException("没有发现插件: " + pluginId); + } + return start(pluginDescriptor); + } + + @Override + public PluginDescriptor stop(String pluginId) throws PluginException { + PluginWrapper pluginWrapper = startedPlugins.get(pluginId); + if(pluginWrapper == null){ + throw new PluginException("没有发现插件: " + pluginId); + } + stop(pluginWrapper); + return pluginWrapper.getPluginDescriptor(); + } + + @Override + public List getPluginDescriptors() { + List pluginDescriptors = new ArrayList<>(resolvedPlugins.values()); + for (PluginWrapper value : startedPlugins.values()) { + pluginDescriptors.add(value.getPluginDescriptor()); + } + return pluginDescriptors; + } + + @Override + public List getPluginWrappers() { + List pluginWrappers = new ArrayList<>(startedPlugins.size()); + for (PluginWrapper value : startedPlugins.values()) { + pluginWrappers.add(new PluginWrapperFace(value)); + } + return pluginWrappers; + } + + private PluginDescriptor load(Path pluginPath) throws PluginException { + try { + provider.getPluginChecker().check(pluginPath); + } catch (Exception e) { + throw new PluginException("非法插件: " + pluginPath, e); + } + PluginDescriptor pluginDescriptor = provider.getPluginDescriptor().load(pluginPath); + if(pluginDescriptor == null){ + return null; + } + String pluginId = pluginDescriptor.getPluginId(); + if(resolvedPlugins.containsKey(pluginId) || startedPlugins.containsKey(pluginId)){ + log.error("已经存在插件: {}", pluginId); + return null; + } + resolvedPlugins.put(pluginDescriptor.getPluginId(), pluginDescriptor); + return pluginDescriptor; + } + + private PluginDescriptor start(PluginDescriptor pluginDescriptor) throws PluginException { + String pluginId = pluginDescriptor.getPluginId(); + if(startedPlugins.containsKey(pluginId)){ + throw new PluginException("已经存在插件: " + pluginId); + } + try { + provider.getPluginChecker().check(pluginDescriptor); + PluginWrapperInside pluginWrapper = provider.getPluginLoader().load(pluginDescriptor); + pluginWrapper.setPluginState(PluginState.RESOLVED); + start(pluginWrapper); + pluginWrapper.setPluginState(PluginState.STARTED); + log.info("启动插件 [{}] 成功.", pluginId); + return pluginDescriptor; + } catch (Exception e) { + throw new PluginException("启动插件 [" + pluginId + "] 失败. ", e); + } + } + + private void start(PluginWrapper pluginWrapper){ + String pluginId = pluginWrapper.getPluginId(); + pluginWrapper.getPluginApplicationContext().run(); + startedPlugins.put(pluginId, pluginWrapper); + resolvedPlugins.remove(pluginId); + } + + private void stop(PluginWrapper pluginWrapper){ + String pluginId = pluginWrapper.getPluginId(); + pluginWrapper.getPluginApplicationContext().close(); + resolvedPlugins.put(pluginId, pluginWrapper.getPluginDescriptor()); + startedPlugins.remove(pluginId); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java new file mode 100644 index 0000000..15de429 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -0,0 +1,102 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.classloader.DefaultMainResourceDefiner; +import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.ProdPluginDescriptorLoader; +import com.gitee.starblues.core.loader.DefaultPluginLoader; +import com.gitee.starblues.core.loader.PluginLoader; +import com.gitee.starblues.core.scanner.BasePluginScanner; +import com.gitee.starblues.core.scanner.DevPathResolve; +import com.gitee.starblues.core.scanner.PluginScanner; +import com.gitee.starblues.core.scanner.ProdPathResolve; +import com.gitee.starblues.core.version.SemverVersionInspector; +import com.gitee.starblues.core.version.VersionInspector; +import com.gitee.starblues.utils.Assert; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class DefaultRealizeProvider implements RealizeProvider { + + private PluginScanner pluginScanner; + private PluginDescriptorLoader pluginDescriptorLoader; + private PluginLoader pluginLoader; + private PluginChecker pluginChecker; + private VersionInspector versionInspector; + + private final RuntimeMode runtimeMode; + private final String mainPackage; + + public DefaultRealizeProvider(RuntimeMode runtimeMode, + String mainPackage){ + this.runtimeMode = Assert.isNotNull(runtimeMode, "参数 runtimeMode 不能为空"); + this.mainPackage = Assert.isNotEmpty(mainPackage, "参数 mainPackage 不能为空"); + init(); + } + + protected void init() { + BasePluginScanner basePluginScanner = new BasePluginScanner(); + PluginDescriptorLoader pluginDescriptorLoader = null; + if(runtimeMode == RuntimeMode.DEV){ + basePluginScanner.setPathResolve(new DevPathResolve()); + pluginDescriptorLoader = new DevPluginDescriptorLoader(); + } else { + basePluginScanner.setPathResolve(new ProdPathResolve()); + pluginDescriptorLoader = new ProdPluginDescriptorLoader(); + } + + setPluginScanner(basePluginScanner); + setPluginDescriptorLoader(pluginDescriptorLoader); + setPluginLoader(new DefaultPluginLoader(new DefaultMainResourceDefiner(mainPackage))); + setPluginChecker(new DefaultPluginChecker()); + setVersionInspector(new SemverVersionInspector()); + } + + public void setPluginScanner(PluginScanner pluginScanner) { + this.pluginScanner = Assert.isNotNull(pluginScanner, "pluginScanner 不能为空"); + } + + public void setPluginDescriptorLoader(PluginDescriptorLoader pluginDescriptorLoader) { + this.pluginDescriptorLoader = Assert.isNotNull(pluginDescriptorLoader, + "pluginDescriptorLoader 不能为空"); + } + + public void setPluginLoader(PluginLoader pluginLoader) { + this.pluginLoader = Assert.isNotNull(pluginLoader, "pluginLoader 不能为空"); + } + + public void setPluginChecker(PluginChecker pluginChecker) { + this.pluginChecker = Assert.isNotNull(pluginChecker, "pluginChecker 不能为空"); + } + + public void setVersionInspector(VersionInspector versionInspector) { + this.versionInspector = Assert.isNotNull(versionInspector, "versionInspector 不能为空"); + } + + @Override + public PluginScanner getPluginScanner() { + return Assert.isNotNull(pluginScanner, "PluginScanner 实现不能为空"); + } + + @Override + public PluginDescriptorLoader getPluginDescriptor() { + return Assert.isNotNull(pluginDescriptorLoader, "PluginDescriptorLoader 实现不能为空"); + } + + @Override + public PluginLoader getPluginLoader() { + return Assert.isNotNull(pluginLoader, "PluginLoader 实现不能为空"); + } + + @Override + public PluginChecker getPluginChecker() { + return Assert.isNotNull(pluginChecker, "PluginChecker 实现不能为空"); + } + + @Override + public VersionInspector getVersionInspector() { + return Assert.isNotNull(versionInspector, "VersionInspector 实现不能为空"); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java new file mode 100644 index 0000000..72b16ef --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java @@ -0,0 +1,26 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import java.nio.file.Path; + +/** + * 检查插件是否合法 + * @author starBlues + */ +public interface PluginChecker { + + /** + * 根据路径检查 + * @param path path + * @throws Exception 检查异常 + */ + void check(Path path) throws Exception; + + /** + * 检查 + * @param descriptor 插件信息 + * @throws Exception 检查异常 + */ + void check(PluginDescriptor descriptor) throws Exception; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java new file mode 100644 index 0000000..3c801a3 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java @@ -0,0 +1,40 @@ +package com.gitee.starblues.core; + +import java.util.List; +import java.util.Set; + +/** + * 配置 + * @author starBlues + * @version 3.0.0 + */ +public class PluginConfiguration { + + private Set disabledPluginId; + private List sortedPluginId; + + public void setDisabledPluginIds(Set disabledPluginId) { + this.disabledPluginId = disabledPluginId; + } + + public void setSortedPluginId(List sortedPluginId) { + this.sortedPluginId = sortedPluginId; + } + + /** + * 得到禁用的插件id + * @return Set + */ + public Set getDisabledPluginId(){ + return disabledPluginId; + } + + /** + * 得到按照循序启动的插件id + * @return Set + */ + public List getSortedPluginId(){ + return sortedPluginId; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java new file mode 100644 index 0000000..1029bfa --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java @@ -0,0 +1,34 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.utils.ObjectUtils; + +/** + * 插件异常 + * @author starBlues + * @version 3.0.03 + */ +public class PluginException extends Exception{ + + public PluginException() { + super(); + } + + public PluginException(String message) { + this(null, message); + } + + public PluginException(String message, Throwable cause) { + this(null, message, cause); + } + + public PluginException(String pluginId, String message) { + this(null, message, null); + } + + public PluginException(String pluginId, String message, Throwable cause) { + super(ObjectUtils.isEmpty(pluginId) ? message : "插件[" + pluginId + "]操作异常. " + message, + cause); + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java new file mode 100644 index 0000000..fc9face --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -0,0 +1,92 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.integration.operator.module.PluginInfo; + +import java.nio.file.Path; +import java.util.List; + +/** + * 插件管理者 + * @author starBlues + */ +public interface PluginManager { + + /** + * 得到插件root目录 + * @return List + */ + List getPluginsRoot(); + + /** + * 加载配置目录中全部插件 + * @return 加载的插件信息 + */ + List loadPlugins(); + + /** + * 安装具体插件路径来加载插件 + * @param pluginPath 插件路径 + * @return 加载的插件信息 + * @throws PluginException 插件异常 + */ + PluginDescriptor load(String pluginPath) throws PluginException; + + /** + * 卸载加载插件 + * @param pluginId 插件id + */ + void unLoad(String pluginId); + + /** + * 安装路径直接安装插件, 并启动 + * @param pluginPath 插件路径 + * @return 安装的插件信息 + * @throws PluginException 插件异常 + */ + PluginDescriptor install(String pluginPath) throws PluginException; + + /** + * 卸载插件 + * @param pluginId 插件id + * @throws PluginException 插件异常 + */ + void uninstall(String pluginId) throws PluginException; + + /** + * 更新已经安装的插件 + * @param pluginPath 新版本插件路径 + * @throws PluginException 插件异常 + */ + void upgrade(String pluginPath) throws PluginException; + + /** + * 启动处于 RESOLVED 状态的插件 + * @param pluginId 插件id + * @return PluginDescriptor + * @throws PluginException 插件异常 + */ + PluginDescriptor start(String pluginId) throws PluginException; + + /** + * 停止启动的插件 + * @param pluginId 插件id + * @return PluginDescriptor + * @throws PluginException 插件异常 + */ + PluginDescriptor stop(String pluginId) throws PluginException; + + /** + * 得到全部的插件信息 + * @return List PluginDescriptor + */ + List getPluginDescriptors(); + + /** + * 得到全部的插件信息 + * @return List PluginWrapper + */ + List getPluginWrappers(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java new file mode 100644 index 0000000..ac616b1 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java @@ -0,0 +1,61 @@ +package com.gitee.starblues.core; + +/** + * 插件状态枚举 + * @author starBlues + * @version 3.0.0 + */ +public enum PluginState { + + /** + * 创建状态 + */ + CREATED("CREATED"), + + + /** + * 禁用状态 + */ + DISABLED("DISABLED"), + + /** + * 被加载了 + */ + RESOLVED("LOADED"), + + /** + * 启动状态 + */ + STARTED("STARTED"), + + /** + * 停止状态 + */ + STOPPED("STOPPED"); + + + private final String status; + + PluginState(String status) { + this.status = status; + } + + public boolean equals(String status) { + return (this.status.equalsIgnoreCase(status)); + } + + @Override + public String toString() { + return status; + } + + public static PluginState parse(String string) { + for (PluginState status : values()) { + if (status.equals(string)) { + return status; + } + } + return null; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java new file mode 100644 index 0000000..9537eac --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -0,0 +1,44 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +import com.gitee.starblues.core.loader.PluginLoader; +import com.gitee.starblues.core.scanner.PluginScanner; +import com.gitee.starblues.core.version.VersionInspector; +/** + * 插件扩展配置 + * @author starBlues + * @version 3.0.0 + */ +public interface RealizeProvider { + + /** + * 得到 PluginScanner 实现 + * @return PluginScanner + */ + PluginScanner getPluginScanner(); + + /** + * 得到 PluginDescriptorLoader 实现 + * @return PluginDescriptorLoader + */ + PluginDescriptorLoader getPluginDescriptor(); + + /** + * 得到 PluginLoader 实现 + * @return PluginLoader + */ + PluginLoader getPluginLoader(); + + /** + * 得到 PluginChecker 实现 + * @return PluginChecker + */ + PluginChecker getPluginChecker(); + + /** + * 得到 VersionInspector 实现 + * @return VersionInspector + */ + VersionInspector getVersionInspector(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java new file mode 100644 index 0000000..28664fe --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.core; + +/** + * 插件运行环境 + * @author starBlues + * @version 3.0.0 + */ +public enum RuntimeMode { + + /** + * 开发环境 + */ + DEV("dev"), + + /** + * 生产环境 + */ + PROD("prod"); + + private final String mode; + + RuntimeMode(String mode) { + this.mode = mode; + } + + @Override + public String toString() { + return mode; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java new file mode 100644 index 0000000..cbc235d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java @@ -0,0 +1,11 @@ +package com.gitee.starblues.core.classloader; + +import java.security.SecureClassLoader; + +/** + * 插件 ClassLoader + * @author starBlues + * @version 3.0.0 + */ +public abstract class AbstractPluginClassLoader extends SecureClassLoader { +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java new file mode 100644 index 0000000..410fdeb --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -0,0 +1,59 @@ +package com.gitee.starblues.core.classloader; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 抽象的资源加载者 + * @author starBlues + * @version 3.0.0 + */ +public abstract class AbstractResourceLoader { + + + private final Map resourceCache = new ConcurrentHashMap<>(); + + protected void addResource(String name, Resource resource) { + if(resourceCache.containsKey(name)){ + return; + } + resourceCache.put(name, resource); + } + + /** + * 初始化 resource + * @throws Exception 初始异常 + */ + public void init() throws Exception{ + + } + + protected boolean existResource(String name){ + return resourceCache.containsKey(name); + } + + public Resource findResource(final String name) { + return resourceCache.get(name); + } + + public InputStream getInputStream(final String name) { + Resource resourceInfo = resourceCache.get(name); + if (resourceInfo != null) { + return new ByteArrayInputStream(resourceInfo.getBytes()); + } else { + return null; + } + } + + public void clear() { + for (Resource resource : resourceCache.values()) { + resource.tryCloseUrlSystemFile(); + } + resourceCache.clear(); + } + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java new file mode 100644 index 0000000..49ce206 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -0,0 +1,73 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; + +import java.io.File; +import java.io.FileInputStream; +import java.net.URL; + +/** + * classpath 资源加载者 + * @author starBlues + * @version 3.0.0 + */ +public class ClassPathLoader extends AbstractResourceLoader{ + + private final URL url; + + public ClassPathLoader(URL url) { + this.url = Assert.isNotNull(url, "url 不能为空"); + } + + @Override + public void init() throws Exception { + File file = new File(url.toURI()); + load(file, ""); + } + + private void load(File file, String packageName) throws Exception { + if(file.isFile()){ + // 文件 + loadResource(file, packageName); + return; + } + if(file.isDirectory()){ + File[] listFiles = file.listFiles(); + if(listFiles == null || listFiles.length == 0){ + return; + } + for (File subFile : listFiles) { + String currentPackage = packageName; + if (subFile.isDirectory()) { + if (!ObjectUtils.isEmpty(currentPackage)) { + currentPackage = currentPackage + "/"; + } + currentPackage = currentPackage + subFile.getName(); + } + load(subFile, currentPackage); + } + } + } + + private void loadResource(File file, String packageName) throws Exception{ + try (FileInputStream fileInputStream = new FileInputStream(file)) { + byte[] bytes = new byte[(int) file.length()]; + + if (fileInputStream.read(bytes) != -1) { + String name; + String fileName = file.getName(); + if(!ObjectUtils.isEmpty(packageName)){ + name = packageName + "/" + fileName; + } else { + name = fileName; + } + Resource resource = new Resource( + name, url, new URL(url.toString() + name), bytes + ); + addResource(name, resource); + } + } + + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java new file mode 100644 index 0000000..f53cfd9 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java @@ -0,0 +1,99 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.Assert; +import org.springframework.core.io.support.SpringFactoriesLoader; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +/** + * 默认主程序资源定义者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultMainResourceDefiner implements MainResourceDefiner{ + + private final Set mainClass = new HashSet<>(); + private final Set mainResources = new HashSet<>(); + private final Set springFactories = new HashSet<>(); + + private final String mainPackageName; + + public DefaultMainResourceDefiner(String mainPackageName){ + this.mainPackageName = Assert.isNotEmpty(mainPackageName, + "参数 mainPackageName 不能为空"); + initDefaultClass(mainPackageName); + initDefaultResources(mainPackageName); + initDefaultSpringFactories(); + } + + + @Override + public Set getClassNames() { + return mainClass; + } + + @Override + public Set getResources() { + return mainResources; + } + + @Override + public Set getSpringFactories() { + return springFactories; + } + + protected void initDefaultClass(String mainPackageName) { + // == java == + mainClass.add("java."); + mainClass.add("javax."); + + // == main == + mainClass.add(mainPackageName); + + // === spring-boot-starter === + // logback-classic + mainClass.add("ch.qos.logback.classic"); + mainClass.add("org.slf4j.impl"); + // logback-core + mainClass.add("ch.qos.logback.core"); + // log4j-api + mainClass.add("org.apache.logging.log4j"); + // log4j-to-slf4j + mainClass.add("org.apache.logging.slf4j"); + // jul-to-slf4j + mainClass.add("org.slf4j.bridge"); + // slf4j-api + mainClass.add("org.slf4j"); + + // spring-boot + mainClass.add("org.springframework.boot"); + // spring-boot-autoconfigure + mainClass.add("org.springframework.boot.autoconfigure"); + // spring-core spring-context spring-aop spring-beans + mainClass.add("org.aopalliance"); + mainClass.add("org.springframework.aop"); + // spring-beans spring-context spring-core spring-expression + mainClass.add("org.springframework"); + // spring-jcl + mainClass.add("org.apache.commons.logging"); + // snakeyaml + mainClass.add("org.yaml.snakeyaml"); + } + + private void initDefaultResources(String mainPackageName) { + mainResources.add(mainPackageName.replace(".", "/")); + mainResources.add("org/springframework"); + mainResources.add("org/slf4j/Logger"); + mainResources.add("org/aopalliance"); + mainResources.add(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION); + } + + private void initDefaultSpringFactories() { + springFactories.add("/spring-boot/"); + springFactories.add("/spring-beans/"); + // 当前框架名称 + springFactories.add(mainPackageName); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java new file mode 100644 index 0000000..495dd4b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java @@ -0,0 +1,25 @@ +package com.gitee.starblues.core.classloader; + +import java.util.Set; + +/** + * 空的 MainResourceDefiner + * @author starBlues + * @version 3.0.0 + */ +public class EmptyMainResourceDefiner implements MainResourceDefiner{ + @Override + public Set getClassNames() { + return null; + } + + @Override + public Set getResources() { + return null; + } + + @Override + public Set getSpringFactories() { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java new file mode 100644 index 0000000..2a1e12a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -0,0 +1,59 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.Assert; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.URL; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +/** + * jar 资源加载者 + * @author starBlues + * @version 3.0.0 + */ +public class JarResourceLoader extends AbstractResourceLoader{ + + private final URL sourceUrl; + private final URL baseUrl; + + public JarResourceLoader(URL url) throws Exception{ + this.sourceUrl = Assert.isNotNull(url, "url 不能为空"); + this.baseUrl = new URL("jar:" + url.toString() + "!/"); + } + + @Override + public void init() throws Exception { + // 解析 + try (InputStream fileInputStream = sourceUrl.openStream(); + BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); + JarInputStream jarStream = new JarInputStream(bufferedInputStream); + ){ + JarEntry jarEntry = null; + while ((jarEntry = jarStream.getNextJarEntry()) != null) { + if (jarEntry.isDirectory()) { + continue; + } + String name = jarEntry.getName(); + if (existResource(name)) { + continue; + } + byte[] bytes = new byte[2048]; + + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + int len = 0; + while ((len = jarStream.read(bytes)) > 0) { + out.write(bytes, 0, len); + } + URL url = new URL(baseUrl.toString() + name); + Resource resource = new Resource( + name, baseUrl, url, out.toByteArray() + ); + addResource(name, resource); + } + } + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java new file mode 100644 index 0000000..c8ea2b3 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java @@ -0,0 +1,32 @@ +package com.gitee.starblues.core.classloader; + +import java.util.Set; + +/** + * 主程序定义者, 从主程序加载资源的定义者 + * @author starBlues + * @version 3.0.0 + */ +public interface MainResourceDefiner { + + /** + * 类名 + * @return 类名前缀集合 + */ + Set getClassNames(); + + /** + * 资源名称 + * @return 资源名称集合 + */ + Set getResources(); + + + /** + * spring spi 定义 + * @return spring spi 集合 + */ + Set getSpringFactories(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java new file mode 100644 index 0000000..51b1457 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -0,0 +1,173 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.ObjectUtils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 插件 classLoader + * @author starBlues + * @version 3.0.0 + */ +public class PluginClassLoader extends AbstractPluginClassLoader { + + private final Map> pluginClassCache = new ConcurrentHashMap<>(); + + private final String pluginId; + private final ClassLoader parent; + private final ResourceLoaderFactory resourceLoaderFactory; + private final MainResourceDefiner mainResourceDefiner; + + public PluginClassLoader(String pluginId, Path classpath, ClassLoader parent) { + this(pluginId, classpath, parent, null); + } + + public PluginClassLoader(String pluginId, Path classpath, ClassLoader parent, MainResourceDefiner definer) { + resourceLoaderFactory = new ResourceLoaderFactory(); + resourceLoaderFactory.addResource(classpath); + this.pluginId = pluginId; + this.parent = parent; + if(definer == null){ + definer = new EmptyMainResourceDefiner(); + } + this.mainResourceDefiner = definer; + } + + + public void addResource(File file) { + resourceLoaderFactory.addResource(file); + } + + public String getPluginId() { + return pluginId; + } + + @Override + public Class loadClass(String className) throws ClassNotFoundException { + synchronized (getClassLoadingLock(className)) { + Set classNames = mainResourceDefiner.getClassNames(); + if(exist(classNames, className)){ + return parent.loadClass(className); + } + Class loadedClass = findLoadedClass(className); + if (loadedClass != null) { + return loadedClass; + } + loadedClass = findPluginClass(className); + if (loadedClass != null) { + return loadedClass; + } + throw new ClassNotFoundException(className); + } + } + + private Class findPluginClass(String name) { + synchronized (pluginClassCache){ + Class aClass = null; + String formatClassName = formatClassName(name); + aClass = pluginClassCache.get(formatClassName); + if (aClass != null) { + return aClass; + } + + Resource resource = resourceLoaderFactory.findResource(formatClassName); + if(resource == null){ + return null; + } + byte[] bytes = null; + bytes = resource.getBytes(); + aClass = defineClass(name, bytes, 0, bytes.length ); + if(aClass == null) { + return null; + } + if (aClass.getPackage() == null) { + int lastDotIndex = name.lastIndexOf( '.' ); + String packageName = (lastDotIndex >= 0) ? name.substring( 0, lastDotIndex) : ""; + definePackage(packageName, null, null, null, null, null, null, null ); + } + pluginClassCache.put(name, aClass); + return aClass; + } + } + + + @Override + public InputStream getResourceAsStream(String name) { + Set resources = mainResourceDefiner.getResources(); + if(exist(resources, name)){ + return parent.getResourceAsStream(name); + } + return resourceLoaderFactory.getInputStream(name); + } + + @Override + public URL getResource(String name) { + Set resources = mainResourceDefiner.getResources(); + if(exist(resources, name)){ + return parent.getResource(name); + } + Resource resource = resourceLoaderFactory.findResource(name); + if(resource == null){ + return null; + } + return resource.getUrl(); + } + + @Override + public Enumeration getResources(String name) throws IOException { + Vector vector = new Vector<>(); + Set resources = mainResourceDefiner.getResources(); + Set springFactories = mainResourceDefiner.getSpringFactories(); + if(exist(resources, name)){ + Enumeration enumeration = parent.getResources(name); + while (enumeration.hasMoreElements()){ + URL url = enumeration.nextElement(); + String path = url.getPath(); + if(exist(springFactories, path)){ + vector.add(url); + } + } + } + List resourceList = resourceLoaderFactory.findResources(name); + if(!ObjectUtils.isEmpty(resourceList)){ + for (Resource resource : resourceList) { + vector.add(resource.getUrl()); + } + } + return vector.elements(); + } + + private String formatClassName(String className) { + className = className.replace( '/', '~' ); + className = className.replace( '.', '/' ) + ".class"; + className = className.replace( '~', '/' ); + return className; + } + + private boolean exist(Set set, String name){ + if(ObjectUtils.isEmpty(set) || ObjectUtils.isEmpty(name)){ + return false; + } + for (String value : set) { + if(name.contains(value)){ + return true; + } + } + return false; + } + + public void clear(){ + synchronized (pluginClassCache){ + pluginClassCache.clear(); + resourceLoaderFactory.clear(); + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java new file mode 100644 index 0000000..8fc36df --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java @@ -0,0 +1,55 @@ +package com.gitee.starblues.core.classloader; + +import java.net.URL; +import java.nio.file.Paths; + +/** + * 资源信息 + * @author starBlues + * @version 3.0.0 + */ +public class Resource { + + private final String name; + private final URL baseUrl; + private final URL url; + private final byte[] bytes; + + public Resource(String name, URL baseUrl, URL url, byte[] bytes) { + this.name = name; + this.baseUrl = baseUrl; + this.url = url; + this.bytes = bytes; + } + + public String getName() { + return name; + } + + public URL getBaseUrl() { + return baseUrl; + } + + public URL getUrl() { + return url; + } + + public byte[] getBytes() { + return bytes; + } + + + void tryCloseUrlSystemFile(){ + try { + Paths.get(baseUrl.toURI()).getFileSystem().close(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Paths.get(url.toURI()).getFileSystem().close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java new file mode 100644 index 0000000..491458c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java @@ -0,0 +1,102 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.PluginFileUtils; + +import java.io.File; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +/** + * @author starBlues + */ +public class ResourceLoaderFactory extends AbstractResourceLoader { + + private final List resourceLoaders = new ArrayList<>(); + + + public void addResource(String path) { + if(path == null || "".equals(path)){ + return; + } + addResource(Paths.get(path)); + } + + public void addResource(File file) { + if(file == null){ + return; + } + addResource(file.toPath()); + } + + public synchronized void addResource(Path path) { + if(path == null){ + return; + } + try { + URL url = path.toUri().toURL(); + AbstractResourceLoader resourceLoader = null; + if(PluginFileUtils.isJarFile(path)) { + resourceLoader = new JarResourceLoader(url); + } else if(Files.isDirectory(path)){ + resourceLoader = new ClassPathLoader(url); + } + if(resourceLoader != null){ + resourceLoader.init(); + resourceLoaders.add(resourceLoader); + } + } catch (Exception e){ + e.printStackTrace(); + } + } + + + @Override + public synchronized Resource findResource(String name) { + for (AbstractResourceLoader resourceLoader : resourceLoaders) { + Resource resourceInfo = resourceLoader.findResource(name); + if(resourceInfo != null){ + return resourceInfo; + } + } + return null; + } + + public synchronized List findResources(String name) { + List resourceInfos = new ArrayList<>(); + for (AbstractResourceLoader resourceLoader : resourceLoaders) { + Resource resource = resourceLoader.findResource(name); + if(resource != null){ + resourceInfos.add(resource); + } + } + return resourceInfos; + } + + @Override + public synchronized InputStream getInputStream(String name) { + for (AbstractResourceLoader resourceLoader : resourceLoaders) { + InputStream inputStream = resourceLoader.getInputStream(name); + if(inputStream != null){ + return inputStream; + } + } + return null; + } + + @Override + public synchronized void clear() { + for (AbstractResourceLoader resourceLoader : resourceLoaders) { + try { + resourceLoader.clear(); + } catch (Exception e){ + // 忽略 + } + } + resourceLoaders.clear(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java new file mode 100644 index 0000000..100c62b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -0,0 +1,73 @@ +package com.gitee.starblues.core.descriptor; + +import com.gitee.starblues.core.PluginException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.Properties; + +/** + * 抽象的 PluginDescriptorLoader + * @author starBlues + * @version 3.0.0 + */ +public abstract class AbstractPluginDescriptorLoader implements PluginDescriptorLoader{ + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + @Override + public PluginDescriptor load(Path location) throws PluginException { + Properties properties = null; + try { + properties = getProperties(location); + if(properties == null){ + logger.warn("路径[{}]没有发现引导文件[{}]", location, BOOTSTRAP_FILE_NAME); + return null; + } + return create(properties, location); + } catch (Exception e) { + throw new PluginException("获取解析[" + location + "]插件引导文件失败." + e.getMessage(), e); + } + } + + /** + * 子类获取 Properties + * @param location properties 路径 + * @return Properties + * @throws Exception 异常 + */ + protected abstract Properties getProperties(Path location) throws Exception; + + protected PluginDescriptor create(Properties properties, Path path){ + DefaultPluginDescriptor descriptor = new DefaultPluginDescriptor( + properties.getProperty(PLUGIN_ID), + properties.getProperty(PLUGIN_VERSION), + properties.getProperty(PLUGIN_CLASS), + path + ); + descriptor.setPluginLibDir(properties.getProperty(PLUGIN_LIB_DIR)); + descriptor.setDescription(properties.getProperty(PLUGIN_DESCRIPTION)); + descriptor.setRequires(properties.getProperty(PLUGIN_REQUIRES)); + descriptor.setProvider(properties.getProperty(PLUGIN_PROVIDER)); + descriptor.setLicense(properties.getProperty(PLUGIN_LICENSE)); + descriptor.setConfigFileName(properties.getProperty(PLUGIN_CONFIG_FILE_NAME)); + return descriptor; + } + + + protected Properties getProperties(InputStream inputStream) throws Exception{ + Properties properties = new Properties(); + try (InputStreamReader input = new InputStreamReader(inputStream, + StandardCharsets.UTF_8)) { + properties.load(input); + } + return properties; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java new file mode 100644 index 0000000..7882d18 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java @@ -0,0 +1,118 @@ +package com.gitee.starblues.core.descriptor; + +import com.gitee.starblues.utils.Assert; + +import java.nio.file.Path; +import java.util.List; + +import static com.gitee.starblues.core.descriptor.PluginDescriptorLoader.*; + +/** + * 默认插件描述者 + * + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginDescriptor implements PluginDescriptor{ + + private final String pluginId; + private final String pluginVersion; + private final String pluginClass; + private final Path pluginPath; + + private String pluginLibDir; + private String description; + private String requires; + private String provider; + private String license; + + private String configFileName; + + public DefaultPluginDescriptor(String pluginId, String pluginVersion, + String pluginClass, Path pluginPath) { + this.pluginId = Assert.isNotEmpty(pluginId, PLUGIN_ID + "不能为空"); + this.pluginVersion = Assert.isNotEmpty(pluginVersion, PLUGIN_VERSION + "不能为空"); + this.pluginClass = Assert.isNotEmpty(pluginClass, PLUGIN_CLASS + "不能为空"); + this.pluginPath = Assert.isNotNull(pluginPath, "插件路径[pluginPath]不能为空"); + } + + void setDescription(String description) { + this.description = description; + } + + void setRequires(String requires) { + this.requires = requires; + } + + void setProvider(String provider) { + this.provider = provider; + } + + void setLicense(String license) { + this.license = license; + } + + void setConfigFileName(String configFileName) { + this.configFileName = configFileName; + } + + @Override + public String getPluginId() { + return pluginId; + } + + @Override + public String getPluginVersion() { + return pluginVersion; + } + + @Override + public String getPluginClass() { + return pluginClass; + } + + @Override + public Path getPluginPath() { + return pluginPath; + } + + @Override + public String getPluginLibDir() { + return pluginLibDir; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String getRequires() { + return requires; + } + + @Override + public String getProvider() { + return provider; + } + + @Override + public String getLicense() { + return license; + } + + @Override + public List getPluginDependency() { + return null; + } + + @Override + public String getConfigFileName() { + return configFileName; + } + + public void setPluginLibDir(String pluginLibDir) { + this.pluginLibDir = pluginLibDir; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java new file mode 100644 index 0000000..92f4304 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java @@ -0,0 +1,35 @@ +package com.gitee.starblues.core.descriptor; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; + +/** + * 开发环境 PluginDescriptorLoader 加载者 + * @author starBlues + * @version 3.0.0 + */ +public class DevPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ + + @Override + protected Properties getProperties(Path location) throws Exception { + String bootstrapFilePath = location.toString() + File.separator + BOOTSTRAP_FILE_NAME; + File file = new File(bootstrapFilePath); + if(!file.exists()){ + return null; + } + Path path = Paths.get(bootstrapFilePath); + try { + return super.getProperties(Files.newInputStream(path)); + } finally { + try { + path.getFileSystem().close(); + } catch (Exception e) { + // 忽略 + } + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java new file mode 100644 index 0000000..2860cc8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.core.descriptor; + +/** + * 插件依赖信息 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginDependency { + + + /** + * 依赖插件id + * @return String + */ + String getDependencyId(); + + /** + * 依赖插件版本 + * @return String + */ + String getDependencyVersion(); + + /** + * 是否必须的 + * @return boolean + */ + boolean optional(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java new file mode 100644 index 0000000..ff96f67 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -0,0 +1,79 @@ +package com.gitee.starblues.core.descriptor; + +import java.nio.file.Path; +import java.util.List; + +/** + * 插件信息 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginDescriptor { + + /** + * 获取插件id + * @return String + */ + String getPluginId(); + + /** + * 获取插件版本 + * @return String + */ + String getPluginVersion(); + + /** + * 获取插件引导类 + * @return String + */ + String getPluginClass(); + + /** + * 获取插件路径 + * @return Path + */ + Path getPluginPath(); + + /** + * 获取插件依赖jar包目录 + * @return String + */ + String getPluginLibDir(); + + /** + * 获取插件描述 + * @return String + */ + String getDescription(); + + /** + * 获取插件所需主程序版本 + * @return String + */ + String getRequires(); + + /** + * 获取插件提供开发者 + * @return String + */ + String getProvider(); + + /** + * 获取插件 license + * @return String + */ + String getLicense(); + + /** + * 获取插件配置文件名称 + * @return String + */ + String getConfigFileName(); + + /** + * 获取当前插件依赖 + * @return List + */ + List getPluginDependency(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java new file mode 100644 index 0000000..0071e01 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java @@ -0,0 +1,37 @@ +package com.gitee.starblues.core.descriptor; + +import com.gitee.starblues.core.PluginException; + +import java.nio.file.Path; + +/** + * 插件描述加载者 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginDescriptorLoader { + + String BOOTSTRAP_FILE_NAME = "plugin.properties"; + + String PLUGIN_ID = "plugin.id"; + String PLUGIN_CLASS = "plugin.class"; + String PLUGIN_VERSION = "plugin.version"; + String PLUGIN_LIB_DIR = "plugin.libDir"; + String PLUGIN_DESCRIPTION = "plugin.description"; + String PLUGIN_PROVIDER = "plugin.provider"; + String PLUGIN_DEPENDENCIES = "plugin.dependencies"; + + String PLUGIN_REQUIRES = "plugin.requires"; + String PLUGIN_LICENSE = "plugin.license"; + String PLUGIN_CONFIG_FILE_NAME = "plugin.configFileName"; + + /** + * 加载 PluginDescriptor + * @param location 引导配置文件路径 + * @return PluginDescriptor + * @throws PluginException 加载异常 + */ + PluginDescriptor load(Path location) throws PluginException; + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java new file mode 100644 index 0000000..b6e968c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.core.descriptor; + +import java.io.InputStream; +import java.nio.file.Path; +import java.util.Properties; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * 生产环境 PluginDescriptorLoader 加载者 + * @author starBlues + * @version 3.0.0 + */ +public class ProdPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ + + @Override + protected Properties getProperties(Path location) throws Exception { + JarFile jarFile = new JarFile(location.toFile()); + JarEntry jarEntry = jarFile.getJarEntry(BOOTSTRAP_FILE_NAME); + if(jarEntry == null){ + return null; + } + try { + InputStream inputStream = jarFile.getInputStream(jarEntry); + return getProperties(inputStream); + } finally { + jarFile.close(); + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java new file mode 100644 index 0000000..d93d8dd --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java @@ -0,0 +1,137 @@ +package com.gitee.starblues.core.loader; + +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.classloader.MainResourceDefiner; +import com.gitee.starblues.core.classloader.PluginClassLoader; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.spring.BasePluginSpringApplication; +import com.gitee.starblues.core.spring.PluginSpringApplication; +import com.gitee.starblues.core.spring.environment.PluginLocalConfigFileProcessor; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; +import org.springframework.util.ClassUtils; + +import java.io.File; +import java.lang.ref.WeakReference; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; + +/** + * 默认的插件加载者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginLoader implements PluginLoader{ + + private final MainResourceDefiner mainResourceDefiner; + + private final List> classLoaderCache = new ArrayList<>(); + + public DefaultPluginLoader(MainResourceDefiner mainResourceDefiner) { + this.mainResourceDefiner = mainResourceDefiner; + } + + @Override + public PluginWrapperInside load(PluginDescriptor descriptor) throws Exception { + Assert.isNotNull(descriptor, "参数 PluginDescriptor 不能为空"); + PluginClassLoader classLoader = getClassLoader(descriptor); + installLib(classLoader, descriptor.getPluginLibDir()); + Class bootstrapClass = classLoader.loadClass(descriptor.getPluginClass()); + PluginSpringApplication springApplication = getPluginSpringApplication(descriptor, + classLoader, bootstrapClass); + PluginWrapperInside pluginWrapperInside = new PluginWrapperInside( + descriptor.getPluginId(), + descriptor, + classLoader, + bootstrapClass, + descriptor.getPluginPath(), + springApplication.getApplicationContext() + ); + pluginWrapperInside.setPluginState(PluginState.CREATED); + return pluginWrapperInside; + } + + private PluginSpringApplication getPluginSpringApplication(PluginDescriptor descriptor, + ClassLoader classLoader, + Class bootstrapClass) { + return new BasePluginSpringApplication(classLoader, bootstrapClass, descriptor.getConfigFileName()); + } + + + protected synchronized PluginClassLoader getClassLoader(PluginDescriptor descriptor){ + String pluginId = descriptor.getPluginId(); + Path classPath = descriptor.getPluginPath(); + Iterator> iterator = classLoaderCache.iterator(); + PluginClassLoader pnClassLoader = null; + while (iterator.hasNext()){ + WeakReference weakReference = iterator.next(); + PluginClassLoader cacheClassLoader = weakReference.get(); + if(cacheClassLoader == null){ + iterator.remove(); + continue; + } + if(Objects.equals(pluginId, cacheClassLoader.getPluginId())){ + pnClassLoader = cacheClassLoader; + pnClassLoader.addResource(classPath.toFile()); + } + } + if(pnClassLoader == null){ + pnClassLoader = new PluginClassLoader(pluginId, classPath, getParentClassLoader(), + mainResourceDefiner); + classLoaderCache.add(new WeakReference<>(pnClassLoader)); + } + return pnClassLoader; + } + + protected void installLib(PluginClassLoader classLoader, String lib){ + if(ObjectUtils.isEmpty(lib)){ + return; + } + File file = new File(lib); + addJarFile(classLoader, file); + if(file.isDirectory()){ + File[] files = file.listFiles(); + if(files == null || files.length == 0){ + return; + } + for (File subFile : files) { + addJarFile(classLoader, subFile); + } + } + } + + + private void addJarFile(PluginClassLoader pnClassLoader, File file){ + if(!file.exists()){ + return; + } + if(PluginFileUtils.isJarFile(file.toPath())){ + pnClassLoader.addResource(file); + } + } + + protected ClassLoader getParentClassLoader(){ + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + } catch (Throwable ex) { + // 忽略 + } + if (cl == null) { + cl = ClassUtils.class.getClassLoader(); + if (cl == null) { + try { + cl = ClassLoader.getSystemClassLoader(); + } catch (Throwable ex) { + // 忽略 + } + } + } + return cl; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java new file mode 100644 index 0000000..74981d0 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java @@ -0,0 +1,22 @@ +package com.gitee.starblues.core.loader; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; + +/** + * 插件加载者 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginLoader { + + + /** + * 根据插件描述加载插件 + * @param descriptor 插件描述 + * @return PluginWrapper + * @throws Exception 加载异常 + */ + PluginWrapperInside load(PluginDescriptor descriptor) throws Exception; + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java new file mode 100644 index 0000000..a0f53c2 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java @@ -0,0 +1,58 @@ +package com.gitee.starblues.core.loader; + +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.spring.PluginSpringApplication; + +import java.nio.file.Path; + +/** + * 插件包装 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginWrapper { + + /** + * 得到插件id + * @return String + */ + String getPluginId(); + + /** + * 得到插件描述 + * @return PluginDescriptor + */ + PluginDescriptor getPluginDescriptor(); + + /** + * 得到插件classLoader + * @return ClassLoader + */ + ClassLoader getPluginClassLoader(); + + /** + * 得到插件引导类 + * @return Class + */ + Class getPluginClass(); + + /** + * 得到插件路径 + * @return Path + */ + Path getPluginPath(); + + /** + * 得到插件 SpringApplication + * @return PluginSpringApplication + */ + PluginSpringApplication getPluginApplicationContext(); + + /** + * 得到插件状态 + * @return PluginState + */ + PluginState getPluginState(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java new file mode 100644 index 0000000..f540d3c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java @@ -0,0 +1,56 @@ +package com.gitee.starblues.core.loader; + +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import org.apache.catalina.core.ApplicationContext; + +import java.nio.file.Path; + +/** + * 外部 PluginWrapperFace + * @author starBlues + * @version 3.0.0 + */ +public class PluginWrapperFace implements PluginWrapper{ + + private final PluginWrapper pluginWrapper; + + public PluginWrapperFace(PluginWrapper pluginWrapper) { + this.pluginWrapper = pluginWrapper; + } + + @Override + public String getPluginId() { + return pluginWrapper.getPluginId(); + } + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginWrapper.getPluginDescriptor(); + } + + @Override + public ClassLoader getPluginClassLoader() { + return pluginWrapper.getPluginClassLoader(); + } + + @Override + public Class getPluginClass() { + return pluginWrapper.getPluginClass(); + } + + @Override + public Path getPluginPath() { + return pluginWrapper.getPluginPath(); + } + + @Override + public ApplicationContext getPluginApplicationContext() { + return pluginWrapper.getPluginApplicationContext(); + } + + @Override + public PluginState getPluginState() { + return pluginWrapper.getPluginState(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java new file mode 100644 index 0000000..670cec4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java @@ -0,0 +1,76 @@ +package com.gitee.starblues.core.loader; + +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.spring.PluginSpringApplication; +import org.apache.catalina.core.ApplicationContext; +import org.springframework.context.support.GenericApplicationContext; + +import java.nio.file.Path; + +/** + * 内部的 + * @author starBlues + */ +public class PluginWrapperInside implements PluginWrapper{ + + private final String pluginId; + private final PluginDescriptor pluginDescriptor; + private final ClassLoader pluginClassLoader; + private final Class pluginClass; + private final Path pluginPath; + private final PluginSpringApplication pluginSpringApplication; + private PluginState pluginState; + + public PluginWrapperInside(String pluginId, PluginDescriptor pluginDescriptor, + ClassLoader pluginClassLoader, Class pluginClass, + Path pluginPath, PluginSpringApplication pluginSpringApplication) { + this.pluginId = pluginId; + this.pluginDescriptor = pluginDescriptor; + this.pluginClassLoader = pluginClassLoader; + this.pluginClass = pluginClass; + this.pluginPath = pluginPath; + this.pluginSpringApplication = pluginSpringApplication; + } + + public void setPluginState(PluginState pluginState) { + this.pluginState = pluginState; + } + + @Override + public String getPluginId() { + return pluginId; + } + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginDescriptor; + } + + @Override + public ClassLoader getPluginClassLoader() { + return pluginClassLoader; + } + + @Override + public Class getPluginClass() { + return pluginClass; + } + + @Override + public Path getPluginPath() { + return pluginPath; + } + + @Override + public PluginSpringApplication getPluginApplicationContext() { + return pluginSpringApplication; + } + + @Override + public PluginState getPluginState() { + return pluginState; + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java new file mode 100644 index 0000000..c4e2fbd --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java @@ -0,0 +1,5 @@ +/** + * @author starBlues + * @version 3.0.0 + */ +package com.gitee.starblues.core; \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java new file mode 100644 index 0000000..fd115e8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java @@ -0,0 +1,60 @@ +package com.gitee.starblues.core.scanner; + +import com.gitee.starblues.utils.ObjectUtils; + +import java.io.File; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * 基本的插件扫描者 + * @author starBlues + * @version 3.0.0 + */ +public class BasePluginScanner implements PluginScanner{ + + private PathResolve pathResolve; + + public void setPathResolve(PathResolve pathResolve) { + this.pathResolve = pathResolve; + } + + @Override + public List scan(List rootDir) { + List pluginPaths = new ArrayList<>(); + for (String dir : rootDir) { + if(ObjectUtils.isEmpty(dir)){ + continue; + } + File file = new File(dir); + if(!file.exists()){ + continue; + } + resolve(file, pluginPaths); + } + return pluginPaths; + } + + protected void resolve(File currentFile, List pluginPaths){ + if(currentFile == null || !currentFile.exists()){ + return; + } + if(pathResolve == null){ + return; + } + Path currentPath = currentFile.toPath(); + currentPath = pathResolve.resolve(currentPath); + if(currentPath != null){ + pluginPaths.add(currentPath); + } else { + File[] files = currentFile.listFiles(); + if(files == null || files.length == 0){ + return; + } + for (File file : files) { + resolve(file, pluginPaths); + } + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java new file mode 100644 index 0000000..c69f5df --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java @@ -0,0 +1,39 @@ +package com.gitee.starblues.core.scanner; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +/** + * 开发环境路径解决器 + * @author starBlues + * @version 3.0.0 + */ +public class DevPathResolve implements PathResolve{ + + private final List devCompilePackageNames = new ArrayList<>(); + + public DevPathResolve() { + addCompilePackageName(); + } + + protected void addCompilePackageName(){ + // 添加maven编译目录 + devCompilePackageNames.add("target".concat(File.separator).concat("classes")); + } + + @Override + public Path resolve(Path path) { + for (String devCompilePackageName : devCompilePackageNames) { + String compilePackagePathStr = path.toString() + File.separator + devCompilePackageName; + Path compilePackagePath = Paths.get(compilePackagePathStr); + if(Files.exists(compilePackagePath)){ + return compilePackagePath; + } + } + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java new file mode 100644 index 0000000..5397ba7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java @@ -0,0 +1,20 @@ +package com.gitee.starblues.core.scanner; + +import java.nio.file.Path; + +/** + * 目录解决器 + * @author starBlues + * @version 3.0.0 + */ +public interface PathResolve { + + /** + * 过滤并返回正确的路径 + * @param path 待过滤路径 + * @return path 处理后的路径, 返回null 表示不可用 + */ + Path resolve(Path path); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java new file mode 100644 index 0000000..e48ea87 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java @@ -0,0 +1,21 @@ +package com.gitee.starblues.core.scanner; + +import java.nio.file.Path; +import java.util.List; + +/** + * 插件扫描者 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginScanner { + + /** + * 从 rootDir 集合中扫描出插件路径 + * @param rootDir 根目录 + * @return 扫描出的目录 + */ + List scan(List rootDir); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java new file mode 100644 index 0000000..7f071cb --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java @@ -0,0 +1,41 @@ +package com.gitee.starblues.core.scanner; + +import com.gitee.starblues.utils.ObjectUtils; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * 生产环境目录解决器 + * @author starBlues + * @version 3.0.0 + */ +public class ProdPathResolve implements PathResolve{ + + private final List extensionNames = new ArrayList<>(); + + public ProdPathResolve(){ + addExtensionName(".jar"); + } + + protected void addExtensionName(String extensionName){ + if(ObjectUtils.isEmpty(extensionName)){ + return; + } + // jar包 + extensionNames.add(extensionName); + } + + @Override + public Path resolve(Path path) { + String fileName = path.getFileName().toString(); + for (String extensionName : extensionNames) { + boolean exist = fileName.toLowerCase().endsWith(extensionName.toUpperCase()); + if(exist){ + return path; + } + } + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java new file mode 100644 index 0000000..25b1846 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java @@ -0,0 +1,102 @@ +package com.gitee.starblues.core.spring; + +import com.gitee.starblues.core.spring.environment.PluginEnvironmentProcessor; +import com.gitee.starblues.core.spring.environment.PluginLocalConfigFileProcessor; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.Ordered; + +import java.util.ArrayList; +import java.util.List; + +/** + * PluginSpringApplication + * @author starBlues + * @version 3.0.0 + */ +public class BasePluginSpringApplication implements PluginSpringApplication{ + + private final DefaultListableBeanFactory beanFactory; + private final PluginApplicationContext applicationContext; + private final PluginBeanDefinitionLoader beanDefinitionLoader; + private final String configFileName; + private final List environmentProcessors; + + + public BasePluginSpringApplication(ClassLoader classLoader, + Class primarySources){ + this(classLoader, primarySources, null); + } + + public BasePluginSpringApplication(ClassLoader classLoader, + Class primarySources, + String configFileName){ + Assert.isNotNull(classLoader, "classLoader 不能为空"); + Assert.isNotNull(primarySources, "primarySources 不能为空"); + + this.beanFactory = new DefaultListableBeanFactory(); + this.beanFactory.setBeanClassLoader(classLoader); + + this.applicationContext = new PluginApplicationContext(beanFactory, classLoader); + this.beanDefinitionLoader = new PluginBeanDefinitionLoader(beanFactory, primarySources); + this.configFileName = configFileName; + this.environmentProcessors = new ArrayList<>(); + addDefaultEnvironmentProcessor(); + } + + + protected void addDefaultEnvironmentProcessor(){ + PluginLocalConfigFileProcessor configFileProcessor = new PluginLocalConfigFileProcessor(); + if(!ObjectUtils.isEmpty(configFileName)){ + configFileProcessor.setSearchNames(configFileName); + } + addEnvironmentProcessor(configFileProcessor); + } + + public void addEnvironmentProcessor(PluginEnvironmentProcessor environmentProcessor){ + if(environmentProcessor == null){ + return; + } + environmentProcessors.add(environmentProcessor); + } + + + @Override + public GenericApplicationContext run() { + processEnvironment(); + loadBean(); + refresh(); + return applicationContext; + } + + + protected void processEnvironment() { + List orderPluginEnvironmentProcessor = + CommonUtils.order(environmentProcessors, Ordered::getOrder); + for (PluginEnvironmentProcessor environmentProcessor : orderPluginEnvironmentProcessor) { + environmentProcessor.postProcessEnvironment(applicationContext.getEnvironment(), + applicationContext.getResourceLoader()); + } + } + + protected void loadBean() { + beanDefinitionLoader.load(); + } + + protected void refresh() { + applicationContext.refresh(); + } + + @Override + public void close() { + applicationContext.close(); + } + + @Override + public GenericApplicationContext getApplicationContext() { + return applicationContext; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java new file mode 100644 index 0000000..d84e6da --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.core.spring; + +import com.gitee.starblues.utils.Assert; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.ResourceLoader; + +/** + * 插件 ApplicationContext + * @author starBlues + * @version 3.0.0 + */ +public class PluginApplicationContext extends AnnotationConfigApplicationContext { + + private ResourceLoader resourceLoader; + + public PluginApplicationContext(DefaultListableBeanFactory beanFactory, ClassLoader classLoader) { + super(beanFactory); + Assert.isNotNull(classLoader, "classLoader 不能为空"); + this.resourceLoader = new DefaultResourceLoader(classLoader); + setClassLoader(classLoader); + setResourceLoader(resourceLoader); + setEnvironment(new StandardEnvironment()); + } + + public ResourceLoader getResourceLoader() { + return resourceLoader; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java new file mode 100644 index 0000000..87d5370 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java @@ -0,0 +1,281 @@ +package com.gitee.starblues.core.spring; + +import com.gitee.starblues.utils.Assert; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; +import org.springframework.beans.factory.support.AbstractBeanDefinitionReader; +import org.springframework.beans.factory.support.BeanDefinitionReader; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanNameGenerator; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; +import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; +import org.springframework.core.SpringProperties; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter; +import org.springframework.core.type.filter.TypeFilter; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.util.HashSet; +import java.util.Set; + +/** + * 加载插件中的bean + * @author starBlues + * @version 3.0.0 + */ +public class PluginBeanDefinitionLoader { + private static final boolean XML_ENABLED = !SpringProperties.getFlag("spring.xml.ignore"); + + private final Object[] sources; + + private final AnnotatedBeanDefinitionReader annotatedReader; + + private final AbstractBeanDefinitionReader xmlReader; + + private final BeanDefinitionReader groovyReader; + + private final ClassPathBeanDefinitionScanner scanner; + + private ResourceLoader resourceLoader; + + PluginBeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) { + Assert.isNotNull(registry, "参数 registry 不能为空"); + Assert.isNotEmpty(sources, "参数 sources 不能为空"); + this.sources = sources; + this.annotatedReader = new AnnotatedBeanDefinitionReader(registry); + this.xmlReader = (XML_ENABLED ? new XmlBeanDefinitionReader(registry) : null); + this.groovyReader = (isGroovyPresent() ? new GroovyBeanDefinitionReader(registry) : null); + this.scanner = new ClassPathBeanDefinitionScanner(registry); + this.scanner.addExcludeFilter(new PluginBeanDefinitionLoader.ClassExcludeFilter(sources)); + } + + void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { + this.annotatedReader.setBeanNameGenerator(beanNameGenerator); + this.scanner.setBeanNameGenerator(beanNameGenerator); + if (this.xmlReader != null) { + this.xmlReader.setBeanNameGenerator(beanNameGenerator); + } + } + + + void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + this.scanner.setResourceLoader(resourceLoader); + if (this.xmlReader != null) { + this.xmlReader.setResourceLoader(resourceLoader); + } + } + + + void setEnvironment(ConfigurableEnvironment environment) { + this.annotatedReader.setEnvironment(environment); + this.scanner.setEnvironment(environment); + if (this.xmlReader != null) { + this.xmlReader.setEnvironment(environment); + } + } + + void load() { + for (Object source : this.sources) { + load(source); + } + } + + private void load(Object source) { + Assert.isNotEmpty(source, "Source must not be null"); + if (source instanceof Class) { + load((Class) source); + return; + } + if (source instanceof Resource) { + load((Resource) source); + return; + } + if (source instanceof Package) { + load((Package) source); + return; + } + if (source instanceof CharSequence) { + load((CharSequence) source); + return; + } + throw new IllegalArgumentException("Invalid source type " + source.getClass()); + } + + private void load(Class source) { + if (isEligible(source)) { + this.annotatedReader.register(source); + } + } + + private void load(Resource source) { + if (source.getFilename().endsWith(".groovy")) { + if (this.groovyReader == null) { + throw new BeanDefinitionStoreException("Cannot load Groovy beans without Groovy on classpath"); + } + this.groovyReader.loadBeanDefinitions(source); + } + else { + if (this.xmlReader == null) { + throw new BeanDefinitionStoreException("Cannot load XML bean definitions when XML support is disabled"); + } + this.xmlReader.loadBeanDefinitions(source); + } + } + + private void load(Package source) { + this.scanner.scan(source.getName()); + } + + private void load(CharSequence source) { + String resolvedSource = this.scanner.getEnvironment().resolvePlaceholders(source.toString()); + // Attempt as a Class + try { + load(ClassUtils.forName(resolvedSource, null)); + return; + } + catch (IllegalArgumentException | ClassNotFoundException ex) { + // swallow exception and continue + } + // Attempt as Resources + if (loadAsResources(resolvedSource)) { + return; + } + // Attempt as package + Package packageResource = findPackage(resolvedSource); + if (packageResource != null) { + load(packageResource); + return; + } + throw new IllegalArgumentException("Invalid source '" + resolvedSource + "'"); + } + + private boolean loadAsResources(String resolvedSource) { + boolean foundCandidate = false; + Resource[] resources = findResources(resolvedSource); + for (Resource resource : resources) { + if (isLoadCandidate(resource)) { + foundCandidate = true; + load(resource); + } + } + return foundCandidate; + } + + private boolean isGroovyPresent() { + return ClassUtils.isPresent("groovy.lang.MetaClass", null); + } + + private Resource[] findResources(String source) { + ResourceLoader loader = (this.resourceLoader != null) ? this.resourceLoader + : new PathMatchingResourcePatternResolver(); + try { + if (loader instanceof ResourcePatternResolver) { + return ((ResourcePatternResolver) loader).getResources(source); + } + return new Resource[] { loader.getResource(source) }; + } + catch (IOException ex) { + throw new IllegalStateException("Error reading source '" + source + "'"); + } + } + + private boolean isLoadCandidate(Resource resource) { + if (resource == null || !resource.exists()) { + return false; + } + if (resource instanceof ClassPathResource) { + // A simple package without a '.' may accidentally get loaded as an XML + // document if we're not careful. The result of getInputStream() will be + // a file list of the package content. We double check here that it's not + // actually a package. + String path = ((ClassPathResource) resource).getPath(); + if (path.indexOf('.') == -1) { + try { + return Package.getPackage(path) == null; + } + catch (Exception ex) { + // Ignore + } + } + } + return true; + } + + private Package findPackage(CharSequence source) { + Package pkg = Package.getPackage(source.toString()); + if (pkg != null) { + return pkg; + } + try { + // Attempt to find a class in this package + ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); + Resource[] resources = resolver + .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); + for (Resource resource : resources) { + String className = StringUtils.stripFilenameExtension(resource.getFilename()); + load(Class.forName(source.toString() + "." + className)); + break; + } + } + catch (Exception ex) { + // swallow exception and continue + } + return Package.getPackage(source.toString()); + } + + /** + * Check whether the bean is eligible for registration. + * @param type candidate bean type + * @return true if the given bean type is eligible for registration, i.e. not a groovy + * closure nor an anonymous class + */ + private boolean isEligible(Class type) { + return !(type.isAnonymousClass() || isGroovyClosure(type) || hasNoConstructors(type)); + } + + private boolean isGroovyClosure(Class type) { + return type.getName().matches(".*\\$_.*closure.*"); + } + + private boolean hasNoConstructors(Class type) { + Constructor[] constructors = type.getDeclaredConstructors(); + return ObjectUtils.isEmpty(constructors); + } + + /** + * Simple {@link TypeFilter} used to ensure that specified {@link Class} sources are + * not accidentally re-added during scanning. + */ + private static class ClassExcludeFilter extends AbstractTypeHierarchyTraversingFilter { + + private final Set classNames = new HashSet<>(); + + ClassExcludeFilter(Object... sources) { + super(false, false); + for (Object source : sources) { + if (source instanceof Class) { + this.classNames.add(((Class) source).getName()); + } + } + } + + @Override + protected boolean matchClassName(String className) { + return this.classNames.contains(className); + } + + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java new file mode 100644 index 0000000..9bccb61 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java @@ -0,0 +1,33 @@ +package com.gitee.starblues.core.spring; + +import org.apache.catalina.core.ApplicationContext; +import org.springframework.context.support.GenericApplicationContext; + +/** + * 插件 SpringApplication + * @author starBlues + * @version 3.0.0 + */ +public interface PluginSpringApplication { + + + /** + * 运行 + * @return GenericApplicationContext + */ + GenericApplicationContext run(); + + /** + * 关闭 + */ + void close(); + + + /** + * 得到 ApplicationContext + * @return GenericApplicationContext + */ + GenericApplicationContext getApplicationContext(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java new file mode 100644 index 0000000..7991e36 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java @@ -0,0 +1,50 @@ +package com.gitee.starblues.core.spring.environment; + +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; + +import java.util.Set; +import java.util.function.Consumer; + +/** + * PropertySource 过滤 + * @author starBlues + * @version 3.0.0 + */ +public class FilteredPropertySource extends PropertySource> { + + private final Set filteredProperties; + + FilteredPropertySource(PropertySource original, Set filteredProperties) { + super(original.getName(), original); + this.filteredProperties = filteredProperties; + } + + @Override + public Object getProperty(String name) { + if (this.filteredProperties.contains(name)) { + return null; + } + return getSource().getProperty(name); + } + + static void apply(ConfigurableEnvironment environment, String propertySourceName, Set filteredProperties, + Consumer> operation) { + MutablePropertySources propertySources = environment.getPropertySources(); + PropertySource original = propertySources.get(propertySourceName); + if (original == null) { + operation.accept(null); + return; + } + propertySources.replace(propertySourceName, new FilteredPropertySource(original, filteredProperties)); + try { + operation.accept(original); + } + finally { + propertySources.replace(propertySourceName, original); + } + } + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java new file mode 100644 index 0000000..0b79687 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java @@ -0,0 +1,7 @@ +package com.gitee.starblues.core.spring.environment; + +/** + * @author starBlues + */ +public class LocalConfigFileLoader { +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java new file mode 100644 index 0000000..423070b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java @@ -0,0 +1,21 @@ +package com.gitee.starblues.core.spring.environment; + +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.io.ResourceLoader; + +/** + * 插件 Environment 处理者 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginEnvironmentProcessor extends Ordered { + + /** + * 处理 Environment + * @param environment ConfigurableEnvironment + * @param pnClassLoader ResourceLoader + */ + void postProcessEnvironment(ConfigurableEnvironment environment, ResourceLoader pnClassLoader); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java new file mode 100644 index 0000000..603f027 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java @@ -0,0 +1,862 @@ +package com.gitee.starblues.core.spring.environment; + +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ResourceUtils; +import org.apache.commons.logging.Log; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.DefaultPropertiesPropertySource; +import org.springframework.boot.context.config.ConfigDataLocation; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; +import org.springframework.boot.context.properties.source.ConfigurationPropertySources; +import org.springframework.boot.env.PropertySourceLoader; +import org.springframework.boot.env.RandomValuePropertySource; +import org.springframework.boot.logging.DeferredLog; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.ConfigurationClassPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.*; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.io.support.SpringFactoriesLoader; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * copy from springboot + * @author starBlues + * @version 3.0.0 + */ +public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcessor { + + private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"; + + private static final String DEFAULT_NAMES = "application"; + + /** + * The "active profiles" property name. + */ + public static final String ACTIVE_PROFILES_PROPERTY = "spring.profiles.active"; + + /** + * The "includes profiles" property name. + */ + public static final String INCLUDE_PROFILES_PROPERTY = "spring.profiles.include"; + + /** + * The "config name" property name. + */ + public static final String CONFIG_NAME_PROPERTY = "spring.config.name"; + + /** + * The "config location" property name. + */ + public static final String CONFIG_LOCATION_PROPERTY = "spring.config.location"; + + private final Set NO_SEARCH_NAMES = Collections.singleton(null); + + private final Bindable STRING_ARRAY = Bindable.of(String[].class); + + private final Bindable> STRING_LIST = Bindable.listOf(String.class); + + private final Set LOAD_FILTERED_PROPERTY; + + /** + * The "config additional location" property name. + */ + public final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location"; + + /** + * The default order for the processor. + */ + public final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; + + private final Log logger = new DeferredLog(); + + private final Resource[] EMPTY_RESOURCES = {}; + + private final Comparator FILE_COMPARATOR = Comparator.comparing(File::getAbsolutePath); + + private String searchLocations; + + private String names; + + private int order = DEFAULT_ORDER; + + public PluginLocalConfigFileProcessor() { + Set filteredProperties = new HashSet<>(); + filteredProperties.add("spring.profiles.active"); + filteredProperties.add("spring.profiles.include"); + LOAD_FILTERED_PROPERTY = Collections.unmodifiableSet(filteredProperties); + } + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, ResourceLoader pnClassLoader) { + addPropertySources(environment, pnClassLoader); + } + + /** + * Add config file property sources to the specified environment. + * @param environment the environment to add source to + * @param resourceLoader the resource loader + * @see #addPostProcessors(ConfigurableApplicationContext) + */ + protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { + RandomValuePropertySource.addToEnvironment(environment); + new Loader(environment, resourceLoader).load(); + } + + /** + * Add appropriate post-processors to post-configure the property-sources. + * @param context the context to configure + */ + protected void addPostProcessors(ConfigurableApplicationContext context) { + context.addBeanFactoryPostProcessor(new PropertySourceOrderingPostProcessor(context)); + } + + public void setOrder(int order) { + this.order = order; + } + + @Override + public int getOrder() { + return this.order; + } + + /** + * Set the search locations that will be considered as a comma-separated list. Each + * search location should be a directory path (ending in "/") and it will be prefixed + * by the file names constructed from {@link #setSearchNames(String) search names} and + * profiles (if any) plus file extensions supported by the properties loaders. + * Locations are considered in the order specified, with later items taking precedence + * (like a map merge). + * @param locations the search locations + */ + public void setSearchLocations(String locations) { + this.searchLocations = Assert.isNotEmpty(locations, "locations 不能为空"); + } + + /** + * Sets the names of the files that should be loaded (excluding file extension) as a + * comma-separated list. + * @param names the names to load + */ + public void setSearchNames(String names) { + this.names = Assert.isNotEmpty(names, "names 不能为空"); + } + + /** + * {@link BeanFactoryPostProcessor} to re-order our property sources below any + * {@code @PropertySource} items added by the {@link ConfigurationClassPostProcessor}. + */ + private static class PropertySourceOrderingPostProcessor implements BeanFactoryPostProcessor, Ordered { + + private final ConfigurableApplicationContext context; + + PropertySourceOrderingPostProcessor(ConfigurableApplicationContext context) { + this.context = context; + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + reorderSources(this.context.getEnvironment()); + } + + private void reorderSources(ConfigurableEnvironment environment) { + DefaultPropertiesPropertySource.moveToEnd(environment); + } + + } + + + private class Loader { + + private final Log logger = this.logger; + + private final ConfigurableEnvironment environment; + + private final PropertySourcesPlaceholdersResolver placeholdersResolver; + + private final ResourceLoader resourceLoader; + + private final List propertySourceLoaders; + + private Deque profiles; + + private List processedProfiles; + + private boolean activatedProfiles; + + private Map loaded; + + private Map> loadDocumentsCache = new HashMap<>(); + + Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { + this.environment = environment; + this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment); + this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(null); + this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, + this.resourceLoader.getClassLoader()); + } + + void load() { + FilteredPropertySource.apply(this.environment, DefaultPropertiesPropertySource.NAME, LOAD_FILTERED_PROPERTY, + this::loadWithFilteredProperties); + } + + private void loadWithFilteredProperties(PropertySource defaultProperties) { + this.profiles = new LinkedList<>(); + this.processedProfiles = new LinkedList<>(); + this.activatedProfiles = false; + this.loaded = new LinkedHashMap<>(); + initializeProfiles(); + while (!this.profiles.isEmpty()) { + Profile profile = this.profiles.poll(); + if (isDefaultProfile(profile)) { + addProfileToEnvironment(profile.getName()); + } + load(profile, this::getPositiveProfileFilter, addToLoaded(MutablePropertySources::addLast, false)); + this.processedProfiles.add(profile); + } + load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true)); + addLoadedPropertySources(); + applyActiveProfiles(defaultProperties); + } + + /** + * Initialize profile information from both the {@link Environment} active + * profiles and any {@code spring.profiles.active}/{@code spring.profiles.include} + * properties that are already set. + */ + private void initializeProfiles() { + // The default profile for these purposes is represented as null. We add it + // first so that it is processed first and has lowest priority. + this.profiles.add(null); + Binder binder = Binder.get(this.environment); + Set activatedViaProperty = getProfiles(binder, ACTIVE_PROFILES_PROPERTY); + Set includedViaProperty = getProfiles(binder, INCLUDE_PROFILES_PROPERTY); + List otherActiveProfiles = getOtherActiveProfiles(activatedViaProperty, includedViaProperty); + this.profiles.addAll(otherActiveProfiles); + // Any pre-existing active profiles set via property sources (e.g. + // System properties) take precedence over those added in config files. + this.profiles.addAll(includedViaProperty); + addActiveProfiles(activatedViaProperty); + if (this.profiles.size() == 1) { // only has null profile + for (String defaultProfileName : getDefaultProfiles(binder)) { + Profile defaultProfile = new Profile(defaultProfileName, true); + this.profiles.add(defaultProfile); + } + } + } + + private String[] getDefaultProfiles(Binder binder) { + return binder.bind(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, STRING_ARRAY) + .orElseGet(this.environment::getDefaultProfiles); + } + + private List getOtherActiveProfiles(Set activatedViaProperty, + Set includedViaProperty) { + return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new).filter( + (profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile)) + .collect(Collectors.toList()); + } + + void addActiveProfiles(Set profiles) { + if (profiles.isEmpty()) { + return; + } + if (this.activatedProfiles) { + if (this.logger.isDebugEnabled()) { + this.logger.debug("Profiles already activated, '" + profiles + "' will not be applied"); + } + return; + } + this.profiles.addAll(profiles); + if (this.logger.isDebugEnabled()) { + this.logger.debug("Activated activeProfiles " + ObjectUtils.collectionToCommaDelimitedString(profiles)); + } + this.activatedProfiles = true; + removeUnprocessedDefaultProfiles(); + } + + private void removeUnprocessedDefaultProfiles() { + this.profiles.removeIf((profile) -> (profile != null && profile.isDefaultProfile())); + } + + private DocumentFilter getPositiveProfileFilter(Profile profile) { + return (Document document) -> { + if (profile == null) { + return ObjectUtils.isEmpty(document.getProfiles()); + } + return ObjectUtils.containsElement(document.getProfiles(), profile.getName()) + && this.environment.acceptsProfiles(Profiles.of(document.getProfiles())); + }; + } + + private DocumentFilter getNegativeProfileFilter(Profile profile) { + return (Document document) -> (profile == null && !ObjectUtils.isEmpty(document.getProfiles()) + && this.environment.acceptsProfiles(Profiles.of(document.getProfiles()))); + } + + private DocumentConsumer addToLoaded(BiConsumer> addMethod, + boolean checkForExisting) { + return (profile, document) -> { + if (checkForExisting) { + for (MutablePropertySources merged : this.loaded.values()) { + if (merged.contains(document.getPropertySource().getName())) { + return; + } + } + } + MutablePropertySources merged = this.loaded.computeIfAbsent(profile, + (k) -> new MutablePropertySources()); + addMethod.accept(merged, document.getPropertySource()); + }; + } + + private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) { + getSearchLocations().forEach((location) -> { + String nonOptionalLocation = ConfigDataLocation.of(location).getValue(); + boolean isDirectory = location.endsWith("/"); + Set names = isDirectory ? getSearchNames() : NO_SEARCH_NAMES; + names.forEach((name) -> load(nonOptionalLocation, name, profile, filterFactory, consumer)); + }); + } + + private void load(String location, String name, Profile profile, DocumentFilterFactory filterFactory, + DocumentConsumer consumer) { + if (!ObjectUtils.hasText(name)) { + for (PropertySourceLoader loader : this.propertySourceLoaders) { + if (canLoadFileExtension(loader, location)) { + load(loader, location, profile, filterFactory.getDocumentFilter(profile), consumer); + return; + } + } + throw new IllegalStateException("File extension of config file location '" + location + + "' is not known to any PropertySourceLoader. If the location is meant to reference " + + "a directory, it must end in '/'"); + } + Set processed = new HashSet<>(); + for (PropertySourceLoader loader : this.propertySourceLoaders) { + for (String fileExtension : loader.getFileExtensions()) { + if (processed.add(fileExtension)) { + loadForFileExtension(loader, location + name, "." + fileExtension, profile, filterFactory, + consumer); + } + } + } + } + + private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { + return Arrays.stream(loader.getFileExtensions()) + .anyMatch((fileExtension) -> ObjectUtils.endsWithIgnoreCase(name, fileExtension)); + } + + private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension, + Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) { + DocumentFilter defaultFilter = filterFactory.getDocumentFilter(null); + DocumentFilter profileFilter = filterFactory.getDocumentFilter(profile); + if (profile != null) { + // Try profile-specific file & profile section in profile file (gh-340) + String profileSpecificFile = prefix + "-" + profile + fileExtension; + load(loader, profileSpecificFile, profile, defaultFilter, consumer); + load(loader, profileSpecificFile, profile, profileFilter, consumer); + // Try profile specific sections in files we've already processed + for (Profile processedProfile : this.processedProfiles) { + if (processedProfile != null) { + String previouslyLoaded = prefix + "-" + processedProfile + fileExtension; + load(loader, previouslyLoaded, profile, profileFilter, consumer); + } + } + } + // Also try the profile-specific section (if any) of the normal file + load(loader, prefix + fileExtension, profile, profileFilter, consumer); + } + + private void load(PropertySourceLoader loader, String location, Profile profile, DocumentFilter filter, + DocumentConsumer consumer) { + Resource[] resources = getResources(location); + for (Resource resource : resources) { + try { + if (resource == null || !resource.exists()) { + if (this.logger.isTraceEnabled()) { + StringBuilder description = getDescription("Skipped missing config ", location, resource, + profile); + this.logger.trace(description); + } + continue; + } + if (!ObjectUtils.hasText(ObjectUtils.getFilenameExtension(resource.getFilename()))) { + if (this.logger.isTraceEnabled()) { + StringBuilder description = getDescription("Skipped empty config extension ", location, + resource, profile); + this.logger.trace(description); + } + continue; + } + if (resource.isFile() && isPatternLocation(location) && hasHiddenPathElement(resource)) { + if (this.logger.isTraceEnabled()) { + StringBuilder description = getDescription("Skipped location with hidden path element ", + location, resource, profile); + this.logger.trace(description); + } + continue; + } + String name = "applicationConfig: [" + getLocationName(location, resource) + "]"; + List documents = loadDocuments(loader, name, resource); + if (ObjectUtils.isEmpty(documents)) { + if (this.logger.isTraceEnabled()) { + StringBuilder description = getDescription("Skipped unloaded config ", location, resource, + profile); + this.logger.trace(description); + } + continue; + } + List loaded = new ArrayList<>(); + for (Document document : documents) { + if (filter.match(document)) { + addActiveProfiles(document.getActiveProfiles()); + addIncludedProfiles(document.getIncludeProfiles()); + loaded.add(document); + } + } + Collections.reverse(loaded); + if (!loaded.isEmpty()) { + loaded.forEach((document) -> consumer.accept(profile, document)); + if (this.logger.isDebugEnabled()) { + StringBuilder description = getDescription("Loaded config file ", location, resource, + profile); + this.logger.debug(description); + } + } + } catch (Exception ex) { + StringBuilder description = getDescription("Failed to load property source from ", location, + resource, profile); + throw new IllegalStateException(description.toString(), ex); + } finally { + try { + if(resource != null && resource.exists() && resource.isOpen()){ + resource.getInputStream().close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + private boolean hasHiddenPathElement(Resource resource) throws IOException { + String cleanPath = ObjectUtils.cleanPath(resource.getFile().getAbsolutePath()); + for (Path value : Paths.get(cleanPath)) { + if (value.toString().startsWith("..")) { + return true; + } + } + return false; + } + + private String getLocationName(String locationReference, Resource resource) { + if (!locationReference.contains("*")) { + return locationReference; + } + if (resource instanceof FileSystemResource) { + return ((FileSystemResource) resource).getPath(); + } + return resource.getDescription(); + } + + private Resource[] getResources(String locationReference) { + try { + if (isPatternLocation(locationReference)) { + return getResourcesFromPatternLocationReference(locationReference); + } + return new Resource[] { this.resourceLoader.getResource(locationReference) }; + } + catch (Exception ex) { + return EMPTY_RESOURCES; + } + } + + private boolean isPatternLocation(String location) { + return location.contains("*"); + } + + private Resource[] getResourcesFromPatternLocationReference(String locationReference) throws IOException { + String directoryPath = locationReference.substring(0, locationReference.indexOf("*/")); + Resource resource = this.resourceLoader.getResource(directoryPath); + File[] files = resource.getFile().listFiles(File::isDirectory); + if (files != null) { + String fileName = locationReference.substring(locationReference.lastIndexOf("/") + 1); + Arrays.sort(files, FILE_COMPARATOR); + return Arrays.stream(files).map((file) -> file.listFiles((dir, name) -> name.equals(fileName))) + .filter(Objects::nonNull).flatMap((Function>) Arrays::stream) + .map(FileSystemResource::new).toArray(Resource[]::new); + } + return EMPTY_RESOURCES; + } + + private void addIncludedProfiles(Set includeProfiles) { + LinkedList existingProfiles = new LinkedList<>(this.profiles); + this.profiles.clear(); + this.profiles.addAll(includeProfiles); + this.profiles.removeAll(this.processedProfiles); + this.profiles.addAll(existingProfiles); + } + + private List loadDocuments(PropertySourceLoader loader, String name, Resource resource) + throws IOException { + DocumentsCacheKey cacheKey = new DocumentsCacheKey(loader, resource); + List documents = this.loadDocumentsCache.get(cacheKey); + if (documents == null) { + List> loaded = loader.load(name, resource); + documents = asDocuments(loaded); + this.loadDocumentsCache.put(cacheKey, documents); + } + return documents; + } + + private List asDocuments(List> loaded) { + if (loaded == null) { + return Collections.emptyList(); + } + return loaded.stream().map((propertySource) -> { + Binder binder = new Binder(ConfigurationPropertySources.from(propertySource), + this.placeholdersResolver); + String[] profiles = binder.bind("spring.profiles", STRING_ARRAY).orElse(null); + Set activeProfiles = getProfiles(binder, ACTIVE_PROFILES_PROPERTY); + Set includeProfiles = getProfiles(binder, INCLUDE_PROFILES_PROPERTY); + return new Document(propertySource, profiles, activeProfiles, includeProfiles); + }).collect(Collectors.toList()); + } + + private StringBuilder getDescription(String prefix, String locationReference, Resource resource, + Profile profile) { + StringBuilder result = new StringBuilder(prefix); + try { + if (resource != null) { + String uri = resource.getURI().toASCIIString(); + result.append("'"); + result.append(uri); + result.append("' ("); + result.append(locationReference); + result.append(")"); + } + } + catch (IOException ex) { + result.append(locationReference); + } + if (profile != null) { + result.append(" for profile "); + result.append(profile); + } + return result; + } + + private Set getProfiles(Binder binder, String name) { + return binder.bind(name, STRING_ARRAY).map(this::asProfileSet).orElse(Collections.emptySet()); + } + + private Set asProfileSet(String[] profileNames) { + List profiles = new ArrayList<>(); + for (String profileName : profileNames) { + profiles.add(new Profile(profileName)); + } + return new LinkedHashSet<>(profiles); + } + + private void addProfileToEnvironment(String profile) { + for (String activeProfile : this.environment.getActiveProfiles()) { + if (activeProfile.equals(profile)) { + return; + } + } + this.environment.addActiveProfile(profile); + } + + private Set getSearchLocations() { + Set locations = getSearchLocations(CONFIG_ADDITIONAL_LOCATION_PROPERTY); + if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) { + locations.addAll(getSearchLocations(CONFIG_LOCATION_PROPERTY)); + } + else { + locations.addAll( + asResolvedSet(PluginLocalConfigFileProcessor.this.searchLocations, DEFAULT_SEARCH_LOCATIONS)); + } + return locations; + } + + private Set getSearchLocations(String propertyName) { + Set locations = new LinkedHashSet<>(); + if (this.environment.containsProperty(propertyName)) { + for (String path : asResolvedSet(this.environment.getProperty(propertyName), null)) { + if (!path.contains("$")) { + path = ObjectUtils.cleanPath(path); + Assert.state(!path.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX), + "Classpath wildcard patterns cannot be used as a search location"); + validateWildcardLocation(path); + if (!ResourceUtils.isUrl(path)) { + path = ResourceUtils.FILE_URL_PREFIX + path; + } + } + locations.add(path); + } + } + return locations; + } + + private void validateWildcardLocation(String path) { + if (path.contains("*")) { + Assert.state(ObjectUtils.countOccurrencesOf(path, "*") == 1, + () -> "Search location '" + path + "' cannot contain multiple wildcards"); + String directoryPath = path.substring(0, path.lastIndexOf("/") + 1); + Assert.state(directoryPath.endsWith("*/"), () -> "Search location '" + path + "' must end with '*/'"); + } + } + + private Set getSearchNames() { + if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) { + String property = this.environment.getProperty(CONFIG_NAME_PROPERTY); + Set names = asResolvedSet(property, null); + names.forEach(this::assertValidConfigName); + return names; + } + return asResolvedSet(PluginLocalConfigFileProcessor.this.names, DEFAULT_NAMES); + } + + private Set asResolvedSet(String value, String fallback) { + List list = Arrays.asList(ObjectUtils.trimArrayElements(ObjectUtils.commaDelimitedListToStringArray( + (value != null) ? this.environment.resolvePlaceholders(value) : fallback))); + Collections.reverse(list); + return new LinkedHashSet<>(list); + } + + private void assertValidConfigName(String name) { + Assert.state(!name.contains("*"), () -> "Config name '" + name + "' cannot contain wildcards"); + } + + private void addLoadedPropertySources() { + MutablePropertySources destination = this.environment.getPropertySources(); + List loaded = new ArrayList<>(this.loaded.values()); + Collections.reverse(loaded); + String lastAdded = null; + Set added = new HashSet<>(); + for (MutablePropertySources sources : loaded) { + for (PropertySource source : sources) { + if (added.add(source.getName())) { + addLoadedPropertySource(destination, lastAdded, source); + lastAdded = source.getName(); + } + } + } + } + + private void addLoadedPropertySource(MutablePropertySources destination, String lastAdded, + PropertySource source) { + if (lastAdded == null) { + if (destination.contains(DefaultPropertiesPropertySource.NAME)) { + destination.addBefore(DefaultPropertiesPropertySource.NAME, source); + } + else { + destination.addLast(source); + } + } + else { + destination.addAfter(lastAdded, source); + } + } + + private void applyActiveProfiles(PropertySource defaultProperties) { + List activeProfiles = new ArrayList<>(); + if (defaultProperties != null) { + Binder binder = new Binder(ConfigurationPropertySources.from(defaultProperties), + new PropertySourcesPlaceholdersResolver(this.environment)); + activeProfiles.addAll(bindStringList(binder, "spring.profiles.include")); + if (!this.activatedProfiles) { + activeProfiles.addAll(bindStringList(binder, "spring.profiles.active")); + } + } + this.processedProfiles.stream().filter(this::isDefaultProfile).map(Profile::getName) + .forEach(activeProfiles::add); + this.environment.setActiveProfiles(activeProfiles.toArray(new String[0])); + } + + private boolean isDefaultProfile(Profile profile) { + return profile != null && !profile.isDefaultProfile(); + } + + private List bindStringList(Binder binder, String property) { + return binder.bind(property, STRING_LIST).orElse(Collections.emptyList()); + } + + } + + private static class Profile { + + private final String name; + + private final boolean defaultProfile; + + Profile(String name) { + this(name, false); + } + + Profile(String name, boolean defaultProfile) { + Assert.isNotEmpty(name, "name 不能为空"); + this.name = name; + this.defaultProfile = defaultProfile; + } + + String getName() { + return this.name; + } + + boolean isDefaultProfile() { + return this.defaultProfile; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj == null || obj.getClass() != getClass()) { + return false; + } + return ((Profile) obj).name.equals(this.name); + } + + @Override + public int hashCode() { + return this.name.hashCode(); + } + + @Override + public String toString() { + return this.name; + } + + } + + /** + * Cache key used to save loading the same document multiple times. + */ + private static class DocumentsCacheKey { + + private final PropertySourceLoader loader; + + private final Resource resource; + + DocumentsCacheKey(PropertySourceLoader loader, Resource resource) { + this.loader = loader; + this.resource = resource; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + DocumentsCacheKey other = (DocumentsCacheKey) obj; + return this.loader.equals(other.loader) && this.resource.equals(other.resource); + } + + @Override + public int hashCode() { + return this.loader.hashCode() * 31 + this.resource.hashCode(); + } + + } + + /** + * A single document loaded by a {@link PropertySourceLoader}. + */ + private static class Document { + + private final PropertySource propertySource; + + private String[] profiles; + + private final Set activeProfiles; + + private final Set includeProfiles; + + Document(PropertySource propertySource, String[] profiles, Set activeProfiles, + Set includeProfiles) { + this.propertySource = propertySource; + this.profiles = profiles; + this.activeProfiles = activeProfiles; + this.includeProfiles = includeProfiles; + } + + PropertySource getPropertySource() { + return this.propertySource; + } + + String[] getProfiles() { + return this.profiles; + } + + Set getActiveProfiles() { + return this.activeProfiles; + } + + Set getIncludeProfiles() { + return this.includeProfiles; + } + + @Override + public String toString() { + return this.propertySource.toString(); + } + + } + + @FunctionalInterface + private interface DocumentFilterFactory { + + /** + * Create a filter for the given profile. + * @param profile the profile or {@code null} + * @return the filter + */ + DocumentFilter getDocumentFilter(Profile profile); + + } + + @FunctionalInterface + private interface DocumentFilter { + + boolean match(Document document); + + } + + @FunctionalInterface + private interface DocumentConsumer { + + void accept(Profile profile, Document document); + + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java new file mode 100644 index 0000000..d4b86b2 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java @@ -0,0 +1,19 @@ +package com.gitee.starblues.core.version; + +import com.github.zafarkhaja.semver.Version; + +/** + * Semver标准版本检查 + * @author starBlues + * @version 3.0.0 + */ +public class SemverVersionInspector implements VersionInspector{ + + @Override + public int compareTo(String version1, String version2) { + Version v1 = Version.valueOf(version1); + Version v2 = Version.valueOf(version2); + return v1.compareTo(v2); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java new file mode 100644 index 0000000..0702df8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java @@ -0,0 +1,19 @@ +package com.gitee.starblues.core.version; + +/** + * 版本检查 + * @author starBlues + * @version 3.0.0 + */ +public interface VersionInspector { + + + /** + * 比较 v1 和 v2版本. + * @param v1 版本号码1 + * @param v2 版本号码2 + * @return 如果 v1大于等于v2, 则返回大于等于0的数字, 否则返回小于0的数字 + */ + int compareTo(String v1, String v2); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index 641f5c8..e0d6baf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -1,7 +1,6 @@ package com.gitee.starblues.integration; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; +import com.gitee.starblues.core.RuntimeMode; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -33,6 +32,12 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Value("${enable:true}") private Boolean enable; + /** + * 主程序包名 + */ + @Value("${mainPackageName:}") + private String mainPackageName; + /** * 插件的路径 */ @@ -124,7 +129,12 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public RuntimeMode environment() { - return RuntimeMode.byName(runMode); + return RuntimeMode.valueOf(runMode); + } + + @Override + public String mainPackageName() { + return mainPackageName; } @Override @@ -147,7 +157,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String uploadTempPath() { - if(StringUtils.isNullOrEmpty(uploadTempPath)){ + if(!ObjectUtils.isEmpty(uploadTempPath)){ return super.uploadTempPath(); } return uploadTempPath; @@ -155,7 +165,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String backupPath() { - if(StringUtils.isNullOrEmpty(backupPath)){ + if(!ObjectUtils.isEmpty(backupPath)){ return super.backupPath(); } return backupPath; @@ -163,7 +173,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String pluginRestPathPrefix() { - if(StringUtils.isNullOrEmpty(pluginRestPathPrefix)){ + if(!ObjectUtils.isEmpty(pluginRestPathPrefix)){ return super.pluginRestPathPrefix(); } else { return pluginRestPathPrefix; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java index e1ed2ab..50abac8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java @@ -1,7 +1,6 @@ package com.gitee.starblues.integration; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; +import com.gitee.starblues.core.RuntimeMode; import org.springframework.util.ObjectUtils; import java.util.List; @@ -14,6 +13,7 @@ import java.util.Set; * @author starBlues * @version 2.4.4 */ +@Deprecated public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ private final boolean enable; @@ -87,7 +87,7 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ private Boolean enable; - private RuntimeMode runtimeMode = RuntimeMode.DEVELOPMENT; + private RuntimeMode runtimeMode = RuntimeMode.DEV; private List pluginPath; private String pluginConfigFilePath = ""; @@ -200,6 +200,11 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ return runtimeMode; } + @Override + public String mainPackageName() { + return null; + } + @Override public List pluginPath() { if(ObjectUtils.isEmpty(pluginPath)){ @@ -216,7 +221,7 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ @Override public String uploadTempPath() { - if(StringUtils.isNullOrEmpty(uploadTempPath)){ + if(!ObjectUtils.isEmpty(uploadTempPath)){ return super.uploadTempPath(); } else { return uploadTempPath; @@ -225,7 +230,7 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ @Override public String backupPath() { - if(StringUtils.isNullOrEmpty(backupPath)){ + if(!ObjectUtils.isEmpty(backupPath)){ return super.backupPath(); } else { return backupPath; @@ -234,7 +239,7 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ @Override public String pluginRestPathPrefix() { - if(StringUtils.isNullOrEmpty(pluginRestPathPrefix)){ + if(!ObjectUtils.isEmpty(pluginRestPathPrefix)){ return super.pluginRestPathPrefix(); } else { return pluginRestPathPrefix; @@ -277,7 +282,7 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ @Override public String version() { - if(StringUtils.isNullOrEmpty(version)){ + if(!ObjectUtils.isEmpty(version)){ return super.version(); } return version; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index c1da683..db69485 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -1,6 +1,6 @@ package com.gitee.starblues.integration; -import org.pf4j.RuntimeMode; +import com.gitee.starblues.core.RuntimeMode; import java.util.ArrayList; import java.util.List; @@ -17,9 +17,9 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf @Override public List pluginPath() { List pluginPath = new ArrayList<>(1); - if(environment() == RuntimeMode.DEPLOYMENT){ + if(environment() == RuntimeMode.DEV){ pluginPath.add("plugins"); - } else if(environment() == RuntimeMode.DEVELOPMENT){ + } else if(environment() == RuntimeMode.PROD){ pluginPath.add("./plugins/"); } return pluginPath; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index 29c73d6..31d05cd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration; -import org.pf4j.RuntimeMode; + +import com.gitee.starblues.core.RuntimeMode; import java.util.List; import java.util.Set; @@ -14,11 +15,17 @@ import java.util.Set; public interface IntegrationConfiguration { /** - * 运行环境。运行项目时的模式。分为开发环境(DEVELOPMENT)、生产环境(DEPLOYMENT) - * @return RuntimeMode.DEVELOPMENT、RuntimeMode.DEPLOYMENT + * 运行环境。运行项目时的模式。分为开发环境(Dev)、生产环境(Prod) + * @return RuntimeMode.DEV、RuntimeMode.PROD */ RuntimeMode environment(); + /** + * 主程序包名 + * @return String + */ + String mainPackageName(); + /** * 插件的路径。可设置多个插件路径 * 开发环境建议直接配置为插件模块的父级目录。例如: plugins。如果启动主程序时, 插件为加载, 请检查该配置是否正确。 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index 01cd3ac..c2ed2ec 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -1,22 +1,20 @@ package com.gitee.starblues.integration.application; +import com.gitee.starblues.core.PluginManager; +import com.gitee.starblues.integration.manager.DefaultPluginManagerFactory; +import com.gitee.starblues.integration.manager.PluginManagerFactory; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; -import com.gitee.starblues.integration.pf4j.DefaultPf4jFactory; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.integration.pf4j.Pf4jFactory; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.DefaultPluginOperator; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; -import org.pf4j.PluginManager; -import org.pf4j.PluginStateListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.util.ObjectUtils; import java.util.List; import java.util.Objects; @@ -32,7 +30,7 @@ public class DefaultPluginApplication extends AbstractPluginApplication { private final Logger log = LoggerFactory.getLogger(this.getClass()); - protected Pf4jFactory integrationFactory; + protected PluginManagerFactory pluginManagerFactory; private PluginUser pluginUser; private PluginOperator pluginOperator; @@ -42,8 +40,8 @@ public class DefaultPluginApplication extends AbstractPluginApplication { public DefaultPluginApplication() { } - public DefaultPluginApplication(Pf4jFactory integrationFactory){ - this.integrationFactory = integrationFactory; + public DefaultPluginApplication(PluginManagerFactory pluginManagerFactory){ + this.pluginManagerFactory = pluginManagerFactory; } @@ -55,11 +53,10 @@ public class DefaultPluginApplication extends AbstractPluginApplication { throw new RuntimeException("Plugin has been initialized"); } IntegrationConfiguration configuration = getConfiguration(applicationContext); - if(integrationFactory == null){ - integrationFactory = new DefaultPf4jFactory(configuration); + if(pluginManagerFactory == null){ + pluginManagerFactory = new DefaultPluginManagerFactory(configuration); } - PluginManager pluginManager = integrationFactory.getPluginManager(); - addPf4jStateListener(pluginManager, applicationContext); + PluginManager pluginManager = pluginManagerFactory.getPluginManager(); pluginUser = createPluginUser(applicationContext, pluginManager); pluginOperator = createPluginOperator(applicationContext, pluginManager, configuration); try { @@ -114,21 +111,21 @@ public class DefaultPluginApplication extends AbstractPluginApplication { return pluginUser; } - /** - * 将pf4j中的监听器加入 - * @param pluginManager pluginManager - * @param applicationContext ApplicationContext - */ - private void addPf4jStateListener(PluginManager pluginManager, ApplicationContext applicationContext){ - List pluginStateListeners = pluginStateListenerFactory - .buildListenerClass((GenericApplicationContext) applicationContext); - if(ObjectUtils.isEmpty(pluginStateListeners)){ - return; - } - for (PluginStateListener pluginStateListener : pluginStateListeners) { - pluginManager.addPluginStateListener(pluginStateListener); - } - } +// /** +// * 将pf4j中的监听器加入 +// * @param pluginManager pluginManager +// * @param applicationContext ApplicationContext +// */ +// private void addPf4jStateListener(PluginManager pluginManager, ApplicationContext applicationContext){ +// List pluginStateListeners = pluginStateListenerFactory +// .buildListenerClass((GenericApplicationContext) applicationContext); +// if(ObjectUtils.isEmpty(pluginStateListeners)){ +// return; +// } +// for (PluginStateListener pluginStateListener : pluginStateListeners) { +// pluginManager.addPluginStateListener(pluginStateListener); +// } +// } /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java new file mode 100644 index 0000000..0f8d7c4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java @@ -0,0 +1,33 @@ +package com.gitee.starblues.integration.manager; + +import com.gitee.starblues.core.*; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.utils.Assert; + +import java.util.List; + +/** + * 默认的 PluginManagerFactory + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginManagerFactory implements PluginManagerFactory{ + + private final IntegrationConfiguration configuration; + + public DefaultPluginManagerFactory(IntegrationConfiguration configuration) { + this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); + } + + @Override + public PluginManager getPluginManager() { + RuntimeMode runtimeMode = Assert.isNotEmpty(configuration.environment(), + "配置[environment]不能为空"); + String mainPackageName = Assert.isNotEmpty(configuration.mainPackageName(), + "配置[mainPackageName]不能为空"); + List pluginPaths = Assert.isNotEmpty(configuration.pluginPath(), + "配置[pluginPath]不能为空"); + RealizeProvider realizeProvider = new DefaultRealizeProvider(runtimeMode, mainPackageName); + return new DefaultPluginManager(realizeProvider, pluginPaths); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java new file mode 100644 index 0000000..1d62aeb --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java @@ -0,0 +1,19 @@ +package com.gitee.starblues.integration.manager; + +import com.gitee.starblues.core.PluginManager; + +/** + * PluginManager 工厂 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginManagerFactory { + + /** + * 得到 PluginManager + * @return PluginManager + */ + PluginManager getPluginManager(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 27b174e..a2fa381 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -1,5 +1,7 @@ package com.gitee.starblues.integration.operator; +import com.gitee.starblues.core.PluginManager; +import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.factory.DefaultPluginFactory; import com.gitee.starblues.factory.PluginFactory; import com.gitee.starblues.factory.PluginRegistryInfo; @@ -11,16 +13,13 @@ import com.gitee.starblues.integration.operator.module.PluginInfo; import com.gitee.starblues.integration.operator.verify.DefaultPluginVerify; import com.gitee.starblues.integration.operator.verify.PluginLegalVerify; import com.gitee.starblues.utils.GlobalRegistryInfo; +import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; import com.gitee.starblues.utils.PluginOperatorInfo; -import org.pf4j.*; -import org.pf4j.util.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; @@ -103,32 +102,22 @@ public class DefaultPluginOperator implements PluginOperator { // 启动前, 清除空文件 PluginFileUtils.cleanEmptyFile(pluginManager.getPluginsRoot()); - // 开始初始化插件工厂 - pluginFactory.initialize(); // 开始加载插件 - pluginManager.loadPlugins(); - pluginManager.startPlugins(); - List pluginWrappers = pluginManager.getStartedPlugins(); - if(pluginWrappers == null || pluginWrappers.isEmpty()){ - log.warn("Not found plugin!"); + List pluginDescriptors = pluginManager.loadPlugins(); + if(ObjectUtils.isEmpty(pluginDescriptors)){ + log.warn("没有发现插件!"); pluginInitializerListenerFactory.complete(); return false; } boolean isFoundException = false; - for (PluginWrapper pluginWrapper : pluginWrappers) { - String pluginId = pluginWrapper.getPluginId(); - GlobalRegistryInfo.addOperatorPluginInfo(pluginId, - PluginOperatorInfo.OperatorType.INSTALL, false); + for (PluginDescriptor descriptor : pluginDescriptors) { try { - // 依次注册插件信息到Spring boot - pluginFactory.registry(PluginRegistryInfo.build(pluginWrapper, pluginManager, - applicationContext, true)); + pluginManager.start(descriptor.getPluginId()); } catch (Exception e){ - log.error("Plugin '{}' registry failure. Reason : {}", pluginId, e.getMessage(), e); + log.error("启动插件 '{}' 失败. {}", descriptor.getPluginId(), e.getMessage(), e); isFoundException = true; } } - pluginFactory.build(); isInit = true; if(isFoundException){ log.error("Plugins initialize failure"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java index d669f05..cce1c05 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java @@ -9,6 +9,7 @@ import java.util.Set; * @author starBlues * @version 2.4.0 */ +@Deprecated public class ConfigPluginStatusProvider implements PluginStatusProvider { private Set enablePluginIds = new HashSet<>(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java index b74365e..818d173 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java @@ -16,6 +16,7 @@ import java.util.stream.Collectors; * @author starBlues * @version 2.4.0 */ +@Deprecated public class DefaultPf4jFactory implements Pf4jFactory { private final IntegrationConfiguration configuration; @@ -30,7 +31,7 @@ public class DefaultPf4jFactory implements Pf4jFactory { if(configuration == null){ throw new NullPointerException("IntegrationConfiguration is null"); } - RuntimeMode environment = configuration.environment(); + RuntimeMode environment = null; if(environment == null){ throw new RuntimeException("Configuration RuntimeMode is null" + configuration.environment()); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java index c1d3185..1b3eac1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java @@ -11,6 +11,7 @@ import java.nio.file.Path; * @author starBlues * @version 2.4.0 */ +@Deprecated public class JarPluginLoader implements PluginLoader { protected PluginManager pluginManager; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java index f36903c..b1b7c81 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java @@ -9,6 +9,7 @@ import org.pf4j.PluginManager; * @version 2.2.0 * @see DefaultPluginApplication */ +@Deprecated public interface Pf4jFactory { /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java index 33d9bf2..0b54e81 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java @@ -18,6 +18,7 @@ import java.util.Objects; * @author starBlues * @version 2.4.0 */ +@Deprecated public class SortDependencyResolver extends DependencyResolver { private final static Logger LOGGER = LoggerFactory.getLogger(SortDependencyResolver.class); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java index 701d42e..eaa04f7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java @@ -7,6 +7,7 @@ import org.pf4j.DefaultPluginDescriptor; * @author starBlues * @version 2.4.5 */ +@Deprecated public class DefaultPluginDescriptorExtend extends DefaultPluginDescriptor implements PluginDescriptorExtend{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java index b683b77..f6dee34 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java @@ -13,6 +13,7 @@ import java.util.jar.Manifest; * @author starBlues * @version 2.4.5 */ +@Deprecated public class ManifestPluginDescriptorFinderExtend extends ManifestPluginDescriptorFinder { public static final String PLUGIN_CONFIG_FILE_NAME = "Plugin-ConfigFileName"; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java index 4a4f8d9..da7708c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java @@ -7,6 +7,7 @@ import org.pf4j.PluginDescriptor; * @author starBlues * @version 2.4.5 */ +@Deprecated public interface PluginDescriptorExtend extends PluginDescriptor { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java index 1054d16..f4bf3d7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java @@ -19,6 +19,7 @@ import java.util.Properties; * @author starBlues * @version 2.4.5 */ +@Deprecated public class ResolvePropertiesPluginDescriptorFinder extends PropertiesPluginDescriptorFinder { @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java index d669043..42e4125 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java @@ -16,6 +16,7 @@ import java.util.Properties; * @author starBlues * @version 2.4.5 */ +@Deprecated public class ResourcesPluginDescriptorFinder extends PropertiesPluginDescriptorFinder { public static final String PLUGIN_CONFIG_FILE_NAME = "plugin.configFileName"; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java new file mode 100644 index 0000000..1991d5e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java @@ -0,0 +1,72 @@ +package com.gitee.starblues.utils; + + +import sun.awt.geom.AreaOp; + +import java.util.function.Supplier; + +/** + * @author starBlues + * @version 3.0.0 + */ +public abstract class Assert { + + private Assert(){}; + + public static void isTrue(boolean expression, String message) { + if (!expression) { + throw new IllegalArgumentException(message); + } + } + + public static void isTrue(boolean expression, Supplier messageSupplier) { + if (!expression) { + throw new IllegalArgumentException(nullSafeGet(messageSupplier)); + } + } + + public static void state(boolean expression, String message) { + if (!expression) { + throw new IllegalStateException(message); + } + } + + public static void state(boolean expression, Supplier messageSupplier) { + if (!expression) { + throw new IllegalStateException(nullSafeGet(messageSupplier)); + } + } + + public static T isNotNull(T t, String message) { + if (t == null) { + throw new IllegalArgumentException(message); + } + return t; + } + + public static T isNotNull(T t, Supplier messageSupplier) { + if (t == null) { + throw new IllegalArgumentException(nullSafeGet(messageSupplier)); + } + return t; + } + + public static T isNotEmpty(T t, String message) { + if (ObjectUtils.isEmpty(t)) { + throw new IllegalArgumentException(message); + } + return t; + } + + public static T isNotEmpty(T t, Supplier messageSupplier) { + if (ObjectUtils.isEmpty(t)) { + throw new IllegalArgumentException(nullSafeGet(messageSupplier)); + } + return t; + } + + private static String nullSafeGet(Supplier messageSupplier) { + return (messageSupplier != null ? messageSupplier.get() : null); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java index 87a270c..519b0b8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java @@ -28,9 +28,9 @@ public class CommonUtils { */ public static List order(List list, Function orderImpl){ if(list == null){ - return list; + return null; } - Collections.sort(list, Comparator.comparing(orderImpl, Comparator.nullsLast(Comparator.reverseOrder()))); + list.sort(Comparator.comparing(orderImpl, Comparator.nullsLast(Comparator.reverseOrder()))); return list; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java new file mode 100644 index 0000000..bdd2923 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java @@ -0,0 +1,377 @@ +package com.gitee.starblues.utils; + +import org.springframework.lang.Nullable; +import org.springframework.util.CollectionUtils; + +import java.lang.reflect.Array; +import java.util.*; + +/** + * Object 工具类 + * @author starBlues + * @version 3.0.0 + */ +public class ObjectUtils { + + private static final String[] EMPTY_STRING_ARRAY = {}; + + private static final String FOLDER_SEPARATOR = "/"; + + private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; + + private static final String TOP_PATH = ".."; + + private static final String CURRENT_PATH = "."; + + private static final char EXTENSION_SEPARATOR = '.'; + + private ObjectUtils(){} + + + public static boolean isEmpty(CharSequence cs) { + return cs == null || cs.length() == 0; + } + + public static boolean isEmpty(Object obj) { + if (obj == null) { + return true; + } + + if (obj instanceof Optional) { + return !((Optional) obj).isPresent(); + } + if (obj instanceof CharSequence) { + return ((CharSequence) obj).length() == 0; + } + if (obj.getClass().isArray()) { + return Array.getLength(obj) == 0; + } + if (obj instanceof Collection) { + return ((Collection) obj).isEmpty(); + } + if (obj instanceof Map) { + return ((Map) obj).isEmpty(); + } + return false; + } + + public static boolean hasText(@Nullable CharSequence str) { + return (str != null && str.length() > 0 && containsText(str)); + } + + public static String[] trimArrayElements(String[] array) { + if (isEmpty(array)) { + return array; + } + + String[] result = new String[array.length]; + for (int i = 0; i < array.length; i++) { + String element = array[i]; + result[i] = (element != null ? element.trim() : null); + } + return result; + } + + + public static String[] commaDelimitedListToStringArray(@Nullable String str) { + return delimitedListToStringArray(str, ","); + } + + public static String[] delimitedListToStringArray(@Nullable String str, @Nullable String delimiter) { + return delimitedListToStringArray(str, delimiter, null); + } + + public static String[] delimitedListToStringArray( + @Nullable String str, @Nullable String delimiter, @Nullable String charsToDelete) { + + if (str == null) { + return EMPTY_STRING_ARRAY; + } + if (delimiter == null) { + return new String[] {str}; + } + + List result = new ArrayList<>(); + if (delimiter.isEmpty()) { + for (int i = 0; i < str.length(); i++) { + result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); + } + } + else { + int pos = 0; + int delPos; + while ((delPos = str.indexOf(delimiter, pos)) != -1) { + result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); + pos = delPos + delimiter.length(); + } + if (str.length() > 0 && pos <= str.length()) { + // Add rest of String, but not in case of empty input. + result.add(deleteAny(str.substring(pos), charsToDelete)); + } + } + return toStringArray(result); + } + + public static String[] toStringArray(@Nullable Collection collection) { + return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); + } + + + public static String deleteAny(String inString, @Nullable String charsToDelete) { + if (!hasLength(inString) || !hasLength(charsToDelete)) { + return inString; + } + + int lastCharIndex = 0; + char[] result = new char[inString.length()]; + for (int i = 0; i < inString.length(); i++) { + char c = inString.charAt(i); + if (charsToDelete.indexOf(c) == -1) { + result[lastCharIndex++] = c; + } + } + if (lastCharIndex == inString.length()) { + return inString; + } + return new String(result, 0, lastCharIndex); + } + + public static boolean hasLength(String str) { + return (str != null && !str.isEmpty()); + } + + public static String collectionToCommaDelimitedString(@Nullable Collection coll) { + return collectionToDelimitedString(coll, ","); + } + + public static String collectionToDelimitedString(@Nullable Collection coll, String delim) { + return collectionToDelimitedString(coll, delim, "", ""); + } + + public static String collectionToDelimitedString( + @Nullable Collection coll, String delim, String prefix, String suffix) { + + if (CollectionUtils.isEmpty(coll)) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + Iterator it = coll.iterator(); + while (it.hasNext()) { + sb.append(prefix).append(it.next()).append(suffix); + if (it.hasNext()) { + sb.append(delim); + } + } + return sb.toString(); + } + + + public static boolean containsElement(@Nullable Object[] array, Object element) { + if (array == null) { + return false; + } + for (Object arrayEle : array) { + if (nullSafeEquals(arrayEle, element)) { + return true; + } + } + return false; + } + + public static boolean nullSafeEquals(@Nullable Object o1, @Nullable 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; + } + + public static boolean endsWithIgnoreCase(@Nullable String str, @Nullable String suffix) { + return (str != null && suffix != null && str.length() >= suffix.length() && + str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length())); + } + + public static String getFilenameExtension(@Nullable String path) { + if (path == null) { + return null; + } + + int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); + if (extIndex == -1) { + return null; + } + + int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); + if (folderIndex > extIndex) { + return null; + } + + return path.substring(extIndex + 1); + } + + public static String cleanPath(String path) { + if (!hasLength(path)) { + return path; + } + String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); + + // Shortcut if there is no work to do + if (pathToUse.indexOf('.') == -1) { + return pathToUse; + } + + int prefixIndex = pathToUse.indexOf(':'); + String prefix = ""; + if (prefixIndex != -1) { + prefix = pathToUse.substring(0, prefixIndex + 1); + if (prefix.contains(FOLDER_SEPARATOR)) { + prefix = ""; + } + else { + pathToUse = pathToUse.substring(prefixIndex + 1); + } + } + if (pathToUse.startsWith(FOLDER_SEPARATOR)) { + prefix = prefix + FOLDER_SEPARATOR; + pathToUse = pathToUse.substring(1); + } + + String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); + Deque pathElements = new ArrayDeque<>(); + int tops = 0; + + for (int i = pathArray.length - 1; i >= 0; i--) { + String element = pathArray[i]; + if (CURRENT_PATH.equals(element)) { + // Points to current directory - drop it. + } + else if (TOP_PATH.equals(element)) { + // Registering top path found. + tops++; + } + else { + if (tops > 0) { + // Merging path element with element corresponding to top path. + tops--; + } + else { + // Normal path element found. + pathElements.addFirst(element); + } + } + } + + // All path elements stayed the same - shortcut + if (pathArray.length == pathElements.size()) { + return prefix + pathToUse; + } + // Remaining top paths need to be retained. + for (int i = 0; i < tops; i++) { + pathElements.addFirst(TOP_PATH); + } + // If nothing else left, at least explicitly point to current path. + if (pathElements.size() == 1 && pathElements.getLast().isEmpty() && !prefix.endsWith(FOLDER_SEPARATOR)) { + pathElements.addFirst(CURRENT_PATH); + } + + return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); + } + + + public static String replace(String inString, String oldPattern, @Nullable String newPattern) { + if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { + return inString; + } + int index = inString.indexOf(oldPattern); + if (index == -1) { + // no occurrence -> can return input as-is + return inString; + } + + int capacity = inString.length(); + if (newPattern.length() > oldPattern.length()) { + capacity += 16; + } + StringBuilder sb = new StringBuilder(capacity); + + int pos = 0; // our position in the old string + int patLen = oldPattern.length(); + while (index >= 0) { + sb.append(inString, pos, index); + sb.append(newPattern); + pos = index + patLen; + index = inString.indexOf(oldPattern, pos); + } + + // append any characters to the right of a match + sb.append(inString, pos, inString.length()); + return sb.toString(); + } + + + public static int countOccurrencesOf(String str, String sub) { + if (!hasLength(str) || !hasLength(sub)) { + return 0; + } + + int count = 0; + int pos = 0; + int idx; + while ((idx = str.indexOf(sub, pos)) != -1) { + ++count; + pos = idx + sub.length(); + } + return count; + } + + 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; + } + + 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; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java index e40b1bf..0dc7ce8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java @@ -14,6 +14,7 @@ import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; +import java.util.List; /** * 插件文件工具类 @@ -50,37 +51,37 @@ public final class PluginFileUtils { } - public static void cleanEmptyFile(Path path){ - if(path == null){ + public static void cleanEmptyFile(List paths){ + if(ObjectUtils.isEmpty(paths)){ return; } - if(!Files.exists(path)){ - return; - } - try { - Files.list(path) - .forEach(subPath -> { - File file = subPath.toFile(); - if(!file.isFile()){ - return; - } - long length = file.length(); - if(length == 0){ - try { - Files.deleteIfExists(subPath); - } catch (IOException e) { - e.printStackTrace(); + for (Path path : paths) { + if(!Files.exists(path)){ + continue; + } + try { + Files.list(path) + .forEach(subPath -> { + File file = subPath.toFile(); + if(!file.isFile()){ + return; } - } - }); - } catch (IOException e) { - e.printStackTrace(); + long length = file.length(); + if(length == 0){ + try { + Files.deleteIfExists(subPath); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + } catch (IOException e) { + e.printStackTrace(); + } } - } - /** * 如果文件不存在, 则会创建 * @param path 插件路径 @@ -98,5 +99,23 @@ public final class PluginFileUtils { return path; } + /** + * 是否为 zip 文件 + * @param path 文件路径 + * @return boolean + */ + public static boolean isZipFile(Path path) { + return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".zip"); + } + + /** + * 是否为 jar 文件 + * @param path 文件路径 + * @return boolean + */ + public static boolean isJarFile(Path path) { + return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".jar"); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java new file mode 100644 index 0000000..25bce2d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -0,0 +1,84 @@ +package com.gitee.starblues.utils; + + +import java.lang.reflect.Field; +import java.util.Objects; + +/** + * 反射工具类 + * @author starBlues + * @version 3.0.0 + */ +public abstract class ReflectionUtils { + + private ReflectionUtils(){} + + public static Field findField(Class clazz, String name) { + return findField(clazz, name, null); + } + + public static Field findField(Class clazz, String fieldName, Class fieldType) { + Objects.requireNonNull(clazz, "clazz must not be null"); + if(fieldName == null && fieldType == null){ + throw new IllegalArgumentException("fieldName or fieldType of the field must be specified"); + } + + Field[] declaredFields = clazz.getDeclaredFields(); + if(declaredFields.length == 0){ + return null; + } + for (Field field : declaredFields) { + if ((fieldName == null || fieldName.equals(field.getName())) && + (fieldType == null || fieldType.equals(field.getType()))) { + return field; + } + } + return null; + } + + + public static Object getField(Object o, String fieldName) { + return getField(o, fieldName, null); + } + + public static Object getField(Object o, String fieldName, Class fieldType) { + Class currentClass = o.getClass(); + Field field = findField(currentClass, fieldName, fieldType); + while (true){ + if(field != null) { + break; + } + currentClass = currentClass.getSuperclass(); + if(currentClass == null){ + break; + } + field = findField(currentClass, fieldName, fieldType); + } + if(field == null){ + return null; + } + field.setAccessible(true); + try { + return field.get(o); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + public static void setField(Object o, String fieldName, Object value) { + setField(o, fieldName, null, value); + } + + public static void setField(Object o, String fieldName, Class fieldType, Object value) { + Field field = findField(o.getClass(), fieldName, fieldType); + if(field != null){ + field.setAccessible(true); + try { + field.set(o, value); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index ae61d51..11d204b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -8,6 +8,8 @@ import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.net.MalformedURLException; +import java.net.URL; import java.nio.file.Paths; /** @@ -28,6 +30,9 @@ public class ResourceUtils { public final static String TYPE_SPLIT = ":"; + public static final String CLASSPATH_URL_PREFIX = "classpath:"; + public static final String FILE_URL_PREFIX = "file:"; + /** * 获取匹配路绝 * @param locationMatch 原始匹配路径。规则为: file:xxx, classpath:xxx , package:xxx @@ -95,4 +100,21 @@ public class ResourceUtils { return home; } + + public static boolean isUrl(String resourceLocation) { + if (resourceLocation == null) { + return false; + } + if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) { + return true; + } + try { + new URL(resourceLocation); + return true; + } + catch (MalformedURLException ex) { + return false; + } + } + } -- Gitee From 4e5047b2313618ed7ad1f360a9564bfec05d8af4 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Mon, 29 Nov 2021 10:21:03 +0800 Subject: [PATCH 03/37] commit cloud code --- pom.xml | 1 + .../pom.xml | 222 ++++++++++++ .../extension/cloud/SpringCloudExtension.java | 66 ++++ .../cloud/nacos/NacosBeanRegistrar.java | 155 ++++++++ .../cloud/nacos/NacosDataParserHandler.java | 159 +++++++++ .../cloud/nacos/NacosPropertySource.java | 95 +++++ .../nacos/config/NacosConfigProperties.java | 81 +++++ .../cloud/nacos/config/NacosProperties.java | 30 ++ .../nacos/config/SpringCloudProperties.java | 20 ++ .../cloud/openfeign/FeignClientBeanGroup.java | 40 +++ .../openfeign/FeignClientSpecification.java | 70 ++++ .../cloud/openfeign/OpenFeignRegistrar.java | 332 ++++++++++++++++++ .../nacos/NacosRibbonClientConfiguration.java | 43 +++ .../nacos/RibbonNacosAutoConfiguration.java | 23 ++ 14 files changed, 1337 insertions(+) create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java create mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java diff --git a/pom.xml b/pom.xml index e2f5a00..a41e02c 100644 --- a/pom.xml +++ b/pom.xml @@ -14,6 +14,7 @@ springboot-plugin-framework springboot-plugin-framework-extension + springboot-plugin-framework-example diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml new file mode 100644 index 0000000..ebe70af --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml @@ -0,0 +1,222 @@ + + + + springboot-plugin-framework-parent + com.gitee.starblues + 2.4.6-RELEASE + + 4.0.0 + + springboot-plugin-framework-extension-cloud + 插件扩展-微服务模块扩展 + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + https://gitee.com/starblues/springboot-plugin-framework-parent + scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git + scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git + 1.0 + + + + + sonatype-nexus-snapshots + oss Snapshots Repository + https://oss.sonatype.org/content/repositories/snapshots + + + sonatype-nexus-staging + oss Staging Repository + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + StarBlues + starblues@foxmail.com + https://gitee.com/starblues/ + + + + + 1.8 + UTF-8 + + 3.8.1 + 3.1.0 + 3.1.0 + 3.1.0 + 1.6 + + 2.4.6-RELEASE + 5.0.7.RELEASE + 2.2.6.RELEASE + + + + + com.gitee.starblues + springboot-plugin-framework + ${springboot-plugin-framework.version} + provided + + + + org.springframework + spring-context + ${spring-version} + provided + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + ${nacos-cloud-version} + provided + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + ${nacos-cloud-version} + provided + + + + org.springframework.cloud + spring-cloud-starter-openfeign + 2.2.6.RELEASE + provided + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + 2.2.6.RELEASE + provided + + + + + + + dev + + true + + + true + + + + + release + + false + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + org.apache.maven.plugins + maven-assembly-plugin + ${maven-assembly-plugin.version} + + + jar-with-dependencies + + ${project.artifactId}-${project.version} + false + false + + + true + true + + + + + + make-assembly + package + + single + + + + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + package + + jar-no-fork + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + ${plugin.skip} + + + + package + + jar + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven-gpg-plugin.version} + + ${plugin.skip} + + + + sign-artifacts + verify + + sign + + + + + + + + \ No newline at end of file diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java new file mode 100644 index 0000000..01689b9 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java @@ -0,0 +1,66 @@ +package com.gitee.starblues.extension.cloud; + +import com.gitee.starblues.extension.AbstractExtension; +import com.gitee.starblues.extension.cloud.nacos.NacosBeanRegistrar; +import com.gitee.starblues.extension.cloud.openfeign.FeignClientBeanGroup; +import com.gitee.starblues.extension.cloud.openfeign.OpenFeignRegistrar; +import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; +import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; +import org.springframework.context.ApplicationContext; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author starBlues + * @version 2.4.6 + */ +public class SpringCloudExtension extends AbstractExtension { + + private final Type type; + private final boolean enableOpenFeign; + + public SpringCloudExtension(Type type, boolean enableOpenFeign){ + this.type = type; + this.enableOpenFeign = enableOpenFeign; + } + + public SpringCloudExtension(Type type){ + this(type, false); + } + + @Override + public String key() { + return "SpringCloud"; + } + + @Override + public List getPluginBeanRegistrar(ApplicationContext mainApplicationContext) { + List pluginBeanRegistrarExtends = new ArrayList<>(); + if(type == Type.NACOS){ + pluginBeanRegistrarExtends.add(new NacosBeanRegistrar()); + } + if(enableOpenFeign){ + pluginBeanRegistrarExtends.add(new OpenFeignRegistrar()); + } + return pluginBeanRegistrarExtends; + } + + @Override + public List getPluginClassGroup(ApplicationContext mainApplicationContext) { + if(enableOpenFeign){ + List pluginClassGroupExtends = new ArrayList<>(1); + pluginClassGroupExtends.add(new FeignClientBeanGroup()); + return pluginClassGroupExtends; + } + return null; + } + + public enum Type{ + /** + * nacos + */ + NACOS + } + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java new file mode 100644 index 0000000..d646f9d --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java @@ -0,0 +1,155 @@ +package com.gitee.starblues.extension.cloud.nacos; + +import com.alibaba.cloud.nacos.NacosConfigManager; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosServiceManager; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; +import com.gitee.starblues.extension.cloud.nacos.config.NacosConfigProperties; +import com.gitee.starblues.extension.cloud.nacos.config.NacosProperties; +import com.gitee.starblues.extension.cloud.nacos.config.SpringCloudProperties; +import com.gitee.starblues.factory.PluginRegistryInfo; +import com.gitee.starblues.factory.SpringBeanRegister; +import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; +import com.gitee.starblues.utils.PluginConfigUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.PropertySource; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +/** + * @author starBlues + * @version 2.4.6 + */ +public class NacosBeanRegistrar implements PluginBeanRegistrarExtend { + + private final static Logger log = LoggerFactory.getLogger(NacosBeanRegistrar.class); + + @Override + public String key() { + return "SpringCloud-Nacos"; + } + + @Override + public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { + GenericApplicationContext mainApplicationContext = pluginRegistryInfo.getMainApplicationContext(); + NacosConfigManager nacosConfigManager = mainApplicationContext.getBean(NacosConfigManager.class); + + SpringCloudProperties springCloudProperties = pluginRegistryInfo.getPluginBinder() + .bind(SpringCloudProperties.PREFIX, Bindable.of(SpringCloudProperties.class)) + .orElseGet(() -> null); + + if(springCloudProperties == null){ + // todo 注释 + return; + } + + ConfigService configService = nacosConfigManager.getConfigService(); + NacosProperties nacos = springCloudProperties.getNacos(); + if(nacos != null && nacos.getConfigs() != null){ + // 处理配置文件 + List configs = nacos.getConfigs(); + ConfigurableEnvironment environment = pluginRegistryInfo.getPluginApplicationContext().getEnvironment(); + processConfig(configService, environment, configs, nacos.getTimeout()); + } + + + // 注册中心 + SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); + springBeanRegister.registerSingleton("nacosDiscoveryProperties", + mainApplicationContext.getBean(NacosDiscoveryProperties.class)); + springBeanRegister.registerSingleton("nacosServiceManager", + mainApplicationContext.getBean(NacosServiceManager.class)); + } + + + private void processConfig(ConfigService configService, + ConfigurableEnvironment environment, + List configProperties, + Integer timeout){ + checkConfiguration(configProperties, "nacos-config"); + for (NacosConfigProperties properties : configProperties) { + if(properties == null){ + continue; + } + List dataIds = new ArrayList<>(); + if(properties.isFollowProfile()){ + String[] activeProfiles = environment.getActiveProfiles(); + for (String activeProfile : activeProfiles) { + NacosConfigProperties nacosConfigProperties = new NacosConfigProperties(); + BeanUtils.copyProperties(properties, nacosConfigProperties); + String dataId = PluginConfigUtils.joinConfigFileName(properties.getDataId(), activeProfile); + nacosConfigProperties.setDataId(dataId); + dataIds.add(nacosConfigProperties); + } + } else { + dataIds.add(properties); + } + + for (NacosConfigProperties config : dataIds) { + List> propertySources = loadNacosData(configService, config.getDataId(), + config.getGroup(), + config.getFileExtension(), timeout); + NacosPropertySource nacosPropertySource = new NacosPropertySource(propertySources, config.getGroup(), + config.getDataId(), new Date(), + config.isRefresh()); + if(!nacosPropertySource.getSource().isEmpty()){ + environment.getPropertySources().addLast(nacosPropertySource); + } + } + } + } + + + + private List> loadNacosData(ConfigService configService, + String dataId, String group, String fileExtension, + Integer timeout){ + String data = null; + try { + data = configService.getConfig(dataId, group, timeout); + if (StringUtils.isEmpty(data)) { + log.warn( + "Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]", + dataId, group); + return Collections.emptyList(); + } + if (log.isDebugEnabled()) { + log.debug(String.format( + "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId, + group, data)); + } + return NacosDataParserHandler.getInstance().parseNacosData(dataId, data, + fileExtension); + } + catch (NacosException e) { + log.error("get data from Nacos error,dataId:{} ", dataId, e); + } + catch (Exception e) { + log.error("parse data from Nacos error,dataId:{},data:{}", dataId, data, e); + } + return Collections.emptyList(); + } + + private void checkConfiguration(List configs, + String tips) { + for (int i = 0; i < configs.size(); i++) { + String dataId = configs.get(i).getDataId(); + if (dataId == null || dataId.trim().length() == 0) { + throw new IllegalStateException(String.format( + "the [ spring.cloud.nacos.config.%s[%s] ] must give a dataId", + tips, i)); + } + } + } + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java new file mode 100644 index 0000000..4eb2057 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java @@ -0,0 +1,159 @@ +package com.gitee.starblues.extension.cloud.nacos; + +import com.alibaba.cloud.nacos.parser.NacosByteArrayResource; +import com.alibaba.cloud.nacos.parser.NacosJsonPropertySourceLoader; +import com.alibaba.cloud.nacos.parser.NacosXmlPropertySourceLoader; +import com.alibaba.cloud.nacos.utils.NacosConfigUtils; +import org.springframework.boot.env.OriginTrackedMapPropertySource; +import org.springframework.boot.env.PropertiesPropertySourceLoader; +import org.springframework.boot.env.PropertySourceLoader; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + + +/** + * copy from com.alibaba.cloud.nacos.parser.NacosDataParserHandler + * @author starBlues + * @version 2.4.6 + * @see com.alibaba.cloud.nacos.parser.NacosDataParserHandler + */ +public class NacosDataParserHandler { + + static final String DOT = "."; + + /** + * default extension. + */ + private static final String DEFAULT_EXTENSION = "properties"; + + private static List propertySourceLoaders; + + private NacosDataParserHandler() { + propertySourceLoaders = new ArrayList<>(); + propertySourceLoaders.add(new PropertiesPropertySourceLoader()); + propertySourceLoaders.add(new YamlPropertySourceLoader()); + propertySourceLoaders.add(new NacosJsonPropertySourceLoader()); + propertySourceLoaders.add(new NacosXmlPropertySourceLoader()); + } + + /** + * Parsing nacos configuration content. + * @param configName name of nacos-config + * @param configValue value from nacos-config + * @param extension identifies the type of configValue + * @return result of Map + * @throws IOException thrown if there is a problem parsing config. + */ + public List> parseNacosData(String configName, String configValue, + String extension) throws IOException { + if (StringUtils.isEmpty(configValue)) { + return Collections.emptyList(); + } + if (StringUtils.isEmpty(extension)) { + extension = this.getFileExtension(configName); + } + for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { + if (!canLoadFileExtension(propertySourceLoader, extension)) { + continue; + } + NacosByteArrayResource nacosByteArrayResource; + if (propertySourceLoader instanceof PropertiesPropertySourceLoader) { + // PropertiesPropertySourceLoader internal is to use the ISO_8859_1, + // the Chinese will be garbled, needs to transform into unicode. + nacosByteArrayResource = new NacosByteArrayResource( + NacosConfigUtils.selectiveConvertUnicode(configValue).getBytes(), + configName); + } + else { + nacosByteArrayResource = new NacosByteArrayResource( + configValue.getBytes(), configName); + } + nacosByteArrayResource.setFilename(getFileName(configName, extension)); + List> propertySourceList = propertySourceLoader + .load(configName, nacosByteArrayResource); + if (CollectionUtils.isEmpty(propertySourceList)) { + return Collections.emptyList(); + } + return propertySourceList.stream().filter(Objects::nonNull) + .map(propertySource -> { + if (propertySource instanceof EnumerablePropertySource) { + String[] propertyNames = ((EnumerablePropertySource) propertySource) + .getPropertyNames(); + if (propertyNames != null && propertyNames.length > 0) { + Map map = new LinkedHashMap<>(); + Arrays.stream(propertyNames).forEach(name -> { + map.put(name, propertySource.getProperty(name)); + }); + return new OriginTrackedMapPropertySource( + propertySource.getName(), map, true); + } + } + return propertySource; + }).collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + /** + * check the current extension can be processed. + * @param loader the propertySourceLoader + * @param extension file extension + * @return if can match extension + */ + private boolean canLoadFileExtension(PropertySourceLoader loader, String extension) { + return Arrays.stream(loader.getFileExtensions()) + .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(extension, + fileExtension)); + } + + /** + * @param name filename + * @return file extension, default {@code DEFAULT_EXTENSION} if don't get + */ + public String getFileExtension(String name) { + if (StringUtils.isEmpty(name)) { + return DEFAULT_EXTENSION; + } + int idx = name.lastIndexOf(DOT); + if (idx > 0 && idx < name.length() - 1) { + return name.substring(idx + 1); + } + return DEFAULT_EXTENSION; + } + + private String getFileName(String name, String extension) { + if (StringUtils.isEmpty(extension)) { + return name; + } + if (StringUtils.isEmpty(name)) { + return extension; + } + int idx = name.lastIndexOf(DOT); + if (idx > 0 && idx < name.length() - 1) { + String ext = name.substring(idx + 1); + if (extension.equalsIgnoreCase(ext)) { + return name; + } + } + return name + DOT + extension; + } + + public static NacosDataParserHandler getInstance() { + return ParserHandler.HANDLER; + } + + private static class ParserHandler { + + private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler(); + + } + + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java new file mode 100644 index 0000000..82ecdd3 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java @@ -0,0 +1,95 @@ +package com.gitee.starblues.extension.cloud.nacos; + +import com.alibaba.cloud.nacos.NacosConfigProperties; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.util.CollectionUtils; + +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; + + +/** + * copy from com.alibaba.cloud.nacos.client.NacosPropertySource + * @author starBlues + * @version 2.4.6 + * @see com.alibaba.cloud.nacos.client.NacosPropertySource + */ +public class NacosPropertySource extends MapPropertySource { + + /** + * Nacos Group. + */ + private final String group; + + /** + * Nacos dataID. + */ + private final String dataId; + + /** + * timestamp the property get. + */ + private final Date timestamp; + + /** + * Whether to support dynamic refresh for this Property Source. + */ + private final boolean isRefreshable; + + NacosPropertySource(String group, String dataId, Map source, + Date timestamp, boolean isRefreshable) { + super(String.join(NacosConfigProperties.COMMAS, dataId, group), source); + this.group = group; + this.dataId = dataId; + this.timestamp = timestamp; + this.isRefreshable = isRefreshable; + } + + NacosPropertySource(List> propertySources, String group, + String dataId, Date timestamp, boolean isRefreshable) { + this(group, dataId, getSourceMap(group, dataId, propertySources), timestamp, + isRefreshable); + } + + @SuppressWarnings("all") + private static Map getSourceMap(String group, String dataId, + List> propertySources) { + if (CollectionUtils.isEmpty(propertySources)) { + return Collections.emptyMap(); + } + // If only one, return the internal element, otherwise wrap it. + if (propertySources.size() == 1) { + PropertySource propertySource = propertySources.get(0); + if (propertySource != null && propertySource.getSource() instanceof Map) { + return (Map) propertySource.getSource(); + } + } + // If it is multiple, it will be returned as it is, and the internal elements + // cannot be directly retrieved, so the user needs to implement the retrieval + // logic by himself + return Collections.singletonMap( + String.join(NacosConfigProperties.COMMAS, dataId, group), + propertySources); + } + + public String getGroup() { + return this.group; + } + + public String getDataId() { + return dataId; + } + + public Date getTimestamp() { + return timestamp; + } + + public boolean isRefreshable() { + return isRefreshable; + } + +} + diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java new file mode 100644 index 0000000..8878e29 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java @@ -0,0 +1,81 @@ +package com.gitee.starblues.extension.cloud.nacos.config; + +import java.util.Objects; + +/** + * @author starBlues + * @version 2.4.5 + */ +public class NacosConfigProperties { + + private String dataId; + + private String group = "DEFAULT_GROUP"; + + private String fileExtension = "properties"; + + private boolean refresh = false; + + private boolean followProfile = false; + + public String getDataId() { + return dataId; + } + + public void setDataId(String dataId) { + this.dataId = dataId; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getFileExtension() { + return fileExtension; + } + + public void setFileExtension(String fileExtension) { + this.fileExtension = fileExtension; + } + + public boolean isRefresh() { + return refresh; + } + + public void setRefresh(boolean refresh) { + this.refresh = refresh; + } + + public boolean isFollowProfile() { + return followProfile; + } + + public void setFollowProfile(boolean followProfile) { + this.followProfile = followProfile; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof NacosConfigProperties)) { + return false; + } + NacosConfigProperties that = (NacosConfigProperties) o; + return isRefresh() == that.isRefresh() && + isFollowProfile() == that.isFollowProfile() && + getDataId().equals(that.getDataId()) && + getGroup().equals(that.getGroup()) && + getFileExtension().equals(that.getFileExtension()); + } + + @Override + public int hashCode() { + return Objects.hash(getDataId(), getGroup(), getFileExtension(), isRefresh(), isFollowProfile()); + } +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java new file mode 100644 index 0000000..b1b994a --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.extension.cloud.nacos.config; + +import java.util.List; + +/** + * @author starBlues + * @version 2.4.5 + */ +public class NacosProperties { + + private List configs; + + private Integer timeout = 1000; + + public List getConfigs() { + return configs; + } + + public void setConfigs(List configs) { + this.configs = configs; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java new file mode 100644 index 0000000..7606fde --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java @@ -0,0 +1,20 @@ +package com.gitee.starblues.extension.cloud.nacos.config; + +/** + * @author starBlues + * @version 2.4.5 + */ +public class SpringCloudProperties { + + public static final String PREFIX = "spring-cloud"; + + private NacosProperties nacos; + + public NacosProperties getNacos() { + return nacos; + } + + public void setNacos(NacosProperties nacos) { + this.nacos = nacos; + } +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java new file mode 100644 index 0000000..faa41d5 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java @@ -0,0 +1,40 @@ +package com.gitee.starblues.extension.cloud.openfeign; + +import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; +import com.gitee.starblues.realize.BasePlugin; +import com.gitee.starblues.utils.AnnotationsUtils; +import org.springframework.cloud.openfeign.FeignClient; + +/** + * FeignClient bean class 分组 + * @author starBlues + * @version 2.4.6 + */ +public class FeignClientBeanGroup implements PluginClassGroupExtend { + + public static final String KEY = "feignClientBeanClass"; + public static final String GROUP_ID = "feignClientBeanClassGroupExtend"; + + @Override + public String key() { + return KEY ; + } + + @Override + public String groupId() { + return GROUP_ID; + } + + @Override + public void initialize(BasePlugin basePlugin) { + + } + + @Override + public boolean filter(Class aClass) { + if(aClass == null){ + return false; + } + return AnnotationsUtils.haveAnnotations(aClass, false, FeignClient.class); + } +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java new file mode 100644 index 0000000..0ade998 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java @@ -0,0 +1,70 @@ +package com.gitee.starblues.extension.cloud.openfeign; + +import org.springframework.cloud.context.named.NamedContextFactory; + +import java.util.Arrays; +import java.util.Objects; + +/** + * copy org.springframework.cloud.openfeign.FeignClientSpecification + * @author starBlues + * @version 2.4.6 + */ +public class FeignClientSpecification implements NamedContextFactory.Specification { + + private String name; + + private Class[] configuration; + + FeignClientSpecification() { + } + + FeignClientSpecification(String name, Class[] configuration) { + this.name = name; + this.configuration = configuration; + } + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public Class[] getConfiguration() { + return this.configuration; + } + + public void setConfiguration(Class[] configuration) { + this.configuration = configuration; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FeignClientSpecification that = (FeignClientSpecification) o; + return Objects.equals(this.name, that.name) + && Arrays.equals(this.configuration, that.configuration); + } + + @Override + public int hashCode() { + return Objects.hash(this.name, this.configuration); + } + + @Override + public String toString() { + return new StringBuilder("FeignClientSpecification{").append("name='") + .append(this.name).append("', ").append("configuration=") + .append(Arrays.toString(this.configuration)).append("}").toString(); + } + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java new file mode 100644 index 0000000..4f977ef --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java @@ -0,0 +1,332 @@ +package com.gitee.starblues.extension.cloud.openfeign; + +import com.gitee.starblues.extension.cloud.openfeign.nacos.RibbonNacosAutoConfiguration; +import com.gitee.starblues.factory.PluginRegistryInfo; +import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; +import com.gitee.starblues.realize.BasePlugin; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.FeignClientFactoryBean; +import org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoConfiguration; +import org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration; +import org.springframework.cloud.openfeign.hateoas.FeignHalAutoConfiguration; +import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.io.support.SpringFactoriesLoader; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.*; + +/** + * OpenFeign 注册者 + * @author starBlues + * @version 2.4.6 + */ +public class OpenFeignRegistrar implements PluginBeanRegistrarExtend { + + @Override + public String key() { + return "OpenFeignRegistrar"; + } + + @Override + public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { + // 先注册 feignClient bean + boolean isRegistry = registryFeignClientBean(pluginRegistryInfo); + if(!isRegistry){ + // 如果发现 FeignClient 则, 不进行注册 openFeign + return; + } + installAutoConfiguration(pluginRegistryInfo); + } + + private void installAutoConfiguration(PluginRegistryInfo pluginRegistryInfo) { + List basePlugins = SpringFactoriesLoader + .loadFactories(pluginRegistryInfo.getBasePlugin().getClass(), pluginRegistryInfo.getPluginClassLoader()); + + + GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); + pluginApplicationContext.registerBean(FeignRibbonClientAutoConfiguration.class); + pluginApplicationContext.registerBean(FeignHalAutoConfiguration.class); + pluginApplicationContext.registerBean(FeignAutoConfiguration.class); + pluginApplicationContext.registerBean(FeignAcceptGzipEncodingAutoConfiguration.class); + pluginApplicationContext.registerBean(FeignContentGzipEncodingAutoConfiguration.class); + //pluginApplicationContext.registerBean(FeignLoadBalancerAutoConfiguration.class); + pluginApplicationContext.registerBean(RibbonNacosAutoConfiguration.class); + pluginApplicationContext.registerBean(RibbonAutoConfiguration.class); + pluginApplicationContext.registerBean(HttpMessageConvertersAutoConfiguration.class); + } + + private boolean registryFeignClientBean(PluginRegistryInfo pluginRegistryInfo) { + List> groupClasses = pluginRegistryInfo.getGroupClasses(FeignClientBeanGroup.GROUP_ID); + if(ObjectUtils.isEmpty(groupClasses)){ + return false; + } + GenericApplicationContext registry = pluginRegistryInfo.getPluginApplicationContext(); + for (Class groupClass : groupClasses) { + AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(groupClass); + AnnotationMetadata annotationMetadata = beanDefinition.getMetadata(); + Assert.isTrue(annotationMetadata.isInterface(), + "@FeignClient can only be specified on an interface"); + + Map attributes = annotationMetadata + .getAnnotationAttributes(FeignClient.class.getCanonicalName()); + if(attributes == null){ + continue; + } + String name = getClientName(attributes); + registerClientConfiguration(registry, name, attributes.get("configuration")); + + BeanDefinitionHolder beanDefinitionHolder = getBeanDefinition(registry, annotationMetadata, attributes); + pluginRegistryInfo.getSpringBeanRegister().registerBeanDefinition(beanDefinitionHolder); + } + return true; + } + + private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, + Object configuration) { + if(configuration == null){ + return; + } + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .genericBeanDefinition(FeignClientSpecification.class); + builder.addConstructorArgValue(name); + builder.addConstructorArgValue(configuration); + registry.registerBeanDefinition( + name + "." + FeignClientSpecification.class.getSimpleName(), + builder.getBeanDefinition()); + } + + private BeanDefinitionHolder getBeanDefinition(GenericApplicationContext applicationContext, + AnnotationMetadata annotationMetadata, + Map attributes) { + String className = annotationMetadata.getClassName(); + Class clazz = ClassUtils.resolveClassName(className, applicationContext.getClassLoader()); + String contextId = getContextId(applicationContext, attributes); + String name = getName(applicationContext, attributes); + FeignClientFactoryBean factoryBean = new FeignClientFactoryBean(); + factoryBean.setBeanFactory(applicationContext); + factoryBean.setName(name); + factoryBean.setContextId(contextId); + factoryBean.setType(clazz); + BeanDefinitionBuilder definition = BeanDefinitionBuilder + .genericBeanDefinition(clazz, () -> { + factoryBean.setUrl(getUrl(applicationContext, attributes)); + factoryBean.setPath(getPath(applicationContext, attributes)); + factoryBean.setDecode404(Boolean + .parseBoolean(String.valueOf(attributes.get("decode404")))); + Object fallback = attributes.get("fallback"); + if (fallback != null) { + factoryBean.setFallback(fallback instanceof Class + ? (Class) fallback + : ClassUtils.resolveClassName(fallback.toString(), null)); + } + Object fallbackFactory = attributes.get("fallbackFactory"); + if (fallbackFactory != null) { + factoryBean.setFallbackFactory(fallbackFactory instanceof Class + ? (Class) fallbackFactory + : ClassUtils.resolveClassName(fallbackFactory.toString(), + null)); + } + return factoryBean.getObject(); + }); + definition.setAutowireMode(2); + definition.setLazyInit(true); + validate(attributes); + + AbstractBeanDefinition beanDefinition = definition.getBeanDefinition(); + beanDefinition.setAttribute("factoryBeanObjectType", className); + beanDefinition.setAttribute("feignClientsRegistrarFactoryBean", factoryBean); + + // has a default, won't be null + boolean primary = (Boolean) attributes.get("primary"); + + beanDefinition.setPrimary(primary); + + String[] qualifiers = getQualifiers(attributes); + if (ObjectUtils.isEmpty(qualifiers)) { + qualifiers = new String[] { contextId + "FeignClient" }; + } + + return new BeanDefinitionHolder(beanDefinition, className, qualifiers); + } + + private void validate(Map attributes) { + AnnotationAttributes annotation = AnnotationAttributes.fromMap(attributes); + // This blows up if an aliased property is overspecified + // FIXME annotation.getAliasedString("name", FeignClient.class, null); + validateFallback(annotation.getClass("fallback")); + validateFallbackFactory(annotation.getClass("fallbackFactory")); + } + + private void validateFallback(final Class clazz) { + Assert.isTrue(!clazz.isInterface(), + "Fallback class must implement the interface annotated by @FeignClient"); + } + + private void validateFallbackFactory(final Class clazz) { + Assert.isTrue(!clazz.isInterface(), "Fallback factory must produce instances " + + "of fallback classes that implement the interface annotated by @FeignClient"); + } + + private String getContextId(GenericApplicationContext applicationContext, + Map attributes) { + String contextId = (String) attributes.get("contextId"); + if (!StringUtils.hasText(contextId)) { + return getName(applicationContext, attributes); + } + + contextId = resolve(applicationContext, contextId); + return getName(contextId); + } + + private String getQualifier(Map client) { + if (client == null) { + return null; + } + String qualifier = (String) client.get("qualifier"); + if (StringUtils.hasText(qualifier)) { + return qualifier; + } + return null; + } + + private String[] getQualifiers(Map client) { + if (client == null) { + return null; + } + List qualifierList = new ArrayList<>( + Arrays.asList((String[]) client.get("qualifiers"))); + qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier)); + if (qualifierList.isEmpty() && getQualifier(client) != null) { + qualifierList = Collections.singletonList(getQualifier(client)); + } + return !qualifierList.isEmpty() ? qualifierList.toArray(new String[0]) : null; + } + + private String getName(GenericApplicationContext applicationContext, + Map attributes) { + String name = (String) attributes.get("serviceId"); + if (!StringUtils.hasText(name)) { + name = (String) attributes.get("name"); + } + if (!StringUtils.hasText(name)) { + name = (String) attributes.get("value"); + } + name = resolve(applicationContext, name); + return getName(name); + } + + private String getName(String name) { + if (!StringUtils.hasText(name)) { + return ""; + } + + String host = null; + try { + String url; + if (!name.startsWith("http://") && !name.startsWith("https://")) { + url = "http://" + name; + } + else { + url = name; + } + host = new URI(url).getHost(); + + } catch (URISyntaxException e) { + // 忽略 + } + Assert.state(host != null, "Service id not legal hostname (" + name + ")"); + return name; + } + + private String getUrl(GenericApplicationContext applicationContext, + Map attributes) { + String url = resolve(applicationContext, (String) attributes.get("url")); + return getUrl(url); + } + + private String getUrl(String url) { + if (StringUtils.hasText(url) && !(url.startsWith("#{") && url.contains("}"))) { + if (!url.contains("://")) { + url = "http://" + url; + } + try { + new URL(url); + } + catch (MalformedURLException e) { + throw new IllegalArgumentException(url + " is malformed", e); + } + } + return url; + } + + + private String getPath(GenericApplicationContext applicationContext, + Map attributes) { + String path = resolve(applicationContext, (String) attributes.get("path")); + return getPath(path); + } + + + private String getPath(String path) { + if (StringUtils.hasText(path)) { + path = path.trim(); + if (!path.startsWith("/")) { + path = "/" + path; + } + if (path.endsWith("/")) { + path = path.substring(0, path.length() - 1); + } + } + return path; + } + + private String getClientName(Map client) { + if (client == null) { + return null; + } + String value = (String) client.get("contextId"); + if (!StringUtils.hasText(value)) { + value = (String) client.get("value"); + } + if (!StringUtils.hasText(value)) { + value = (String) client.get("name"); + } + if (!StringUtils.hasText(value)) { + value = (String) client.get("serviceId"); + } + if (StringUtils.hasText(value)) { + return value; + } + + throw new IllegalStateException("Either 'name' or 'value' must be provided in @" + + FeignClient.class.getSimpleName()); + } + + private String resolve(GenericApplicationContext applicationContext, String value) { + if (StringUtils.hasText(value)) { + return applicationContext.getEnvironment().resolvePlaceholders(value); + } + return value; + } + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java new file mode 100644 index 0000000..c6f2e1a --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java @@ -0,0 +1,43 @@ +package com.gitee.starblues.extension.cloud.openfeign.nacos; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.ribbon.NacosServerIntrospector; +import com.alibaba.cloud.nacos.ribbon.NacosServerList; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ServerList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.netflix.ribbon.PropertiesFactory; +import org.springframework.context.annotation.Bean; + +/** + * @author zhangzhuo@acoinfo.com + * @version 1.0 + * @date 2021-11-05 + */ +public class NacosRibbonClientConfiguration { + + @Autowired + private PropertiesFactory propertiesFactory; + + @Bean + @ConditionalOnMissingBean + public ServerList ribbonServerList(IClientConfig config, + NacosDiscoveryProperties nacosDiscoveryProperties) { + if (this.propertiesFactory.isSet(ServerList.class, config.getClientName())) { + ServerList serverList = this.propertiesFactory.get(ServerList.class, config, + config.getClientName()); + return serverList; + } + NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + serverList.initWithNiwsConfig(config); + return serverList; + } + + @Bean + @ConditionalOnMissingBean + public NacosServerIntrospector nacosServerIntrospector() { + return new NacosServerIntrospector(); + } + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java new file mode 100644 index 0000000..fde8549 --- /dev/null +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java @@ -0,0 +1,23 @@ +package com.gitee.starblues.extension.cloud.openfeign.nacos; + +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.context.annotation.Configuration; + +/** + * @author zhangzhuo@acoinfo.com + * @version 1.0 + * @date 2021-11-05 + */ +@Configuration +//@EnableConfigurationProperties +//@ConditionalOnBean(SpringClientFactory.class) +//@ConditionalOnRibbonNacos +//@ConditionalOnNacosDiscoveryEnabled +@AutoConfigureAfter(RibbonAutoConfiguration.class) +@RibbonClients(defaultConfiguration = { + NacosRibbonClientConfiguration.class +}) +public class RibbonNacosAutoConfiguration { +} -- Gitee From 64a2f262058eb934de0a6ac5739934c6ed93f01e Mon Sep 17 00:00:00 2001 From: StarBlues Date: Mon, 29 Nov 2021 17:33:18 +0800 Subject: [PATCH 04/37] commit code --- .../starblues/core/DefaultPluginManager.java | 109 +++- .../core/DefaultRealizeProvider.java | 5 + .../gitee/starblues/core/PluginManager.java | 29 +- .../gitee/starblues/core/RealizeProvider.java | 6 + .../com/gitee/starblues/core/RuntimeMode.java | 8 + .../DefaultMainResourceDefiner.java | 5 + .../core/classloader/PluginClassLoader.java | 11 +- .../core/loader/DefaultPluginLoader.java | 15 +- .../starblues/core/loader/PluginWrapper.java | 7 - .../core/loader/PluginWrapperFace.java | 5 - .../core/loader/PluginWrapperInside.java | 13 +- ...PluginPipeApplicationContextProcessor.java | 2 +- .../pipe/bean/ConfigFileBeanRegistrar.java | 200 +++--- .../AutoIntegrationConfiguration.java | 18 +- .../integration/ConfigurationBuilder.java | 3 +- .../integration/IntegrationConfiguration.java | 2 +- .../integration/SpringBootPluginStarter.java | 53 ++ .../application/AutoPluginApplication.java | 7 - .../application/DefaultPluginApplication.java | 50 +- .../manager/DefaultPluginManagerFactory.java | 4 +- .../operator/DefaultPluginOperator.java | 606 ++---------------- .../integration/operator/PluginOperator.java | 2 +- .../operator/PluginOperatorWrapper.java | 2 +- .../operator/module/PluginInfo.java | 12 +- .../operator/verify/DefaultPluginVerify.java | 83 +-- .../operator/verify/PluginLegalVerify.java | 115 ++-- .../operator/verify/PluginVerify.java | 46 +- .../integration/user/DefaultPluginUser.java | 20 +- .../integration/user/PluginUser.java | 14 - .../realize/ConfigDefinitionTip.java | 7 +- .../spring/BasePluginSpringApplication.java | 32 +- .../starblues/spring/DefaultSpringPlugin.java | 73 +++ .../spring/EmptyAutoConfiguration.java | 8 + .../spring/PluginApplicationContext.java | 2 +- .../spring/PluginBeanDefinitionLoader.java | 2 +- .../spring/PluginSpringApplication.java | 3 +- .../gitee/starblues/spring/SpringPlugin.java | 19 + .../spring/SpringPluginRegistryInfo.java | 30 + .../environment/FilteredPropertySource.java | 2 +- .../environment/LocalConfigFileLoader.java | 2 +- .../PluginEnvironmentProcessor.java | 2 +- .../PluginLocalConfigFileProcessor.java | 4 +- .../spring/process/AfterRefreshProcessor.java | 18 + .../process/AfterRefreshProcessorFactory.java | 58 ++ .../process/BeforeRefreshProcessor.java | 18 + .../BeforeRefreshProcessorFactory.java | 58 ++ .../spring-configuration-metadata.json | 7 + .../main/resources/META-INF/spring.factories | 3 + 48 files changed, 849 insertions(+), 951 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/BasePluginSpringApplication.java (77%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/PluginApplicationContext.java (96%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/PluginBeanDefinitionLoader.java (99%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/PluginSpringApplication.java (84%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/environment/FilteredPropertySource.java (96%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/environment/LocalConfigFileLoader.java (56%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/environment/PluginEnvironmentProcessor.java (90%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{core => }/spring/environment/PluginLocalConfigFileProcessor.java (99%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java create mode 100644 springboot-plugin-framework/src/main/resources/META-INF/spring.factories diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 714e6b0..13dfe93 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -1,6 +1,7 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.core.loader.PluginWrapperFace; import com.gitee.starblues.core.loader.PluginWrapperInside; @@ -32,7 +33,7 @@ public class DefaultPluginManager implements PluginManager{ private final AtomicBoolean loaded = new AtomicBoolean(false); - private final Map startedPlugins = new ConcurrentHashMap<>(); + private final Map startedPlugins = new ConcurrentHashMap<>(); private final Map resolvedPlugins = new ConcurrentHashMap<>(); public DefaultPluginManager(RealizeProvider realizeProvider, String ...pluginRootDirs) { @@ -50,7 +51,7 @@ public class DefaultPluginManager implements PluginManager{ } @Override - public List getPluginsRoot() { + public List getPluginsRoots() { return pluginRootDirs.stream() .filter(Objects::nonNull) .map(Paths::get) @@ -65,7 +66,15 @@ public class DefaultPluginManager implements PluginManager{ try { List scanPluginPaths = provider.getPluginScanner().scan(pluginRootDirs); if(ObjectUtils.isEmpty(scanPluginPaths)){ - log.warn("没有发现插件!"); + StringBuilder warn = new StringBuilder("\n\n路径 {} 中未发现插件.\n"); + warn.append("1. 请检查路径是否合适.\n"); + warn.append("2. 请检查插件包中是否存在[") + .append(PluginDescriptorLoader.BOOTSTRAP_FILE_NAME) + .append("]插件引导文件.\n"); + if(provider.getRuntimeMode() == RuntimeMode.DEV){ + warn.append("3. 请检查插件包是否手动编译.\n"); + } + log.warn(warn.toString(), pluginRootDirs); return Collections.emptyList(); } List result = new ArrayList<>(scanPluginPaths.size()); @@ -86,9 +95,39 @@ public class DefaultPluginManager implements PluginManager{ } @Override - public PluginDescriptor load(String pluginPath) throws PluginException { - Path path = Paths.get(pluginPath); - return load(path); + public boolean verify(Path jarPath) { + try { + provider.getPluginChecker().check(jarPath); + PluginDescriptor pluginDescriptor = provider.getPluginDescriptor().load(jarPath); + if(pluginDescriptor == null){ + return false; + } + provider.getPluginChecker().check(pluginDescriptor); + return true; + } catch (Exception e) { + log.error("插件jar包校验失败. [{}]" , jarPath, e); + return false; + } + } + + @Override + public PluginDescriptor load(Path pluginPath) throws PluginException { + try { + provider.getPluginChecker().check(pluginPath); + } catch (Exception e) { + throw new PluginException("非法插件: " + pluginPath, e); + } + PluginDescriptor pluginDescriptor = provider.getPluginDescriptor().load(pluginPath); + if(pluginDescriptor == null){ + return null; + } + String pluginId = pluginDescriptor.getPluginId(); + if(resolvedPlugins.containsKey(pluginId) || startedPlugins.containsKey(pluginId)){ + log.error("已经存在插件: {}", pluginId); + return null; + } + resolvedPlugins.put(pluginDescriptor.getPluginId(), pluginDescriptor); + return pluginDescriptor; } @Override @@ -97,23 +136,30 @@ public class DefaultPluginManager implements PluginManager{ } @Override - public PluginDescriptor install(String pluginPath) throws PluginException { + public PluginDescriptor install(Path pluginPath) throws PluginException { PluginDescriptor pluginDescriptor = load(pluginPath); if(pluginDescriptor == null){ throw new PluginException("安装[" + pluginPath + "]插件包失败."); } - return start(pluginDescriptor); + try { + return start(pluginDescriptor); + } catch (Exception e){ + unLoad(pluginDescriptor.getPluginId()); + throw new PluginException("安装启动[" + pluginPath + "]插件包失败."); + } } @Override public synchronized void uninstall(String pluginId) throws PluginException { - PluginWrapper pluginWrapper = startedPlugins.get(pluginId); + PluginWrapperInside pluginWrapper = startedPlugins.get(pluginId); PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); if(pluginWrapper == null && pluginDescriptor == null){ throw new PluginException("没有发现插件: " + pluginId); } if(pluginWrapper != null){ - stop(pluginWrapper); + if(pluginWrapper.getPluginState() == PluginState.STARTED){ + stop(pluginWrapper); + } startedPlugins.remove(pluginId); } else { resolvedPlugins.remove(pluginId); @@ -121,7 +167,7 @@ public class DefaultPluginManager implements PluginManager{ } @Override - public void upgrade(String pluginPath) throws PluginException { + public void upgrade(Path pluginPath) throws PluginException { PluginDescriptor upgradePluginDescriptor = load(pluginPath); if(upgradePluginDescriptor == null){ throw new PluginException("解析[" + pluginPath + "]插件更新包失败."); @@ -164,7 +210,7 @@ public class DefaultPluginManager implements PluginManager{ @Override public PluginDescriptor stop(String pluginId) throws PluginException { - PluginWrapper pluginWrapper = startedPlugins.get(pluginId); + PluginWrapperInside pluginWrapper = startedPlugins.get(pluginId); if(pluginWrapper == null){ throw new PluginException("没有发现插件: " + pluginId); } @@ -181,6 +227,15 @@ public class DefaultPluginManager implements PluginManager{ return pluginDescriptors; } + @Override + public PluginDescriptor getPluginDescriptor(String pluginId) { + PluginWrapper pluginWrapper = startedPlugins.get(pluginId); + if(pluginWrapper != null){ + return pluginWrapper.getPluginDescriptor(); + } + return resolvedPlugins.get(pluginId); + } + @Override public List getPluginWrappers() { List pluginWrappers = new ArrayList<>(startedPlugins.size()); @@ -190,23 +245,9 @@ public class DefaultPluginManager implements PluginManager{ return pluginWrappers; } - private PluginDescriptor load(Path pluginPath) throws PluginException { - try { - provider.getPluginChecker().check(pluginPath); - } catch (Exception e) { - throw new PluginException("非法插件: " + pluginPath, e); - } - PluginDescriptor pluginDescriptor = provider.getPluginDescriptor().load(pluginPath); - if(pluginDescriptor == null){ - return null; - } - String pluginId = pluginDescriptor.getPluginId(); - if(resolvedPlugins.containsKey(pluginId) || startedPlugins.containsKey(pluginId)){ - log.error("已经存在插件: {}", pluginId); - return null; - } - resolvedPlugins.put(pluginDescriptor.getPluginId(), pluginDescriptor); - return pluginDescriptor; + @Override + public PluginWrapper getPluginWrapper(String pluginId) { + return startedPlugins.get(pluginId); } private PluginDescriptor start(PluginDescriptor pluginDescriptor) throws PluginException { @@ -219,24 +260,22 @@ public class DefaultPluginManager implements PluginManager{ PluginWrapperInside pluginWrapper = provider.getPluginLoader().load(pluginDescriptor); pluginWrapper.setPluginState(PluginState.RESOLVED); start(pluginWrapper); - pluginWrapper.setPluginState(PluginState.STARTED); - log.info("启动插件 [{}] 成功.", pluginId); return pluginDescriptor; } catch (Exception e) { throw new PluginException("启动插件 [" + pluginId + "] 失败. ", e); } } - private void start(PluginWrapper pluginWrapper){ + private void start(PluginWrapperInside pluginWrapper){ String pluginId = pluginWrapper.getPluginId(); - pluginWrapper.getPluginApplicationContext().run(); + pluginWrapper.setPluginState(PluginState.STARTED); startedPlugins.put(pluginId, pluginWrapper); resolvedPlugins.remove(pluginId); } - private void stop(PluginWrapper pluginWrapper){ + private void stop(PluginWrapperInside pluginWrapper){ String pluginId = pluginWrapper.getPluginId(); - pluginWrapper.getPluginApplicationContext().close(); + pluginWrapper.setPluginState(PluginState.STOPPED); resolvedPlugins.put(pluginId, pluginWrapper.getPluginDescriptor()); startedPlugins.remove(pluginId); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java index 15de429..88f3a12 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -75,6 +75,11 @@ public class DefaultRealizeProvider implements RealizeProvider { this.versionInspector = Assert.isNotNull(versionInspector, "versionInspector 不能为空"); } + @Override + public RuntimeMode getRuntimeMode() { + return runtimeMode; + } + @Override public PluginScanner getPluginScanner() { return Assert.isNotNull(pluginScanner, "PluginScanner 实现不能为空"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java index fc9face..14f25a8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -17,7 +17,7 @@ public interface PluginManager { * 得到插件root目录 * @return List */ - List getPluginsRoot(); + List getPluginsRoots(); /** * 加载配置目录中全部插件 @@ -25,13 +25,20 @@ public interface PluginManager { */ List loadPlugins(); + /** + * 校验插件jar包 + * @param jarPath 插件jar包 + * @return 校验结果. true 成功, false 失败 + */ + boolean verify(Path jarPath); + /** * 安装具体插件路径来加载插件 * @param pluginPath 插件路径 * @return 加载的插件信息 * @throws PluginException 插件异常 */ - PluginDescriptor load(String pluginPath) throws PluginException; + PluginDescriptor load(Path pluginPath) throws PluginException; /** * 卸载加载插件 @@ -45,7 +52,7 @@ public interface PluginManager { * @return 安装的插件信息 * @throws PluginException 插件异常 */ - PluginDescriptor install(String pluginPath) throws PluginException; + PluginDescriptor install(Path pluginPath) throws PluginException; /** * 卸载插件 @@ -59,7 +66,7 @@ public interface PluginManager { * @param pluginPath 新版本插件路径 * @throws PluginException 插件异常 */ - void upgrade(String pluginPath) throws PluginException; + void upgrade(Path pluginPath) throws PluginException; /** * 启动处于 RESOLVED 状态的插件 @@ -83,10 +90,24 @@ public interface PluginManager { */ List getPluginDescriptors(); + /** + * 根据插件id获取插件描述信息 + * @param pluginId 插件id + * @return PluginDescriptor + */ + PluginDescriptor getPluginDescriptor(String pluginId); + /** * 得到全部的插件信息 * @return List PluginWrapper */ List getPluginWrappers(); + /** + * 根据插件id获取插件 PluginWrapper + * @param pluginId 插件id + * @return PluginWrapper + */ + PluginWrapper getPluginWrapper(String pluginId); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java index 9537eac..1a2ca90 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -11,6 +11,12 @@ import com.gitee.starblues.core.version.VersionInspector; */ public interface RealizeProvider { + /** + * 当前运行环境 + * @return RuntimeMode + */ + RuntimeMode getRuntimeMode(); + /** * 得到 PluginScanner 实现 * @return PluginScanner diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java index 28664fe..75cd554 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java @@ -23,6 +23,14 @@ public enum RuntimeMode { this.mode = mode; } + public static RuntimeMode byName(String model){ + if(DEV.name().equalsIgnoreCase(model)){ + return RuntimeMode.DEV; + } else { + return RuntimeMode.PROD; + } + } + @Override public String toString() { return mode; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java index f53cfd9..99588f4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java @@ -52,6 +52,9 @@ public class DefaultMainResourceDefiner implements MainResourceDefiner{ // == main == mainClass.add(mainPackageName); + // == springboot-plugin-framework == + mainClass.add("com.gitee.starblues"); + // === spring-boot-starter === // logback-classic mainClass.add("ch.qos.logback.classic"); @@ -84,6 +87,7 @@ public class DefaultMainResourceDefiner implements MainResourceDefiner{ private void initDefaultResources(String mainPackageName) { mainResources.add(mainPackageName.replace(".", "/")); + mainResources.add("com/gitee/starblues"); mainResources.add("org/springframework"); mainResources.add("org/slf4j/Logger"); mainResources.add("org/aopalliance"); @@ -93,6 +97,7 @@ public class DefaultMainResourceDefiner implements MainResourceDefiner{ private void initDefaultSpringFactories() { springFactories.add("/spring-boot/"); springFactories.add("/spring-beans/"); + springFactories.add("/springboot-plugin-framework/"); // 当前框架名称 springFactories.add(mainPackageName); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index 51b1457..2b93ca9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -52,10 +52,17 @@ public class PluginClassLoader extends AbstractPluginClassLoader { public Class loadClass(String className) throws ClassNotFoundException { synchronized (getClassLoadingLock(className)) { Set classNames = mainResourceDefiner.getClassNames(); + Class loadedClass = null; if(exist(classNames, className)){ - return parent.loadClass(className); + try { + loadedClass = parent.loadClass(className); + } catch (Exception e){ + // 忽略 + } + } + if(loadedClass == null){ + loadedClass = findLoadedClass(className); } - Class loadedClass = findLoadedClass(className); if (loadedClass != null) { return loadedClass; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java index d93d8dd..3476ca2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java @@ -4,9 +4,6 @@ import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.classloader.MainResourceDefiner; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.spring.BasePluginSpringApplication; -import com.gitee.starblues.core.spring.PluginSpringApplication; -import com.gitee.starblues.core.spring.environment.PluginLocalConfigFileProcessor; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; @@ -41,27 +38,17 @@ public class DefaultPluginLoader implements PluginLoader{ PluginClassLoader classLoader = getClassLoader(descriptor); installLib(classLoader, descriptor.getPluginLibDir()); Class bootstrapClass = classLoader.loadClass(descriptor.getPluginClass()); - PluginSpringApplication springApplication = getPluginSpringApplication(descriptor, - classLoader, bootstrapClass); PluginWrapperInside pluginWrapperInside = new PluginWrapperInside( descriptor.getPluginId(), descriptor, classLoader, bootstrapClass, - descriptor.getPluginPath(), - springApplication.getApplicationContext() + descriptor.getPluginPath() ); pluginWrapperInside.setPluginState(PluginState.CREATED); return pluginWrapperInside; } - private PluginSpringApplication getPluginSpringApplication(PluginDescriptor descriptor, - ClassLoader classLoader, - Class bootstrapClass) { - return new BasePluginSpringApplication(classLoader, bootstrapClass, descriptor.getConfigFileName()); - } - - protected synchronized PluginClassLoader getClassLoader(PluginDescriptor descriptor){ String pluginId = descriptor.getPluginId(); Path classPath = descriptor.getPluginPath(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java index a0f53c2..c3dff99 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java @@ -2,7 +2,6 @@ package com.gitee.starblues.core.loader; import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.spring.PluginSpringApplication; import java.nio.file.Path; @@ -43,12 +42,6 @@ public interface PluginWrapper { */ Path getPluginPath(); - /** - * 得到插件 SpringApplication - * @return PluginSpringApplication - */ - PluginSpringApplication getPluginApplicationContext(); - /** * 得到插件状态 * @return PluginState diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java index f540d3c..c815f03 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java @@ -44,11 +44,6 @@ public class PluginWrapperFace implements PluginWrapper{ return pluginWrapper.getPluginPath(); } - @Override - public ApplicationContext getPluginApplicationContext() { - return pluginWrapper.getPluginApplicationContext(); - } - @Override public PluginState getPluginState() { return pluginWrapper.getPluginState(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java index 670cec4..558cfb3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java @@ -2,9 +2,6 @@ package com.gitee.starblues.core.loader; import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.spring.PluginSpringApplication; -import org.apache.catalina.core.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; import java.nio.file.Path; @@ -19,18 +16,15 @@ public class PluginWrapperInside implements PluginWrapper{ private final ClassLoader pluginClassLoader; private final Class pluginClass; private final Path pluginPath; - private final PluginSpringApplication pluginSpringApplication; private PluginState pluginState; public PluginWrapperInside(String pluginId, PluginDescriptor pluginDescriptor, - ClassLoader pluginClassLoader, Class pluginClass, - Path pluginPath, PluginSpringApplication pluginSpringApplication) { + ClassLoader pluginClassLoader, Class pluginClass, Path pluginPath) { this.pluginId = pluginId; this.pluginDescriptor = pluginDescriptor; this.pluginClassLoader = pluginClassLoader; this.pluginClass = pluginClass; this.pluginPath = pluginPath; - this.pluginSpringApplication = pluginSpringApplication; } public void setPluginState(PluginState pluginState) { @@ -62,11 +56,6 @@ public class PluginWrapperInside implements PluginWrapper{ return pluginPath; } - @Override - public PluginSpringApplication getPluginApplicationContext() { - return pluginSpringApplication; - } - @Override public PluginState getPluginState() { return pluginState; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java index cfbca03..dcbcaa8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java @@ -41,7 +41,7 @@ public class PluginPipeApplicationContextProcessor implements PluginPipeProcesso pluginBeanDefinitionRegistrars.add(new SpringBootConfigFileRegistrar(mainApplicationContext)); pluginBeanDefinitionRegistrars.add(new PluginInsetBeanRegistrar()); pluginBeanDefinitionRegistrars.add(new ConfigBeanRegistrar()); - pluginBeanDefinitionRegistrars.add(new ConfigFileBeanRegistrar(mainApplicationContext)); + //pluginBeanDefinitionRegistrars.add(new ConfigFileBeanRegistrar(mainApplicationContext)); pluginBeanDefinitionRegistrars.add(new BasicBeanRegistrar()); pluginBeanDefinitionRegistrars.add(new InvokeBeanRegistrar()); pluginBeanDefinitionRegistrars.addAll(ExtensionInitializer.getPluginBeanRegistrarExtends()); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java index 912334d..dd0cc73 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java @@ -1,100 +1,100 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.gitee.starblues.annotation.ConfigDefinition; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.bean.configuration.ConfigurationParser; -import com.gitee.starblues.factory.process.pipe.bean.configuration.PluginConfigDefinition; -import com.gitee.starblues.factory.process.pipe.bean.configuration.YamlConfigurationParser; -import com.gitee.starblues.factory.process.pipe.classs.group.ConfigDefinitionGroup; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.realize.ConfigDefinitionTip; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.PluginConfigUtils; -import org.pf4j.util.StringUtils; -import org.springframework.context.ApplicationContext; -import org.springframework.util.ReflectionUtils; - -import java.lang.reflect.Field; -import java.util.List; - -/** - * 插件中配置文件 bean 的处理者。包括配置文件 - * @author starBlues - * @version 2.4.0 - */ -public class ConfigFileBeanRegistrar implements PluginBeanRegistrar { - - private final ConfigurationParser configurationParser; - private final IntegrationConfiguration integrationConfiguration; - - public ConfigFileBeanRegistrar(ApplicationContext mainApplicationContext) { - integrationConfiguration = - mainApplicationContext.getBean(IntegrationConfiguration.class); - this.configurationParser = new YamlConfigurationParser(integrationConfiguration); - } - - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List> configDefinitions = - pluginRegistryInfo.getGroupClasses(ConfigDefinitionGroup.GROUP_ID); - if(configDefinitions == null || configDefinitions.isEmpty()){ - return; - } - for (Class aClass : configDefinitions) { - registry(pluginRegistryInfo, aClass); - } - } - - /** - * 注册配置文件 - * @param pluginRegistryInfo 插件注册的信息 - * @param aClass 配置文件类 - * @throws Exception Exception - */ - private void registry(PluginRegistryInfo pluginRegistryInfo, Class aClass) throws Exception{ - ConfigDefinition configDefinition = aClass.getAnnotation(ConfigDefinition.class); - if(configDefinition == null){ - return; - } - PluginConfigUtils.FileNamePack fileNamePack = PluginConfigUtils.getConfigFileName( - configDefinition.fileName(), - configDefinition.prodSuffix(), - configDefinition.devSuffix(), - integrationConfiguration.environment()); - String fileName = PluginConfigUtils.joinConfigFileName(fileNamePack); - Object parseObject = null; - if(!StringUtils.isNullOrEmpty(fileName)){ - PluginConfigDefinition pluginConfigDefinition = - new PluginConfigDefinition(fileName, aClass); - parseObject = configurationParser.parse(pluginRegistryInfo, - pluginConfigDefinition); - } else { - parseObject = aClass.newInstance(); - } - - String name = aClass.getName(); - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - setConfigDefinitionTip(pluginRegistryInfo, parseObject); - springBeanRegister.registerSingleton(name, parseObject); - pluginRegistryInfo.addConfigSingleton(parseObject); - } - - /** - * 设置小工具类 - * @param parseObject 当前的配置对象 - */ - private void setConfigDefinitionTip(PluginRegistryInfo pluginRegistryInfo, Object parseObject) { - Class aClass = parseObject.getClass(); - List fields = ClassUtils.getAllFields(aClass); - ConfigDefinitionTip configDefinitionTip = new ConfigDefinitionTip(pluginRegistryInfo); - for (Field field : fields) { - if(field.getType() == ConfigDefinitionTip.class){ - field.setAccessible(true); - ReflectionUtils.setField(field, parseObject, configDefinitionTip); - } - } - } - -} +//package com.gitee.starblues.factory.process.pipe.bean; +// +//import com.gitee.starblues.annotation.ConfigDefinition; +//import com.gitee.starblues.factory.PluginRegistryInfo; +//import com.gitee.starblues.factory.SpringBeanRegister; +//import com.gitee.starblues.factory.process.pipe.bean.configuration.ConfigurationParser; +//import com.gitee.starblues.factory.process.pipe.bean.configuration.PluginConfigDefinition; +//import com.gitee.starblues.factory.process.pipe.bean.configuration.YamlConfigurationParser; +//import com.gitee.starblues.factory.process.pipe.classs.group.ConfigDefinitionGroup; +//import com.gitee.starblues.integration.IntegrationConfiguration; +//import com.gitee.starblues.realize.ConfigDefinitionTip; +//import com.gitee.starblues.utils.ClassUtils; +//import com.gitee.starblues.utils.PluginConfigUtils; +//import org.pf4j.util.StringUtils; +//import org.springframework.context.ApplicationContext; +//import org.springframework.util.ReflectionUtils; +// +//import java.lang.reflect.Field; +//import java.util.List; +// +///** +// * 插件中配置文件 bean 的处理者。包括配置文件 +// * @author starBlues +// * @version 2.4.0 +// */ +//public class ConfigFileBeanRegistrar implements PluginBeanRegistrar { +// +// private final ConfigurationParser configurationParser; +// private final IntegrationConfiguration integrationConfiguration; +// +// public ConfigFileBeanRegistrar(ApplicationContext mainApplicationContext) { +// integrationConfiguration = +// mainApplicationContext.getBean(IntegrationConfiguration.class); +// this.configurationParser = new YamlConfigurationParser(integrationConfiguration); +// } +// +// +// @Override +// public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { +// List> configDefinitions = +// pluginRegistryInfo.getGroupClasses(ConfigDefinitionGroup.GROUP_ID); +// if(configDefinitions == null || configDefinitions.isEmpty()){ +// return; +// } +// for (Class aClass : configDefinitions) { +// registry(pluginRegistryInfo, aClass); +// } +// } +// +// /** +// * 注册配置文件 +// * @param pluginRegistryInfo 插件注册的信息 +// * @param aClass 配置文件类 +// * @throws Exception Exception +// */ +// private void registry(PluginRegistryInfo pluginRegistryInfo, Class aClass) throws Exception{ +// ConfigDefinition configDefinition = aClass.getAnnotation(ConfigDefinition.class); +// if(configDefinition == null){ +// return; +// } +// PluginConfigUtils.FileNamePack fileNamePack = PluginConfigUtils.getConfigFileName( +// configDefinition.fileName(), +// configDefinition.prodSuffix(), +// configDefinition.devSuffix(), +// integrationConfiguration.environment()); +// String fileName = PluginConfigUtils.joinConfigFileName(fileNamePack); +// Object parseObject = null; +// if(!StringUtils.isNullOrEmpty(fileName)){ +// PluginConfigDefinition pluginConfigDefinition = +// new PluginConfigDefinition(fileName, aClass); +// parseObject = configurationParser.parse(pluginRegistryInfo, +// pluginConfigDefinition); +// } else { +// parseObject = aClass.newInstance(); +// } +// +// String name = aClass.getName(); +// SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); +// setConfigDefinitionTip(pluginRegistryInfo, parseObject); +// springBeanRegister.registerSingleton(name, parseObject); +// pluginRegistryInfo.addConfigSingleton(parseObject); +// } +// +// /** +// * 设置小工具类 +// * @param parseObject 当前的配置对象 +// */ +// private void setConfigDefinitionTip(PluginRegistryInfo pluginRegistryInfo, Object parseObject) { +// Class aClass = parseObject.getClass(); +// List fields = ClassUtils.getAllFields(aClass); +// ConfigDefinitionTip configDefinitionTip = new ConfigDefinitionTip(pluginRegistryInfo); +// for (Field field : fields) { +// if(field.getType() == ConfigDefinitionTip.class){ +// field.setAccessible(true); +// ReflectionUtils.setField(field, parseObject, configDefinitionTip); +// } +// } +// } +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index e0d6baf..9dfe954 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -35,8 +35,8 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio /** * 主程序包名 */ - @Value("${mainPackageName:}") - private String mainPackageName; + @Value("${mainPackage:}") + private String mainPackage; /** * 插件的路径 @@ -129,12 +129,12 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public RuntimeMode environment() { - return RuntimeMode.valueOf(runMode); + return RuntimeMode.byName(runMode); } @Override - public String mainPackageName() { - return mainPackageName; + public String mainPackage() { + return mainPackage; } @Override @@ -254,6 +254,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.enable = enable; } + public String getMainPackage() { + return mainPackage; + } + + public void setMainPackage(String mainPackage) { + this.mainPackage = mainPackage; + } + public List getPluginPath() { if(ObjectUtils.isEmpty(pluginPath)){ return super.pluginPath(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java index 50abac8..3caf8d6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java @@ -201,10 +201,9 @@ public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ } @Override - public String mainPackageName() { + public String mainPackage() { return null; } - @Override public List pluginPath() { if(ObjectUtils.isEmpty(pluginPath)){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index 31d05cd..1eeef6c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -24,7 +24,7 @@ public interface IntegrationConfiguration { * 主程序包名 * @return String */ - String mainPackageName(); + String mainPackage(); /** * 插件的路径。可设置多个插件路径 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java new file mode 100644 index 0000000..e4c5265 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java @@ -0,0 +1,53 @@ +package com.gitee.starblues.integration; + +import com.gitee.starblues.core.RealizeProvider; +import com.gitee.starblues.integration.application.AutoPluginApplication; +import com.gitee.starblues.integration.operator.PluginOperator; +import com.gitee.starblues.integration.user.PluginUser; +import com.gitee.starblues.spring.SpringPlugin; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @author starBlues + * @version 3.0.0 + */ +@Configuration(proxyBeanMethods = true) +@EnableConfigurationProperties(AutoIntegrationConfiguration.class) +@ConditionalOnProperty(value = "plugin.enable", havingValue = "true", matchIfMissing = false) +public class SpringBootPluginStarter extends AutoPluginApplication { + + + @Bean + @ConditionalOnMissingBean + @Override + protected PluginUser createPluginUser(ApplicationContext applicationContext) { + return super.createPluginUser(applicationContext); + } + + @Bean + @ConditionalOnMissingBean + @Override + protected PluginOperator createPluginOperator(ApplicationContext applicationContext, IntegrationConfiguration configuration) { + return super.createPluginOperator(applicationContext, configuration); + } + + @Bean + @ConditionalOnMissingBean + @Override + protected SpringPlugin createSpringPlugin(GenericApplicationContext applicationContext) { + return super.createSpringPlugin(applicationContext); + } + + @Bean + @ConditionalOnMissingBean + @Override + protected RealizeProvider createRealizeProvider(IntegrationConfiguration configuration) { + return super.createRealizeProvider(configuration); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java index 8898307..31575c0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java @@ -18,13 +18,6 @@ public class AutoPluginApplication extends DefaultPluginApplication private ApplicationContext applicationContext; private PluginInitializerListener pluginInitializerListener; - public AutoPluginApplication() { - super(); - } - - public AutoPluginApplication(Pf4jFactory pf4jFactory) { - super(pf4jFactory); - } /** * 设置插件初始化监听器 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index c2ed2ec..836c7ba 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -1,8 +1,7 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.core.PluginManager; -import com.gitee.starblues.integration.manager.DefaultPluginManagerFactory; -import com.gitee.starblues.integration.manager.PluginManagerFactory; +import com.gitee.starblues.core.DefaultRealizeProvider; +import com.gitee.starblues.core.RealizeProvider; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; @@ -10,13 +9,12 @@ import com.gitee.starblues.integration.operator.DefaultPluginOperator; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.gitee.starblues.spring.DefaultSpringPlugin; +import com.gitee.starblues.spring.SpringPlugin; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; -import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; @@ -28,9 +26,6 @@ import java.util.concurrent.atomic.AtomicBoolean; */ public class DefaultPluginApplication extends AbstractPluginApplication { - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - protected PluginManagerFactory pluginManagerFactory; private PluginUser pluginUser; private PluginOperator pluginOperator; @@ -40,11 +35,6 @@ public class DefaultPluginApplication extends AbstractPluginApplication { public DefaultPluginApplication() { } - public DefaultPluginApplication(PluginManagerFactory pluginManagerFactory){ - this.pluginManagerFactory = pluginManagerFactory; - } - - @Override public synchronized void initialize(ApplicationContext applicationContext, PluginInitializerListener listener) { @@ -53,12 +43,8 @@ public class DefaultPluginApplication extends AbstractPluginApplication { throw new RuntimeException("Plugin has been initialized"); } IntegrationConfiguration configuration = getConfiguration(applicationContext); - if(pluginManagerFactory == null){ - pluginManagerFactory = new DefaultPluginManagerFactory(configuration); - } - PluginManager pluginManager = pluginManagerFactory.getPluginManager(); - pluginUser = createPluginUser(applicationContext, pluginManager); - pluginOperator = createPluginOperator(applicationContext, pluginManager, configuration); + pluginUser = createPluginUser(applicationContext); + pluginOperator = createPluginOperator(applicationContext, configuration); try { setBeanFactory(applicationContext); pluginOperator.initPlugins(listener); @@ -71,33 +57,37 @@ public class DefaultPluginApplication extends AbstractPluginApplication { /** * 创建插件使用者。子类可扩展 * @param applicationContext Spring ApplicationContext - * @param pluginManager 插件管理器 * @return PluginUser */ - protected PluginUser createPluginUser(ApplicationContext applicationContext, - PluginManager pluginManager){ - return new DefaultPluginUser(applicationContext, pluginManager); + protected PluginUser createPluginUser(ApplicationContext applicationContext){ + return new DefaultPluginUser(applicationContext); } /** * 创建插件操作者。子类可扩展 * @param applicationContext Spring ApplicationContext - * @param pluginManager 插件管理器 * @param configuration 当前集成的配置 * @return PluginOperator */ protected PluginOperator createPluginOperator(ApplicationContext applicationContext, - PluginManager pluginManager, IntegrationConfiguration configuration){ + GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext; PluginOperator pluginOperator = new DefaultPluginOperator( - applicationContext, - configuration, - pluginManager, - this.listenerFactory + genericApplicationContext, + createSpringPlugin(genericApplicationContext), + createRealizeProvider(configuration), + configuration ); return new PluginOperatorWrapper(pluginOperator, configuration); } + protected SpringPlugin createSpringPlugin(GenericApplicationContext applicationContext){ + return new DefaultSpringPlugin(applicationContext); + } + + protected RealizeProvider createRealizeProvider(IntegrationConfiguration configuration){ + return new DefaultRealizeProvider(configuration.environment(), configuration.mainPackage()); + } @Override public PluginOperator getPluginOperator() { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java index 0f8d7c4..5f93d33 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java @@ -23,8 +23,8 @@ public class DefaultPluginManagerFactory implements PluginManagerFactory{ public PluginManager getPluginManager() { RuntimeMode runtimeMode = Assert.isNotEmpty(configuration.environment(), "配置[environment]不能为空"); - String mainPackageName = Assert.isNotEmpty(configuration.mainPackageName(), - "配置[mainPackageName]不能为空"); + String mainPackageName = Assert.isNotEmpty(configuration.mainPackage(), + "配置[mainPackage]不能为空"); List pluginPaths = Assert.isNotEmpty(configuration.pluginPath(), "配置[pluginPath]不能为空"); RealizeProvider realizeProvider = new DefaultRealizeProvider(runtimeMode, mainPackageName); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index a2fa381..2756ba2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -1,671 +1,191 @@ package com.gitee.starblues.integration.operator; +import com.gitee.starblues.core.DefaultPluginManager; import com.gitee.starblues.core.PluginManager; +import com.gitee.starblues.core.RealizeProvider; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.factory.DefaultPluginFactory; -import com.gitee.starblues.factory.PluginFactory; -import com.gitee.starblues.factory.PluginRegistryInfo; +import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.listener.PluginInitializerListenerFactory; -import com.gitee.starblues.integration.listener.PluginListenerFactory; import com.gitee.starblues.integration.operator.module.PluginInfo; -import com.gitee.starblues.integration.operator.verify.DefaultPluginVerify; -import com.gitee.starblues.integration.operator.verify.PluginLegalVerify; -import com.gitee.starblues.utils.GlobalRegistryInfo; +import com.gitee.starblues.spring.SpringPlugin; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; -import com.gitee.starblues.utils.PluginOperatorInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.multipart.MultipartFile; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; import java.util.*; -import java.util.stream.Collectors; +import java.util.concurrent.atomic.AtomicBoolean; /** * 默认的插件操作者 * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public class DefaultPluginOperator implements PluginOperator { - - private boolean isInit = false; protected final Logger log = LoggerFactory.getLogger(this.getClass()); - private final static DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); - - protected final GenericApplicationContext applicationContext; - protected final IntegrationConfiguration integrationConfiguration; - protected final PluginManager pluginManager; - protected final PluginFactory pluginFactory; - protected final PluginInitializerListenerFactory pluginInitializerListenerFactory; - - protected PluginLegalVerify pluginLegalVerify; + private final AtomicBoolean isInit = new AtomicBoolean(false); + private final GenericApplicationContext applicationContext; + private final IntegrationConfiguration configuration; - public DefaultPluginOperator(ApplicationContext applicationContext, - IntegrationConfiguration integrationConfiguration, - PluginManager pluginManager, - PluginListenerFactory pluginListenerFactory) { - Objects.requireNonNull(integrationConfiguration, "applicationContext can't be null"); - Objects.requireNonNull(integrationConfiguration, "IntegrationConfiguration can't be null"); - Objects.requireNonNull(pluginManager, "PluginManager can't be null"); - this.applicationContext = (GenericApplicationContext) applicationContext; - this.integrationConfiguration = integrationConfiguration; - this.pluginManager = pluginManager; - this.pluginFactory = new DefaultPluginFactory(applicationContext, pluginListenerFactory); - this.pluginInitializerListenerFactory = new PluginInitializerListenerFactory(applicationContext); + private final SpringPlugin springPlugin; + private final PluginManager pluginManager; - this.pluginLegalVerify = new DefaultPluginVerify(pluginManager); + public DefaultPluginOperator(GenericApplicationContext applicationContext, + SpringPlugin springPlugin, + RealizeProvider realizeProvider, + IntegrationConfiguration configuration) { + this.applicationContext = applicationContext; + this.configuration = configuration; + this.springPlugin = springPlugin; + this.pluginManager = new DefaultPluginManager(realizeProvider, configuration.pluginPath()); } - - /** - * 设置插件校验器 - * @param uploadPluginVerify uploadPluginVerify - */ - public void setUploadPluginVerify(PluginLegalVerify uploadPluginVerify) { - if(uploadPluginVerify != null){ - this.pluginLegalVerify = uploadPluginVerify; - } - } - @Override public synchronized boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception { - if(isInit){ - throw new RuntimeException("Plugins Already initialized. Cannot be initialized again"); + if(isInit.get()){ + throw new RuntimeException("插件已经被初始化了, 不能再初始化."); } try { - pluginInitializerListenerFactory.addPluginInitializerListeners(pluginInitializerListener); - log.info("Plugins start initialize of root path '{}'", pluginManager.getPluginsRoot().toString()); + //pluginInitializerListenerFactory.addPluginInitializerListeners(pluginInitializerListener); + log.info("开始初始化加载插件: '{}'", pluginManager.getPluginsRoots().toString()); // 触发插件初始化监听器 - pluginInitializerListenerFactory.before(); - if(!integrationConfiguration.enable()){ + //pluginInitializerListenerFactory.before(); + if(!configuration.enable()){ // 如果禁用的话, 直接返回 - pluginInitializerListenerFactory.complete(); + //pluginInitializerListenerFactory.complete(); return false; } // 启动前, 清除空文件 - PluginFileUtils.cleanEmptyFile(pluginManager.getPluginsRoot()); + PluginFileUtils.cleanEmptyFile(pluginManager.getPluginsRoots()); // 开始加载插件 List pluginDescriptors = pluginManager.loadPlugins(); if(ObjectUtils.isEmpty(pluginDescriptors)){ - log.warn("没有发现插件!"); - pluginInitializerListenerFactory.complete(); + //pluginInitializerListenerFactory.complete(); return false; } boolean isFoundException = false; for (PluginDescriptor descriptor : pluginDescriptors) { try { pluginManager.start(descriptor.getPluginId()); + springPlugin.registry(pluginManager.getPluginWrapper(descriptor.getPluginId())); + log.info("启动插件[{}@{}]成功", descriptor.getPluginId(), descriptor.getPluginVersion()); } catch (Exception e){ - log.error("启动插件 '{}' 失败. {}", descriptor.getPluginId(), e.getMessage(), e); + log.error("启动插件[{}]失败. {}", descriptor.getPluginId(), e.getMessage(), e); isFoundException = true; } } - isInit = true; + isInit.set(true); if(isFoundException){ - log.error("Plugins initialize failure"); - pluginInitializerListenerFactory.failure(new Exception("Plugins initialize failure")); + log.error("插件初始化失败"); + //pluginInitializerListenerFactory.failure(new Exception("插件初始化失败")); return false; } else { - log.info("Plugins initialize success"); - pluginInitializerListenerFactory.complete(); + log.info("插件初始化成功"); + //pluginInitializerListenerFactory.complete(); return true; } } catch (Exception e){ - pluginInitializerListenerFactory.failure(e); + //pluginInitializerListenerFactory.failure(e); throw e; } } @Override public boolean verify(Path jarPath) throws Exception { - pluginLegalVerify.verify(jarPath); - return true; + return false; } - @Override - public synchronized PluginInfo install(Path jarPath) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin cannot be installed in 'dev' environment"); - } - if(jarPath == null){ - throw new IllegalArgumentException("Method:install param 'pluginId' can not be empty"); - } - String pluginId = null; - try { - PluginInfo pluginInfo = load(jarPath); - if(pluginInfo == null){ - log.error("Plugin '{}' install failure, this pluginInfo id is empty.", pluginId); - return null; - } - PluginDescriptor pluginDescriptor = pluginInfo.getPluginDescriptor(); - if(pluginDescriptor == null){ - log.error("Plugin install failure."); - return null; - } - pluginId = pluginDescriptor.getPluginId(); - GlobalRegistryInfo.addOperatorPluginInfo(pluginId, PluginOperatorInfo.OperatorType.INSTALL, true); - if(start(pluginId)){ - log.info("Plugin '{}' install success", pluginId); - return getPluginInfo(pluginId); - } else { - try { - uninstall(pluginId, false); - } catch (Exception uninstallException){ - log.error("Plugin '{}' uninstall failure. {}", pluginId, uninstallException.getMessage()); - } - return null; - } - } catch (Exception e){ - // 说明load成功, 但是没有启动成功, 则卸载该插件 - log.error("Plugin '{}' install failure. {}", pluginId, e.getMessage()); - if(!ObjectUtils.isEmpty(pluginId)){ - try { - uninstall(pluginId, false); - } catch (Exception uninstallException){ - log.error("Plugin '{}' uninstall failure. {}", pluginId, uninstallException.getMessage()); - } - } - throw e; - } finally { - if(!ObjectUtils.isEmpty(pluginId)){ - GlobalRegistryInfo.setOperatorPluginInfo(pluginId, false); - } - } + public PluginInfo install(Path jarPath) throws Exception { + return null; } @Override - public synchronized boolean uninstall(String pluginId, boolean isBackup) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin cannot be uninstalled in 'dev' environment"); - } - if(ObjectUtils.isEmpty(pluginId)){ - throw new IllegalArgumentException("Method:uninstall param 'pluginId' can not be empty"); - } - PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); - if(pluginWrapper == null){ - throw new Exception("Plugin uninstall failure, Not found plugin '" + pluginId + "'"); - } - - Exception exception = null; - if(pluginWrapper.getPluginState() == PluginState.STARTED){ - try { - pluginFactory.unRegistry(pluginId); - pluginFactory.build(); - } catch (Exception e){ - log.error("Plugin '{}' uninstall failure, {}", pluginId, e.getMessage()); - exception = e; - } - } - - try { - if (pluginManager.unloadPlugin(pluginId)) { - Path pluginPath = pluginWrapper.getPluginPath(); - boolean opPluginFile; - if(isBackup){ - // 将插件文件移到备份文件中 - opPluginFile = backup(pluginPath, "uninstall", 1); - } else { - // 不备份的话。直接删除该文件 - opPluginFile = Files.deleteIfExists(pluginPath); - } - if(opPluginFile){ - log.info("Plugin '{}' uninstall success", pluginId); - } else { - log.error("Plugin '{}' uninstall failure. process plugin file failure", pluginId); - } - return opPluginFile; - } else { - log.error("Plugin '{}' uninstall failure", pluginId); - return false; - } - } catch (Exception e){ - if(exception != null){ - exception.printStackTrace(); - } - log.error("Plugin '{}' uninstall failure. {}", pluginId, e.getMessage()); - throw e; - } + public boolean uninstall(String pluginId, boolean isBackup) throws Exception { + return false; } @Override public PluginInfo load(Path jarPath) throws Exception { - if(!Files.exists(jarPath)){ - throw new FileNotFoundException("Not found this path " + jarPath); - } - // 校验插件文件 - pluginLegalVerify.verify(jarPath); - Path pluginsRoot = pluginManager.getPluginsRoot(); - Path pluginPath = null; - if(jarPath.getParent().compareTo(pluginsRoot) == 0){ - // 说明该插件文件存在于插件root目录下。直接加载该插件 - pluginPath = jarPath; - } else { - File sourceFile = jarPath.toFile(); - String targetPathString = pluginsRoot.toString() + File.separator + - sourceFile.getName(); - Path targetPath = Paths.get(targetPathString); - if(Files.exists(targetPath)){ - // 如果存在该文件, 则移动备份 - backup(targetPath, "install-backup", 1); - } - PluginFileUtils.createExistFile(targetPath); - Files.copy(jarPath, targetPath, StandardCopyOption.REPLACE_EXISTING); - pluginPath = targetPath; - } - String pluginId = null; - try { - pluginId = pluginManager.loadPlugin(pluginPath); - if(pluginId != null){ - return getPluginInfo(pluginId); - } - return null; - } catch (Exception e){ - if(pluginId != null){ - log.error("Load plugin success, but get pluginInfo failure. so remove plugin '{}'", pluginId); - try { - pluginManager.unloadPlugin(pluginId); - } finally { - Files.delete(pluginPath); - } - } else { - log.error("Load plugin failure"); - } - return null; - } + return null; } @Override public PluginInfo load(MultipartFile pluginFile) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin cannot uploadPluginAndStart in the 'dev' environment"); - } - if(pluginFile == null){ - throw new IllegalArgumentException("Method:uploadPluginAndStart param 'pluginFile' can not be null"); - } - Path jarPath = uploadPlugin(pluginFile); - return load(jarPath); + return null; } @Override public boolean unload(String pluginId, boolean isBackup) throws Exception { - PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); - if(pluginWrapper == null){ - throw new Exception("Plugin unload failure, Not found plugin '" + pluginId + "'"); - } - pluginManager.unloadPlugin(pluginId); - if(isBackup){ - backup(pluginWrapper.getPluginPath(), "unload", 1); - } - return true; + return false; } @Override - public synchronized boolean start(String pluginId) throws Exception { - if(ObjectUtils.isEmpty(pluginId)){ - throw new IllegalArgumentException("Method:start param 'pluginId' can not be empty"); - } - PluginWrapper pluginWrapper = getPluginWrapper(pluginId, "Start"); - if(pluginWrapper.getPluginState() == PluginState.STARTED){ - throw new Exception("This plugin '" + pluginId + "' have already started"); - } - try { - PluginState pluginState = pluginManager.startPlugin(pluginId); - if(pluginState == PluginState.STARTED){ - GlobalRegistryInfo.addOperatorPluginInfo(pluginId, PluginOperatorInfo.OperatorType.START, false); - pluginFactory.registry(PluginRegistryInfo.build(pluginWrapper, pluginManager, - applicationContext,false)); - pluginFactory.build(); - log.info("Plugin '{}' start success", pluginId); - return true; - } - log.error("Plugin '{}' start failure, plugin state is not start. Current plugin state is '{}'", - pluginId, pluginState.toString()); - - } catch (Exception e){ - log.error("Plugin '{}' start failure. {}", pluginId, e.getMessage(), e); - log.info("Start stop plugin '{}'", pluginId); - try { - stop(pluginId); - } catch (Exception stopException){ - log.error("Plugin '{}' stop failure. {}", pluginId, e.getMessage()); - } - } + public boolean start(String pluginId) throws Exception { return false; } @Override - public synchronized boolean stop(String pluginId) throws Exception { - if(ObjectUtils.isEmpty(pluginId)){ - throw new IllegalArgumentException("Method:stop param 'pluginId' can not be empty"); - } - PluginWrapper pluginWrapper = getPluginWrapper(pluginId, "Stop"); - if(pluginWrapper.getPluginState() != PluginState.STARTED){ - throw new Exception("This plugin '" + pluginId + "' is not started"); - } - try { - pluginFactory.unRegistry(pluginId); - pluginFactory.build(); - log.info("Plugin '{}' unRegistry success", pluginId); - } catch (Exception e){ - log.error("Plugin '{}' stop failure. {}", pluginId, e.getMessage(), e); - } - try { - pluginManager.stopPlugin(pluginId); - log.info("Plugin '{}' stop success", pluginId); - return true; - } catch (Exception e){ - log.error("Plugin '{}' stop failure. {}", pluginId, e.getMessage()); - throw e; - } + public boolean stop(String pluginId) throws Exception { + return false; } - @Override - public synchronized PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin cannot uploadPluginAndStart in the 'dev' environment"); - } - if(pluginFile == null){ - throw new IllegalArgumentException("Method:uploadPluginAndStart param 'pluginFile' can not be null"); - } - Path path = uploadPlugin(pluginFile); - return this.install(path); + public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception { + return null; } @Override - public synchronized boolean installConfigFile(Path configFilePath) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin config file cannot be installed in the 'dev' environment"); - } - if(!Files.exists(configFilePath)){ - throw new FileNotFoundException("configFilePath '" + configFilePath + "' does not exist!"); - } - File sourceFile = configFilePath.toFile(); - String configPath = integrationConfiguration.pluginConfigFilePath() + - File.separator + sourceFile.getName(); - Path targetPath = PluginFileUtils.createExistFile(Paths.get(configPath)); - if(Files.exists(targetPath)){ - // 如果文件存在, 则移动备份 - backup(targetPath, "install-config-backup",1); - } - Files.copy(configFilePath, targetPath, StandardCopyOption.REPLACE_EXISTING); - return true; + public boolean installConfigFile(Path configFilePath) throws Exception { + return false; } @Override - public synchronized boolean uploadConfigFile(MultipartFile configFile) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin config file cannot be uploaded in the 'dev' environment"); - } - if(configFile == null){ - throw new IllegalArgumentException("Method:uploadConfigFile param 'configFile' can not be null"); - } - String fileName = configFile.getOriginalFilename(); - String configPath = integrationConfiguration.pluginConfigFilePath() + - File.separator + fileName; - Path targetPath = PluginFileUtils.createExistFile(Paths.get(configPath)); - if(Files.exists(targetPath)){ - // 如果文件存在, 则拷贝备份 - backup(targetPath, "upload-config-backup",2); - } - // 然后写入数据到该文件 - Files.write(targetPath, configFile.getBytes()); - return true; + public boolean uploadConfigFile(MultipartFile configFile) throws Exception { + return false; } @Override - public synchronized boolean backupPlugin(Path backDirPath, String sign) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin cannot backup in the 'dev' environment"); - } - Objects.requireNonNull(backDirPath); - return backup(backDirPath, sign, 2); + public boolean backupPlugin(Path backDirPath, String sign) throws Exception { + return false; } - @Override - public synchronized boolean backupPlugin(String pluginId, String sign) throws Exception { - if(isDev()){ - throw new RuntimeException("Plugin cannot backup in the 'dev' environment"); - } - PluginWrapper pluginManager = getPluginWrapper(pluginId, "BackupPlugin by pluginId"); - return backupPlugin(pluginManager.getPluginPath(), sign); + public boolean backupPlugin(String pluginId, String sign) throws Exception { + return false; } @Override public List getPluginInfo() { - List startedPlugins = pluginManager.getPlugins(); - List pluginInfos = new ArrayList<>(); - if(startedPlugins == null){ - return pluginInfos; - } - return startedPlugins.stream() - .filter(pluginWrapper -> pluginWrapper != null) - .map(pw -> { - return getPluginInfo(pw); - }) - .collect(Collectors.toList()); + return null; } @Override public PluginInfo getPluginInfo(String pluginId) { - PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); - if(pluginWrapper == null){ - log.warn("Not found plugin '{}'", pluginId); - return null; - } - return getPluginInfo(pluginWrapper); + return null; } @Override public Set getPluginFilePaths() throws Exception { - RuntimeMode environment = integrationConfiguration.environment(); - if(environment == RuntimeMode.DEVELOPMENT){ - return new HashSet<>(integrationConfiguration.pluginPath()); - } - List pluginPath = integrationConfiguration.pluginPath(); - Set pathString = new HashSet<>(pluginPath.size()); - for (String path : pluginPath) { - if(ObjectUtils.isEmpty(path)){ - continue; - } - List jars = FileUtils.getJars(Paths.get(path)); - for (File jar : jars) { - pathString.add(jar.getAbsolutePath()); - } - } - return pathString; + return null; } @Override public List getPluginWrapper() { - return pluginManager.getPlugins(); + return null; } @Override public PluginWrapper getPluginWrapper(String pluginId) { - return pluginManager.getPlugin(pluginId); - } - - /** - * 上传插件 - * @param pluginFile 插件文件 - * @return 返回上传的插件路径 - * @throws Exception 异常信息 - */ - protected Path uploadPlugin(MultipartFile pluginFile) throws Exception { - if(pluginFile == null){ - throw new IllegalArgumentException("Method:uploadPlugin param 'pluginFile' can not be null"); - } - // 获取文件的后缀名 - String fileName = pluginFile.getOriginalFilename(); - String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1); - //检查文件格式是否合法 - if(StringUtils.isEmpty(suffixName)){ - throw new IllegalArgumentException("Invalid file type, please select .jar or .zip file"); - } - if(!"jar".equalsIgnoreCase(suffixName) && !"zip".equalsIgnoreCase(suffixName)){ - throw new IllegalArgumentException("Invalid file type, please select .jar or .zip file"); - } - String tempPathString = integrationConfiguration.uploadTempPath() + File.separator + fileName; - Path tempPath = PluginFileUtils.createExistFile(Paths.get(tempPathString)); - Files.write(tempPath, pluginFile.getBytes()); - try { - Path verifyPath = pluginLegalVerify.verify(tempPath); - if(verifyPath != null){ - String targetPathString = pluginManager.getPluginsRoot().toString() + - File.separator + fileName; - Path targetPluginPath = Paths.get(targetPathString); - if(Files.exists(targetPluginPath)){ - // 存在则拷贝一份 - backup(targetPluginPath, "upload", 2); - } - // 拷贝校验的路径到插件路径下 - Files.copy(verifyPath, targetPluginPath, StandardCopyOption.REPLACE_EXISTING); - // 删除临时文件 - Files.deleteIfExists(tempPath); - return targetPluginPath; - } else { - Exception exception = - new Exception(fileName + " verify failure, verifyPath is null"); - verifyFailureDelete(tempPath, exception); - throw exception; - } - } catch (Exception e){ - // 出现异常, 删除刚才上传的临时文件 - verifyFailureDelete(tempPath, e); - throw e; - } + return null; } - - - /** - * 得到插件包装类 - * @param pluginId 插件id - * @param errorMsg 错误信息 - * @return PluginWrapper - * @throws Exception 插件装配异常 - */ - protected PluginWrapper getPluginWrapper(String pluginId, String errorMsg) throws Exception { - PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); - if (pluginWrapper == null) { - throw new Exception(errorMsg + " -> Not found plugin " + pluginId); - } - return pluginWrapper; - } - - - - /** - * 校验文件失败后, 删除临时文件 - * @param tempPluginFile 临时文件路径 - * @param e 异常信息 - * @throws Exception Exception - */ - protected void verifyFailureDelete(Path tempPluginFile, Exception e) throws Exception { - try { - Files.deleteIfExists(tempPluginFile); - }catch (IOException e1){ - throw new Exception("Verify failure and delete temp file failure : " + e.getMessage(), e); - } - } - - /** - * 备份 - * @param sourcePath 源文件的路径 - * @param sign 文件标志 - * @param type 类型 1移动 2拷贝 - * @return 结果 - */ - protected boolean backup(Path sourcePath, String sign, int type) { - try { - if(isDev()){ - // 如果是开发环境, 则不进行备份 - return false; - } - if(sourcePath == null){ - return false; - } - if(!Files.exists(sourcePath)){ - log.error("Path '{}' does not exist", sourcePath.toString()); - return false; - } - String fileName = sourcePath.getFileName().toString(); - String targetName = integrationConfiguration.backupPath() + File.separator; - if(!ObjectUtils.isEmpty(sign)){ - targetName = targetName + sign; - } - targetName = targetName + "_" +getNowTimeByFormat(); - Path target = Paths.get(targetName + "_" + fileName); - if(!Files.exists(target.getParent())){ - Files.createDirectories(target.getParent()); - } - File sourceFile = sourcePath.toFile(); - if(sourceFile.length() == 0){ - // 源文件字节为0, 说明为删除的插件。不需要备份 - return true; - } - if(type == 1){ - // 是移动的话, 则删除源文件 - Files.move(sourcePath, target, StandardCopyOption.REPLACE_EXISTING); - } else { - // 拷贝 - Files.copy(sourcePath, target, StandardCopyOption.REPLACE_EXISTING); - } - return true; - } catch (IOException e) { - log.error("Backup plugin jar '{}' failure. {}", sourcePath.toString(), e.getMessage(), e); - return false; - } - } - - /** - * 获取现在的时间 - * @return String - */ - protected String getNowTimeByFormat(){ - LocalDateTime localDateTime = LocalDateTime.now(); - return FORMAT.format(localDateTime); - } - - /** - * 是否是开发环境 - * @return bolean - */ - protected boolean isDev(){ - return integrationConfiguration.environment() == RuntimeMode.DEVELOPMENT; - } - - /** - * 通过PluginWrapper得到插件信息 - * @param pluginWrapper pluginWrapper - * @return PluginInfo - */ - private PluginInfo getPluginInfo(PluginWrapper pluginWrapper) { - return new PluginInfo(pluginWrapper.getDescriptor(), pluginWrapper.getPluginState(), - pluginWrapper.getPluginPath().toAbsolutePath().toString(), - pluginManager.getRuntimeMode().toString()); - } - - - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java index d9d3a68..ccf77b7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java @@ -1,8 +1,8 @@ package com.gitee.starblues.integration.operator; +import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; -import org.pf4j.PluginWrapper; import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 14b43dc..37ac2b7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -1,12 +1,12 @@ package com.gitee.starblues.integration.operator; +import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; import com.gitee.starblues.realize.UnRegistryValidator; import com.gitee.starblues.utils.SpringBeanUtils; -import org.pf4j.PluginWrapper; import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java index abc527a..4a104c4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java @@ -1,8 +1,8 @@ package com.gitee.starblues.integration.operator.module; -import org.pf4j.PluginDescriptor; -import org.pf4j.PluginState; +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.descriptor.PluginDescriptor; /** * 插件信息 @@ -14,22 +14,22 @@ public class PluginInfo { /** * 插件基本信息 */ - private PluginDescriptor pluginDescriptor; + private final PluginDescriptor pluginDescriptor; /** * 插件状态 */ - private PluginState pluginState; + private final PluginState pluginState; /** * 插件路径 */ - private String path; + private final String path; /** * 运行模式 */ - private String runMode; + private final String runMode; public PluginInfo(PluginDescriptor pluginDescriptor, diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java index fa8692b..859125b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java @@ -1,41 +1,42 @@ -package com.gitee.starblues.integration.operator.verify; - -import com.gitee.starblues.integration.pf4j.DefaultPf4jFactory; -import org.pf4j.*; - -import java.nio.file.Path; -import java.util.Objects; - -/** - * 默认的插件校验器 - * @author starBlues - * @version 2.2.2 - */ -public class DefaultPluginVerify extends PluginLegalVerify{ - - private final PluginManager pluginManager; - - public DefaultPluginVerify(PluginManager pluginManager) { - super(DefaultPf4jFactory.getPluginDescriptorFinder(pluginManager.getRuntimeMode())); - Objects.requireNonNull(pluginManager); - this.pluginManager = pluginManager; - } - - - @Override - protected Path postVerify(Path path, PluginDescriptor pluginDescriptor) throws Exception { - PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginDescriptor.getPluginId()); - if(pluginWrapper == null){ - // 当前没有该插件包运行 - return path; - } - // 如果当前插件在当前环境存在, 则抛出异常 - PluginDescriptor runPluginDescriptor = pluginWrapper.getDescriptor(); - StringBuffer errorMsg = new StringBuffer("The plugin (") - .append("id:<").append(runPluginDescriptor.getPluginId()) - .append("> ; version <").append(runPluginDescriptor.getVersion()) - .append("> ) is already exist in the current environment。 ") - .append("Please uninstall the plugin, then upload and update the plugin"); - throw new Exception(errorMsg.toString()); - } -} +//package com.gitee.starblues.integration.operator.verify; +// +//import com.gitee.starblues.integration.pf4j.DefaultPf4jFactory; +//import org.pf4j.*; +// +//import java.nio.file.Path; +//import java.util.Objects; +// +///** +// * 默认的插件校验器 +// * @author starBlues +// * @version 2.2.2 +// */ +//@Deprecated +//public class DefaultPluginVerify extends PluginLegalVerify{ +// +// private final PluginManager pluginManager; +// +// public DefaultPluginVerify(PluginManager pluginManager) { +// super(DefaultPf4jFactory.getPluginDescriptorFinder(pluginManager.getRuntimeMode())); +// Objects.requireNonNull(pluginManager); +// this.pluginManager = pluginManager; +// } +// +// +// @Override +// protected Path postVerify(Path path, PluginDescriptor pluginDescriptor) throws Exception { +// PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginDescriptor.getPluginId()); +// if(pluginWrapper == null){ +// // 当前没有该插件包运行 +// return path; +// } +// // 如果当前插件在当前环境存在, 则抛出异常 +// PluginDescriptor runPluginDescriptor = pluginWrapper.getDescriptor(); +// StringBuffer errorMsg = new StringBuffer("The plugin (") +// .append("id:<").append(runPluginDescriptor.getPluginId()) +// .append("> ; version <").append(runPluginDescriptor.getVersion()) +// .append("> ) is already exist in the current environment。 ") +// .append("Please uninstall the plugin, then upload and update the plugin"); +// throw new Exception(errorMsg.toString()); +// } +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java index f659b22..217678e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java @@ -1,57 +1,58 @@ -package com.gitee.starblues.integration.operator.verify; - -import org.pf4j.*; -import org.springframework.util.StringUtils; - -import java.nio.file.Path; -import java.util.Objects; - -/** - * 插件包合法校验 - * @author starBlues - * @version 1.0 - */ -public class PluginLegalVerify implements PluginVerify{ - - protected final PluginDescriptorFinder pluginDescriptorFinder; - - public PluginLegalVerify(PluginDescriptorFinder pluginDescriptorFinder) { - Objects.requireNonNull(pluginDescriptorFinder); - this.pluginDescriptorFinder = pluginDescriptorFinder; - } - - - @Override - public Path verify(Path path) throws Exception { - if(path == null){ - throw new IllegalArgumentException("path can not be null"); - } - if(!pluginDescriptorFinder.isApplicable(path)){ - // 插件包不合法 - throw new Exception(path.toString() + " : plugin illegal"); - } - PluginDescriptor pluginDescriptor = pluginDescriptorFinder.find(path); - if(pluginDescriptor == null){ - throw new Exception(path.toString() + " : Not found plugin Descriptor"); - } - if(StringUtils.isEmpty(pluginDescriptor.getPluginId())){ - throw new Exception(path.toString() + " : Plugin id can't be empty"); - } - if(StringUtils.isEmpty(pluginDescriptor.getPluginClass())){ - throw new Exception(path.toString() + " : Not found plugin Class"); - } - return postVerify(path, pluginDescriptor); - } - - /** - * 合法后的校验.可扩展校验 - * @param path 路径 - * @param pluginDescriptor 插件解析者 - * @return 返回路径 - * @throws Exception 插件异常 - */ - protected Path postVerify(Path path, PluginDescriptor pluginDescriptor) throws Exception{ - return path; - } - -} +//package com.gitee.starblues.integration.operator.verify; +// +//import com.gitee.starblues.core.descriptor.PluginDescriptor; +//import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +// +//import java.nio.file.Path; +//import java.util.Objects; +// +///** +// * 插件包合法校验 +// * @author starBlues +// * @version 1.0 +// */ +//@Deprecated +//public class PluginLegalVerify implements PluginVerify{ +// +// protected final PluginDescriptorLoader pluginDescriptorLoader; +// +// public PluginLegalVerify(PluginDescriptorLoader pluginDescriptorLoader) { +// Objects.requireNonNull(pluginDescriptorLoader); +// this.pluginDescriptorLoader = pluginDescriptorLoader; +// } +// +// @Override +// public Path verify(Path path) throws Exception { +//// if(path == null){ +//// throw new IllegalArgumentException("path can not be null"); +//// } +//// if(!pluginDescriptorFinder.isApplicable(path)){ +//// // 插件包不合法 +//// throw new Exception(path.toString() + " : plugin illegal"); +//// } +//// PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(path); +//// if(pluginDescriptor == null){ +//// throw new Exception(path.toString() + " : Not found plugin Descriptor"); +//// } +//// if(Objects.isEmpty(pluginDescriptor.getPluginId())){ +//// throw new Exception(path.toString() + " : Plugin id can't be empty"); +//// } +//// if(StringUtils.isEmpty(pluginDescriptor.getPluginClass())){ +//// throw new Exception(path.toString() + " : Not found plugin Class"); +//// } +//// return postVerify(path, pluginDescriptor); +// return null; +// } +// +// /** +// * 合法后的校验.可扩展校验 +// * @param path 路径 +// * @param pluginDescriptor 插件解析者 +// * @return 返回路径 +// * @throws Exception 插件异常 +// */ +// protected Path postVerify(Path path, PluginDescriptor pluginDescriptor) throws Exception{ +// return path; +// } +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java index d15c418..5a98afd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java @@ -1,23 +1,23 @@ -package com.gitee.starblues.integration.operator.verify; - - -import java.nio.file.Path; - -/** - * 插件合法校验接口 - * @author starBlues - * @version 1.0 - * @see DefaultPluginVerify - * @see PluginLegalVerify - */ -public interface PluginVerify { - - /** - * 校验插件包 - * @param path 插件路径 - * @return 返回校验成功的路径 - * @throws Exception 插件异常 - */ - Path verify(Path path) throws Exception; - -} +//package com.gitee.starblues.integration.operator.verify; +// +// +//import java.nio.file.Path; +// +///** +// * 插件合法校验接口 +// * @author starBlues +// * @version 1.0 +// * @see DefaultPluginVerify +// * @see PluginLegalVerify +// */ +//public interface PluginVerify { +// +// /** +// * 校验插件包 +// * @param path 插件路径 +// * @return 返回校验成功的路径 +// * @throws Exception 插件异常 +// */ +// Path verify(Path path) throws Exception; +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java index 3f3d75a..6e6519f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java @@ -1,8 +1,8 @@ package com.gitee.starblues.integration.user; +import com.gitee.starblues.core.PluginManager; import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; import com.gitee.starblues.utils.SpringBeanUtils; -import org.pf4j.PluginManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; @@ -23,13 +23,9 @@ public class DefaultPluginUser implements PluginUser{ protected final GenericApplicationContext parentApplicationContext; - protected final PluginManager pluginManager; - - public DefaultPluginUser(ApplicationContext parentApplicationContext, PluginManager pluginManager) { + public DefaultPluginUser(ApplicationContext parentApplicationContext) { Objects.requireNonNull(parentApplicationContext, "ApplicationContext can't be null"); - Objects.requireNonNull(pluginManager, "PluginManager can't be null"); this.parentApplicationContext = (GenericApplicationContext)parentApplicationContext; - this.pluginManager = pluginManager; } /** @@ -140,18 +136,6 @@ public class DefaultPluginUser implements PluginUser{ } - /** - * 得到插件扩展接口实现的bean。(非Spring管理) - * @param tClass 接口的类 - * @param bean的类型 - * @return 返回bean - */ - @Override - public List getPluginExtensions(Class tClass){ - return pluginManager.getExtensions(tClass); - } - - private T getBean(String name, boolean haveParent){ List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); if(haveParent){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java index 65bcbf0..e8c6fd1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java @@ -113,18 +113,4 @@ public interface PluginUser { @Deprecated T generateNewInstance(T object); - - - /** - * 使用场景: - * 1. 在主程序定义接口(该接口需要继承 ExtensionPoint 接口)。 - * 2. 插件包中实现该接口 - * 3. 在主程序可以使用该方法获取到实现该接口的实现类。(实现类可以配合 @Extension 控制顺序) - * 注意: 该场景用于非Spring管理的bean, 使用Spring注解无效 - * @param tClass bean的类型 - * @param bean的类型 - * @return List - */ - List getPluginExtensions(Class tClass); - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java index dcb3ae5..5c03962 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java @@ -35,9 +35,10 @@ public class ConfigDefinitionTip { public PluginInfo getCurrentPluginInfo(){ PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); PluginManager pluginManager = pluginWrapper.getPluginManager(); - return new PluginInfo(pluginWrapper.getDescriptor(), pluginWrapper.getPluginState(), - pluginWrapper.getPluginPath().toAbsolutePath().toString(), - pluginManager.getRuntimeMode().toString()); +// return new PluginInfo(pluginWrapper.getDescriptor(), pluginWrapper.getPluginState(), +// pluginWrapper.getPluginPath().toAbsolutePath().toString(), +// pluginManager.getRuntimeMode().toString()); + return null; } /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java similarity index 77% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java index 25b1846..e9b64c2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java @@ -1,7 +1,7 @@ -package com.gitee.starblues.core.spring; +package com.gitee.starblues.spring; -import com.gitee.starblues.core.spring.environment.PluginEnvironmentProcessor; -import com.gitee.starblues.core.spring.environment.PluginLocalConfigFileProcessor; +import com.gitee.starblues.spring.environment.PluginEnvironmentProcessor; +import com.gitee.starblues.spring.environment.PluginLocalConfigFileProcessor; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; @@ -11,6 +11,7 @@ import org.springframework.core.Ordered; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; /** * PluginSpringApplication @@ -19,6 +20,8 @@ import java.util.List; */ public class BasePluginSpringApplication implements PluginSpringApplication{ + private final AtomicBoolean isStarted = new AtomicBoolean(false); + private final DefaultListableBeanFactory beanFactory; private final PluginApplicationContext applicationContext; private final PluginBeanDefinitionLoader beanDefinitionLoader; @@ -66,10 +69,17 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ @Override public GenericApplicationContext run() { - processEnvironment(); - loadBean(); - refresh(); - return applicationContext; + synchronized (isStarted){ + if(isStarted.get()){ + throw new RuntimeException("已经运行了PluginSpringApplication, 无法再运行"); + } + processEnvironment(); + loadBean(); + refresh(); + isStarted.set(true); + return applicationContext; + } + } @@ -92,7 +102,13 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ @Override public void close() { - applicationContext.close(); + synchronized (isStarted){ + if(!isStarted.get()){ + throw new RuntimeException("PluginSpringApplication没有运行, 不能close"); + } + applicationContext.close(); + isStarted.set(false); + } } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java new file mode 100644 index 0000000..d1f923e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java @@ -0,0 +1,73 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; +import com.gitee.starblues.spring.process.AfterRefreshProcessor; +import com.gitee.starblues.spring.process.AfterRefreshProcessorFactory; +import com.gitee.starblues.spring.process.BeforeRefreshProcessor; +import com.gitee.starblues.spring.process.BeforeRefreshProcessorFactory; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class DefaultSpringPlugin implements SpringPlugin { + + private final Map registryInfoMap = new ConcurrentHashMap<>(); + + + private final GenericApplicationContext mainApplicationContext; + + private final BeforeRefreshProcessor beforeRefreshProcessor; + private final AfterRefreshProcessor afterRefreshProcessor; + + + public DefaultSpringPlugin(GenericApplicationContext mainApplicationContext) { + this.mainApplicationContext = mainApplicationContext; + this.beforeRefreshProcessor = new BeforeRefreshProcessorFactory(mainApplicationContext); + this.afterRefreshProcessor = new AfterRefreshProcessorFactory(mainApplicationContext); + } + + @Override + public synchronized void registry(PluginWrapper pluginWrapper) throws Exception { + SpringPluginRegistryInfo registryInfo = createRegistryInfo(pluginWrapper); + beforeRefreshProcessor.registry(registryInfo); + registryInfo.getPluginSpringApplication().run(); + afterRefreshProcessor.registry(registryInfo); + registryInfoMap.put(pluginWrapper.getPluginId(), registryInfo); + PluginInfoContainers.addPluginApplicationContext(pluginWrapper.getPluginId(), + registryInfo.getPluginSpringApplication().getApplicationContext()); + } + + @Override + public synchronized void unRegistry(String pluginId) throws Exception { + SpringPluginRegistryInfo springPluginRegistryInfo = registryInfoMap.get(pluginId); + if(springPluginRegistryInfo == null){ + return; + } + beforeRefreshProcessor.unRegistry(springPluginRegistryInfo); + afterRefreshProcessor.unRegistry(springPluginRegistryInfo); + springPluginRegistryInfo.getPluginSpringApplication().close(); + registryInfoMap.remove(pluginId); + PluginInfoContainers.removePluginApplicationContext(pluginId); + } + + protected SpringPluginRegistryInfo createRegistryInfo(PluginWrapper pluginWrapper){ + PluginSpringApplication springApplication = createSpringApplication(pluginWrapper); + return new SpringPluginRegistryInfo( + pluginWrapper, springApplication, mainApplicationContext + ); + } + + protected PluginSpringApplication createSpringApplication(PluginWrapper pluginWrapper){ + return new BasePluginSpringApplication( + pluginWrapper.getPluginClassLoader(), pluginWrapper.getPluginClass(), + pluginWrapper.getPluginDescriptor().getConfigFileName() + ); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java new file mode 100644 index 0000000..efe715b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java @@ -0,0 +1,8 @@ +package com.gitee.starblues.spring; + +/** + * @author starBlues + * @version 1.0 + */ +public class EmptyAutoConfiguration { +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java similarity index 96% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java index d84e6da..63da2e7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.spring; +package com.gitee.starblues.spring; import com.gitee.starblues.utils.Assert; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java index 87d5370..7efe8ac 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginBeanDefinitionLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.spring; +package com.gitee.starblues.spring; import com.gitee.starblues.utils.Assert; import org.springframework.beans.factory.BeanDefinitionStoreException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java similarity index 84% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java index 9bccb61..49e6ec8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/PluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java @@ -1,6 +1,5 @@ -package com.gitee.starblues.core.spring; +package com.gitee.starblues.spring; -import org.apache.catalina.core.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java new file mode 100644 index 0000000..9ce6944 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java @@ -0,0 +1,19 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.factory.PluginFactory; + +/** + * @author starBlues + * @version 3.0.0 + */ +public interface SpringPlugin { + + + void registry(PluginWrapper pluginWrapper) throws Exception; + + + void unRegistry(String pluginId) throws Exception; + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java new file mode 100644 index 0000000..8262400 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.core.loader.PluginWrapper; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class SpringPluginRegistryInfo { + + private final PluginWrapper pluginWrapper; + private final PluginSpringApplication pluginSpringApplication; + private final GenericApplicationContext mainApplicationContext; + + public SpringPluginRegistryInfo(PluginWrapper pluginWrapper, PluginSpringApplication springApplication, + GenericApplicationContext mainApplicationContext) { + this.pluginWrapper = pluginWrapper; + this.pluginSpringApplication = springApplication; + this.mainApplicationContext = mainApplicationContext; + } + + public PluginWrapper getPluginWrapper() { + return pluginWrapper; + } + + public PluginSpringApplication getPluginSpringApplication() { + return pluginSpringApplication; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java similarity index 96% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java index 7991e36..dee2d3e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/FilteredPropertySource.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.spring.environment; +package com.gitee.starblues.spring.environment; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MutablePropertySources; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java similarity index 56% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java index 0b79687..265fd73 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/LocalConfigFileLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.spring.environment; +package com.gitee.starblues.spring.environment; /** * @author starBlues diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java similarity index 90% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java index 423070b..251ffbb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginEnvironmentProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.spring.environment; +package com.gitee.starblues.spring.environment; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java index 603f027..2a3eae9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/spring/environment/PluginLocalConfigFileProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.spring.environment; +package com.gitee.starblues.spring.environment; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; @@ -191,7 +191,7 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso private class Loader { - private final Log logger = this.logger; + private final Log logger = PluginLocalConfigFileProcessor.this.logger; private final ConfigurableEnvironment environment; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java new file mode 100644 index 0000000..aa265c5 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java @@ -0,0 +1,18 @@ +package com.gitee.starblues.spring.process; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.OrderPriority; + +/** + * @author starBlues + * @version 3.0.0 + */ +public interface AfterRefreshProcessor { + + void registry(SpringPluginRegistryInfo registryInfo); + + void unRegistry(SpringPluginRegistryInfo registryInfo); + + OrderPriority order(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java new file mode 100644 index 0000000..4aa0d23 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java @@ -0,0 +1,58 @@ +package com.gitee.starblues.spring.process; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.OrderPriority; +import com.gitee.starblues.utils.SpringBeanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.List; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ + + private static final Logger LOGGER = LoggerFactory.getLogger(AfterRefreshProcessorFactory.class); + + private final List afterRefreshProcessors; + + public AfterRefreshProcessorFactory(GenericApplicationContext mainApplicationContext) { + List afterRefreshProcessors = SpringBeanUtils.getBeans(mainApplicationContext, AfterRefreshProcessor.class); + afterRefreshProcessors.sort(CommonUtils.orderPriority(AfterRefreshProcessor::order)); + this.afterRefreshProcessors = afterRefreshProcessors; + } + + @Override + public void registry(SpringPluginRegistryInfo registryInfo) { + for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { + try { + afterRefreshProcessor.registry(registryInfo); + } catch (Exception e){ + LOGGER.error("AfterRefreshProcessor: [{}] registry 异常", + afterRefreshProcessor.getClass().getName(), e); + } + } + } + + @Override + public void unRegistry(SpringPluginRegistryInfo registryInfo) { + for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { + try { + afterRefreshProcessor.unRegistry(registryInfo); + } catch (Exception e){ + LOGGER.error("AfterRefreshProcessor: [{}] unRegistry 异常", + afterRefreshProcessor.getClass().getName(), e); + } + } + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java new file mode 100644 index 0000000..aeb9edf --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java @@ -0,0 +1,18 @@ +package com.gitee.starblues.spring.process; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.OrderPriority; + +/** + * @author starBlues + * @version 3.0.0 + */ +public interface BeforeRefreshProcessor { + + void registry(SpringPluginRegistryInfo registryInfo); + + void unRegistry(SpringPluginRegistryInfo registryInfo); + + OrderPriority order(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java new file mode 100644 index 0000000..cf26610 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java @@ -0,0 +1,58 @@ +package com.gitee.starblues.spring.process; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.OrderPriority; +import com.gitee.starblues.utils.SpringBeanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.List; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(BeforeRefreshProcessorFactory.class); + + private final List processors; + + public BeforeRefreshProcessorFactory(GenericApplicationContext mainApplicationContext) { + List processors = SpringBeanUtils.getBeans(mainApplicationContext, BeforeRefreshProcessor.class); + processors.sort(CommonUtils.orderPriority(BeforeRefreshProcessor::order)); + this.processors = processors; + } + + @Override + public void registry(SpringPluginRegistryInfo registryInfo) { + for (BeforeRefreshProcessor processor : processors) { + try { + processor.registry(registryInfo); + } catch (Exception e){ + LOGGER.error("BeforeRefreshProcessor: [{}] registry 异常", + processor.getClass().getName(), e); + } + } + } + + @Override + public void unRegistry(SpringPluginRegistryInfo registryInfo) { + for (BeforeRefreshProcessor processor : processors) { + try { + processor.unRegistry(registryInfo); + } catch (Exception e){ + LOGGER.error("BeforeRefreshProcessor: [{}] unRegistry 异常", + processor.getClass().getName(), e); + } + } + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + +} diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json index 0a221d1..cbf58f8 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json @@ -21,6 +21,13 @@ "description": "是否启用插件功能", "defaultValue": true }, + { + "name": "plugin.mainPackage", + "type": "java.lang.String", + "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", + "description": "主程序包名, 包名建议设置到范围最大级别, 主要用于插件依赖主程序时的类时, 进行包名匹配", + "defaultValue": true + }, { "name": "plugin.pluginPath", "type": "java.lang.String", diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..f2fb06d --- /dev/null +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.gitee.starblues.spring.EmptyAutoConfiguration,\ + com.gitee.starblues.integration.SpringBootPluginStarter \ No newline at end of file -- Gitee From 54feac5abf0a186d6c0e95928336a3561f0f36d0 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Mon, 29 Nov 2021 18:43:48 +0800 Subject: [PATCH 05/37] commit code --- .../spring/BasePluginSpringApplication.java | 1 + .../starblues/spring/DefaultSpringPlugin.java | 2 +- .../DefaultSpringPluginRegistryInfo.java | 39 ++++++++++++++++++ .../spring/SpringPluginRegistryInfo.java | 21 ++-------- .../process/AfterRefreshProcessorFactory.java | 9 ++++- .../BeforeRefreshProcessorFactory.java | 3 +- .../ControllerAfterRefreshProcessor.java | 40 +++++++++++++++++++ .../starblues/utils/SpringBeanUtils.java | 2 +- .../main/resources/META-INF/spring.factories | 1 + 9 files changed, 97 insertions(+), 21 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java index e9b64c2..1ef7917 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java @@ -93,6 +93,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } protected void loadBean() { + applicationContext.scan("com.gitee.starblues.example.basic"); beanDefinitionLoader.load(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java index d1f923e..683ef58 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java @@ -58,7 +58,7 @@ public class DefaultSpringPlugin implements SpringPlugin { protected SpringPluginRegistryInfo createRegistryInfo(PluginWrapper pluginWrapper){ PluginSpringApplication springApplication = createSpringApplication(pluginWrapper); - return new SpringPluginRegistryInfo( + return new DefaultSpringPluginRegistryInfo( pluginWrapper, springApplication, mainApplicationContext ); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java new file mode 100644 index 0000000..0974235 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java @@ -0,0 +1,39 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.core.loader.PluginWrapper; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultSpringPluginRegistryInfo implements SpringPluginRegistryInfo{ + + private final PluginWrapper pluginWrapper; + private final PluginSpringApplication pluginSpringApplication; + private final GenericApplicationContext mainApplicationContext; + + public DefaultSpringPluginRegistryInfo(PluginWrapper pluginWrapper, + PluginSpringApplication springApplication, + GenericApplicationContext mainApplicationContext) { + this.pluginWrapper = pluginWrapper; + this.pluginSpringApplication = springApplication; + this.mainApplicationContext = mainApplicationContext; + } + + @Override + public PluginWrapper getPluginWrapper() { + return pluginWrapper; + } + + @Override + public PluginSpringApplication getPluginSpringApplication() { + return pluginSpringApplication; + } + + @Override + public GenericApplicationContext getMainApplicationContext() { + return mainApplicationContext; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java index 8262400..d6d88f5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java @@ -7,24 +7,11 @@ import org.springframework.context.support.GenericApplicationContext; * @author starBlues * @version 3.0.0 */ -public class SpringPluginRegistryInfo { +public interface SpringPluginRegistryInfo { - private final PluginWrapper pluginWrapper; - private final PluginSpringApplication pluginSpringApplication; - private final GenericApplicationContext mainApplicationContext; + PluginWrapper getPluginWrapper(); - public SpringPluginRegistryInfo(PluginWrapper pluginWrapper, PluginSpringApplication springApplication, - GenericApplicationContext mainApplicationContext) { - this.pluginWrapper = pluginWrapper; - this.pluginSpringApplication = springApplication; - this.mainApplicationContext = mainApplicationContext; - } + PluginSpringApplication getPluginSpringApplication(); - public PluginWrapper getPluginWrapper() { - return pluginWrapper; - } - - public PluginSpringApplication getPluginSpringApplication() { - return pluginSpringApplication; - } + GenericApplicationContext getMainApplicationContext(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java index 4aa0d23..d965061 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java @@ -1,6 +1,7 @@ package com.gitee.starblues.spring.process; import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.process.after.ControllerAfterRefreshProcessor; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.OrderPriority; import com.gitee.starblues.utils.SpringBeanUtils; @@ -21,11 +22,17 @@ public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ private final List afterRefreshProcessors; public AfterRefreshProcessorFactory(GenericApplicationContext mainApplicationContext) { - List afterRefreshProcessors = SpringBeanUtils.getBeans(mainApplicationContext, AfterRefreshProcessor.class); + List afterRefreshProcessors = SpringBeanUtils.getBeans( + mainApplicationContext, AfterRefreshProcessor.class); + addDefault(afterRefreshProcessors); afterRefreshProcessors.sort(CommonUtils.orderPriority(AfterRefreshProcessor::order)); this.afterRefreshProcessors = afterRefreshProcessors; } + protected void addDefault(List afterRefreshProcessors){ + afterRefreshProcessors.add(new ControllerAfterRefreshProcessor()); + } + @Override public void registry(SpringPluginRegistryInfo registryInfo) { for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java index cf26610..daeb3c3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java @@ -21,7 +21,8 @@ public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { private final List processors; public BeforeRefreshProcessorFactory(GenericApplicationContext mainApplicationContext) { - List processors = SpringBeanUtils.getBeans(mainApplicationContext, BeforeRefreshProcessor.class); + List processors = SpringBeanUtils.getBeans( + mainApplicationContext, BeforeRefreshProcessor.class); processors.sort(CommonUtils.orderPriority(BeforeRefreshProcessor::order)); this.processors = processors; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java new file mode 100644 index 0000000..ab1aff8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java @@ -0,0 +1,40 @@ +package com.gitee.starblues.spring.process.after; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.process.AfterRefreshProcessor; +import com.gitee.starblues.utils.OrderPriority; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.stereotype.Controller; + +import java.util.Map; + +/** + * @author starBlues + * @version 1.0 + */ +public class ControllerAfterRefreshProcessor implements AfterRefreshProcessor { + + @Override + public void registry(SpringPluginRegistryInfo registryInfo) { + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); + for (String beanDefinitionName : beanDefinitionNames) { + System.out.println(beanDefinitionName); + } + + + Map beansWithAnnotation = registryInfo.getPluginSpringApplication().getApplicationContext() + .getBeansWithAnnotation(Controller.class); + System.out.println(beansWithAnnotation); + } + + @Override + public void unRegistry(SpringPluginRegistryInfo registryInfo) { + + } + + @Override + public OrderPriority order() { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java index 33d4fb5..fe68758 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java @@ -22,7 +22,7 @@ public class SpringBeanUtils { public static List getBeans(ApplicationContext applicationContext, Class aClass) { Map beansOfTypeMap = applicationContext.getBeansOfType(aClass); if(beansOfTypeMap.isEmpty()){ - return Collections.emptyList(); + return new ArrayList<>(); } return new ArrayList<>(beansOfTypeMap.values()); } diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories index f2fb06d..814d4e5 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories @@ -1,3 +1,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.gitee.starblues.spring.EmptyAutoConfiguration,\ + org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ com.gitee.starblues.integration.SpringBootPluginStarter \ No newline at end of file -- Gitee From 23832355596c4679b5e167d63ca6ad7a9d78b16a Mon Sep 17 00:00:00 2001 From: StarBlues Date: Mon, 29 Nov 2021 18:49:35 +0800 Subject: [PATCH 06/37] commit code --- .../core/classloader/AbstractPluginClassLoader.java | 8 ++++++-- .../core/classloader/AbstractResourceLoader.java | 6 ++++++ .../starblues/core/classloader/PluginClassLoader.java | 10 ++++++++++ .../core/classloader/ResourceLoaderFactory.java | 8 ++++++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java index cbc235d..ab14170 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java @@ -1,11 +1,15 @@ package com.gitee.starblues.core.classloader; -import java.security.SecureClassLoader; +import java.net.URL; +import java.net.URLClassLoader; /** * 插件 ClassLoader * @author starBlues * @version 3.0.0 */ -public abstract class AbstractPluginClassLoader extends SecureClassLoader { +public abstract class AbstractPluginClassLoader extends URLClassLoader { + public AbstractPluginClassLoader() { + super(new URL[]{}, null); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index 410fdeb..b4873a6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -2,6 +2,8 @@ package com.gitee.starblues.core.classloader; import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -47,6 +49,10 @@ public abstract class AbstractResourceLoader { } } + public List getResources(){ + return new ArrayList<>(resourceCache.values()); + } + public void clear() { for (Resource resource : resourceCache.values()) { resource.tryCloseUrlSystemFile(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index 2b93ca9..c485c49 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -74,6 +74,16 @@ public class PluginClassLoader extends AbstractPluginClassLoader { } } + @Override + public URL[] getURLs() { + List resources = resourceLoaderFactory.getResources(); + URL[] urls = new URL[resources.size()]; + for (int i = 0; i < resources.size(); i++) { + urls[i] = resources.get(i).getUrl(); + } + return urls; + } + private Class findPluginClass(String name) { synchronized (pluginClassCache){ Class aClass = null; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java index 491458c..2d3a1fa 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java @@ -54,6 +54,14 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { } } + @Override + public List getResources() { + List resources = new ArrayList<>(); + for (AbstractResourceLoader resourceLoader : resourceLoaders) { + resources.addAll(resourceLoader.getResources()); + } + return resources; + } @Override public synchronized Resource findResource(String name) { -- Gitee From 9b789939df93a2183c6871c78b292bf2898e5851 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Tue, 30 Nov 2021 16:55:27 +0800 Subject: [PATCH 07/37] commit code --- springboot-plugin-framework/pom.xml | 12 -- .../classloader/AbstractResourceLoader.java | 17 ++- .../core/classloader/ClassPathLoader.java | 55 ++++---- .../DefaultMainResourceDefiner.java | 4 + .../core/classloader/JarResourceLoader.java | 3 +- .../core/classloader/PluginClassLoader.java | 35 ++++- .../classloader/ResourceLoaderFactory.java | 4 + .../descriptor/EmptyPluginDescriptor.java | 65 +++++++++ .../process/pipe/PluginInfoContainers.java | 13 +- .../pipe/bean/inset/PluginUtilsInset.java | 2 +- .../AutoIntegrationConfiguration.java | 3 + .../integration/SpringBootPluginStarter.java | 4 +- .../operator/PluginOperatorWrapper.java | 3 +- .../integration/user/DefaultPluginUser.java | 25 ++-- .../gitee/starblues/realize/PluginUtils.java | 31 +++-- .../spring/BasePluginSpringApplication.java | 16 ++- .../starblues/spring/DefaultSpringPlugin.java | 1 + .../DefaultSpringPluginRegistryInfo.java | 7 +- .../spring/PluginListableBeanFactory.java | 40 ++++++ .../spring/PluginSpringApplication.java | 9 +- .../spring/SpringPluginRegistryInfo.java | 3 +- .../OneselfPluginSpringApplication.java | 45 ++++++ .../oneself/OneselfSpringApplication.java | 131 ++++++++++++++++++ .../process/AfterRefreshProcessorFactory.java | 3 +- .../BeforeRefreshProcessorFactory.java | 20 ++- .../ControllerAfterRefreshProcessor.java | 9 +- .../process/before/RegisterNecessaryBean.java | 37 +++++ .../gitee/starblues/utils/ResourceUtils.java | 2 + 28 files changed, 505 insertions(+), 94 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index 52efcb3..29f32a6 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -90,18 +90,6 @@ - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-yaml - ${jackson.version} - - org.slf4j slf4j-api diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index b4873a6..bca2d1a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -1,7 +1,12 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ResourceUtils; + import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -14,9 +19,13 @@ import java.util.concurrent.ConcurrentHashMap; */ public abstract class AbstractResourceLoader { - + protected final URL baseUrl; private final Map resourceCache = new ConcurrentHashMap<>(); + protected AbstractResourceLoader(URL baseUrl) { + this.baseUrl = baseUrl; + } + protected void addResource(String name, Resource resource) { if(resourceCache.containsKey(name)){ return; @@ -37,7 +46,11 @@ public abstract class AbstractResourceLoader { } public Resource findResource(final String name) { - return resourceCache.get(name); + String queryName = name; + if(name.endsWith(ResourceUtils.PACKAGE_SPLIT)){ + queryName = name.substring(0, name.lastIndexOf(ResourceUtils.PACKAGE_SPLIT)); + } + return resourceCache.get(queryName); } public InputStream getInputStream(final String name) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java index 49ce206..37fab91 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -2,10 +2,14 @@ package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ResourceUtils; import java.io.File; import java.io.FileInputStream; +import java.net.MalformedURLException; import java.net.URL; +import java.nio.file.Paths; +import java.util.Set; /** * classpath 资源加载者 @@ -17,20 +21,27 @@ public class ClassPathLoader extends AbstractResourceLoader{ private final URL url; public ClassPathLoader(URL url) { + super(url); this.url = Assert.isNotNull(url, "url 不能为空"); } @Override public void init() throws Exception { File file = new File(url.toURI()); - load(file, ""); + load(file, null); } - private void load(File file, String packageName) throws Exception { - if(file.isFile()){ - // 文件 - loadResource(file, packageName); - return; + private void load(File file, String currentPackageName) throws Exception { + if(currentPackageName == null){ + // 根目录 + currentPackageName = ""; + } else { + if("".equals(currentPackageName)){ + currentPackageName = file.getName(); + } else { + currentPackageName = currentPackageName + ResourceUtils.PACKAGE_SPLIT + file.getName(); + } + loadResource(file, currentPackageName); } if(file.isDirectory()){ File[] listFiles = file.listFiles(); @@ -38,36 +49,30 @@ public class ClassPathLoader extends AbstractResourceLoader{ return; } for (File subFile : listFiles) { - String currentPackage = packageName; - if (subFile.isDirectory()) { - if (!ObjectUtils.isEmpty(currentPackage)) { - currentPackage = currentPackage + "/"; - } - currentPackage = currentPackage + subFile.getName(); - } - load(subFile, currentPackage); + load(subFile, currentPackageName); } } } private void loadResource(File file, String packageName) throws Exception{ + if(file.isDirectory()){ + addResource(file, packageName, null); + return; + } try (FileInputStream fileInputStream = new FileInputStream(file)) { byte[] bytes = new byte[(int) file.length()]; if (fileInputStream.read(bytes) != -1) { - String name; - String fileName = file.getName(); - if(!ObjectUtils.isEmpty(packageName)){ - name = packageName + "/" + fileName; - } else { - name = fileName; - } - Resource resource = new Resource( - name, url, new URL(url.toString() + name), bytes - ); - addResource(name, resource); + addResource(file, packageName, bytes); } } + } + private void addResource(File file, String packageName, byte[] bytes) throws MalformedURLException { + Resource resource = new Resource( + file.getName(), url, new URL(url.toString() + packageName), bytes + ); + addResource(packageName, resource); } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java index 99588f4..64a3951 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java @@ -83,6 +83,9 @@ public class DefaultMainResourceDefiner implements MainResourceDefiner{ mainClass.add("org.apache.commons.logging"); // snakeyaml mainClass.add("org.yaml.snakeyaml"); + + // aop + mainClass.add("org.aspectj"); } private void initDefaultResources(String mainPackageName) { @@ -91,6 +94,7 @@ public class DefaultMainResourceDefiner implements MainResourceDefiner{ mainResources.add("org/springframework"); mainResources.add("org/slf4j/Logger"); mainResources.add("org/aopalliance"); + mainResources.add("org/aspectj"); mainResources.add(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index 2a1e12a..7cc5e59 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -17,11 +17,10 @@ import java.util.jar.JarInputStream; public class JarResourceLoader extends AbstractResourceLoader{ private final URL sourceUrl; - private final URL baseUrl; public JarResourceLoader(URL url) throws Exception{ + super(new URL("jar:" + url.toString() + "!/")); this.sourceUrl = Assert.isNotNull(url, "url 不能为空"); - this.baseUrl = new URL("jar:" + url.toString() + "!/"); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index c485c49..bc0c6ea 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -1,6 +1,7 @@ package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ResourceUtils; import java.io.File; import java.io.IOException; @@ -116,15 +117,25 @@ public class PluginClassLoader extends AbstractPluginClassLoader { @Override public InputStream getResourceAsStream(String name) { + name = formatResourceName(name); Set resources = mainResourceDefiner.getResources(); + InputStream inputStream = null; if(exist(resources, name)){ - return parent.getResourceAsStream(name); + try { + inputStream = parent.getResourceAsStream(name); + } catch (Exception e){ + // 忽略 + } + } + if(inputStream != null){ + return inputStream; } return resourceLoaderFactory.getInputStream(name); } @Override public URL getResource(String name) { + name = formatResourceName(name); Set resources = mainResourceDefiner.getResources(); if(exist(resources, name)){ return parent.getResource(name); @@ -138,6 +149,7 @@ public class PluginClassLoader extends AbstractPluginClassLoader { @Override public Enumeration getResources(String name) throws IOException { + name = formatResourceName(name); Vector vector = new Vector<>(); Set resources = mainResourceDefiner.getResources(); Set springFactories = mainResourceDefiner.getSpringFactories(); @@ -167,7 +179,28 @@ public class PluginClassLoader extends AbstractPluginClassLoader { return className; } + private String formatResourceName(String resourceName){ + if(ObjectUtils.isEmpty(resourceName)) { + return resourceName; + } + String[] split = resourceName.split("/"); + StringBuilder newPath = new StringBuilder(); + for (int i = 0; i < split.length; i++) { + String s = split[i]; + if("".equals(s)){ + continue; + } + if(i == 0){ + newPath = new StringBuilder(s); + } else { + newPath.append(ResourceUtils.PACKAGE_SPLIT).append(s); + } + } + return newPath.toString(); + } + private boolean exist(Set set, String name){ + // TODO 匹配方式有问题 if(ObjectUtils.isEmpty(set) || ObjectUtils.isEmpty(name)){ return false; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java index 2d3a1fa..75db411 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java @@ -18,6 +18,10 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { private final List resourceLoaders = new ArrayList<>(); + public ResourceLoaderFactory() { + super(null); + } + public void addResource(String path) { if(path == null || "".equals(path)){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java new file mode 100644 index 0000000..7513cea --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java @@ -0,0 +1,65 @@ +package com.gitee.starblues.core.descriptor; + +import java.nio.file.Path; +import java.util.List; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class EmptyPluginDescriptor implements PluginDescriptor{ + @Override + public String getPluginId() { + return null; + } + + @Override + public String getPluginVersion() { + return null; + } + + @Override + public String getPluginClass() { + return null; + } + + @Override + public Path getPluginPath() { + return null; + } + + @Override + public String getPluginLibDir() { + return null; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String getRequires() { + return null; + } + + @Override + public String getProvider() { + return null; + } + + @Override + public String getLicense() { + return null; + } + + @Override + public String getConfigFileName() { + return null; + } + + @Override + public List getPluginDependency() { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java index 4c3d2b9..4d1a53c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java @@ -1,5 +1,6 @@ package com.gitee.starblues.factory.process.pipe; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import java.util.*; @@ -12,10 +13,10 @@ import java.util.concurrent.ConcurrentHashMap; */ public class PluginInfoContainers { - private final static Map PLUGIN_APPLICATION_CONTEXTS = + private final static Map PLUGIN_APPLICATION_CONTEXTS = new ConcurrentHashMap<>(); - public static void addPluginApplicationContext(String pluginId, GenericApplicationContext applicationContext){ + public static void addPluginApplicationContext(String pluginId, ConfigurableApplicationContext applicationContext){ PLUGIN_APPLICATION_CONTEXTS.put(pluginId, applicationContext); } @@ -23,16 +24,16 @@ public class PluginInfoContainers { PLUGIN_APPLICATION_CONTEXTS.remove(pluginId); } - static public GenericApplicationContext getPluginApplicationContext(String pluginId) { - GenericApplicationContext applicationContext = PLUGIN_APPLICATION_CONTEXTS.get(pluginId); + static public ConfigurableApplicationContext getPluginApplicationContext(String pluginId) { + ConfigurableApplicationContext applicationContext = PLUGIN_APPLICATION_CONTEXTS.get(pluginId); if(applicationContext == null){ return null; } return applicationContext; } - static public List getPluginApplicationContexts() { - Collection values = PLUGIN_APPLICATION_CONTEXTS.values(); + static public List getPluginApplicationContexts() { + Collection values = PLUGIN_APPLICATION_CONTEXTS.values(); if(values.isEmpty()){ return new ArrayList<>(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java index 5d720d9..cec7e98 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java @@ -21,6 +21,6 @@ public class PluginUtilsInset implements PluginInsetBean{ GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); return new PluginUtils(parentApplicationContext, pluginApplicationContext, - pluginRegistryInfo.getPluginWrapper().getDescriptor()); + null); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index 9dfe954..4ffd75e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -18,6 +18,9 @@ import java.util.Set; @ConfigurationProperties(prefix = "plugin") public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguration{ + public static final String ENABLE_KEY = "plugin.enable"; + + /** * 运行模式 * 开发环境: development、dev diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java index e4c5265..8f85197 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java @@ -4,6 +4,7 @@ import com.gitee.starblues.core.RealizeProvider; import com.gitee.starblues.integration.application.AutoPluginApplication; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.PluginUser; +import com.gitee.starblues.realize.PluginUtils; import com.gitee.starblues.spring.SpringPlugin; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -19,7 +20,7 @@ import org.springframework.context.support.GenericApplicationContext; */ @Configuration(proxyBeanMethods = true) @EnableConfigurationProperties(AutoIntegrationConfiguration.class) -@ConditionalOnProperty(value = "plugin.enable", havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(value = AutoIntegrationConfiguration.ENABLE_KEY, havingValue = "true", matchIfMissing = false) public class SpringBootPluginStarter extends AutoPluginApplication { @@ -50,4 +51,5 @@ public class SpringBootPluginStarter extends AutoPluginApplication { protected RealizeProvider createRealizeProvider(IntegrationConfiguration configuration) { return super.createRealizeProvider(configuration); } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 37ac2b7..1c940d9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -10,6 +10,7 @@ import com.gitee.starblues.utils.SpringBeanUtils; import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.multipart.MultipartFile; @@ -206,7 +207,7 @@ public class PluginOperatorWrapper implements PluginOperator{ * @throws Exception 检查异常 */ private void checkIsUnRegistry(String pluginId) throws Exception{ - GenericApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); + ConfigurableApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); if(pluginApplicationContext == null){ log.error("Plugin '{}' Not found ApplicationContext. So cannot found and execute unRegistryValidator", pluginId); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java index 6e6519f..f4d9e4c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java @@ -6,6 +6,7 @@ import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.util.ObjectUtils; @@ -78,7 +79,7 @@ public class DefaultPluginUser implements PluginUser{ @Override public List getPluginBeans(String pluginId, Class aClass) { - GenericApplicationContext pluginApplicationContext = + ConfigurableApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); if(pluginApplicationContext == null){ return Collections.emptyList(); @@ -88,9 +89,9 @@ public class DefaultPluginUser implements PluginUser{ @Override public List getPluginBeansWithAnnotation(Class annotationType) { - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); + List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); List beans = new ArrayList<>(); - for (GenericApplicationContext pluginApplicationContext : pluginApplicationContexts) { + for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { Map beanMap = pluginApplicationContext.getBeansWithAnnotation(annotationType); if(!ObjectUtils.isEmpty(beanMap)){ beans.addAll(beanMap.values()); @@ -101,7 +102,7 @@ public class DefaultPluginUser implements PluginUser{ @Override public List getPluginBeansWithAnnotation(String pluginId, Class annotationType) { - GenericApplicationContext genericApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); + ConfigurableApplicationContext genericApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); if(genericApplicationContext == null){ return Collections.emptyList(); } @@ -118,10 +119,10 @@ public class DefaultPluginUser implements PluginUser{ if(object == null){ return null; } - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); + List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); pluginApplicationContexts.add(parentApplicationContext); Class aClass = object.getClass(); - for (GenericApplicationContext pluginApplicationContext : pluginApplicationContexts) { + for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { try { // 判断是否存在 pluginApplicationContext.getBean(aClass); @@ -137,11 +138,11 @@ public class DefaultPluginUser implements PluginUser{ private T getBean(String name, boolean haveParent){ - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); + List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); if(haveParent){ pluginApplicationContexts.add(parentApplicationContext); } - for (GenericApplicationContext pluginApplicationContext : pluginApplicationContexts) { + for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { if(pluginApplicationContext.containsBean(name)){ return (T) pluginApplicationContext.getBean(name); } @@ -150,11 +151,11 @@ public class DefaultPluginUser implements PluginUser{ } private T getBean(Class aClass, boolean haveParent) { - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); + List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); if(haveParent){ pluginApplicationContexts.add(parentApplicationContext); } - for (GenericApplicationContext pluginApplicationContext : pluginApplicationContexts) { + for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { try { T bean = pluginApplicationContext.getBean(aClass); if(bean != null){ @@ -175,7 +176,7 @@ public class DefaultPluginUser implements PluginUser{ * @return List */ private List getBeans(Class aClass, int type) { - List pluginApplicationContexts = new ArrayList<>(1); + List pluginApplicationContexts = new ArrayList<>(1); if(type == 1){ pluginApplicationContexts.add(parentApplicationContext); @@ -189,7 +190,7 @@ public class DefaultPluginUser implements PluginUser{ } List result = new ArrayList<>(); - for (GenericApplicationContext pluginApplicationContext : pluginApplicationContexts) { + for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { List pluginBeans = SpringBeanUtils.getBeans(pluginApplicationContext, aClass); if(!pluginBeans.isEmpty()){ result.addAll(pluginBeans); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java index d750e2a..c7df513 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java @@ -1,9 +1,10 @@ package com.gitee.starblues.realize; +import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.SpringBeanUtils; -import org.pf4j.PluginDescriptor; import org.springframework.context.ApplicationContext; +import javax.annotation.Resource; import java.util.List; /** @@ -13,30 +14,39 @@ import java.util.List; */ public class PluginUtils { - protected final ApplicationContext parentApplicationContext; - protected final ApplicationContext pluginApplicationContext; - protected final PluginDescriptor pluginDescriptor; + protected final ApplicationContext mainApplicationContext; + protected ApplicationContext pluginApplicationContext; + protected PluginDescriptor pluginDescriptor; - public PluginUtils(ApplicationContext parentApplicationContext, + @Deprecated + public PluginUtils(ApplicationContext mainApplicationContext, ApplicationContext pluginApplicationContext, PluginDescriptor pluginDescriptor) { - this.parentApplicationContext = parentApplicationContext; + this.mainApplicationContext = mainApplicationContext; this.pluginApplicationContext = pluginApplicationContext; this.pluginDescriptor = pluginDescriptor; } + public PluginUtils(ApplicationContext mainApplicationContext) { + this.mainApplicationContext = mainApplicationContext; + this.pluginApplicationContext = null; + this.pluginDescriptor = null; + } + + /** * 获取主程序的 ApplicationContext * @return ApplicationContext */ public ApplicationContext getMainApplicationContext() { - return parentApplicationContext; + return mainApplicationContext; } /** * 获取当前插件的 ApplicationContext * @return ApplicationContext */ + @Deprecated public ApplicationContext getPluginApplicationContext() { return pluginApplicationContext; } @@ -45,6 +55,7 @@ public class PluginUtils { * 获取当前插件的描述信息 * @return PluginDescriptor */ + @Deprecated public PluginDescriptor getPluginDescriptor(){ return pluginDescriptor; } @@ -57,7 +68,7 @@ public class PluginUtils { * @return bean */ public T getMainBean(String name){ - Object bean = parentApplicationContext.getBean(name); + Object bean = mainApplicationContext.getBean(name); if(bean == null){ return null; } @@ -71,7 +82,7 @@ public class PluginUtils { * @return bean */ public T getMainBean(Class aClass) { - return parentApplicationContext.getBean(aClass); + return mainApplicationContext.getBean(aClass); } /** @@ -81,7 +92,7 @@ public class PluginUtils { * @return bean */ public List getMainBeans(Class aClass){ - return SpringBeanUtils.getBeans(parentApplicationContext, aClass); + return SpringBeanUtils.getBeans(mainApplicationContext, aClass); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java index 1ef7917..0e86d2e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java @@ -6,6 +6,7 @@ import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.Ordered; @@ -22,6 +23,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ private final AtomicBoolean isStarted = new AtomicBoolean(false); + private final DefaultListableBeanFactory beanFactory; private final PluginApplicationContext applicationContext; private final PluginBeanDefinitionLoader beanDefinitionLoader; @@ -29,18 +31,20 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ private final List environmentProcessors; - public BasePluginSpringApplication(ClassLoader classLoader, + public BasePluginSpringApplication(GenericApplicationContext mainApplicationContext, + ClassLoader classLoader, Class primarySources){ - this(classLoader, primarySources, null); + this(mainApplicationContext, classLoader, primarySources, null); } - public BasePluginSpringApplication(ClassLoader classLoader, + public BasePluginSpringApplication(GenericApplicationContext mainApplicationContext, + ClassLoader classLoader, Class primarySources, String configFileName){ Assert.isNotNull(classLoader, "classLoader 不能为空"); Assert.isNotNull(primarySources, "primarySources 不能为空"); - this.beanFactory = new DefaultListableBeanFactory(); + this.beanFactory = new PluginListableBeanFactory(mainApplicationContext); this.beanFactory.setBeanClassLoader(classLoader); this.applicationContext = new PluginApplicationContext(beanFactory, classLoader); @@ -68,7 +72,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ @Override - public GenericApplicationContext run() { + public ConfigurableApplicationContext run() { synchronized (isStarted){ if(isStarted.get()){ throw new RuntimeException("已经运行了PluginSpringApplication, 无法再运行"); @@ -113,7 +117,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } @Override - public GenericApplicationContext getApplicationContext() { + public ConfigurableApplicationContext getApplicationContext() { return applicationContext; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java index 683ef58..bfcabdb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java @@ -65,6 +65,7 @@ public class DefaultSpringPlugin implements SpringPlugin { protected PluginSpringApplication createSpringApplication(PluginWrapper pluginWrapper){ return new BasePluginSpringApplication( + mainApplicationContext, pluginWrapper.getPluginClassLoader(), pluginWrapper.getPluginClass(), pluginWrapper.getPluginDescriptor().getConfigFileName() ); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java index 0974235..fa8ae37 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java @@ -1,6 +1,7 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; /** @@ -11,11 +12,11 @@ public class DefaultSpringPluginRegistryInfo implements SpringPluginRegistryInfo private final PluginWrapper pluginWrapper; private final PluginSpringApplication pluginSpringApplication; - private final GenericApplicationContext mainApplicationContext; + private final ConfigurableApplicationContext mainApplicationContext; public DefaultSpringPluginRegistryInfo(PluginWrapper pluginWrapper, PluginSpringApplication springApplication, - GenericApplicationContext mainApplicationContext) { + ConfigurableApplicationContext mainApplicationContext) { this.pluginWrapper = pluginWrapper; this.pluginSpringApplication = springApplication; this.mainApplicationContext = mainApplicationContext; @@ -32,7 +33,7 @@ public class DefaultSpringPluginRegistryInfo implements SpringPluginRegistryInfo } @Override - public GenericApplicationContext getMainApplicationContext() { + public ConfigurableApplicationContext getMainApplicationContext() { return mainApplicationContext; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java new file mode 100644 index 0000000..7e26191 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java @@ -0,0 +1,40 @@ +package com.gitee.starblues.spring; + +import org.springframework.beans.BeansException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.lang.Nullable; + +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginListableBeanFactory extends DefaultListableBeanFactory { + + private final DefaultListableBeanFactory mainDefaultListableBeanFactory; + + + public PluginListableBeanFactory(GenericApplicationContext applicationContext) { + this.mainDefaultListableBeanFactory = applicationContext.getDefaultListableBeanFactory(); + } + + + @Override + public Object resolveDependency(DependencyDescriptor descriptor, + @Nullable String requestingBeanName, + @Nullable Set autowiredBeanNames, + @Nullable TypeConverter typeConverter) throws BeansException{ + + try { + return super.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); + } catch (Exception e){ + return mainDefaultListableBeanFactory.resolveDependency(descriptor, + requestingBeanName, autowiredBeanNames, typeConverter); + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java index 49e6ec8..5b19c38 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java @@ -1,6 +1,6 @@ package com.gitee.starblues.spring; -import org.springframework.context.support.GenericApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; /** * 插件 SpringApplication @@ -9,12 +9,11 @@ import org.springframework.context.support.GenericApplicationContext; */ public interface PluginSpringApplication { - /** * 运行 - * @return GenericApplicationContext + * @return ConfigurableApplicationContext */ - GenericApplicationContext run(); + ConfigurableApplicationContext run(); /** * 关闭 @@ -26,7 +25,7 @@ public interface PluginSpringApplication { * 得到 ApplicationContext * @return GenericApplicationContext */ - GenericApplicationContext getApplicationContext(); + ConfigurableApplicationContext getApplicationContext(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java index d6d88f5..1cbe845 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java @@ -1,6 +1,7 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; /** @@ -13,5 +14,5 @@ public interface SpringPluginRegistryInfo { PluginSpringApplication getPluginSpringApplication(); - GenericApplicationContext getMainApplicationContext(); + ConfigurableApplicationContext getMainApplicationContext(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java new file mode 100644 index 0000000..c336253 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java @@ -0,0 +1,45 @@ +package com.gitee.starblues.spring.oneself; + +import com.gitee.starblues.spring.PluginSpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class OneselfPluginSpringApplication implements PluginSpringApplication { + + private final OneselfSpringApplication oneselfSpringApplication; + + private ConfigurableApplicationContext applicationContext; + + public OneselfPluginSpringApplication(Class ...primarySources) { + this.oneselfSpringApplication = new OneselfSpringApplication(this, primarySources); + } + + /** + * 插件自主调用 + * @param primarySources primarySources + * @return ConfigurableApplicationContext + */ + public static ConfigurableApplicationContext run(Class ...primarySources){ + return new OneselfPluginSpringApplication(primarySources).run(); + } + + + @Override + public ConfigurableApplicationContext run() { + applicationContext = oneselfSpringApplication.run(); + return this.applicationContext; + } + + @Override + public void close() { + applicationContext.close(); + } + + @Override + public ConfigurableApplicationContext getApplicationContext() { + return applicationContext; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java new file mode 100644 index 0000000..617823d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -0,0 +1,131 @@ +package com.gitee.starblues.spring.oneself; + +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.descriptor.*; +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.spring.DefaultSpringPluginRegistryInfo; +import com.gitee.starblues.spring.PluginSpringApplication; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.process.BeforeRefreshProcessorFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.ResourceLoader; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +/** + * @author starBlues + * @version 1.0 + */ +public class OneselfSpringApplication extends SpringApplication { + + private final Class primarySource; + private final PluginSpringApplication springApplication; + + public OneselfSpringApplication(PluginSpringApplication springApplication, Class... primarySources) { + this(springApplication, null, primarySources); + } + + public OneselfSpringApplication(PluginSpringApplication springApplication, + ResourceLoader resourceLoader, Class... primarySources) { + super(resourceLoader, primarySources); + this.springApplication = springApplication; + if(primarySources.length > 0){ + primarySource = primarySources[0]; + } else { + primarySource = null; + } + } + + @Override + protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { + Map environmentMap = new HashMap<>(); + environmentMap.put(AutoIntegrationConfiguration.ENABLE_KEY, false); + MapPropertySource mapPropertySource = new MapPropertySource("plugin-environment", environmentMap); + environment.getPropertySources().addLast(mapPropertySource); + } + + @Override + protected void refresh(ConfigurableApplicationContext applicationContext) { + // 刷新之前 + BeforeRefreshProcessorFactory beforeRefreshProcessorFactory = + new BeforeRefreshProcessorFactory(null); + SpringPluginRegistryInfo springPluginRegistryInfo = create(applicationContext); + beforeRefreshProcessorFactory.registry(springPluginRegistryInfo); + super.refresh(applicationContext); + } + + private SpringPluginRegistryInfo create(ConfigurableApplicationContext applicationContext){ + return new DefaultSpringPluginRegistryInfo(tryGetPluginWrapper(), new PluginSpringApplication() { + @Override + public ConfigurableApplicationContext run() { + return springApplication.run(); + } + + @Override + public void close() { + springApplication.close(); + } + + @Override + public ConfigurableApplicationContext getApplicationContext() { + return applicationContext; + } + }, applicationContext); + } + + private PluginWrapper tryGetPluginWrapper(){ + try { + PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); + PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(Paths.get(this.getClass().getResource("/").toURI())); + if(pluginDescriptor == null){ + return getPluginWrapper(new EmptyPluginDescriptor()); + } else { + return getPluginWrapper(pluginDescriptor); + } + } catch (Exception e){ + return getPluginWrapper(new EmptyPluginDescriptor()); + } + } + + private PluginWrapper getPluginWrapper(PluginDescriptor pluginDescriptor){ + return new PluginWrapper() { + @Override + public String getPluginId() { + return pluginDescriptor.getPluginId(); + } + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginDescriptor; + } + + @Override + public ClassLoader getPluginClassLoader() { + return this.getClass().getClassLoader(); + } + + @Override + public Class getPluginClass() { + return primarySource; + } + + @Override + public Path getPluginPath() { + return pluginDescriptor.getPluginPath(); + } + + @Override + public PluginState getPluginState() { + return PluginState.STARTED; + } + }; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java index d965061..20160c7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java @@ -7,6 +7,7 @@ import com.gitee.starblues.utils.OrderPriority; import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import java.util.List; @@ -21,7 +22,7 @@ public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ private final List afterRefreshProcessors; - public AfterRefreshProcessorFactory(GenericApplicationContext mainApplicationContext) { + public AfterRefreshProcessorFactory(ConfigurableApplicationContext mainApplicationContext) { List afterRefreshProcessors = SpringBeanUtils.getBeans( mainApplicationContext, AfterRefreshProcessor.class); addDefault(afterRefreshProcessors); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java index daeb3c3..f55456d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java @@ -1,13 +1,17 @@ package com.gitee.starblues.spring.process; import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.process.before.RegisterNecessaryBean; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.OrderPriority; import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; +import java.util.ArrayList; import java.util.List; /** @@ -20,13 +24,23 @@ public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { private final List processors; - public BeforeRefreshProcessorFactory(GenericApplicationContext mainApplicationContext) { - List processors = SpringBeanUtils.getBeans( - mainApplicationContext, BeforeRefreshProcessor.class); + public BeforeRefreshProcessorFactory(ConfigurableApplicationContext mainApplicationContext) { + List processors = null; + if(mainApplicationContext != null){ + processors = SpringBeanUtils.getBeans( + mainApplicationContext, BeforeRefreshProcessor.class); + } else { + processors = new ArrayList<>(); + } + addDefault(processors); processors.sort(CommonUtils.orderPriority(BeforeRefreshProcessor::order)); this.processors = processors; } + private void addDefault(List processors) { + processors.add(new RegisterNecessaryBean()); + } + @Override public void registry(SpringPluginRegistryInfo registryInfo) { for (BeforeRefreshProcessor processor : processors) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java index ab1aff8..02467a6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java @@ -3,7 +3,7 @@ package com.gitee.starblues.spring.process.after; import com.gitee.starblues.spring.SpringPluginRegistryInfo; import com.gitee.starblues.spring.process.AfterRefreshProcessor; import com.gitee.starblues.utils.OrderPriority; -import org.springframework.context.support.GenericApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Controller; import java.util.Map; @@ -16,12 +16,17 @@ public class ControllerAfterRefreshProcessor implements AfterRefreshProcessor { @Override public void registry(SpringPluginRegistryInfo registryInfo) { - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { System.out.println(beanDefinitionName); } + String[] singletonNames = applicationContext.getBeanFactory().getSingletonNames(); + for (String singletonName : singletonNames) { + System.out.println(singletonName); + } + Map beansWithAnnotation = registryInfo.getPluginSpringApplication().getApplicationContext() .getBeansWithAnnotation(Controller.class); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java new file mode 100644 index 0000000..89a8b04 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java @@ -0,0 +1,37 @@ +package com.gitee.starblues.spring.process.before; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.realize.PluginUtils; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.process.BeforeRefreshProcessor; +import com.gitee.starblues.utils.OrderPriority; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class RegisterNecessaryBean implements BeforeRefreshProcessor { + + + @Override + public void registry(SpringPluginRegistryInfo registryInfo) { + + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + + PluginDescriptor pluginDescriptor = registryInfo.getPluginWrapper().getPluginDescriptor(); + applicationContext.getBeanFactory().registerSingleton("pluginDescriptor", + pluginDescriptor); + applicationContext.getBeanFactory().registerSingleton("pluginUtils", new PluginUtils(applicationContext)); + } + + @Override + public void unRegistry(SpringPluginRegistryInfo registryInfo) { + + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 11d204b..98ae68f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -33,6 +33,8 @@ public class ResourceUtils { public static final String CLASSPATH_URL_PREFIX = "classpath:"; public static final String FILE_URL_PREFIX = "file:"; + public static final String PACKAGE_SPLIT = "/"; + /** * 获取匹配路绝 * @param locationMatch 原始匹配路径。规则为: file:xxx, classpath:xxx , package:xxx -- Gitee From 789aa1d554a432e7cd18f124022afb52f8daf6f9 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Tue, 30 Nov 2021 19:02:28 +0800 Subject: [PATCH 08/37] commit code --- .../DefaultIntegrationConfiguration.java | 8 +++- .../oneself/OneselfSpringApplication.java | 45 ++++++++++++++++--- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index db69485..b802a68 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -14,6 +14,10 @@ import java.util.Set; */ public abstract class DefaultIntegrationConfiguration implements IntegrationConfiguration{ + public static final String DEFAULT_PLUGIN_REST_PATH_PREFIX = "plugins"; + public static final boolean DEFAULT_ENABLE_PLUGIN_ID_REST_PATH_PREFIX = true; + + @Override public List pluginPath() { List pluginPath = new ArrayList<>(1); @@ -42,12 +46,12 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf @Override public String pluginRestPathPrefix(){ - return "/plugins"; + return DEFAULT_PLUGIN_REST_PATH_PREFIX; } @Override public boolean enablePluginIdRestPathPrefix() { - return true; + return DEFAULT_ENABLE_PLUGIN_ID_REST_PATH_PREFIX; } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java index 617823d..b493423 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -4,10 +4,12 @@ import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.*; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.integration.DefaultIntegrationConfiguration; import com.gitee.starblues.spring.DefaultSpringPluginRegistryInfo; import com.gitee.starblues.spring.PluginSpringApplication; import com.gitee.starblues.spring.SpringPluginRegistryInfo; import com.gitee.starblues.spring.process.BeforeRefreshProcessorFactory; +import com.gitee.starblues.utils.ObjectUtils; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; @@ -25,9 +27,13 @@ import java.util.Map; */ public class OneselfSpringApplication extends SpringApplication { + public static final String ID = "OneselfPluginSpringApplication"; + private final Class primarySource; private final PluginSpringApplication springApplication; + private final PluginWrapper pluginWrapper; + public OneselfSpringApplication(PluginSpringApplication springApplication, Class... primarySources) { this(springApplication, null, primarySources); } @@ -41,14 +47,21 @@ public class OneselfSpringApplication extends SpringApplication { } else { primarySource = null; } + pluginWrapper = tryGetPluginWrapper(); } @Override protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { - Map environmentMap = new HashMap<>(); - environmentMap.put(AutoIntegrationConfiguration.ENABLE_KEY, false); - MapPropertySource mapPropertySource = new MapPropertySource("plugin-environment", environmentMap); - environment.getPropertySources().addLast(mapPropertySource); + super.configureProfiles(environment, args); + } + + @Override + protected void bindToSpringApplication(ConfigurableEnvironment environment) { + super.bindToSpringApplication(environment); + Map env = new HashMap<>(); + env.put(AutoIntegrationConfiguration.ENABLE_KEY, false); + env.put("server.servlet.context-path", getContextPath(environment)); + environment.getPropertySources().addFirst(new MapPropertySource("springPluginRegistryInfo", env)); } @Override @@ -62,7 +75,7 @@ public class OneselfSpringApplication extends SpringApplication { } private SpringPluginRegistryInfo create(ConfigurableApplicationContext applicationContext){ - return new DefaultSpringPluginRegistryInfo(tryGetPluginWrapper(), new PluginSpringApplication() { + return new DefaultSpringPluginRegistryInfo(pluginWrapper, new PluginSpringApplication() { @Override public ConfigurableApplicationContext run() { return springApplication.run(); @@ -83,7 +96,8 @@ public class OneselfSpringApplication extends SpringApplication { private PluginWrapper tryGetPluginWrapper(){ try { PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); - PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(Paths.get(this.getClass().getResource("/").toURI())); + PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load( + Paths.get(this.getClass().getResource("/").toURI())); if(pluginDescriptor == null){ return getPluginWrapper(new EmptyPluginDescriptor()); } else { @@ -128,4 +142,23 @@ public class OneselfSpringApplication extends SpringApplication { }; } + private String getContextPath(ConfigurableEnvironment environment){ + String pluginRestPathPrefix = environment.getProperty("plugin.pluginRestPathPrefix", String.class); + Boolean enablePluginIdRestPathPrefix = environment.getProperty("plugin.enablePluginIdRestPathPrefix", + Boolean.class); + String contextPath = ""; + if(ObjectUtils.isEmpty(pluginRestPathPrefix)){ + pluginRestPathPrefix = DefaultIntegrationConfiguration.DEFAULT_PLUGIN_REST_PATH_PREFIX; + } + if(enablePluginIdRestPathPrefix == null){ + enablePluginIdRestPathPrefix = DefaultIntegrationConfiguration.DEFAULT_ENABLE_PLUGIN_ID_REST_PATH_PREFIX; + } + String pluginId = pluginWrapper.getPluginId(); + contextPath = "/" + pluginRestPathPrefix; + if(enablePluginIdRestPathPrefix && !ObjectUtils.isEmpty(pluginId)){ + contextPath = contextPath + "/" + pluginId; + } + return contextPath; + } + } -- Gitee From 6c7bfabbbe9d0c6673190aa4b038a421383a056d Mon Sep 17 00:00:00 2001 From: StarBlues Date: Wed, 1 Dec 2021 16:50:59 +0800 Subject: [PATCH 09/37] add plugin controller register --- .../DefaultMainResourceDefiner.java | 1 + .../post/bean/model/ControllerWrapper.java | 15 +- .../AutoIntegrationConfiguration.java | 65 +++-- .../DefaultIntegrationConfiguration.java | 14 +- .../integration/IntegrationConfiguration.java | 19 +- .../spring/BasePluginSpringApplication.java | 1 - .../starblues/spring/DefaultRegistryInfo.java | 39 +++ .../starblues/spring/DefaultSpringPlugin.java | 8 +- .../DefaultSpringPluginRegistryInfo.java | 11 +- .../spring/PluginListableBeanFactory.java | 3 +- .../gitee/starblues/spring/RegistryInfo.java | 35 +++ .../spring/SpringPluginRegistryInfo.java | 22 +- .../OneselfPluginSpringApplication.java | 5 +- .../oneself/OneselfSpringApplication.java | 19 +- .../spring/process/AfterRefreshProcessor.java | 25 +- .../process/AfterRefreshProcessorFactory.java | 32 ++- .../process/BeforeRefreshProcessor.java | 23 +- .../BeforeRefreshProcessorFactory.java | 29 ++- .../process/PluginControllerProcessor.java | 245 ++++++++++++++++++ .../ControllerAfterRefreshProcessor.java | 45 ---- ...va => RegisterNecessaryBeanProcessor.java} | 8 +- .../com/gitee/starblues/utils/ClassUtils.java | 28 +- .../starblues/utils/ReflectionUtils.java | 78 ++++++ .../spring-configuration-metadata.json | 21 +- 24 files changed, 652 insertions(+), 139 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/{RegisterNecessaryBean.java => RegisterNecessaryBeanProcessor.java} (78%) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java index 64a3951..3858e1d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java @@ -48,6 +48,7 @@ public class DefaultMainResourceDefiner implements MainResourceDefiner{ // == java == mainClass.add("java."); mainClass.add("javax."); + mainClass.add("sun.reflect"); // == main == mainClass.add(mainPackageName); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java index ffe7f9b..bf4839b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java @@ -7,7 +7,7 @@ import java.util.Set; /** * controller 包装 * @author starBlues - * @version 2.4.0 + * @version 3.0.0 */ public class ControllerWrapper { @@ -16,6 +16,11 @@ public class ControllerWrapper { */ private String beanName; + /** + * controller 路径前缀 + */ + private String[] pathPrefix; + /** * controller bean 类型 */ @@ -42,6 +47,14 @@ public class ControllerWrapper { this.beanName = beanName; } + public String[] getPathPrefix() { + return pathPrefix; + } + + public void setPathPrefix(String[] pathPrefix) { + this.pathPrefix = pathPrefix; + } + public Set getRequestMappingInfos() { return requestMappingInfos; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index 4ffd75e..b151ede 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -20,6 +20,11 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio public static final String ENABLE_KEY = "plugin.enable"; + /** + * 是否启用插件功能 + */ + @Value("${enable:true}") + private Boolean enable; /** * 运行模式 @@ -29,12 +34,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Value("${runMode:dev}") private String runMode; - /** - * 是否启用插件功能 - */ - @Value("${enable:true}") - private Boolean enable; - /** * 主程序包名 */ @@ -58,6 +57,12 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Value("${pluginRestPathPrefix:/plugins}") private String pluginRestPathPrefix; + /** + * 是否启用插件的 rest controller 接口注册. 默认启用 + */ + @Value("${enablePluginRestController:true}") + private Boolean enablePluginRestController; + /** * 是否启用插件id作为rest接口前缀, 默认为启用. * 如果为启用, 则地址为 /pluginRestPathPrefix/pluginId @@ -130,6 +135,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Value("${enableWebSocket:false}") private Boolean enableWebSocket; + @Override + public boolean enable() { + if(enable == null){ + return true; + } + return enable; + } + @Override public RuntimeMode environment() { return RuntimeMode.byName(runMode); @@ -150,14 +163,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio return pluginConfigFilePath; } - @Override - public boolean enable() { - if(enable == null){ - return true; - } - return enable; - } - @Override public String uploadTempPath() { if(!ObjectUtils.isEmpty(uploadTempPath)){ @@ -174,6 +179,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio return backupPath; } + @Override + public boolean enablePluginRestController() { + if(enablePluginRestController == null){ + return super.enablePluginRestController(); + } + return enablePluginRestController; + } + @Override public String pluginRestPathPrefix() { if(!ObjectUtils.isEmpty(pluginRestPathPrefix)){ @@ -241,14 +254,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio return stopDependents; } - public String getRunMode() { - return runMode; - } - - public void setRunMode(String runMode) { - this.runMode = runMode; - } - public Boolean getEnable() { return enable; } @@ -257,6 +262,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.enable = enable; } + public String getRunMode() { + return runMode; + } + + public void setRunMode(String runMode) { + this.runMode = runMode; + } + public String getMainPackage() { return mainPackage; } @@ -284,6 +297,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.pluginConfigFilePath = pluginConfigFilePath; } + public Boolean getEnablePluginRestController() { + return enablePluginRestController; + } + + public void setEnablePluginRestController(Boolean enablePluginRestController) { + this.enablePluginRestController = enablePluginRestController; + } + public String getPluginRestPathPrefix() { return pluginRestPathPrefix; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index b802a68..12b9e46 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -17,6 +17,10 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf public static final String DEFAULT_PLUGIN_REST_PATH_PREFIX = "plugins"; public static final boolean DEFAULT_ENABLE_PLUGIN_ID_REST_PATH_PREFIX = true; + @Override + public boolean enable() { + return true; + } @Override public List pluginPath() { @@ -29,11 +33,6 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf return pluginPath; } - @Override - public boolean enable() { - return true; - } - @Override public String uploadTempPath(){ return "temp"; @@ -44,6 +43,11 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf return "backupPlugin"; } + @Override + public boolean enablePluginRestController() { + return true; + } + @Override public String pluginRestPathPrefix(){ return DEFAULT_PLUGIN_REST_PATH_PREFIX; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index 1eeef6c..50e6d63 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -14,6 +14,12 @@ import java.util.Set; */ public interface IntegrationConfiguration { + /** + * 是否启用该插件框架 + * @return true 启用, false 禁用 + */ + boolean enable(); + /** * 运行环境。运行项目时的模式。分为开发环境(Dev)、生产环境(Prod) * @return RuntimeMode.DEV、RuntimeMode.PROD @@ -53,6 +59,12 @@ public interface IntegrationConfiguration { */ String backupPath(); + /** + * 是否启用插件的 rest controller 接口注册. 默认启用 + * @return true 启用, false 禁用 + */ + boolean enablePluginRestController(); + /** * 插件 RestController 统一请求的路径前缀 * @return path @@ -67,13 +79,6 @@ public interface IntegrationConfiguration { */ boolean enablePluginIdRestPathPrefix(); - - /** - * 是否启用该插件框架 - * @return true 启用, false 禁用 - */ - boolean enable(); - /** * 启用的插件id * @return Set diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java index 0e86d2e..03e43f6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java @@ -97,7 +97,6 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } protected void loadBean() { - applicationContext.scan("com.gitee.starblues.example.basic"); beanDefinitionLoader.load(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java new file mode 100644 index 0000000..bfe97b5 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java @@ -0,0 +1,39 @@ +package com.gitee.starblues.spring; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class DefaultRegistryInfo implements RegistryInfo{ + + private final Map registryInfo = new ConcurrentHashMap<>(); + + + @Override + public void addRegistryInfo(String key, Object value) { + registryInfo.put(key, value); + } + + @SuppressWarnings("unchecked") + @Override + public T getRegistryInfo(String key) { + Object o = registryInfo.get(key); + if(o == null){ + return null; + } + return (T) o; + } + + @Override + public void removeRegistryInfo(String key) { + registryInfo.remove(key); + } + + @Override + public void clearRegistryInfo() { + registryInfo.clear(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java index bfcabdb..96295d2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java @@ -35,9 +35,9 @@ public class DefaultSpringPlugin implements SpringPlugin { @Override public synchronized void registry(PluginWrapper pluginWrapper) throws Exception { SpringPluginRegistryInfo registryInfo = createRegistryInfo(pluginWrapper); - beforeRefreshProcessor.registry(registryInfo); + beforeRefreshProcessor.registryOfBefore(registryInfo); registryInfo.getPluginSpringApplication().run(); - afterRefreshProcessor.registry(registryInfo); + afterRefreshProcessor.registryOfAfter(registryInfo); registryInfoMap.put(pluginWrapper.getPluginId(), registryInfo); PluginInfoContainers.addPluginApplicationContext(pluginWrapper.getPluginId(), registryInfo.getPluginSpringApplication().getApplicationContext()); @@ -49,8 +49,8 @@ public class DefaultSpringPlugin implements SpringPlugin { if(springPluginRegistryInfo == null){ return; } - beforeRefreshProcessor.unRegistry(springPluginRegistryInfo); - afterRefreshProcessor.unRegistry(springPluginRegistryInfo); + afterRefreshProcessor.unRegistryOfAfter(springPluginRegistryInfo); + beforeRefreshProcessor.unRegistryOfBefore(springPluginRegistryInfo); springPluginRegistryInfo.getPluginSpringApplication().close(); registryInfoMap.remove(pluginId); PluginInfoContainers.removePluginApplicationContext(pluginId); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java index fa8ae37..b0ab7d0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java @@ -1,18 +1,19 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.integration.IntegrationConfiguration; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; /** * @author starBlues * @version 1.0 */ -public class DefaultSpringPluginRegistryInfo implements SpringPluginRegistryInfo{ +public class DefaultSpringPluginRegistryInfo extends DefaultRegistryInfo implements SpringPluginRegistryInfo{ private final PluginWrapper pluginWrapper; private final PluginSpringApplication pluginSpringApplication; private final ConfigurableApplicationContext mainApplicationContext; + private final IntegrationConfiguration configuration; public DefaultSpringPluginRegistryInfo(PluginWrapper pluginWrapper, PluginSpringApplication springApplication, @@ -20,6 +21,7 @@ public class DefaultSpringPluginRegistryInfo implements SpringPluginRegistryInfo this.pluginWrapper = pluginWrapper; this.pluginSpringApplication = springApplication; this.mainApplicationContext = mainApplicationContext; + this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); } @Override @@ -37,4 +39,9 @@ public class DefaultSpringPluginRegistryInfo implements SpringPluginRegistryInfo return mainApplicationContext; } + @Override + public IntegrationConfiguration getConfiguration() { + return configuration; + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java index 7e26191..a4255c5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java @@ -10,8 +10,9 @@ import org.springframework.lang.Nullable; import java.util.Set; /** + * 扩展 DefaultListableBeanFactory * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginListableBeanFactory extends DefaultListableBeanFactory { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java new file mode 100644 index 0000000..96c2b69 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java @@ -0,0 +1,35 @@ +package com.gitee.starblues.spring; + +/** + * 注册信息 + * @author starBlues + * @version 3.0.0 + */ +public interface RegistryInfo { + + /** + * 添加注册的信息 + * @param key 注册信息key + * @param value 注册信息值 + */ + void addRegistryInfo(String key, Object value); + + /** + * 得到注册信息 + * @param key 注册信息key + * @return 注册信息的值 + */ + T getRegistryInfo(String key); + /** + * 移除注册信息 + * @param key 注册信息key + */ + void removeRegistryInfo(String key); + + /** + * 清除全部的注册信息 + */ + void clearRegistryInfo(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java index 1cbe845..e5b424c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java @@ -1,6 +1,7 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.integration.IntegrationConfiguration; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; @@ -8,11 +9,30 @@ import org.springframework.context.support.GenericApplicationContext; * @author starBlues * @version 3.0.0 */ -public interface SpringPluginRegistryInfo { +public interface SpringPluginRegistryInfo extends RegistryInfo{ + /** + * 得到插件 PluginWrapper + * @return PluginWrapper + */ PluginWrapper getPluginWrapper(); + /** + * 得到当前插件的 PluginSpringApplication 实现 + * @return PluginSpringApplication + */ PluginSpringApplication getPluginSpringApplication(); + /** + * 得到主程序的 ApplicationContext + * @return ConfigurableApplicationContext + */ ConfigurableApplicationContext getMainApplicationContext(); + + /** + * 得到集成的配置 + * @return IntegrationConfiguration + */ + IntegrationConfiguration getConfiguration(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java index c336253..fcf5ee4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java @@ -4,8 +4,9 @@ import com.gitee.starblues.spring.PluginSpringApplication; import org.springframework.context.ConfigurableApplicationContext; /** + * 插件可主运行的 PluginSpringApplication 实现, 插件如果需要自动运行, 则使用该类进行引导启动 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class OneselfPluginSpringApplication implements PluginSpringApplication { @@ -18,7 +19,7 @@ public class OneselfPluginSpringApplication implements PluginSpringApplication { } /** - * 插件自主调用 + * 插件自主运行时, 引导入口 * @param primarySources primarySources * @return ConfigurableApplicationContext */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java index b493423..66dd914 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -22,13 +22,13 @@ import java.util.HashMap; import java.util.Map; /** + * 插件自主运行时的SpringApplication环境, 对 SpringApplication 进行再次封装 * @author starBlues - * @version 1.0 + * @version 3.0.0 + * @see SpringApplication */ public class OneselfSpringApplication extends SpringApplication { - public static final String ID = "OneselfPluginSpringApplication"; - private final Class primarySource; private final PluginSpringApplication springApplication; @@ -47,6 +47,7 @@ public class OneselfSpringApplication extends SpringApplication { } else { primarySource = null; } + // 运行之前, 从当前插件的 classpath 下获取插件引导信息 pluginWrapper = tryGetPluginWrapper(); } @@ -59,6 +60,7 @@ public class OneselfSpringApplication extends SpringApplication { protected void bindToSpringApplication(ConfigurableEnvironment environment) { super.bindToSpringApplication(environment); Map env = new HashMap<>(); + // 禁用插件的自动装配 env.put(AutoIntegrationConfiguration.ENABLE_KEY, false); env.put("server.servlet.context-path", getContextPath(environment)); environment.getPropertySources().addFirst(new MapPropertySource("springPluginRegistryInfo", env)); @@ -70,7 +72,7 @@ public class OneselfSpringApplication extends SpringApplication { BeforeRefreshProcessorFactory beforeRefreshProcessorFactory = new BeforeRefreshProcessorFactory(null); SpringPluginRegistryInfo springPluginRegistryInfo = create(applicationContext); - beforeRefreshProcessorFactory.registry(springPluginRegistryInfo); + beforeRefreshProcessorFactory.registryOfBefore(springPluginRegistryInfo); super.refresh(applicationContext); } @@ -93,6 +95,10 @@ public class OneselfSpringApplication extends SpringApplication { }, applicationContext); } + /** + * 尝试从 classpath 获取插件引导信息, 如果不存在, 则生成空的 PluginWrapper + * @return PluginWrapper + */ private PluginWrapper tryGetPluginWrapper(){ try { PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); @@ -142,6 +148,11 @@ public class OneselfSpringApplication extends SpringApplication { }; } + /** + * 获取独立运行插件的接口 url 前缀 + * @param environment environment + * @return String + */ private String getContextPath(ConfigurableEnvironment environment){ String pluginRestPathPrefix = environment.getProperty("plugin.pluginRestPathPrefix", String.class); Boolean enablePluginIdRestPathPrefix = environment.getProperty("plugin.enablePluginIdRestPathPrefix", diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java index aa265c5..cecb3f3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java @@ -4,15 +4,34 @@ import com.gitee.starblues.spring.SpringPluginRegistryInfo; import com.gitee.starblues.utils.OrderPriority; /** + * ApplicationContext.refresh 刷新之前的处理扩展接口 * @author starBlues * @version 3.0.0 */ public interface AfterRefreshProcessor { - void registry(SpringPluginRegistryInfo registryInfo); + /** + * 插件注册时调用 + * @param registryInfo 注册插件信息 + * @throws Exception Exception + */ + void registryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception; - void unRegistry(SpringPluginRegistryInfo registryInfo); + /** + * 插件卸载时调用 + * @param registryInfo 注册插件信息 + * @throws Exception Exception + */ + default void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception{ - OrderPriority order(); + } + + /** + * 执行顺序 OrderPriority + * @return OrderPriority + */ + default OrderPriority orderOfAfter(){ + return OrderPriority.getMiddlePriority(); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java index 20160c7..4cd6f98 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java @@ -1,14 +1,13 @@ package com.gitee.starblues.spring.process; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.process.after.ControllerAfterRefreshProcessor; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.OrderPriority; import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; import java.util.List; @@ -21,24 +20,31 @@ public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ private static final Logger LOGGER = LoggerFactory.getLogger(AfterRefreshProcessorFactory.class); private final List afterRefreshProcessors; + private final IntegrationConfiguration configuration; + private final ConfigurableApplicationContext mainApplicationContext; public AfterRefreshProcessorFactory(ConfigurableApplicationContext mainApplicationContext) { - List afterRefreshProcessors = SpringBeanUtils.getBeans( + this.mainApplicationContext = mainApplicationContext; + this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); + + List processors = SpringBeanUtils.getBeans( mainApplicationContext, AfterRefreshProcessor.class); - addDefault(afterRefreshProcessors); - afterRefreshProcessors.sort(CommonUtils.orderPriority(AfterRefreshProcessor::order)); - this.afterRefreshProcessors = afterRefreshProcessors; + addDefault(processors); + processors.sort(CommonUtils.orderPriority(AfterRefreshProcessor::orderOfAfter)); + this.afterRefreshProcessors = processors; } - protected void addDefault(List afterRefreshProcessors){ - afterRefreshProcessors.add(new ControllerAfterRefreshProcessor()); + protected void addDefault(List processors){ + if(configuration != null && configuration.enablePluginRestController()){ + processors.add(PluginControllerProcessor.getInstance(mainApplicationContext)); + } } @Override - public void registry(SpringPluginRegistryInfo registryInfo) { + public void registryOfAfter(SpringPluginRegistryInfo registryInfo) { for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { try { - afterRefreshProcessor.registry(registryInfo); + afterRefreshProcessor.registryOfAfter(registryInfo); } catch (Exception e){ LOGGER.error("AfterRefreshProcessor: [{}] registry 异常", afterRefreshProcessor.getClass().getName(), e); @@ -47,10 +53,10 @@ public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ } @Override - public void unRegistry(SpringPluginRegistryInfo registryInfo) { + public void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) { for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { try { - afterRefreshProcessor.unRegistry(registryInfo); + afterRefreshProcessor.unRegistryOfAfter(registryInfo); } catch (Exception e){ LOGGER.error("AfterRefreshProcessor: [{}] unRegistry 异常", afterRefreshProcessor.getClass().getName(), e); @@ -59,7 +65,7 @@ public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ } @Override - public OrderPriority order() { + public OrderPriority orderOfAfter() { return OrderPriority.getHighPriority(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java index aeb9edf..fddb55c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java @@ -4,15 +4,32 @@ import com.gitee.starblues.spring.SpringPluginRegistryInfo; import com.gitee.starblues.utils.OrderPriority; /** + * ApplicationContext.refresh 刷新之后的处理扩展接口 * @author starBlues * @version 3.0.0 */ public interface BeforeRefreshProcessor { - void registry(SpringPluginRegistryInfo registryInfo); + /** + * 插件注册时调用 + * @param registryInfo 注册插件信息 + */ + void registryOfBefore(SpringPluginRegistryInfo registryInfo); - void unRegistry(SpringPluginRegistryInfo registryInfo); + /** + * 插件卸载时调用 + * @param registryInfo 注册插件信息 + */ + default void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo){ - OrderPriority order(); + } + + /** + * 执行顺序 OrderPriority + * @return OrderPriority + */ + default OrderPriority orderOfBefore(){ + return OrderPriority.getMiddlePriority(); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java index f55456d..8096260 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java @@ -1,15 +1,14 @@ package com.gitee.starblues.spring.process; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.process.before.RegisterNecessaryBean; +import com.gitee.starblues.spring.process.before.RegisterNecessaryBeanProcessor; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.OrderPriority; import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; import java.util.ArrayList; import java.util.List; @@ -22,30 +21,40 @@ public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(BeforeRefreshProcessorFactory.class); + private final ConfigurableApplicationContext mainApplicationContext; + private final List processors; + private final IntegrationConfiguration configuration; public BeforeRefreshProcessorFactory(ConfigurableApplicationContext mainApplicationContext) { + this.mainApplicationContext = mainApplicationContext; + List processors = null; if(mainApplicationContext != null){ + this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); processors = SpringBeanUtils.getBeans( mainApplicationContext, BeforeRefreshProcessor.class); } else { + configuration = null; processors = new ArrayList<>(); } addDefault(processors); - processors.sort(CommonUtils.orderPriority(BeforeRefreshProcessor::order)); + processors.sort(CommonUtils.orderPriority(BeforeRefreshProcessor::orderOfBefore)); this.processors = processors; } private void addDefault(List processors) { - processors.add(new RegisterNecessaryBean()); + processors.add(new RegisterNecessaryBeanProcessor()); + if(configuration != null && configuration.enablePluginRestController()){ + processors.add(PluginControllerProcessor.getInstance(mainApplicationContext)); + } } @Override - public void registry(SpringPluginRegistryInfo registryInfo) { + public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { for (BeforeRefreshProcessor processor : processors) { try { - processor.registry(registryInfo); + processor.registryOfBefore(registryInfo); } catch (Exception e){ LOGGER.error("BeforeRefreshProcessor: [{}] registry 异常", processor.getClass().getName(), e); @@ -54,10 +63,10 @@ public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { } @Override - public void unRegistry(SpringPluginRegistryInfo registryInfo) { + public void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo) { for (BeforeRefreshProcessor processor : processors) { try { - processor.unRegistry(registryInfo); + processor.unRegistryOfBefore(registryInfo); } catch (Exception e){ LOGGER.error("BeforeRefreshProcessor: [{}] unRegistry 异常", processor.getClass().getName(), e); @@ -66,7 +75,7 @@ public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { } @Override - public OrderPriority order() { + public OrderPriority orderOfBefore() { return OrderPriority.getHighPriority(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java new file mode 100644 index 0000000..5a6024e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java @@ -0,0 +1,245 @@ +package com.gitee.starblues.spring.process; + +import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.PluginSpringApplication; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.*; +import org.pf4j.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.lang.reflect.Method; +import java.util.*; + +/** + * 插件 controller 处理者 + * @author starBlues + * @version 3.0.0 + */ +public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterRefreshProcessor { + + private final static Logger LOG = LoggerFactory.getLogger(PluginControllerProcessor.class); + + private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; + + private final RequestMappingHandlerMapping requestMappingHandlerMapping; + private final Method getMappingForMethod; + + private static PluginControllerProcessor instance; + + private PluginControllerProcessor(ConfigurableApplicationContext mainApplicationContext){ + this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); + this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, + "getMappingForMethod", Method.class, Class.class); + if(this.getMappingForMethod != null){ + this.getMappingForMethod.setAccessible(true); + } + if(getMappingForMethod == null){ + LOG.warn("RequestMappingHandlerMapping 类中没有发现 方法, 无法注册插件接口. " + + "请检查当前环境是否为 web 环境"); + } + } + + public static PluginControllerProcessor getInstance(ConfigurableApplicationContext mainApplicationContext){ + if(instance == null){ + synchronized (PluginControllerProcessor.class){ + if(instance == null){ + instance = new PluginControllerProcessor(mainApplicationContext); + } + } + } + return instance; + } + + @Override + public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { + if(getMappingForMethod == null){ + return; + } + IntegrationConfiguration configuration = registryInfo.getConfiguration(); + if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) + && !configuration.enablePluginIdRestPathPrefix()){ + // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 + return; + } + + PluginSpringApplication pluginSpringApplication = registryInfo.getPluginSpringApplication(); + AnnotationConfigApplicationContext applicationContext = + (AnnotationConfigApplicationContext)pluginSpringApplication.getApplicationContext(); + applicationContext.registerBean("changeRestPathPostProcessor", + ChangeRestPathPostProcessor.class, ()-> new ChangeRestPathPostProcessor(registryInfo)); + } + + @Override + public void registryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + if(getMappingForMethod == null){ + return; + } + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + List controllerWrappers = registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + if(ObjectUtils.isEmpty(controllerWrappers)){ + LOG.warn("插件 [{}] 没有发现可注册的 Controller", pluginId); + return; + } + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + + Iterator iterator = controllerWrappers.iterator(); + while (iterator.hasNext()){ + ControllerWrapper controllerWrapper = iterator.next(); + if(!applicationContext.containsBean(controllerWrapper.getBeanName())){ + iterator.remove(); + } + Object controllerBean = applicationContext.getBean(controllerWrapper.getBeanName()); + Set requestMappingInfos = registry(registryInfo, controllerBean.getClass()); + if(requestMappingInfos.isEmpty()){ + iterator.remove(); + } else { + for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { + LOG.info("插件[{}]注册接口: {}", pluginId, requestMappingInfo.toString()); + } + } + } + } + + @Override + public void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + List controllerWrappers = registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + if(ObjectUtils.isEmpty(controllerWrappers)){ + return; + } + for (ControllerWrapper controllerBeanWrapper : controllerWrappers) { + if(controllerBeanWrapper == null){ + continue; + } + unregister(controllerBeanWrapper); + } + registryInfo.removeRegistryInfo(PROCESS_CONTROLLERS); + } + + private void unregister(ControllerWrapper controllerBeanWrapper) { + Set requestMappingInfos = controllerBeanWrapper.getRequestMappingInfos(); + if(ObjectUtils.isEmpty(requestMappingInfos)){ + return; + } + for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { + requestMappingHandlerMapping.unregisterMapping(requestMappingInfo); + } + } + + private Set registry(SpringPluginRegistryInfo pluginRegistryInfo, Class aClass) + throws Exception { + ConfigurableApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginSpringApplication() + .getApplicationContext(); + Object object = pluginApplicationContext.getBean(aClass); + + Method[] methods = aClass.getMethods(); + Set requestMappingInfos = new HashSet<>(); + for (Method method : methods) { + if (isHaveRequestMapping(method)) { + RequestMappingInfo requestMappingInfo = (RequestMappingInfo) + getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass); + requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method); + requestMappingInfos.add(requestMappingInfo); + } + } + return requestMappingInfos; + } + + /** + * 方法上是否存在 @RequestMapping 注解 + * @param method method + * @return boolean + */ + private boolean isHaveRequestMapping(Method method){ + return AnnotationUtils.findAnnotation(method, RequestMapping.class) != null; + } + + + private static class ChangeRestPathPostProcessor implements BeanPostProcessor { + + private final static Logger LOG = LoggerFactory.getLogger(ChangeRestPathPostProcessor.class); + private final static String COMMON_ERROR = "无法统一处理该 Controller 统一请求路径前缀"; + + private final SpringPluginRegistryInfo registryInfo; + + + + private ChangeRestPathPostProcessor(SpringPluginRegistryInfo registryInfo) { + this.registryInfo = registryInfo; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + Class aClass = bean.getClass(); + Controller controller = AnnotationUtils.findAnnotation(aClass, Controller.class); + if(controller == null){ + return bean; + } + RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class); + if(requestMapping != null){ + changePathForClass(beanName, aClass, requestMapping); + } + return bean; + } + + private void changePathForClass(String beanName, Class aClass, RequestMapping requestMapping){ + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + String pathPrefix = CommonUtils.getPluginRestPrefix(registryInfo.getConfiguration(), pluginId); + + if(StringUtils.isNullOrEmpty(pathPrefix)){ + LOG.error("插件 [{}] Controller类 [{}] 未发现 path 配置, {}", + pluginId, aClass.getSimpleName(), COMMON_ERROR); + return; + } + Set definePaths = new HashSet<>(); + definePaths.addAll(Arrays.asList(requestMapping.path())); + definePaths.addAll(Arrays.asList(requestMapping.value())); + try { + Map memberValues = ClassUtils.getAnnotationsUpdater(requestMapping); + if(memberValues == null){ + LOG.error("插件 [{}] Controller 类 [{}] 无法反射获取注解属性, {}", + pluginId, aClass.getSimpleName(), COMMON_ERROR); + return; + } + String[] newPath = new String[definePaths.size()]; + int i = 0; + for (String definePath : definePaths) { + // 解决插件启用、禁用后, 路径前缀重复的问题。 + if(definePath.contains(pathPrefix)){ + newPath[i++] = definePath; + } else { + newPath[i++] = CommonUtils.restJoiningPath(pathPrefix, definePath); + } + } + if(newPath.length == 0){ + newPath = new String[]{ pathPrefix }; + } + memberValues.put("path", newPath); + memberValues.put("value", newPath); + + List controllerWrappers = this.registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + if(controllerWrappers == null){ + controllerWrappers = new ArrayList<>(); + this.registryInfo.addRegistryInfo(PROCESS_CONTROLLERS, controllerWrappers); + } + ControllerWrapper controllerWrapper = new ControllerWrapper(); + controllerWrapper.setPathPrefix(newPath); + controllerWrapper.setBeanName(beanName); + controllerWrappers.add(controllerWrapper); + } catch (Exception e) { + LOG.error("插件 [{}] Controller 类[{}] 注册异常. {}", pluginId, aClass.getName(), e.getMessage(), e); + } + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java deleted file mode 100644 index 02467a6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/after/ControllerAfterRefreshProcessor.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.gitee.starblues.spring.process.after; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.process.AfterRefreshProcessor; -import com.gitee.starblues.utils.OrderPriority; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.stereotype.Controller; - -import java.util.Map; - -/** - * @author starBlues - * @version 1.0 - */ -public class ControllerAfterRefreshProcessor implements AfterRefreshProcessor { - - @Override - public void registry(SpringPluginRegistryInfo registryInfo) { - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); - String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); - for (String beanDefinitionName : beanDefinitionNames) { - System.out.println(beanDefinitionName); - } - - String[] singletonNames = applicationContext.getBeanFactory().getSingletonNames(); - for (String singletonName : singletonNames) { - System.out.println(singletonName); - } - - - Map beansWithAnnotation = registryInfo.getPluginSpringApplication().getApplicationContext() - .getBeansWithAnnotation(Controller.class); - System.out.println(beansWithAnnotation); - } - - @Override - public void unRegistry(SpringPluginRegistryInfo registryInfo) { - - } - - @Override - public OrderPriority order() { - return null; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBeanProcessor.java similarity index 78% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBeanProcessor.java index 89a8b04..e473d3a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBean.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBeanProcessor.java @@ -11,11 +11,11 @@ import org.springframework.context.ConfigurableApplicationContext; * @author starBlues * @version 1.0 */ -public class RegisterNecessaryBean implements BeforeRefreshProcessor { +public class RegisterNecessaryBeanProcessor implements BeforeRefreshProcessor { @Override - public void registry(SpringPluginRegistryInfo registryInfo) { + public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); @@ -26,12 +26,12 @@ public class RegisterNecessaryBean implements BeforeRefreshProcessor { } @Override - public void unRegistry(SpringPluginRegistryInfo registryInfo) { + public void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo) { } @Override - public OrderPriority order() { + public OrderPriority orderOfBefore() { return OrderPriority.getHighPriority(); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java index 6d25abb..eb346ce 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java @@ -1,8 +1,8 @@ package com.gitee.starblues.utils; -import org.springframework.util.ReflectionUtils; -import java.lang.annotation.Annotation; +import org.springframework.beans.factory.config.BeanPostProcessor; + import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -92,11 +92,31 @@ public class ClassUtils { * @return 修改者集合 * @throws Exception 异常 */ + @SuppressWarnings("unchecked") public static Map getAnnotationsUpdater(Object annotation) throws Exception { InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); - Field field = invocationHandler.getClass().getDeclaredField("memberValues"); - field.setAccessible(true); + Field field = getAnnotationsUpdaterField(invocationHandler); + if(field == null){ + return null; + } return (Map) field.get(invocationHandler); } + private static Field getAnnotationsUpdaterField(InvocationHandler invocationHandler){ + Class aClass = invocationHandler.getClass(); + Field field = ReflectionUtils.findField(aClass, "memberValues", Map.class); + if(field == null){ + field = ReflectionUtils.findField(aClass, "valueCache", Map.class); + } + if(field == null){ + field = ReflectionUtils.findField(aClass, Map.class); + } + if(field != null){ + field.setAccessible(true); + return field; + } else { + return null; + } + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 25bce2d..546acbf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -1,7 +1,13 @@ package com.gitee.starblues.utils; + import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Objects; /** @@ -11,12 +17,18 @@ import java.util.Objects; */ public abstract class ReflectionUtils { + private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + private ReflectionUtils(){} public static Field findField(Class clazz, String name) { return findField(clazz, name, null); } + public static Field findField(Class clazz, Class fieldType) { + return findField(clazz, null, fieldType); + } + public static Field findField(Class clazz, String fieldName, Class fieldType) { Objects.requireNonNull(clazz, "clazz must not be null"); if(fieldName == null && fieldType == null){ @@ -81,4 +93,70 @@ public abstract class ReflectionUtils { } } + public static Method findMethod(Class clazz, String name) { + return findMethod(clazz, name, EMPTY_CLASS_ARRAY); + } + + public static Method findMethod(Class clazz, String name, Class... paramTypes) { + Assert.isNotNull(clazz, "Class must not be null"); + Assert.isNotEmpty(name, "Method name must not be null"); + Class searchType = clazz; + while (searchType != null) { + Method[] methods = (searchType.isInterface() ? searchType.getMethods() : + getDeclaredMethods(searchType, false)); + for (Method method : methods) { + if (name.equals(method.getName()) && (paramTypes == null || hasSameParams(method, paramTypes))) { + return method; + } + } + searchType = searchType.getSuperclass(); + } + return null; + } + + private static Method[] getDeclaredMethods(Class clazz, boolean defensive) { + Assert.isNotNull(clazz, "Class must not be null"); + Method[] result = new Method[]{}; + try { + Method[] declaredMethods = clazz.getDeclaredMethods(); + List defaultMethods = findConcreteMethodsOnInterfaces(clazz); + + if (defaultMethods != null) { + result = new Method[declaredMethods.length + defaultMethods.size()]; + System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length); + int index = declaredMethods.length; + for (Method defaultMethod : defaultMethods) { + result[index] = defaultMethod; + index++; + } + } else { + result = declaredMethods; + } + } catch (Throwable ex) { + throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() + + "] from ClassLoader [" + clazz.getClassLoader() + "]", ex); + } + return result; + } + + private static List findConcreteMethodsOnInterfaces(Class clazz) { + List result = null; + for (Class ifc : clazz.getInterfaces()) { + for (Method ifcMethod : ifc.getMethods()) { + if (!Modifier.isAbstract(ifcMethod.getModifiers())) { + if (result == null) { + result = new ArrayList<>(); + } + result.add(ifcMethod); + } + } + } + return result; + } + + private static boolean hasSameParams(Method method, Class[] paramTypes) { + return (paramTypes.length == method.getParameterCount() && + Arrays.equals(paramTypes, method.getParameterTypes())); + } + } diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json index cbf58f8..2e53f9f 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json @@ -7,13 +7,6 @@ } ], "properties": [ - { - "name": "plugin.runMode", - "type": "java.lang.String", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "运行模式. 开发环境: development、dev; 生产/部署 环境: deployment、prod", - "defaultValue": "dev" - }, { "name": "plugin.enable", "type": "java.lang.Boolean", @@ -21,6 +14,13 @@ "description": "是否启用插件功能", "defaultValue": true }, + { + "name": "plugin.runMode", + "type": "java.lang.String", + "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", + "description": "运行模式. 开发环境: development、dev; 生产/部署 环境: deployment、prod", + "defaultValue": "dev" + }, { "name": "plugin.mainPackage", "type": "java.lang.String", @@ -42,6 +42,13 @@ "description": "插件对应的配置文件存放目录, 只作用于生产环境下", "defaultValue": "/plugin-config" }, + { + "name": "plugin.enablePluginRestController", + "type": "java.lang.Boolean", + "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", + "description": "是否启用插件的 rest controller 接口注册. 默认启用", + "defaultValue": true + }, { "name": "plugin.pluginRestPathPrefix", "type": "java.lang.String", -- Gitee From cedb63e1294ed358cd88ceb9e18b609466914bc4 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 2 Dec 2021 11:00:21 +0800 Subject: [PATCH 10/37] add plugin controller register --- .../starblues/spring/DefaultSpringPlugin.java | 27 ++-- .../DefaultSpringPluginRegistryInfo.java | 7 +- .../spring/EmptyAutoConfiguration.java | 8 -- .../oneself/OneselfSpringApplication.java | 40 ++++-- .../process/AfterRefreshProcessorFactory.java | 72 ---------- .../BeforeRefreshProcessorFactory.java | 82 ----------- .../processor/AbstractProcessorFactory.java | 129 ++++++++++++++++++ .../AfterRefreshProcessor.java | 2 +- .../BeforeRefreshProcessor.java | 2 +- .../processor/DefaultProcessorFactory.java | 46 +++++++ .../PluginControllerProcessor.java | 18 +-- .../spring/processor/ProcessorRunMode.java | 24 ++++ .../RegisterNecessaryBeanProcessor.java | 14 +- .../main/resources/META-INF/spring.factories | 1 - 14 files changed, 258 insertions(+), 214 deletions(-) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{process => processor}/AfterRefreshProcessor.java (95%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{process => processor}/BeforeRefreshProcessor.java (94%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{process => processor}/PluginControllerProcessor.java (94%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{process => processor}/before/RegisterNecessaryBeanProcessor.java (71%) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java index 96295d2..2f47a3f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java @@ -2,10 +2,10 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; -import com.gitee.starblues.spring.process.AfterRefreshProcessor; -import com.gitee.starblues.spring.process.AfterRefreshProcessorFactory; -import com.gitee.starblues.spring.process.BeforeRefreshProcessor; -import com.gitee.starblues.spring.process.BeforeRefreshProcessorFactory; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.processor.AbstractProcessorFactory; +import com.gitee.starblues.spring.processor.DefaultProcessorFactory; +import com.gitee.starblues.spring.processor.ProcessorRunMode; import org.springframework.context.support.GenericApplicationContext; import java.util.Map; @@ -21,23 +21,24 @@ public class DefaultSpringPlugin implements SpringPlugin { private final GenericApplicationContext mainApplicationContext; + private final IntegrationConfiguration configuration; - private final BeforeRefreshProcessor beforeRefreshProcessor; - private final AfterRefreshProcessor afterRefreshProcessor; + private final AbstractProcessorFactory processorFactory; public DefaultSpringPlugin(GenericApplicationContext mainApplicationContext) { this.mainApplicationContext = mainApplicationContext; - this.beforeRefreshProcessor = new BeforeRefreshProcessorFactory(mainApplicationContext); - this.afterRefreshProcessor = new AfterRefreshProcessorFactory(mainApplicationContext); + this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); + this.processorFactory = new DefaultProcessorFactory(mainApplicationContext, configuration, + ProcessorRunMode.PLUGIN); } @Override public synchronized void registry(PluginWrapper pluginWrapper) throws Exception { SpringPluginRegistryInfo registryInfo = createRegistryInfo(pluginWrapper); - beforeRefreshProcessor.registryOfBefore(registryInfo); + processorFactory.registryOfBefore(registryInfo); registryInfo.getPluginSpringApplication().run(); - afterRefreshProcessor.registryOfAfter(registryInfo); + processorFactory.registryOfAfter(registryInfo); registryInfoMap.put(pluginWrapper.getPluginId(), registryInfo); PluginInfoContainers.addPluginApplicationContext(pluginWrapper.getPluginId(), registryInfo.getPluginSpringApplication().getApplicationContext()); @@ -49,8 +50,8 @@ public class DefaultSpringPlugin implements SpringPlugin { if(springPluginRegistryInfo == null){ return; } - afterRefreshProcessor.unRegistryOfAfter(springPluginRegistryInfo); - beforeRefreshProcessor.unRegistryOfBefore(springPluginRegistryInfo); + processorFactory.unRegistryOfAfter(springPluginRegistryInfo); + processorFactory.unRegistryOfBefore(springPluginRegistryInfo); springPluginRegistryInfo.getPluginSpringApplication().close(); registryInfoMap.remove(pluginId); PluginInfoContainers.removePluginApplicationContext(pluginId); @@ -59,7 +60,7 @@ public class DefaultSpringPlugin implements SpringPlugin { protected SpringPluginRegistryInfo createRegistryInfo(PluginWrapper pluginWrapper){ PluginSpringApplication springApplication = createSpringApplication(pluginWrapper); return new DefaultSpringPluginRegistryInfo( - pluginWrapper, springApplication, mainApplicationContext + pluginWrapper, springApplication, mainApplicationContext, configuration ); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java index b0ab7d0..e23cd75 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java @@ -6,7 +6,7 @@ import org.springframework.context.ConfigurableApplicationContext; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DefaultSpringPluginRegistryInfo extends DefaultRegistryInfo implements SpringPluginRegistryInfo{ @@ -17,11 +17,12 @@ public class DefaultSpringPluginRegistryInfo extends DefaultRegistryInfo impleme public DefaultSpringPluginRegistryInfo(PluginWrapper pluginWrapper, PluginSpringApplication springApplication, - ConfigurableApplicationContext mainApplicationContext) { + ConfigurableApplicationContext mainApplicationContext, + IntegrationConfiguration configuration) { this.pluginWrapper = pluginWrapper; this.pluginSpringApplication = springApplication; this.mainApplicationContext = mainApplicationContext; - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); + this.configuration = configuration; } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java deleted file mode 100644 index efe715b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/EmptyAutoConfiguration.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.gitee.starblues.spring; - -/** - * @author starBlues - * @version 1.0 - */ -public class EmptyAutoConfiguration { -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java index 66dd914..760f1d3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -8,9 +8,15 @@ import com.gitee.starblues.integration.DefaultIntegrationConfiguration; import com.gitee.starblues.spring.DefaultSpringPluginRegistryInfo; import com.gitee.starblues.spring.PluginSpringApplication; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.process.BeforeRefreshProcessorFactory; +import com.gitee.starblues.spring.processor.AbstractProcessorFactory; +import com.gitee.starblues.spring.processor.DefaultProcessorFactory; +import com.gitee.starblues.spring.processor.ProcessorRunMode; import com.gitee.starblues.utils.ObjectUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; @@ -29,6 +35,8 @@ import java.util.Map; */ public class OneselfSpringApplication extends SpringApplication { + private final static Logger LOG = LoggerFactory.getLogger(OneselfSpringApplication.class); + private final Class primarySource; private final PluginSpringApplication springApplication; @@ -62,21 +70,37 @@ public class OneselfSpringApplication extends SpringApplication { Map env = new HashMap<>(); // 禁用插件的自动装配 env.put(AutoIntegrationConfiguration.ENABLE_KEY, false); - env.put("server.servlet.context-path", getContextPath(environment)); + String contextPath = getContextPath(environment); + env.put("server.servlet.context-path", contextPath); + LOG.info("当前应用接口前缀为: {}", contextPath); environment.getPropertySources().addFirst(new MapPropertySource("springPluginRegistryInfo", env)); + } @Override protected void refresh(ConfigurableApplicationContext applicationContext) { + AutoIntegrationConfiguration configuration = getConfiguration(applicationContext); // 刷新之前 - BeforeRefreshProcessorFactory beforeRefreshProcessorFactory = - new BeforeRefreshProcessorFactory(null); - SpringPluginRegistryInfo springPluginRegistryInfo = create(applicationContext); - beforeRefreshProcessorFactory.registryOfBefore(springPluginRegistryInfo); + AbstractProcessorFactory processorFactory = + new DefaultProcessorFactory(applicationContext, configuration, ProcessorRunMode.ONESELF); + SpringPluginRegistryInfo springPluginRegistryInfo = create(applicationContext, configuration); + processorFactory.registryOfBefore(springPluginRegistryInfo); super.refresh(applicationContext); } - private SpringPluginRegistryInfo create(ConfigurableApplicationContext applicationContext){ + private AutoIntegrationConfiguration getConfiguration(ConfigurableApplicationContext applicationContext){ + Binder binder = Binder.get(applicationContext.getEnvironment()); + AutoIntegrationConfiguration autoIntegrationConfiguration = + binder.bind("plugin", Bindable.of(AutoIntegrationConfiguration.class)) + .orElseGet(() -> null); + if(autoIntegrationConfiguration != null){ + return autoIntegrationConfiguration; + } + return new AutoIntegrationConfiguration(); + } + + private SpringPluginRegistryInfo create(ConfigurableApplicationContext applicationContext, + AutoIntegrationConfiguration configuration){ return new DefaultSpringPluginRegistryInfo(pluginWrapper, new PluginSpringApplication() { @Override public ConfigurableApplicationContext run() { @@ -92,7 +116,7 @@ public class OneselfSpringApplication extends SpringApplication { public ConfigurableApplicationContext getApplicationContext() { return applicationContext; } - }, applicationContext); + }, applicationContext, configuration); } /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java deleted file mode 100644 index 4cd6f98..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessorFactory.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.gitee.starblues.spring.process; - -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ConfigurableApplicationContext; - -import java.util.List; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class AfterRefreshProcessorFactory implements AfterRefreshProcessor{ - - private static final Logger LOGGER = LoggerFactory.getLogger(AfterRefreshProcessorFactory.class); - - private final List afterRefreshProcessors; - private final IntegrationConfiguration configuration; - private final ConfigurableApplicationContext mainApplicationContext; - - public AfterRefreshProcessorFactory(ConfigurableApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - - List processors = SpringBeanUtils.getBeans( - mainApplicationContext, AfterRefreshProcessor.class); - addDefault(processors); - processors.sort(CommonUtils.orderPriority(AfterRefreshProcessor::orderOfAfter)); - this.afterRefreshProcessors = processors; - } - - protected void addDefault(List processors){ - if(configuration != null && configuration.enablePluginRestController()){ - processors.add(PluginControllerProcessor.getInstance(mainApplicationContext)); - } - } - - @Override - public void registryOfAfter(SpringPluginRegistryInfo registryInfo) { - for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { - try { - afterRefreshProcessor.registryOfAfter(registryInfo); - } catch (Exception e){ - LOGGER.error("AfterRefreshProcessor: [{}] registry 异常", - afterRefreshProcessor.getClass().getName(), e); - } - } - } - - @Override - public void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) { - for (AfterRefreshProcessor afterRefreshProcessor : afterRefreshProcessors) { - try { - afterRefreshProcessor.unRegistryOfAfter(registryInfo); - } catch (Exception e){ - LOGGER.error("AfterRefreshProcessor: [{}] unRegistry 异常", - afterRefreshProcessor.getClass().getName(), e); - } - } - } - - @Override - public OrderPriority orderOfAfter() { - return OrderPriority.getHighPriority(); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java deleted file mode 100644 index 8096260..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessorFactory.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.gitee.starblues.spring.process; - -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.process.before.RegisterNecessaryBeanProcessor; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ConfigurableApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class BeforeRefreshProcessorFactory implements BeforeRefreshProcessor { - - private static final Logger LOGGER = LoggerFactory.getLogger(BeforeRefreshProcessorFactory.class); - - private final ConfigurableApplicationContext mainApplicationContext; - - private final List processors; - private final IntegrationConfiguration configuration; - - public BeforeRefreshProcessorFactory(ConfigurableApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - - List processors = null; - if(mainApplicationContext != null){ - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - processors = SpringBeanUtils.getBeans( - mainApplicationContext, BeforeRefreshProcessor.class); - } else { - configuration = null; - processors = new ArrayList<>(); - } - addDefault(processors); - processors.sort(CommonUtils.orderPriority(BeforeRefreshProcessor::orderOfBefore)); - this.processors = processors; - } - - private void addDefault(List processors) { - processors.add(new RegisterNecessaryBeanProcessor()); - if(configuration != null && configuration.enablePluginRestController()){ - processors.add(PluginControllerProcessor.getInstance(mainApplicationContext)); - } - } - - @Override - public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { - for (BeforeRefreshProcessor processor : processors) { - try { - processor.registryOfBefore(registryInfo); - } catch (Exception e){ - LOGGER.error("BeforeRefreshProcessor: [{}] registry 异常", - processor.getClass().getName(), e); - } - } - } - - @Override - public void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo) { - for (BeforeRefreshProcessor processor : processors) { - try { - processor.unRegistryOfBefore(registryInfo); - } catch (Exception e){ - LOGGER.error("BeforeRefreshProcessor: [{}] unRegistry 异常", - processor.getClass().getName(), e); - } - } - } - - @Override - public OrderPriority orderOfBefore() { - return OrderPriority.getHighPriority(); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java new file mode 100644 index 0000000..585000c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java @@ -0,0 +1,129 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.before.RegisterNecessaryBeanProcessor; +import com.gitee.starblues.utils.CommonUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * @author starBlues + * @version 3.0.0 + */ +public abstract class AbstractProcessorFactory implements BeforeRefreshProcessor, AfterRefreshProcessor{ + + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractProcessorFactory.class); + + private final List afterProcessors; + private final List beforeProcessors; + + protected final ProcessorRunMode processorRunMode; + + protected final IntegrationConfiguration configuration; + protected final ConfigurableApplicationContext mainApplicationContext; + + public AbstractProcessorFactory(ConfigurableApplicationContext mainApplicationContext, + IntegrationConfiguration configuration, + ProcessorRunMode processorRunMode) { + this.mainApplicationContext = mainApplicationContext; + this.configuration = configuration; + + this.processorRunMode = processorRunMode; + + List beforeProcessors = new ArrayList<>(); + List afterProcessors = new ArrayList<>(); + addDefaultBeforeProcessor(beforeProcessors); + addDefaultAfterProcessor(afterProcessors); + addDefaultCommonProcessor(beforeProcessors, afterProcessors); + + this.beforeProcessors = beforeProcessors.stream() + .filter(Objects::nonNull) + .sorted(CommonUtils.orderPriority(BeforeRefreshProcessor::orderOfBefore)) + .collect(Collectors.toList()); + this.afterProcessors = afterProcessors.stream() + .filter(Objects::nonNull) + .sorted(CommonUtils.orderPriority(AfterRefreshProcessor::orderOfAfter)) + .collect(Collectors.toList()); + } + + protected abstract void addDefaultBeforeProcessor(List beforeProcessors); + + protected abstract void addDefaultAfterProcessor(List afterProcessors); + + protected abstract void addDefaultCommonProcessor(List beforeProcessors, + List afterProcessors); + + protected void addDefaultCommonProcessor(List beforeProcessors, + List afterProcessors, + Object o){ + if(o instanceof BeforeRefreshProcessor){ + beforeProcessors.add((BeforeRefreshProcessor)o); + } + if(o instanceof AfterRefreshProcessor){ + afterProcessors.add((AfterRefreshProcessor)o); + } + } + + @Override + public void registryOfAfter(SpringPluginRegistryInfo registryInfo) { + for (AfterRefreshProcessor processor : afterProcessors) { + try { + processor.registryOfAfter(registryInfo); + } catch (Exception e){ + LOGGER.error("AfterRefreshProcessor: [{}] registry 异常", + processor.getClass().getName(), e); + } + } + } + + @Override + public void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) { + for (AfterRefreshProcessor processor : afterProcessors) { + try { + processor.unRegistryOfAfter(registryInfo); + } catch (Exception e){ + LOGGER.error("AfterRefreshProcessor: [{}] unRegistry 异常", + processor.getClass().getName(), e); + } + } + } + + @Override + public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { + for (BeforeRefreshProcessor processor : beforeProcessors) { + try { + processor.registryOfBefore(registryInfo); + } catch (Exception e){ + LOGGER.error("BeforeRefreshProcessor: [{}] registry 异常", + processor.getClass().getName(), e); + } + } + } + + @Override + public void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo) { + for (BeforeRefreshProcessor processor : beforeProcessors) { + try { + processor.unRegistryOfBefore(registryInfo); + } catch (Exception e){ + LOGGER.error("BeforeRefreshProcessor: [{}] unRegistry 异常", + processor.getClass().getName(), e); + } + } + } + + private boolean filterProcessorRunMode(ProcessorRunMode processorRunMode){ + if(processorRunMode == ProcessorRunMode.ALL){ + return true; + } + return processorRunMode == this.processorRunMode; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java similarity index 95% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java index cecb3f3..bff1e67 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/AfterRefreshProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.process; +package com.gitee.starblues.spring.processor; import com.gitee.starblues.spring.SpringPluginRegistryInfo; import com.gitee.starblues.utils.OrderPriority; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java similarity index 94% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java index fddb55c..32556d1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/BeforeRefreshProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.process; +package com.gitee.starblues.spring.processor; import com.gitee.starblues.spring.SpringPluginRegistryInfo; import com.gitee.starblues.utils.OrderPriority; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java new file mode 100644 index 0000000..86a0ba2 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java @@ -0,0 +1,46 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.processor.before.RegisterNecessaryBeanProcessor; +import org.springframework.context.ConfigurableApplicationContext; + +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultProcessorFactory extends AbstractProcessorFactory{ + + public DefaultProcessorFactory(ConfigurableApplicationContext mainApplicationContext, + IntegrationConfiguration configuration, + ProcessorRunMode processorRunMode) { + super(mainApplicationContext, configuration, processorRunMode); + } + + @Override + protected void addDefaultBeforeProcessor(List beforeProcessors) { + beforeProcessors.add(new RegisterNecessaryBeanProcessor()); + } + + @Override + protected void addDefaultAfterProcessor(List afterProcessors){ + + } + + @Override + protected void addDefaultCommonProcessor(List beforeProcessors, + List afterProcessors) { + addPluginControllerProcessor(beforeProcessors, afterProcessors); + } + + private void addPluginControllerProcessor(List beforeProcessors, + List afterProcessors){ + if(configuration != null && configuration.enablePluginRestController() + && processorRunMode == ProcessorRunMode.PLUGIN){ + addDefaultCommonProcessor(beforeProcessors, afterProcessors, + new PluginControllerProcessor(mainApplicationContext)); + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerProcessor.java similarity index 94% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerProcessor.java index 5a6024e..87705f5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/PluginControllerProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.process; +package com.gitee.starblues.spring.processor; import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; @@ -35,9 +35,8 @@ public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterR private final RequestMappingHandlerMapping requestMappingHandlerMapping; private final Method getMappingForMethod; - private static PluginControllerProcessor instance; - private PluginControllerProcessor(ConfigurableApplicationContext mainApplicationContext){ + public PluginControllerProcessor(ConfigurableApplicationContext mainApplicationContext){ this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); @@ -50,19 +49,12 @@ public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterR } } - public static PluginControllerProcessor getInstance(ConfigurableApplicationContext mainApplicationContext){ - if(instance == null){ - synchronized (PluginControllerProcessor.class){ - if(instance == null){ - instance = new PluginControllerProcessor(mainApplicationContext); - } - } - } - return instance; - } @Override public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { + ConfigurableApplicationContext mainApplicationContext = registryInfo.getMainApplicationContext(); + + if(getMappingForMethod == null){ return; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java new file mode 100644 index 0000000..01ad061 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java @@ -0,0 +1,24 @@ +package com.gitee.starblues.spring.processor; + +/** + * @author starBlues + * @version 3.0.0 + */ +public enum ProcessorRunMode { + + /** + * 插件方式运行 + */ + PLUGIN, + + /** + * 自己方式运行 + */ + ONESELF, + + /** + * 任意方式运行 + */ + ALL, + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBeanProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/before/RegisterNecessaryBeanProcessor.java similarity index 71% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBeanProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/before/RegisterNecessaryBeanProcessor.java index e473d3a..b0bd62a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/process/before/RegisterNecessaryBeanProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/before/RegisterNecessaryBeanProcessor.java @@ -1,10 +1,9 @@ -package com.gitee.starblues.spring.process.before; +package com.gitee.starblues.spring.processor.before; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.realize.PluginUtils; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.process.BeforeRefreshProcessor; -import com.gitee.starblues.utils.OrderPriority; +import com.gitee.starblues.spring.processor.BeforeRefreshProcessor; import org.springframework.context.ConfigurableApplicationContext; /** @@ -25,13 +24,4 @@ public class RegisterNecessaryBeanProcessor implements BeforeRefreshProcessor { applicationContext.getBeanFactory().registerSingleton("pluginUtils", new PluginUtils(applicationContext)); } - @Override - public void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo) { - - } - - @Override - public OrderPriority orderOfBefore() { - return OrderPriority.getHighPriority(); - } } diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories index 814d4e5..3c901ff 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories @@ -1,4 +1,3 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.gitee.starblues.spring.EmptyAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ com.gitee.starblues.integration.SpringBootPluginStarter \ No newline at end of file -- Gitee From 295343943b5a0eb6d98f1c79e17a6fb3150b2efc Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 2 Dec 2021 15:59:52 +0800 Subject: [PATCH 11/37] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=89=A9=E5=B1=95?= =?UTF-8?q?=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/DefaultRealizeProvider.java | 27 +++-- .../gitee/starblues/core/RealizeProvider.java | 12 ++ .../gitee/starblues/core/ResourceClear.java | 14 +++ .../classloader/CacheMainResourceMatcher.java | 47 ++++++++ .../DefaultMainResourceDefiner.java | 109 ----------------- .../DefaultMainResourceMatcher.java | 57 +++++++++ .../DefaultMainResourcePatternDefiner.java | 94 +++++++++++++++ ...a => EmptyMainResourcePatternDefiner.java} | 10 +- .../core/classloader/MainResourceMatcher.java | 13 ++ ...r.java => MainResourcePatternDefiner.java} | 14 +-- .../core/classloader/PluginClassLoader.java | 111 ++++++++++-------- .../core/loader/DefaultPluginLoader.java | 11 +- .../AutoIntegrationConfiguration.java | 1 + .../integration/IntegrationExtendPoint.java | 76 ++++++++++++ .../integration/SpringBootPluginStarter.java | 46 +------- .../AbstractPluginApplication.java | 4 +- .../application/AutoPluginApplication.java | 4 +- .../application/DefaultPluginApplication.java | 34 ++---- .../manager/DefaultPluginManagerFactory.java | 3 +- .../operator/DefaultPluginOperator.java | 1 + .../operator/PluginOperatorWrapper.java | 5 +- .../spring/BasePluginSpringApplication.java | 18 ++- .../spring/PluginBeanDefinitionLoader.java | 3 +- .../oneself/OneselfSpringApplication.java | 1 + .../spring-configuration-metadata.json | 7 ++ 25 files changed, 461 insertions(+), 261 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/{EmptyMainResourceDefiner.java => EmptyMainResourcePatternDefiner.java} (49%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/{MainResourceDefiner.java => MainResourcePatternDefiner.java} (57%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java index 88f3a12..6a1c3f4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -1,6 +1,7 @@ package com.gitee.starblues.core; -import com.gitee.starblues.core.classloader.DefaultMainResourceDefiner; +import com.gitee.starblues.core.classloader.DefaultMainResourcePatternDefiner; +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.descriptor.ProdPluginDescriptorLoader; @@ -22,21 +23,19 @@ public class DefaultRealizeProvider implements RealizeProvider { private PluginScanner pluginScanner; private PluginDescriptorLoader pluginDescriptorLoader; + private MainResourcePatternDefiner mainResourcePatternDefiner; private PluginLoader pluginLoader; private PluginChecker pluginChecker; private VersionInspector versionInspector; - private final RuntimeMode runtimeMode; - private final String mainPackage; + protected final RuntimeMode runtimeMode; - public DefaultRealizeProvider(RuntimeMode runtimeMode, - String mainPackage){ + public DefaultRealizeProvider(RuntimeMode runtimeMode){ this.runtimeMode = Assert.isNotNull(runtimeMode, "参数 runtimeMode 不能为空"); - this.mainPackage = Assert.isNotEmpty(mainPackage, "参数 mainPackage 不能为空"); - init(); } - protected void init() { + @Override + public void init() { BasePluginScanner basePluginScanner = new BasePluginScanner(); PluginDescriptorLoader pluginDescriptorLoader = null; if(runtimeMode == RuntimeMode.DEV){ @@ -49,11 +48,16 @@ public class DefaultRealizeProvider implements RealizeProvider { setPluginScanner(basePluginScanner); setPluginDescriptorLoader(pluginDescriptorLoader); - setPluginLoader(new DefaultPluginLoader(new DefaultMainResourceDefiner(mainPackage))); + setPluginLoader(new DefaultPluginLoader(this.mainResourcePatternDefiner)); setPluginChecker(new DefaultPluginChecker()); setVersionInspector(new SemverVersionInspector()); } + public void setMainResourcePatternDefiner(MainResourcePatternDefiner mainResourcePatternDefiner){ + this.mainResourcePatternDefiner = Assert.isNotNull(mainResourcePatternDefiner, + "mainResourcePatternDefiner 不能为空"); + } + public void setPluginScanner(PluginScanner pluginScanner) { this.pluginScanner = Assert.isNotNull(pluginScanner, "pluginScanner 不能为空"); } @@ -90,6 +94,11 @@ public class DefaultRealizeProvider implements RealizeProvider { return Assert.isNotNull(pluginDescriptorLoader, "PluginDescriptorLoader 实现不能为空"); } + @Override + public MainResourcePatternDefiner getMainResourcePatternDefiner() { + return Assert.isNotNull(mainResourcePatternDefiner, "MainResourcePatternDefiner 实现不能为空"); + } + @Override public PluginLoader getPluginLoader() { return Assert.isNotNull(pluginLoader, "PluginLoader 实现不能为空"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java index 1a2ca90..d5f1d51 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.loader.PluginLoader; import com.gitee.starblues.core.scanner.PluginScanner; @@ -11,6 +12,11 @@ import com.gitee.starblues.core.version.VersionInspector; */ public interface RealizeProvider { + /** + * 初始化 + */ + void init(); + /** * 当前运行环境 * @return RuntimeMode @@ -29,6 +35,12 @@ public interface RealizeProvider { */ PluginDescriptorLoader getPluginDescriptor(); + /** + * 得到 MainResourcePatternDefiner 实现 + * @return MainResourcePatternDefiner + */ + MainResourcePatternDefiner getMainResourcePatternDefiner(); + /** * 得到 PluginLoader 实现 * @return PluginLoader diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java new file mode 100644 index 0000000..4ea6ac6 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java @@ -0,0 +1,14 @@ +package com.gitee.starblues.core; + +/** + * @author starBlues + * @version 3.0.0 + */ +public interface ResourceClear { + + /** + * 清除资源 + */ + void clear(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java new file mode 100644 index 0000000..587f229 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java @@ -0,0 +1,47 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.core.ResourceClear; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class CacheMainResourceMatcher extends DefaultMainResourceMatcher implements ResourceClear { + + private final Map resourceUrlMatchCache = new ConcurrentHashMap<>(); + private final Map springFactoriesUrlMatchCache = new ConcurrentHashMap<>(); + + public CacheMainResourceMatcher(MainResourcePatternDefiner mainResourcePatternDefiner) { + super(mainResourcePatternDefiner); + } + + @Override + public boolean match(String resourceUrl) { + Boolean match = resourceUrlMatchCache.get(resourceUrl); + if(match == null){ + match = super.match(resourceUrl); + resourceUrlMatchCache.put(resourceUrl, match); + } + return match; + } + + @Override + public boolean matchSpringFactories(String springFactoriesUrl) { + Boolean match = springFactoriesUrlMatchCache.get(springFactoriesUrl); + if(match == null){ + match = super.matchSpringFactories(springFactoriesUrl); + springFactoriesUrlMatchCache.put(springFactoriesUrl, match); + } + return match; + } + + @Override + public void clear(){ + resourceUrlMatchCache.clear(); + springFactoriesUrlMatchCache.clear(); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java deleted file mode 100644 index 3858e1d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceDefiner.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.gitee.starblues.core.classloader; - -import com.gitee.starblues.utils.Assert; -import org.springframework.core.io.support.SpringFactoriesLoader; - -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -/** - * 默认主程序资源定义者 - * @author starBlues - * @version 3.0.0 - */ -public class DefaultMainResourceDefiner implements MainResourceDefiner{ - - private final Set mainClass = new HashSet<>(); - private final Set mainResources = new HashSet<>(); - private final Set springFactories = new HashSet<>(); - - private final String mainPackageName; - - public DefaultMainResourceDefiner(String mainPackageName){ - this.mainPackageName = Assert.isNotEmpty(mainPackageName, - "参数 mainPackageName 不能为空"); - initDefaultClass(mainPackageName); - initDefaultResources(mainPackageName); - initDefaultSpringFactories(); - } - - - @Override - public Set getClassNames() { - return mainClass; - } - - @Override - public Set getResources() { - return mainResources; - } - - @Override - public Set getSpringFactories() { - return springFactories; - } - - protected void initDefaultClass(String mainPackageName) { - // == java == - mainClass.add("java."); - mainClass.add("javax."); - mainClass.add("sun.reflect"); - - // == main == - mainClass.add(mainPackageName); - - // == springboot-plugin-framework == - mainClass.add("com.gitee.starblues"); - - // === spring-boot-starter === - // logback-classic - mainClass.add("ch.qos.logback.classic"); - mainClass.add("org.slf4j.impl"); - // logback-core - mainClass.add("ch.qos.logback.core"); - // log4j-api - mainClass.add("org.apache.logging.log4j"); - // log4j-to-slf4j - mainClass.add("org.apache.logging.slf4j"); - // jul-to-slf4j - mainClass.add("org.slf4j.bridge"); - // slf4j-api - mainClass.add("org.slf4j"); - - // spring-boot - mainClass.add("org.springframework.boot"); - // spring-boot-autoconfigure - mainClass.add("org.springframework.boot.autoconfigure"); - // spring-core spring-context spring-aop spring-beans - mainClass.add("org.aopalliance"); - mainClass.add("org.springframework.aop"); - // spring-beans spring-context spring-core spring-expression - mainClass.add("org.springframework"); - // spring-jcl - mainClass.add("org.apache.commons.logging"); - // snakeyaml - mainClass.add("org.yaml.snakeyaml"); - - // aop - mainClass.add("org.aspectj"); - } - - private void initDefaultResources(String mainPackageName) { - mainResources.add(mainPackageName.replace(".", "/")); - mainResources.add("com/gitee/starblues"); - mainResources.add("org/springframework"); - mainResources.add("org/slf4j/Logger"); - mainResources.add("org/aopalliance"); - mainResources.add("org/aspectj"); - mainResources.add(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION); - } - - private void initDefaultSpringFactories() { - springFactories.add("/spring-boot/"); - springFactories.add("/spring-beans/"); - springFactories.add("/springboot-plugin-framework/"); - // 当前框架名称 - springFactories.add(mainPackageName); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java new file mode 100644 index 0000000..17dfa14 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java @@ -0,0 +1,57 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.util.AntPathMatcher; +import org.springframework.util.PathMatcher; + +import java.util.Collection; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultMainResourceMatcher implements MainResourceMatcher{ + + private final MainResourcePatternDefiner mainResourcePatternDefiner; + private final PathMatcher pathMatcher; + + public DefaultMainResourceMatcher(MainResourcePatternDefiner mainResourcePatternDefiner) { + this.mainResourcePatternDefiner = mainResourcePatternDefiner; + this.pathMatcher = new AntPathMatcher(); + } + + @Override + public boolean match(String resourceUrl) { + Set resourcePatterns = mainResourcePatternDefiner.getResourcePatterns(); + return match(resourcePatterns, resourceUrl); + } + + @Override + public boolean matchSpringFactories(String springFactoriesUrl) { + Set springFactoriesPatterns = mainResourcePatternDefiner.getSpringFactoriesPatterns(); + return match(springFactoriesPatterns, springFactoriesUrl); + } + + private boolean match(Collection patterns, String url){ + if(ObjectUtils.isEmpty(patterns) || ObjectUtils.isEmpty(url)){ + return false; + } + url = formatUrl(url); + for (String pattern : patterns) { + boolean match = pathMatcher.match(pattern, url); + if(match){ + return true; + } + } + return false; + } + + private String formatUrl(String url){ + url = url.replace("\\", AntPathMatcher.DEFAULT_PATH_SEPARATOR); + if(url.startsWith(AntPathMatcher.DEFAULT_PATH_SEPARATOR)){ + url = url.substring(url.indexOf(AntPathMatcher.DEFAULT_PATH_SEPARATOR) + 1); + } + return url; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java new file mode 100644 index 0000000..f9e5b4e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java @@ -0,0 +1,94 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.context.ApplicationContext; + +import java.util.*; + +/** + * 默认主程序资源定义者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultMainResourcePatternDefiner implements MainResourcePatternDefiner { + + private final Set resourcePatterns = new HashSet<>(); + private final Set springFactoriesPatterns = new HashSet<>(); + + private final String mainPackageName; + + public DefaultMainResourcePatternDefiner(String mainPackageName){ + this.mainPackageName = Assert.isNotEmpty(mainPackageName, + "参数 mainPackageName 不能为空"); + initDefaultResources(); + initDefaultSpringFactories(); + } + + @Override + public Set getResourcePatterns() { + return resourcePatterns; + } + + @Override + public Set getSpringFactoriesPatterns() { + return springFactoriesPatterns; + } + + + private void initDefaultResources() { + // == java == + resourcePatterns.add("java/**"); + resourcePatterns.add("javax/**"); + resourcePatterns.add("sun/**"); + + // == main == + resourcePatterns.add(mainPackageName.replace(".", "/")); + + // == springboot-plugin-framework == + resourcePatterns.add("com/gitee/starblues/**"); + + // aop + resourcePatterns.add("org/aspectj/**"); + resourcePatterns.add("org/aopalliance/**"); + + // === spring-boot-starter === + // logback-classic + resourcePatterns.add("ch/qos/logback/classic/**"); + resourcePatterns.add("org/slf4j/impl/**"); + // logback-core + resourcePatterns.add("ch/qos/logback/core/**"); + // log4j-api + resourcePatterns.add("org/apache/logging/log4j/**"); + // log4j-to-slf4j + resourcePatterns.add("org/apache/logging/slf4j/**"); + // slf4j-api jul-to-slf4j(org/slf4j/bridge/**) + resourcePatterns.add("org/slf4j/**"); + + resourcePatterns.add("META-INF/spring.factories"); + + // spring + resourcePatterns.add("org/springframework/**"); + + // spring-boot + resourcePatterns.add("org/springframework/boot/**"); + // spring-boot-autoconfigure + resourcePatterns.add("org/springframework/boot/autoconfigure/**"); + // spring-core spring-context spring-aop spring-beans + resourcePatterns.add("org/aopalliance/**"); + resourcePatterns.add("org/springframework/aop/**"); + // spring-beans spring-context spring-core spring-expression + resourcePatterns.add("org/springframework/**"); + // spring-jcl + resourcePatterns.add("org/apache.commons/logging/**"); + // snakeyaml + resourcePatterns.add("org/yaml/snakeyaml/**"); + } + + private void initDefaultSpringFactories() { + springFactoriesPatterns.add("**/spring-boot/**"); + springFactoriesPatterns.add("**/spring-beans/**"); + // 当前框架名称 + springFactoriesPatterns.add("**/springboot-plugin-framework/**"); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java similarity index 49% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java index 495dd4b..a8338f7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourceDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java @@ -7,19 +7,15 @@ import java.util.Set; * @author starBlues * @version 3.0.0 */ -public class EmptyMainResourceDefiner implements MainResourceDefiner{ - @Override - public Set getClassNames() { - return null; - } +public class EmptyMainResourcePatternDefiner implements MainResourcePatternDefiner { @Override - public Set getResources() { + public Set getResourcePatterns() { return null; } @Override - public Set getSpringFactories() { + public Set getSpringFactoriesPatterns() { return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java new file mode 100644 index 0000000..182fd81 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java @@ -0,0 +1,13 @@ +package com.gitee.starblues.core.classloader; + +/** + * @author starBlues + * @version 1.0 + */ +public interface MainResourceMatcher { + + + boolean match(String resourceUrl); + + boolean matchSpringFactories(String springFactoriesUrl); +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java similarity index 57% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java index c8ea2b3..64fe72f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java @@ -7,26 +7,20 @@ import java.util.Set; * @author starBlues * @version 3.0.0 */ -public interface MainResourceDefiner { +public interface MainResourcePatternDefiner { /** - * 类名 - * @return 类名前缀集合 - */ - Set getClassNames(); - - /** - * 资源名称 + * 资源名称. * @return 资源名称集合 */ - Set getResources(); + Set getResourcePatterns(); /** * spring spi 定义 * @return spring spi 集合 */ - Set getSpringFactories(); + Set getSpringFactoriesPatterns(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index bc0c6ea..fdc3ad4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -1,13 +1,18 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.core.ResourceClear; +import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ResourceUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -16,28 +21,33 @@ import java.util.concurrent.ConcurrentHashMap; * @author starBlues * @version 3.0.0 */ -public class PluginClassLoader extends AbstractPluginClassLoader { +public class PluginClassLoader extends AbstractPluginClassLoader implements ResourceClear { private final Map> pluginClassCache = new ConcurrentHashMap<>(); private final String pluginId; private final ClassLoader parent; private final ResourceLoaderFactory resourceLoaderFactory; - private final MainResourceDefiner mainResourceDefiner; - public PluginClassLoader(String pluginId, Path classpath, ClassLoader parent) { - this(pluginId, classpath, parent, null); - } + private MainResourceMatcher mainResourceMatcher; + - public PluginClassLoader(String pluginId, Path classpath, ClassLoader parent, MainResourceDefiner definer) { + public PluginClassLoader(String pluginId, + Path classpath, + ClassLoader parentClassLoader, + MainResourcePatternDefiner mainResourcePatternDefiner) { resourceLoaderFactory = new ResourceLoaderFactory(); resourceLoaderFactory.addResource(classpath); - this.pluginId = pluginId; - this.parent = parent; - if(definer == null){ - definer = new EmptyMainResourceDefiner(); - } - this.mainResourceDefiner = definer; + + this.pluginId = Assert.isNotEmpty(pluginId, "参数 pluginId 不能为空"); + this.parent = Assert.isNotNull(parentClassLoader, "参数 parentClassLoader 不能为空"); + MainResourcePatternDefiner patternDefiner = Assert.isNotNull(mainResourcePatternDefiner, + "参数 mainResourcePatternDefiner 不能为空"); + setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); + } + + protected void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ + this.mainResourceMatcher = Assert.isNotNull(mainResourceMatcher, "参数 mainResourceMatcher 不能为空"); } @@ -52,9 +62,8 @@ public class PluginClassLoader extends AbstractPluginClassLoader { @Override public Class loadClass(String className) throws ClassNotFoundException { synchronized (getClassLoadingLock(className)) { - Set classNames = mainResourceDefiner.getClassNames(); Class loadedClass = null; - if(exist(classNames, className)){ + if(mainResourceMatcher.match(className.replace(".", "/"))){ try { loadedClass = parent.loadClass(className); } catch (Exception e){ @@ -75,19 +84,9 @@ public class PluginClassLoader extends AbstractPluginClassLoader { } } - @Override - public URL[] getURLs() { - List resources = resourceLoaderFactory.getResources(); - URL[] urls = new URL[resources.size()]; - for (int i = 0; i < resources.size(); i++) { - urls[i] = resources.get(i).getUrl(); - } - return urls; - } - private Class findPluginClass(String name) { synchronized (pluginClassCache){ - Class aClass = null; + Class aClass; String formatClassName = formatClassName(name); aClass = pluginClassCache.get(formatClassName); if (aClass != null) { @@ -98,8 +97,7 @@ public class PluginClassLoader extends AbstractPluginClassLoader { if(resource == null){ return null; } - byte[] bytes = null; - bytes = resource.getBytes(); + byte[] bytes = resource.getBytes(); aClass = defineClass(name, bytes, 0, bytes.length ); if(aClass == null) { return null; @@ -107,20 +105,30 @@ public class PluginClassLoader extends AbstractPluginClassLoader { if (aClass.getPackage() == null) { int lastDotIndex = name.lastIndexOf( '.' ); String packageName = (lastDotIndex >= 0) ? name.substring( 0, lastDotIndex) : ""; - definePackage(packageName, null, null, null, null, null, null, null ); + definePackage(packageName, null, null, null, + null, null, null, null ); } pluginClassCache.put(name, aClass); return aClass; } } + @Override + public URL[] getURLs() { + List resources = resourceLoaderFactory.getResources(); + URL[] urls = new URL[resources.size()]; + for (int i = 0; i < resources.size(); i++) { + urls[i] = resources.get(i).getUrl(); + } + return urls; + } + @Override public InputStream getResourceAsStream(String name) { name = formatResourceName(name); - Set resources = mainResourceDefiner.getResources(); InputStream inputStream = null; - if(exist(resources, name)){ + if(mainResourceMatcher.match(name)){ try { inputStream = parent.getResourceAsStream(name); } catch (Exception e){ @@ -136,9 +144,12 @@ public class PluginClassLoader extends AbstractPluginClassLoader { @Override public URL getResource(String name) { name = formatResourceName(name); - Set resources = mainResourceDefiner.getResources(); - if(exist(resources, name)){ - return parent.getResource(name); + URL url = null; + if(mainResourceMatcher.match(name)){ + url = parent.getResource(name); + } + if(url != null){ + return url; } Resource resource = resourceLoaderFactory.findResource(name); if(resource == null){ @@ -151,15 +162,20 @@ public class PluginClassLoader extends AbstractPluginClassLoader { public Enumeration getResources(String name) throws IOException { name = formatResourceName(name); Vector vector = new Vector<>(); - Set resources = mainResourceDefiner.getResources(); - Set springFactories = mainResourceDefiner.getSpringFactories(); - if(exist(resources, name)){ + if(mainResourceMatcher.match(name)){ Enumeration enumeration = parent.getResources(name); while (enumeration.hasMoreElements()){ URL url = enumeration.nextElement(); - String path = url.getPath(); - if(exist(springFactories, path)){ - vector.add(url); + try { + URI uri = url.toURI(); + String path = Paths.get(uri).toString(); + if(mainResourceMatcher.matchSpringFactories(path)){ + vector.add(url); + } + } catch (Exception e) { + if(mainResourceMatcher.matchSpringFactories(url.getPath())){ + vector.add(url); + } } } } @@ -199,23 +215,14 @@ public class PluginClassLoader extends AbstractPluginClassLoader { return newPath.toString(); } - private boolean exist(Set set, String name){ - // TODO 匹配方式有问题 - if(ObjectUtils.isEmpty(set) || ObjectUtils.isEmpty(name)){ - return false; - } - for (String value : set) { - if(name.contains(value)){ - return true; - } - } - return false; - } - + @Override public void clear(){ synchronized (pluginClassCache){ pluginClassCache.clear(); resourceLoaderFactory.clear(); + if(mainResourceMatcher instanceof ResourceClear){ + ((ResourceClear) mainResourceMatcher).clear(); + } } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java index 3476ca2..334940d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java @@ -1,7 +1,7 @@ package com.gitee.starblues.core.loader; import com.gitee.starblues.core.PluginState; -import com.gitee.starblues.core.classloader.MainResourceDefiner; +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; @@ -24,12 +24,13 @@ import java.util.Objects; */ public class DefaultPluginLoader implements PluginLoader{ - private final MainResourceDefiner mainResourceDefiner; + private final MainResourcePatternDefiner mainResourcePatternDefiner; private final List> classLoaderCache = new ArrayList<>(); - public DefaultPluginLoader(MainResourceDefiner mainResourceDefiner) { - this.mainResourceDefiner = mainResourceDefiner; + public DefaultPluginLoader(MainResourcePatternDefiner mainResourcePatternDefiner) { + this.mainResourcePatternDefiner = Assert.isNotNull(mainResourcePatternDefiner, + "参数 mainResourcePatternDefiner 不能为空"); } @Override @@ -68,7 +69,7 @@ public class DefaultPluginLoader implements PluginLoader{ } if(pnClassLoader == null){ pnClassLoader = new PluginClassLoader(pluginId, classPath, getParentClassLoader(), - mainResourceDefiner); + mainResourcePatternDefiner); classLoaderCache.add(new WeakReference<>(pnClassLoader)); } return pnClassLoader; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index b151ede..bfe7f1a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -19,6 +19,7 @@ import java.util.Set; public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguration{ public static final String ENABLE_KEY = "plugin.enable"; + public static final String ENABLE_STARTER_KEY = "plugin.enable-starter"; /** * 是否启用插件功能 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java new file mode 100644 index 0000000..987dc68 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java @@ -0,0 +1,76 @@ +package com.gitee.starblues.integration; + +import com.gitee.starblues.core.DefaultRealizeProvider; +import com.gitee.starblues.core.RealizeProvider; +import com.gitee.starblues.core.classloader.DefaultMainResourcePatternDefiner; +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; +import com.gitee.starblues.integration.operator.DefaultPluginOperator; +import com.gitee.starblues.integration.operator.PluginOperator; +import com.gitee.starblues.integration.operator.PluginOperatorWrapper; +import com.gitee.starblues.integration.user.DefaultPluginUser; +import com.gitee.starblues.integration.user.PluginUser; +import com.gitee.starblues.spring.DefaultSpringPlugin; +import com.gitee.starblues.spring.SpringPlugin; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.support.GenericApplicationContext; + +/** + * 集成扩展点 + * @author starBlues + * @version 3.0.0 + */ +public class IntegrationExtendPoint { + + private final GenericApplicationContext applicationContext; + private final IntegrationConfiguration configuration; + + public IntegrationExtendPoint(GenericApplicationContext applicationContext, + IntegrationConfiguration configuration) { + this.applicationContext = applicationContext; + this.configuration = configuration; + } + + @Bean + @ConditionalOnMissingBean + public PluginUser createPluginUser() { + return new DefaultPluginUser(applicationContext); + } + + @Bean + @ConditionalOnMissingBean + public PluginOperator createPluginOperator(RealizeProvider realizeProvider, + SpringPlugin springPlugin) { + PluginOperator pluginOperator = new DefaultPluginOperator( + applicationContext, + springPlugin, + realizeProvider, + configuration + ); + return new PluginOperatorWrapper(pluginOperator, configuration); + } + + @Bean + @ConditionalOnMissingBean + public SpringPlugin createSpringPlugin(){ + return new DefaultSpringPlugin(applicationContext); + } + + @Bean + @ConditionalOnMissingBean + public RealizeProvider realizeProvider(MainResourcePatternDefiner mainResourcePatternDefiner) { + DefaultRealizeProvider defaultRealizeProvider = new DefaultRealizeProvider(configuration.environment()); + if(mainResourcePatternDefiner != null){ + defaultRealizeProvider.setMainResourcePatternDefiner(mainResourcePatternDefiner); + } + defaultRealizeProvider.init(); + return defaultRealizeProvider; + } + + @Bean + @ConditionalOnMissingBean + public MainResourcePatternDefiner mainResourcePatternDefiner(){ + return new DefaultMainResourcePatternDefiner(configuration.mainPackage()); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java index 8f85197..feddab2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java @@ -1,18 +1,10 @@ package com.gitee.starblues.integration; -import com.gitee.starblues.core.RealizeProvider; import com.gitee.starblues.integration.application.AutoPluginApplication; -import com.gitee.starblues.integration.operator.PluginOperator; -import com.gitee.starblues.integration.user.PluginUser; -import com.gitee.starblues.realize.PluginUtils; -import com.gitee.starblues.spring.SpringPlugin; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.GenericApplicationContext; +import org.springframework.context.annotation.Import; /** * @author starBlues @@ -20,36 +12,8 @@ import org.springframework.context.support.GenericApplicationContext; */ @Configuration(proxyBeanMethods = true) @EnableConfigurationProperties(AutoIntegrationConfiguration.class) -@ConditionalOnProperty(value = AutoIntegrationConfiguration.ENABLE_KEY, havingValue = "true", matchIfMissing = false) -public class SpringBootPluginStarter extends AutoPluginApplication { - - - @Bean - @ConditionalOnMissingBean - @Override - protected PluginUser createPluginUser(ApplicationContext applicationContext) { - return super.createPluginUser(applicationContext); - } - - @Bean - @ConditionalOnMissingBean - @Override - protected PluginOperator createPluginOperator(ApplicationContext applicationContext, IntegrationConfiguration configuration) { - return super.createPluginOperator(applicationContext, configuration); - } - - @Bean - @ConditionalOnMissingBean - @Override - protected SpringPlugin createSpringPlugin(GenericApplicationContext applicationContext) { - return super.createSpringPlugin(applicationContext); - } - - @Bean - @ConditionalOnMissingBean - @Override - protected RealizeProvider createRealizeProvider(IntegrationConfiguration configuration) { - return super.createRealizeProvider(configuration); - } +@ConditionalOnExpression("${" + AutoIntegrationConfiguration.ENABLE_STARTER_KEY + ":true}") +@Import(AutoPluginApplication.class) +public class SpringBootPluginStarter { } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java index 4079a72..ab044c2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java @@ -86,8 +86,8 @@ public abstract class AbstractPluginApplication implements PluginApplication { // no show exception } if(configuration == null){ - throw new BeanCreationException("Not Found IntegrationConfiguration, Please define " + - "IntegrationConfiguration to Spring Bean."); + throw new BeanCreationException("没有发现 Bean, " + + "请在 Spring 容器中将 定义为Bean"); } return configuration; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java index 31575c0..7a2705f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java @@ -1,10 +1,11 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.integration.pf4j.Pf4jFactory; +import com.gitee.starblues.integration.IntegrationExtendPoint; import com.gitee.starblues.integration.listener.PluginInitializerListener; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Import; /** * 自动初始化的 PluginApplication。该PluginApplication 基于 Spring InitializingBean 自动初始化插件。 @@ -12,6 +13,7 @@ import org.springframework.context.ApplicationContextAware; * @author starBlues * @version 2.2.0 */ +@Import(IntegrationExtendPoint.class) public class AutoPluginApplication extends DefaultPluginApplication implements PluginApplication, InitializingBean, ApplicationContextAware { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index 836c7ba..1362976 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -2,6 +2,8 @@ package com.gitee.starblues.integration.application; import com.gitee.starblues.core.DefaultRealizeProvider; import com.gitee.starblues.core.RealizeProvider; +import com.gitee.starblues.core.classloader.DefaultMainResourcePatternDefiner; +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; @@ -11,6 +13,8 @@ import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; import com.gitee.starblues.spring.DefaultSpringPlugin; import com.gitee.starblues.spring.SpringPlugin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; @@ -26,6 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean; */ public class DefaultPluginApplication extends AbstractPluginApplication { + private final static Logger LOG = LoggerFactory.getLogger(DefaultPluginApplication.class); private PluginUser pluginUser; private PluginOperator pluginOperator; @@ -42,10 +47,14 @@ public class DefaultPluginApplication extends AbstractPluginApplication { if(beInitialized.get()){ throw new RuntimeException("Plugin has been initialized"); } + // 检查Configuration IntegrationConfiguration configuration = getConfiguration(applicationContext); pluginUser = createPluginUser(applicationContext); - pluginOperator = createPluginOperator(applicationContext, configuration); + pluginOperator = createPluginOperator(applicationContext); try { + if(!(pluginOperator instanceof PluginOperatorWrapper)){ + pluginOperator = new PluginOperatorWrapper(pluginOperator, configuration); + } setBeanFactory(applicationContext); pluginOperator.initPlugins(listener); beInitialized.set(true); @@ -60,33 +69,16 @@ public class DefaultPluginApplication extends AbstractPluginApplication { * @return PluginUser */ protected PluginUser createPluginUser(ApplicationContext applicationContext){ - return new DefaultPluginUser(applicationContext); + return applicationContext.getBean(PluginUser.class); } /** * 创建插件操作者。子类可扩展 * @param applicationContext Spring ApplicationContext - * @param configuration 当前集成的配置 * @return PluginOperator */ - protected PluginOperator createPluginOperator(ApplicationContext applicationContext, - IntegrationConfiguration configuration){ - GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext; - PluginOperator pluginOperator = new DefaultPluginOperator( - genericApplicationContext, - createSpringPlugin(genericApplicationContext), - createRealizeProvider(configuration), - configuration - ); - return new PluginOperatorWrapper(pluginOperator, configuration); - } - - protected SpringPlugin createSpringPlugin(GenericApplicationContext applicationContext){ - return new DefaultSpringPlugin(applicationContext); - } - - protected RealizeProvider createRealizeProvider(IntegrationConfiguration configuration){ - return new DefaultRealizeProvider(configuration.environment(), configuration.mainPackage()); + protected PluginOperator createPluginOperator(ApplicationContext applicationContext){ + return applicationContext.getBean(PluginOperator.class); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java index 5f93d33..c150b8c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java @@ -11,6 +11,7 @@ import java.util.List; * @author starBlues * @version 3.0.0 */ +@Deprecated public class DefaultPluginManagerFactory implements PluginManagerFactory{ private final IntegrationConfiguration configuration; @@ -27,7 +28,7 @@ public class DefaultPluginManagerFactory implements PluginManagerFactory{ "配置[mainPackage]不能为空"); List pluginPaths = Assert.isNotEmpty(configuration.pluginPath(), "配置[pluginPath]不能为空"); - RealizeProvider realizeProvider = new DefaultRealizeProvider(runtimeMode, mainPackageName); + RealizeProvider realizeProvider = new DefaultRealizeProvider(runtimeMode); return new DefaultPluginManager(realizeProvider, pluginPaths); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 2756ba2..453fb0c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -58,6 +58,7 @@ public class DefaultPluginOperator implements PluginOperator { // 触发插件初始化监听器 //pluginInitializerListenerFactory.before(); if(!configuration.enable()){ + log.info("插件功能已被禁用!"); // 如果禁用的话, 直接返回 //pluginInitializerListenerFactory.complete(); return false; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 1c940d9..690a4ef 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -39,6 +39,9 @@ public class PluginOperatorWrapper implements PluginOperator{ @Override public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception { + if(isDisable()){ + return false; + } return pluginOperator.initPlugins(pluginInitializerListener); } @@ -197,7 +200,7 @@ public class PluginOperatorWrapper implements PluginOperator{ return false; } // 如果禁用的话, 直接返回 - log.info("The Plugin module is disabled!"); + log.info("插件功能已被禁用!"); return true; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java index 03e43f6..32e79b3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java @@ -1,5 +1,6 @@ package com.gitee.starblues.spring; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.spring.environment.PluginEnvironmentProcessor; import com.gitee.starblues.spring.environment.PluginLocalConfigFileProcessor; import com.gitee.starblues.utils.Assert; @@ -9,9 +10,13 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -78,6 +83,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ throw new RuntimeException("已经运行了PluginSpringApplication, 无法再运行"); } processEnvironment(); + addPluginEnvironment(); loadBean(); refresh(); isStarted.set(true); @@ -86,7 +92,6 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } - protected void processEnvironment() { List orderPluginEnvironmentProcessor = CommonUtils.order(environmentProcessors, Ordered::getOrder); @@ -96,6 +101,17 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } } + + private void addPluginEnvironment() { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + Map pluginEnvironment = new HashMap<>(); + pluginEnvironment.put(AutoIntegrationConfiguration.ENABLE_KEY, false); + pluginEnvironment.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); + environment.getPropertySources().addFirst(new MapPropertySource("pluginEnvironment", pluginEnvironment)); + + } + + protected void loadBean() { beanDefinitionLoader.load(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java index 7efe8ac..2ee5614 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java @@ -26,6 +26,7 @@ import org.springframework.util.StringUtils; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.HashSet; +import java.util.Objects; import java.util.Set; /** @@ -119,7 +120,7 @@ public class PluginBeanDefinitionLoader { } private void load(Resource source) { - if (source.getFilename().endsWith(".groovy")) { + if (Objects.requireNonNull(source.getFilename()).endsWith(".groovy")) { if (this.groovyReader == null) { throw new BeanDefinitionStoreException("Cannot load Groovy beans without Groovy on classpath"); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java index 760f1d3..0f0452c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -70,6 +70,7 @@ public class OneselfSpringApplication extends SpringApplication { Map env = new HashMap<>(); // 禁用插件的自动装配 env.put(AutoIntegrationConfiguration.ENABLE_KEY, false); + env.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); String contextPath = getContextPath(environment); env.put("server.servlet.context-path", contextPath); LOG.info("当前应用接口前缀为: {}", contextPath); diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json index 2e53f9f..420f888 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json @@ -14,6 +14,13 @@ "description": "是否启用插件功能", "defaultValue": true }, + { + "name": "plugin.enable-starter", + "type": "java.lang.Boolean", + "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", + "description": "是否启用starter自动装配功能", + "defaultValue": true + }, { "name": "plugin.runMode", "type": "java.lang.String", -- Gitee From 172459a6b3f38f93c5e346c8841830a13f2c64fc Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 2 Dec 2021 17:06:33 +0800 Subject: [PATCH 12/37] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../spring/BasePluginSpringApplication.java | 16 ++++++- .../spring/PluginApplicationContext.java | 2 +- .../environment/LocalConfigFileLoader.java | 7 --- .../PluginLocalConfigFileProcessor.java | 48 ++++++++++++++----- .../starblues/utils/PluginFileUtils.java | 17 +++++++ 5 files changed, 68 insertions(+), 22 deletions(-) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java index 32e79b3..9f0b086 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java @@ -1,12 +1,16 @@ package com.gitee.starblues.spring; +import com.gitee.starblues.core.RuntimeMode; import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.environment.PluginEnvironmentProcessor; import com.gitee.starblues.spring.environment.PluginLocalConfigFileProcessor; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.Ordered; @@ -31,6 +35,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ private final DefaultListableBeanFactory beanFactory; private final PluginApplicationContext applicationContext; + private final IntegrationConfiguration configuration; private final PluginBeanDefinitionLoader beanDefinitionLoader; private final String configFileName; private final List environmentProcessors; @@ -52,6 +57,8 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ this.beanFactory = new PluginListableBeanFactory(mainApplicationContext); this.beanFactory.setBeanClassLoader(classLoader); + this.configuration = mainApplicationContext.getBean(AutoIntegrationConfiguration.class); + this.applicationContext = new PluginApplicationContext(beanFactory, classLoader); this.beanDefinitionLoader = new PluginBeanDefinitionLoader(beanFactory, primarySources); this.configFileName = configFileName; @@ -61,9 +68,9 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ protected void addDefaultEnvironmentProcessor(){ - PluginLocalConfigFileProcessor configFileProcessor = new PluginLocalConfigFileProcessor(); + PluginLocalConfigFileProcessor configFileProcessor = new PluginLocalConfigFileProcessor(configuration); if(!ObjectUtils.isEmpty(configFileName)){ - configFileProcessor.setSearchNames(configFileName); + configFileProcessor.setSearchNames(PluginFileUtils.getFileName(configFileName)); } addEnvironmentProcessor(configFileProcessor); } @@ -84,6 +91,7 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } processEnvironment(); addPluginEnvironment(); + addDefaultProcessor(); loadBean(); refresh(); isStarted.set(true); @@ -108,7 +116,11 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ pluginEnvironment.put(AutoIntegrationConfiguration.ENABLE_KEY, false); pluginEnvironment.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); environment.getPropertySources().addFirst(new MapPropertySource("pluginEnvironment", pluginEnvironment)); + } + private void addDefaultProcessor() { + // 注册 ConfigurationPropertiesBindingPostProcessor, 用于将配置信息绑定到Bean上 + ConfigurationPropertiesBindingPostProcessor.register(applicationContext); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java index 63da2e7..42955e1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java @@ -14,7 +14,7 @@ import org.springframework.core.io.ResourceLoader; */ public class PluginApplicationContext extends AnnotationConfigApplicationContext { - private ResourceLoader resourceLoader; + private final ResourceLoader resourceLoader; public PluginApplicationContext(DefaultListableBeanFactory beanFactory, ClassLoader classLoader) { super(beanFactory); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java deleted file mode 100644 index 265fd73..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/LocalConfigFileLoader.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.gitee.starblues.spring.environment; - -/** - * @author starBlues - */ -public class LocalConfigFileLoader { -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java index 2a3eae9..0086b66 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java @@ -1,5 +1,7 @@ package com.gitee.starblues.spring.environment; +import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ResourceUtils; @@ -44,7 +46,8 @@ import java.util.stream.Stream; */ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcessor { - private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"; + private static final String DEFAULT_SEARCH_LOCATIONS = + "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"; private static final String DEFAULT_NAMES = "application"; @@ -98,11 +101,35 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso private int order = DEFAULT_ORDER; - public PluginLocalConfigFileProcessor() { + public PluginLocalConfigFileProcessor(IntegrationConfiguration configuration) { Set filteredProperties = new HashSet<>(); filteredProperties.add("spring.profiles.active"); filteredProperties.add("spring.profiles.include"); LOAD_FILTERED_PROPERTY = Collections.unmodifiableSet(filteredProperties); + + resolveSearchLocations(configuration); + } + + /** + * 根据环境设置查询配置文件路径 + * @param configuration IntegrationConfiguration + */ + private void resolveSearchLocations(IntegrationConfiguration configuration) { + RuntimeMode runtimeMode = configuration.environment(); + if(runtimeMode== RuntimeMode.DEV){ + setSearchLocations("classpath:/"); + } else { + String pluginConfigFilePath = configuration.pluginConfigFilePath(); + if(ObjectUtils.isEmpty(pluginConfigFilePath)){ + pluginConfigFilePath = ""; + } else { + pluginConfigFilePath = "file:" + pluginConfigFilePath + ","; + } + // 生产环境读取文件顺序: + // pluginConfigFilePath配置的目录 > 当前插件jar包目录 > 当前插件jar包/config/*/ 目录 > 当前插件包/config/ 下的目录 > classpath:/ + pluginConfigFilePath = pluginConfigFilePath + "file:./,file:./config/*/,file:./config/,classpath:/"; + setSearchLocations(pluginConfigFilePath); + } } @Override @@ -593,16 +620,8 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso this.environment.addActiveProfile(profile); } - private Set getSearchLocations() { - Set locations = getSearchLocations(CONFIG_ADDITIONAL_LOCATION_PROPERTY); - if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) { - locations.addAll(getSearchLocations(CONFIG_LOCATION_PROPERTY)); - } - else { - locations.addAll( - asResolvedSet(PluginLocalConfigFileProcessor.this.searchLocations, DEFAULT_SEARCH_LOCATIONS)); - } - return locations; + private List getSearchLocations() { + return asResolvedList(PluginLocalConfigFileProcessor.this.searchLocations, DEFAULT_SEARCH_LOCATIONS); } private Set getSearchLocations(String propertyName) { @@ -650,6 +669,11 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso return new LinkedHashSet<>(list); } + private List asResolvedList(String value, String fallback) { + return Arrays.asList(ObjectUtils.trimArrayElements(ObjectUtils.commaDelimitedListToStringArray( + (value != null) ? this.environment.resolvePlaceholders(value) : fallback))); + } + private void assertValidConfigName(String name) { Assert.state(!name.contains("*"), () -> "Config name '" + name + "' cannot contain wildcards"); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java index 0dc7ce8..d9230ac 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java @@ -24,6 +24,8 @@ import java.util.List; */ public final class PluginFileUtils { + private static final String FILE_POINT = "."; + private PluginFileUtils(){} @@ -117,5 +119,20 @@ public final class PluginFileUtils { return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".jar"); } + /** + * 得到文件名称 + * @param fileName 原始文件名称. 比如: file.txt + * @return String + */ + public static String getFileName(String fileName){ + if(ObjectUtils.isEmpty(fileName)){ + return fileName; + } + if(fileName.lastIndexOf(FILE_POINT) > 0){ + return fileName.substring(0, fileName.lastIndexOf(FILE_POINT)); + } else { + return fileName; + } + } } -- Gitee From 5e2742dd9c89d3d2b4756ca74feef87ed2ee117d Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 2 Dec 2021 17:57:40 +0800 Subject: [PATCH 13/37] =?UTF-8?q?=E4=BF=AE=E6=94=B9jar=20loader?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/classloader/AbstractResourceLoader.java | 6 +----- .../gitee/starblues/core/classloader/ClassPathLoader.java | 2 +- .../starblues/core/classloader/JarResourceLoader.java | 8 ++++++-- .../starblues/core/classloader/PluginClassLoader.java | 3 +++ .../gitee/starblues/core/scanner/BasePluginScanner.java | 6 +++--- .../com/gitee/starblues/core/scanner/ProdPathResolve.java | 2 +- .../environment/PluginLocalConfigFileProcessor.java | 8 +++++++- 7 files changed, 22 insertions(+), 13 deletions(-) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index bca2d1a..3e8048e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -46,11 +46,7 @@ public abstract class AbstractResourceLoader { } public Resource findResource(final String name) { - String queryName = name; - if(name.endsWith(ResourceUtils.PACKAGE_SPLIT)){ - queryName = name.substring(0, name.lastIndexOf(ResourceUtils.PACKAGE_SPLIT)); - } - return resourceCache.get(queryName); + return resourceCache.get(name); } public InputStream getInputStream(final String name) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java index 37fab91..996b6b1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -56,7 +56,7 @@ public class ClassPathLoader extends AbstractResourceLoader{ private void loadResource(File file, String packageName) throws Exception{ if(file.isDirectory()){ - addResource(file, packageName, null); + addResource(file, packageName + ResourceUtils.PACKAGE_SPLIT, null); return; } try (FileInputStream fileInputStream = new FileInputStream(file)) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index 7cc5e59..44302b5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -32,10 +32,15 @@ public class JarResourceLoader extends AbstractResourceLoader{ ){ JarEntry jarEntry = null; while ((jarEntry = jarStream.getNextJarEntry()) != null) { + String name = jarEntry.getName(); + URL url = new URL(baseUrl.toString() + name); if (jarEntry.isDirectory()) { + Resource resource = new Resource( + name, baseUrl, url, null + ); + addResource(name, resource); continue; } - String name = jarEntry.getName(); if (existResource(name)) { continue; } @@ -46,7 +51,6 @@ public class JarResourceLoader extends AbstractResourceLoader{ while ((len = jarStream.read(bytes)) > 0) { out.write(bytes, 0, len); } - URL url = new URL(baseUrl.toString() + name); Resource resource = new Resource( name, baseUrl, url, out.toByteArray() ); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index fdc3ad4..f61feab 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -212,6 +212,9 @@ public class PluginClassLoader extends AbstractPluginClassLoader implements Reso newPath.append(ResourceUtils.PACKAGE_SPLIT).append(s); } } + if(resourceName.endsWith(ResourceUtils.PACKAGE_SPLIT)){ + newPath.append(ResourceUtils.PACKAGE_SPLIT); + } return newPath.toString(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java index fd115e8..40f3ab6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java @@ -23,6 +23,9 @@ public class BasePluginScanner implements PluginScanner{ @Override public List scan(List rootDir) { List pluginPaths = new ArrayList<>(); + if(pathResolve == null){ + return pluginPaths; + } for (String dir : rootDir) { if(ObjectUtils.isEmpty(dir)){ continue; @@ -40,9 +43,6 @@ public class BasePluginScanner implements PluginScanner{ if(currentFile == null || !currentFile.exists()){ return; } - if(pathResolve == null){ - return; - } Path currentPath = currentFile.toPath(); currentPath = pathResolve.resolve(currentPath); if(currentPath != null){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java index 7f071cb..19bfad4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java @@ -31,7 +31,7 @@ public class ProdPathResolve implements PathResolve{ public Path resolve(Path path) { String fileName = path.getFileName().toString(); for (String extensionName : extensionNames) { - boolean exist = fileName.toLowerCase().endsWith(extensionName.toUpperCase()); + boolean exist = fileName.toLowerCase().endsWith(extensionName.toLowerCase()); if(exist){ return path; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java index 0086b66..7282343 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java @@ -31,6 +31,7 @@ import org.springframework.core.io.support.SpringFactoriesLoader; import java.io.File; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; @@ -123,7 +124,12 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso if(ObjectUtils.isEmpty(pluginConfigFilePath)){ pluginConfigFilePath = ""; } else { - pluginConfigFilePath = "file:" + pluginConfigFilePath + ","; + Path path = Paths.get(pluginConfigFilePath); + if(Files.exists(path)){ + pluginConfigFilePath = path.toUri().toString() + ","; + } else { + pluginConfigFilePath = ""; + } } // 生产环境读取文件顺序: // pluginConfigFilePath配置的目录 > 当前插件jar包目录 > 当前插件jar包/config/*/ 目录 > 当前插件包/config/ 下的目录 > classpath:/ -- Gitee From 78f874c539a4af6d0cedb1889f498c92865752da Mon Sep 17 00:00:00 2001 From: StarBlues Date: Tue, 7 Dec 2021 18:00:23 +0800 Subject: [PATCH 14/37] 3.0.0-v2 --- .../annotation/invoke/InvokeBean.java | 26 +++ .../annotation/invoke/InvokeParam.java | 21 ++ .../process/pipe/PluginInfoContainers.java | 1 + .../process/pipe/classs/PluginClassGroup.java | 13 ++ .../process/pipe/extract/ExtractFactory.java | 16 +- .../application/EmptyPluginApplication.java | 71 ++++++ .../operator/EmptyPluginOperator.java | 111 +++++++++ .../integration/user/EmptyPluginUser.java | 60 +++++ ...va => DefaultPluginSpringApplication.java} | 106 ++++++--- .../starblues/spring/DefaultRegistryInfo.java | 14 +- .../starblues/spring/DefaultSpringPlugin.java | 37 +-- .../DefaultSpringPluginRegistryInfo.java | 11 +- .../spring/PluginSpringApplication.java | 13 +- .../gitee/starblues/spring/RegistryInfo.java | 12 + .../gitee/starblues/spring/SpringPlugin.java | 20 +- .../spring/listener/BeanRegistryListener.java | 61 +++++ .../spring/listener/ClassScannerListener.java | 132 +++++++++++ .../InvokeOtherPluginRegistryListener.java | 54 +++++ .../ListenerRunMode.java} | 18 +- .../NecessaryBeanRegistryListener.java} | 27 ++- .../PluginControllerRegistryListener.java | 220 ++++++++++++++++++ .../PluginSpringApplicationRunListener.java | 42 ++++ .../PluginSpringApplicationRunListeners.java | 94 ++++++++ .../OneselfApplicationContextListener.java | 62 +++++ .../OneselfPluginSpringApplication.java | 46 +--- .../oneself/OneselfSpringApplication.java | 118 ++++++---- .../OneselfSpringPluginRegistryInfo.java | 51 ++++ .../processor/AbstractProcessorFactory.java | 129 ---------- .../processor/AfterRefreshProcessor.java | 37 --- .../processor/BeanRegistryProcessor.java | 30 +++ .../processor/BeforeRefreshProcessor.java | 35 --- .../processor/ClassScannerProcessor.java | 135 +++++++++++ .../processor/DefaultProcessorFactory.java | 46 ---- .../FrameDefineBeanRegistryProcessor.java | 30 +++ .../processor/InvokeOtherPluginProcessor.java | 123 ++++++++++ .../OneselfBeanRegistryProcessor.java | 30 +++ ...=> PluginControllerRegistryProcessor.java} | 78 +++---- .../processor/SpringPluginProcessor.java | 49 ++++ .../SpringPluginProcessorFactory.java | 104 +++++++++ .../classgroup/CallerClassGroup.java | 24 ++ .../classgroup/ComposeClassGroup.java | 24 ++ .../classgroup/PluginClassGroup.java | 35 +++ .../processor/invoke/InvokeBeanFactory.java | 50 ++++ .../processor/invoke/InvokeProxyHandler.java | 144 ++++++++++++ .../processor/invoke/InvokeSupperCache.java | 80 +++++++ .../PluginClassPathBeanDefinitionScanner.java | 23 ++ .../java/com/gitee/starblues/utils/Order.java | 16 ++ .../com/gitee/starblues/utils/ScanUtils.java | 17 ++ 48 files changed, 2219 insertions(+), 477 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{BasePluginSpringApplication.java => DefaultPluginSpringApplication.java} (54%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{processor/ProcessorRunMode.java => listener/ListenerRunMode.java} (36%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{processor/before/RegisterNecessaryBeanProcessor.java => listener/NecessaryBeanRegistryListener.java} (50%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/{PluginControllerProcessor.java => PluginControllerRegistryProcessor.java} (82%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java new file mode 100644 index 0000000..60b8fd4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java @@ -0,0 +1,26 @@ +package com.gitee.starblues.annotation.invoke; + +import java.lang.annotation.*; + +/** + * @author starBlues + * @version 1.0 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface InvokeBean { + + /** + * bean 名称 + * @return String + */ + String value(); + + /** + * 可指定具体,插件id. 可选. 如果不填, 默认会进行所有插件扫描 + * @return String + */ + String pluginId(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java new file mode 100644 index 0000000..eda3df3 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java @@ -0,0 +1,21 @@ +package com.gitee.starblues.annotation.invoke; + +import java.lang.annotation.*; + +/** + * @author starBlues + * @version 1.0 + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface InvokeParam { + + /** + * 自定义参数名称 + * @return 参数名称 + */ + String value(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java index 4d1a53c..7c482e1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java @@ -11,6 +11,7 @@ import java.util.concurrent.ConcurrentHashMap; * @author starBlues * @version 2.4.0 */ +@Deprecated public class PluginInfoContainers { private final static Map PLUGIN_APPLICATION_CONTEXTS = diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java index 99dbf3c..77a7cf4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java @@ -10,6 +10,19 @@ import com.gitee.starblues.realize.BasePlugin; */ public interface PluginClassGroup { + String KEY = "PluginClassGroup_"; + + String OTHER_CLASS_GROUP_ID = KEY + "otherClass"; + + /** + * 得到全分组id + * @param groupId 分组id + * @return String + */ + static String getFullId(String groupId){ + return KEY + groupId; + } + /** * 组id * @return 组id diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java index 3c218be..7a6278f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java @@ -164,6 +164,7 @@ public class ExtractFactory { * @param 接口类型泛型 * @return 扩展实现集合 */ + @SuppressWarnings("unchecked") public List getExtractByInterClass(String pluginId, Class interfaceClass){ if(interfaceClass == null){ return Collections.emptyList(); @@ -173,10 +174,11 @@ public class ExtractFactory { if(extractCoordinateObjectMap == null || extractCoordinateObjectMap.isEmpty()){ return Collections.emptyList(); } - for (Object o : extractCoordinateObjectMap.values()) { - Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(o.getClass()); + for (ExtractWrapper wrapper : extractCoordinateObjectMap.values()) { + Object object = wrapper.getObject(); + Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(object.getClass()); if(allInterfacesForClassAsSet.contains(interfaceClass)){ - extracts.add((T)o); + extracts.add((T)object); } } return extracts; @@ -213,17 +215,13 @@ public class ExtractFactory { * @return Extract 注解 */ private Extract getExtract(Object extractObject){ - Extract annotation = extractObject.getClass().getAnnotation(Extract.class); - if(annotation == null){ - return null; - } - return annotation; + return extractObject.getClass().getAnnotation(Extract.class); } /** * 扩展对象包装类型 **/ - private class ExtractWrapper{ + private static class ExtractWrapper{ private final Object object; private final int order; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java new file mode 100644 index 0000000..1df096d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java @@ -0,0 +1,71 @@ +package com.gitee.starblues.integration.application; + +import com.gitee.starblues.extension.AbstractExtension; +import com.gitee.starblues.integration.listener.PluginInitializerListener; +import com.gitee.starblues.integration.listener.PluginListener; +import com.gitee.starblues.integration.operator.EmptyPluginOperator; +import com.gitee.starblues.integration.operator.PluginOperator; +import com.gitee.starblues.integration.user.EmptyPluginUser; +import com.gitee.starblues.integration.user.PluginUser; +import org.pf4j.PluginStateListener; +import org.springframework.context.ApplicationContext; + +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class EmptyPluginApplication implements PluginApplication{ + + + @Override + public void initialize(ApplicationContext applicationContext, PluginInitializerListener listener) { + + } + + @Override + public PluginOperator getPluginOperator() { + return new EmptyPluginOperator(); + } + + @Override + public PluginUser getPluginUser() { + return new EmptyPluginUser(); + } + + @Override + public PluginApplication addExtension(AbstractExtension extension) { + return null; + } + + @Override + public void addListener(PluginListener pluginListener) { + + } + + @Override + public void addListener(Class pluginListenerClass) { + + } + + @Override + public void addListener(List pluginListeners) { + + } + + @Override + public void addPf4jStateListener(PluginStateListener pluginListener) { + + } + + @Override + public void addPf4jStateListener(Class pluginListenerClass) { + + } + + @Override + public void addPf4jStateListener(List pluginListeners) { + + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java new file mode 100644 index 0000000..4a197ae --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java @@ -0,0 +1,111 @@ +package com.gitee.starblues.integration.operator; + +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.integration.listener.PluginInitializerListener; +import com.gitee.starblues.integration.operator.module.PluginInfo; +import org.springframework.web.multipart.MultipartFile; + +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class EmptyPluginOperator implements PluginOperator{ + @Override + public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception { + return false; + } + + @Override + public boolean verify(Path jarPath) throws Exception { + return false; + } + + @Override + public PluginInfo install(Path jarPath) throws Exception { + return null; + } + + @Override + public boolean uninstall(String pluginId, boolean isBackup) throws Exception { + return false; + } + + @Override + public PluginInfo load(Path jarPath) throws Exception { + return null; + } + + @Override + public PluginInfo load(MultipartFile pluginFile) throws Exception { + return null; + } + + @Override + public boolean unload(String pluginId, boolean isBackup) throws Exception { + return false; + } + + @Override + public boolean start(String pluginId) throws Exception { + return false; + } + + @Override + public boolean stop(String pluginId) throws Exception { + return false; + } + + @Override + public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception { + return null; + } + + @Override + public boolean installConfigFile(Path configFilePath) throws Exception { + return false; + } + + @Override + public boolean uploadConfigFile(MultipartFile configFile) throws Exception { + return false; + } + + @Override + public boolean backupPlugin(Path backDirPath, String sign) throws Exception { + return false; + } + + @Override + public boolean backupPlugin(String pluginId, String sign) throws Exception { + return false; + } + + @Override + public List getPluginInfo() { + return null; + } + + @Override + public PluginInfo getPluginInfo(String pluginId) { + return null; + } + + @Override + public Set getPluginFilePaths() throws Exception { + return null; + } + + @Override + public List getPluginWrapper() { + return null; + } + + @Override + public PluginWrapper getPluginWrapper(String pluginId) { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java new file mode 100644 index 0000000..d051211 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java @@ -0,0 +1,60 @@ +package com.gitee.starblues.integration.user; + +import java.lang.annotation.Annotation; +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class EmptyPluginUser implements PluginUser{ + @Override + public T getBean(String name) { + return null; + } + + @Override + public T getBean(Class aClass) { + return null; + } + + @Override + public T getPluginBean(String name) { + return null; + } + + @Override + public List getBeans(Class aClass) { + return null; + } + + @Override + public List getMainBeans(Class aClass) { + return null; + } + + @Override + public List getPluginBeans(Class aClass) { + return null; + } + + @Override + public List getPluginBeans(String pluginId, Class aClass) { + return null; + } + + @Override + public List getPluginBeansWithAnnotation(Class annotationType) { + return null; + } + + @Override + public List getPluginBeansWithAnnotation(String pluginId, Class annotationType) { + return null; + } + + @Override + public T generateNewInstance(T object) { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java similarity index 54% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java index 9f0b086..f6e7268 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/BasePluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java @@ -1,21 +1,24 @@ package com.gitee.starblues.spring; -import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.environment.PluginEnvironmentProcessor; import com.gitee.starblues.spring.environment.PluginLocalConfigFileProcessor; +import com.gitee.starblues.spring.listener.*; +import com.gitee.starblues.spring.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.processor.SpringPluginProcessorFactory; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.ResourceLoader; import java.util.ArrayList; import java.util.HashMap; @@ -28,46 +31,42 @@ import java.util.concurrent.atomic.AtomicBoolean; * @author starBlues * @version 3.0.0 */ -public class BasePluginSpringApplication implements PluginSpringApplication{ +public class DefaultPluginSpringApplication implements PluginSpringApplication{ private final AtomicBoolean isStarted = new AtomicBoolean(false); + private final GenericApplicationContext mainApplicationContext; private final DefaultListableBeanFactory beanFactory; private final PluginApplicationContext applicationContext; private final IntegrationConfiguration configuration; - private final PluginBeanDefinitionLoader beanDefinitionLoader; - private final String configFileName; private final List environmentProcessors; + private final SpringPluginRegistryInfo registryInfo; - public BasePluginSpringApplication(GenericApplicationContext mainApplicationContext, - ClassLoader classLoader, - Class primarySources){ - this(mainApplicationContext, classLoader, primarySources, null); - } + private SpringPluginProcessor springPluginProcessor; - public BasePluginSpringApplication(GenericApplicationContext mainApplicationContext, - ClassLoader classLoader, - Class primarySources, - String configFileName){ - Assert.isNotNull(classLoader, "classLoader 不能为空"); - Assert.isNotNull(primarySources, "primarySources 不能为空"); + public DefaultPluginSpringApplication(GenericApplicationContext mainApplicationContext, + SpringPluginRegistryInfo registryInfo){ + Assert.isNotNull(mainApplicationContext, "参数 mainApplicationContext 不能为空"); + Assert.isNotNull(registryInfo, "参数 registryInfo 不能为空"); + this.mainApplicationContext = mainApplicationContext; + this.registryInfo = registryInfo; + PluginWrapper pluginWrapper = registryInfo.getPluginWrapper(); + ClassLoader classLoader = pluginWrapper.getPluginClassLoader(); this.beanFactory = new PluginListableBeanFactory(mainApplicationContext); this.beanFactory.setBeanClassLoader(classLoader); - this.configuration = mainApplicationContext.getBean(AutoIntegrationConfiguration.class); - this.applicationContext = new PluginApplicationContext(beanFactory, classLoader); - this.beanDefinitionLoader = new PluginBeanDefinitionLoader(beanFactory, primarySources); - this.configFileName = configFileName; this.environmentProcessors = new ArrayList<>(); - addDefaultEnvironmentProcessor(); - } + addDefaultEnvironmentProcessor(pluginWrapper); + springPluginProcessor = new SpringPluginProcessorFactory(SpringPluginProcessor.RunMode.PLUGIN); + } - protected void addDefaultEnvironmentProcessor(){ + protected void addDefaultEnvironmentProcessor(PluginWrapper pluginWrapper){ + String configFileName = pluginWrapper.getPluginDescriptor().getConfigFileName(); PluginLocalConfigFileProcessor configFileProcessor = new PluginLocalConfigFileProcessor(configuration); if(!ObjectUtils.isEmpty(configFileName)){ configFileProcessor.setSearchNames(PluginFileUtils.getFileName(configFileName)); @@ -84,22 +83,43 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ @Override - public ConfigurableApplicationContext run() { + public GenericApplicationContext run() throws Exception{ synchronized (isStarted){ if(isStarted.get()){ throw new RuntimeException("已经运行了PluginSpringApplication, 无法再运行"); } - processEnvironment(); - addPluginEnvironment(); - addDefaultProcessor(); - loadBean(); - refresh(); - isStarted.set(true); - return applicationContext; + try { + springPluginProcessor.init(mainApplicationContext); + processEnvironment(); + addPluginEnvironment(); + addDefaultProcessor(); + springPluginProcessor.refreshBefore(registryInfo); + refresh(); + springPluginProcessor.refreshAfter(registryInfo); + isStarted.set(true); + return applicationContext; + } catch (Exception e){ + springPluginProcessor.failure(registryInfo); + throw e; + } } + } + + private PluginSpringApplicationRunListeners getRunListeners() { + PluginSpringApplicationRunListeners runListeners = new PluginSpringApplicationRunListeners(ListenerRunMode.PLUGIN); + addDefaultListeners(runListeners); + return runListeners; + } + protected void addDefaultListeners(PluginSpringApplicationRunListeners runListeners){ + runListeners.addListener(new ClassScannerListener()); + runListeners.addListener(new BeanRegistryListener()); + runListeners.addListener(new NecessaryBeanRegistryListener()); + runListeners.addListener(new InvokeOtherPluginRegistryListener()); + runListeners.addListener(new PluginControllerRegistryListener(mainApplicationContext)); } + protected void processEnvironment() { List orderPluginEnvironmentProcessor = CommonUtils.order(environmentProcessors, Ordered::getOrder); @@ -109,7 +129,6 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ } } - private void addPluginEnvironment() { ConfigurableEnvironment environment = applicationContext.getEnvironment(); Map pluginEnvironment = new HashMap<>(); @@ -125,11 +144,15 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ protected void loadBean() { - beanDefinitionLoader.load(); + //beanDefinitionLoader.load(); } protected void refresh() { applicationContext.refresh(); + String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); + for (String beanDefinitionName : beanDefinitionNames) { + System.out.println(beanDefinitionName); + } } @Override @@ -138,13 +161,24 @@ public class BasePluginSpringApplication implements PluginSpringApplication{ if(!isStarted.get()){ throw new RuntimeException("PluginSpringApplication没有运行, 不能close"); } - applicationContext.close(); - isStarted.set(false); + try { + springPluginProcessor.close(registryInfo); + } catch (Exception e) { + e.printStackTrace(); + } finally { + applicationContext.close(); + isStarted.set(false); + } } } @Override - public ConfigurableApplicationContext getApplicationContext() { + public GenericApplicationContext getApplicationContext() { return applicationContext; } + + @Override + public ResourceLoader getResourceLoader() { + return applicationContext.getResourceLoader(); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java index bfe97b5..4c98165 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java @@ -1,7 +1,9 @@ package com.gitee.starblues.spring; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; /** * @author starBlues @@ -11,7 +13,6 @@ public class DefaultRegistryInfo implements RegistryInfo{ private final Map registryInfo = new ConcurrentHashMap<>(); - @Override public void addRegistryInfo(String key, Object value) { registryInfo.put(key, value); @@ -27,6 +28,17 @@ public class DefaultRegistryInfo implements RegistryInfo{ return (T) o; } + @Override + public T getRegistryInfo(String key, Supplier notExistCreate) { + T t = getRegistryInfo(key); + if(t != null){ + return t; + } + t = notExistCreate.get(); + registryInfo.put(key, t); + return t; + } + @Override public void removeRegistryInfo(String key) { registryInfo.remove(key); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java index 2f47a3f..f089862 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java @@ -1,13 +1,9 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.processor.AbstractProcessorFactory; -import com.gitee.starblues.spring.processor.DefaultProcessorFactory; -import com.gitee.starblues.spring.processor.ProcessorRunMode; import org.springframework.context.support.GenericApplicationContext; +import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -19,29 +15,17 @@ public class DefaultSpringPlugin implements SpringPlugin { private final Map registryInfoMap = new ConcurrentHashMap<>(); - private final GenericApplicationContext mainApplicationContext; - private final IntegrationConfiguration configuration; - - private final AbstractProcessorFactory processorFactory; - public DefaultSpringPlugin(GenericApplicationContext mainApplicationContext) { this.mainApplicationContext = mainApplicationContext; - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - this.processorFactory = new DefaultProcessorFactory(mainApplicationContext, configuration, - ProcessorRunMode.PLUGIN); } @Override public synchronized void registry(PluginWrapper pluginWrapper) throws Exception { SpringPluginRegistryInfo registryInfo = createRegistryInfo(pluginWrapper); - processorFactory.registryOfBefore(registryInfo); registryInfo.getPluginSpringApplication().run(); - processorFactory.registryOfAfter(registryInfo); registryInfoMap.put(pluginWrapper.getPluginId(), registryInfo); - PluginInfoContainers.addPluginApplicationContext(pluginWrapper.getPluginId(), - registryInfo.getPluginSpringApplication().getApplicationContext()); } @Override @@ -50,25 +34,18 @@ public class DefaultSpringPlugin implements SpringPlugin { if(springPluginRegistryInfo == null){ return; } - processorFactory.unRegistryOfAfter(springPluginRegistryInfo); - processorFactory.unRegistryOfBefore(springPluginRegistryInfo); springPluginRegistryInfo.getPluginSpringApplication().close(); registryInfoMap.remove(pluginId); - PluginInfoContainers.removePluginApplicationContext(pluginId); } - protected SpringPluginRegistryInfo createRegistryInfo(PluginWrapper pluginWrapper){ - PluginSpringApplication springApplication = createSpringApplication(pluginWrapper); - return new DefaultSpringPluginRegistryInfo( - pluginWrapper, springApplication, mainApplicationContext, configuration - ); + @Override + public Map getPluginRegistryInfos() { + return new HashMap<>(registryInfoMap); } - protected PluginSpringApplication createSpringApplication(PluginWrapper pluginWrapper){ - return new BasePluginSpringApplication( - mainApplicationContext, - pluginWrapper.getPluginClassLoader(), pluginWrapper.getPluginClass(), - pluginWrapper.getPluginDescriptor().getConfigFileName() + protected SpringPluginRegistryInfo createRegistryInfo(PluginWrapper pluginWrapper){ + return new DefaultSpringPluginRegistryInfo( + pluginWrapper, mainApplicationContext ); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java index e23cd75..f9a2f7c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java @@ -3,6 +3,7 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; /** * @author starBlues @@ -12,17 +13,15 @@ public class DefaultSpringPluginRegistryInfo extends DefaultRegistryInfo impleme private final PluginWrapper pluginWrapper; private final PluginSpringApplication pluginSpringApplication; - private final ConfigurableApplicationContext mainApplicationContext; + private final GenericApplicationContext mainApplicationContext; private final IntegrationConfiguration configuration; public DefaultSpringPluginRegistryInfo(PluginWrapper pluginWrapper, - PluginSpringApplication springApplication, - ConfigurableApplicationContext mainApplicationContext, - IntegrationConfiguration configuration) { + GenericApplicationContext mainApplicationContext) { this.pluginWrapper = pluginWrapper; - this.pluginSpringApplication = springApplication; + this.pluginSpringApplication = new DefaultPluginSpringApplication(mainApplicationContext, this); this.mainApplicationContext = mainApplicationContext; - this.configuration = configuration; + this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java index 5b19c38..bc3586f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java @@ -1,6 +1,8 @@ package com.gitee.starblues.spring; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.io.ResourceLoader; /** * 插件 SpringApplication @@ -12,8 +14,9 @@ public interface PluginSpringApplication { /** * 运行 * @return ConfigurableApplicationContext + * @throws Exception Exception */ - ConfigurableApplicationContext run(); + GenericApplicationContext run() throws Exception; /** * 关闭 @@ -25,7 +28,13 @@ public interface PluginSpringApplication { * 得到 ApplicationContext * @return GenericApplicationContext */ - ConfigurableApplicationContext getApplicationContext(); + GenericApplicationContext getApplicationContext(); + + /** + * 得到 ResourceLoader + * @return ResourceLoader + */ + ResourceLoader getResourceLoader(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java index 96c2b69..8ea143d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java @@ -1,5 +1,7 @@ package com.gitee.starblues.spring; +import java.util.function.Supplier; + /** * 注册信息 * @author starBlues @@ -20,6 +22,16 @@ public interface RegistryInfo { * @return 注册信息的值 */ T getRegistryInfo(String key); + + /** + * 得到注册信息 + * @param key 注册信息key + * @param notExistCreate 不存在的话, 进行创建操作 + * @return 注册信息的值 + */ + T getRegistryInfo(String key, Supplier notExistCreate); + + /** * 移除注册信息 * @param key 注册信息key diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java index 9ce6944..e66c831 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java @@ -3,17 +3,33 @@ package com.gitee.starblues.spring; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.factory.PluginFactory; +import java.util.Map; + /** * @author starBlues * @version 3.0.0 */ public interface SpringPlugin { - + /** + * 注册插件 + * @param pluginWrapper pluginWrapper + * @throws Exception Exception + */ void registry(PluginWrapper pluginWrapper) throws Exception; - + /** + * 卸载插件 + * @param pluginId 插件id + * @throws Exception Exception + */ void unRegistry(String pluginId) throws Exception; + /** + * 获取当前注册的插件信息 + * @return Map + */ + Map getPluginRegistryInfos(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java new file mode 100644 index 0000000..129f270 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java @@ -0,0 +1,61 @@ +package com.gitee.starblues.spring.listener; + +import com.gitee.starblues.annotation.Supplier; +import com.gitee.starblues.factory.SpringBeanRegister; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.classgroup.ComposeClassGroup; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.OrderPriority; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; + +import java.util.List; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class BeanRegistryListener implements PluginSpringApplicationRunListener { + + @Override + public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + SpringBeanRegister springBeanRegister = new SpringBeanRegister(applicationContext); + List> classes = registryInfo.getRegistryInfo(ComposeClassGroup.ID); + if(ObjectUtils.isEmpty(classes)){ + return; + } + for (Class aClass : classes) { + String beanName = springBeanRegister.register(aClass); + cacheInvokeSupplier(aClass, beanName, registryInfo); + } + } + + @Override + public void stop(SpringPluginRegistryInfo registryInfo) throws Exception { + InvokeSupperCache.remove(registryInfo.getPluginWrapper().getPluginId()); + } + + private void cacheInvokeSupplier(Class aClass, String beanName, SpringPluginRegistryInfo registryInfo){ + Supplier supplier = AnnotationUtils.findAnnotation(aClass, Supplier.class); + if(supplier == null){ + return; + } + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + InvokeSupperCache.add(pluginId, new InvokeSupperCache.Cache(supplier.value(), beanName, applicationContext)); + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + + @Override + public ListenerRunMode runMode() { + return ListenerRunMode.PLUGIN; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java new file mode 100644 index 0000000..e3fb331 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java @@ -0,0 +1,132 @@ +package com.gitee.starblues.spring.listener; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; +import com.gitee.starblues.spring.processor.classgroup.ComposeClassGroup; +import com.gitee.starblues.spring.processor.classgroup.PluginClassGroup; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.OrderPriority; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.type.classreading.CachingMetadataReaderFactory; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.util.ClassUtils; + +import java.util.*; + +/** + * @author starBlues + * @version 1.0 + */ +public class ClassScannerListener implements PluginSpringApplicationRunListener { + private final static Logger LOGGER = LoggerFactory.getLogger(ClassScannerListener.class); + + static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; + + private final List pluginClassGroup = new ArrayList<>(); + + public ClassScannerListener(){ + addPluginClassGroup(); + } + + protected void addPluginClassGroup(){ + pluginClassGroup.add(new ComposeClassGroup()); + pluginClassGroup.add(new CallerClassGroup()); + } + + + @Override + public void starting(SpringPluginRegistryInfo registryInfo) throws Exception{ + ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); + ResourceLoader resourceLoader = new DefaultResourceLoader(pluginClassLoader); + ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(resourceLoader); + Set packageSearchPaths = getPackageSearchPaths(registryInfo); + MetadataReaderFactory metadataReaderFactory = getMetadataReaderFactory(registryInfo); + for (String packageSearchPath : packageSearchPaths) { + Resource[] resources = patternResolver.getResources(packageSearchPath); + for (Resource resource : resources) { + MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); + String className = metadataReader.getClassMetadata().getClassName(); + Class aClass = pluginClassLoader.loadClass(className); + groupClass(aClass, registryInfo); + } + } + } + + private void groupClass(Class aClass, SpringPluginRegistryInfo registryInfo){ + boolean filterResult = false; + for (PluginClassGroup classGroup : pluginClassGroup) { + String groupId = classGroup.groupId(); + if(ObjectUtils.isEmpty(groupId)){ + continue; + } + boolean filter = classGroup.filter(aClass); + if(filter){ + addClass(groupId, aClass, registryInfo); + filterResult = true; + } + } + if(!filterResult){ + addClass(PluginClassGroup.OTHER_CLASS_GROUP_ID, aClass, registryInfo); + } + } + + + private void addClass(String groupId, Class aClass, SpringPluginRegistryInfo registryInfo){ + List> classes = registryInfo.getRegistryInfo(groupId, ArrayList::new); + classes.add(aClass); + } + + + protected Set getPackageSearchPaths(SpringPluginRegistryInfo registryInfo) { + Class pluginClass = registryInfo.getPluginWrapper().getPluginClass(); + String[] scanBasePackages = getScanBasePackages(pluginClass); + Set packageSearchPaths = new HashSet<>(); + ConfigurableEnvironment environment = registryInfo.getPluginSpringApplication() + .getApplicationContext().getEnvironment(); + for (String scanBasePackage : scanBasePackages) { + String scanPackageName = ClassUtils.convertClassNameToResourcePath( + environment.resolveRequiredPlaceholders(scanBasePackage)); + scanPackageName = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + + scanPackageName + '/' + DEFAULT_RESOURCE_PATTERN; + packageSearchPaths.add(scanPackageName); + } + return packageSearchPaths; + } + + + protected String[] getScanBasePackages(Class pluginClass){ + SpringBootApplication springBootApplication = pluginClass.getAnnotation(SpringBootApplication.class); + if(springBootApplication != null){ + String[] scanBasePackages = springBootApplication.scanBasePackages(); + if(scanBasePackages.length > 0){ + return scanBasePackages; + } + } + return new String[]{ pluginClass.getPackage().getName() }; + } + + protected MetadataReaderFactory getMetadataReaderFactory(SpringPluginRegistryInfo registryInfo){ + ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); + return new CachingMetadataReaderFactory(pluginClassLoader); + } + + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + + @Override + public ListenerRunMode runMode() { + return ListenerRunMode.ALL; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java new file mode 100644 index 0000000..4296b57 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java @@ -0,0 +1,54 @@ +package com.gitee.starblues.spring.listener; + +import com.gitee.starblues.annotation.Caller; +import com.gitee.starblues.factory.SpringBeanRegister; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; +import com.gitee.starblues.spring.processor.invoke.InvokeBeanFactory; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; + +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class InvokeOtherPluginRegistryListener implements PluginSpringApplicationRunListener { + + + public InvokeOtherPluginRegistryListener() { + } + + @Override + public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { + List> classes = registryInfo.getRegistryInfo(CallerClassGroup.ID); + if(ObjectUtils.isEmpty(classes)){ + return; + } + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + SpringBeanRegister springBeanRegister = new SpringBeanRegister(applicationContext); + for (Class aClass : classes) { + Caller caller = AnnotationUtils.findAnnotation(aClass, Caller.class); + if(caller == null){ + continue; + } + springBeanRegister.register(aClass, definition -> { + // 是调用方 + definition.getPropertyValues().add("callerAnnotation", caller); + definition.getPropertyValues().add("callerInterface", aClass); + definition.getPropertyValues().add("registryInfo", registryInfo); + definition.setBeanClass(InvokeBeanFactory.class); + definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE); + }); + } + } + + @Override + public ListenerRunMode runMode() { + return ListenerRunMode.ALL; + } + +} \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java similarity index 36% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java index 01ad061..9747a82 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ProcessorRunMode.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java @@ -1,24 +1,24 @@ -package com.gitee.starblues.spring.processor; +package com.gitee.starblues.spring.listener; /** * @author starBlues - * @version 3.0.0 + * @version 1.0 */ -public enum ProcessorRunMode { +public enum ListenerRunMode { /** - * 插件方式运行 + * 全部运行 */ - PLUGIN, + ALL, /** - * 自己方式运行 + * 插件环境运行 */ - ONESELF, + PLUGIN, /** - * 任意方式运行 + * 插件独立运行 */ - ALL, + ONESELF } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/before/RegisterNecessaryBeanProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java similarity index 50% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/before/RegisterNecessaryBeanProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java index b0bd62a..8cbcf1d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/before/RegisterNecessaryBeanProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java @@ -1,27 +1,36 @@ -package com.gitee.starblues.spring.processor.before; +package com.gitee.starblues.spring.listener; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.realize.PluginUtils; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.BeforeRefreshProcessor; +import com.gitee.starblues.utils.OrderPriority; import org.springframework.context.ConfigurableApplicationContext; /** * @author starBlues * @version 1.0 */ -public class RegisterNecessaryBeanProcessor implements BeforeRefreshProcessor { - +public class NecessaryBeanRegistryListener implements PluginSpringApplicationRunListener { @Override - public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { - - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); - + public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); PluginDescriptor pluginDescriptor = registryInfo.getPluginWrapper().getPluginDescriptor(); applicationContext.getBeanFactory().registerSingleton("pluginDescriptor", pluginDescriptor); - applicationContext.getBeanFactory().registerSingleton("pluginUtils", new PluginUtils(applicationContext)); + applicationContext.getBeanFactory().registerSingleton("pluginUtils", + new PluginUtils(applicationContext)); + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority().down(-10); + } + + @Override + public ListenerRunMode runMode() { + return ListenerRunMode.ALL; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java new file mode 100644 index 0000000..86d412b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java @@ -0,0 +1,220 @@ +package com.gitee.starblues.spring.listener; + +import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.PluginSpringApplication; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.ClassUtils; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ReflectionUtils; +import org.pf4j.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginControllerRegistryListener implements PluginSpringApplicationRunListener { + + private final static Logger LOG = LoggerFactory.getLogger(PluginControllerRegistryListener.class); + private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; + + private final GenericApplicationContext mainApplicationContext; + + private RequestMappingHandlerMapping requestMappingHandlerMapping; + private Method getMappingForMethod; + + private final AtomicBoolean canRegistered = new AtomicBoolean(false); + + public PluginControllerRegistryListener(GenericApplicationContext mainApplicationContext) { + this.mainApplicationContext = mainApplicationContext; + } + + @Override + public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { + + IntegrationConfiguration configuration = registryInfo.getConfiguration(); + if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) + && !configuration.enablePluginIdRestPathPrefix()){ + // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 + return; + } + + this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); + this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, + "getMappingForMethod", Method.class, Class.class); + if(getMappingForMethod == null){ + LOG.warn("RequestMappingHandlerMapping 类中没有发现 方法, 无法注册插件接口. " + + "请检查当前环境是否为 web 环境"); + } + this.getMappingForMethod.setAccessible(true); + + PluginSpringApplication pluginSpringApplication = registryInfo.getPluginSpringApplication(); + AnnotationConfigApplicationContext applicationContext = + (AnnotationConfigApplicationContext)pluginSpringApplication.getApplicationContext(); + applicationContext.registerBean("changeRestPathPostProcessor", + ChangeRestPathPostProcessor.class, ()-> new ChangeRestPathPostProcessor(registryInfo)); + canRegistered.set(true); + } + + + @Override + public void started(SpringPluginRegistryInfo registryInfo) throws Exception { + if(!canRegistered.get()){ + return; + } + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + List controllerWrappers = registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + if(ObjectUtils.isEmpty(controllerWrappers)){ + LOG.warn("插件 [{}] 没有发现可注册的 Controller", pluginId); + return; + } + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + + Iterator iterator = controllerWrappers.iterator(); + while (iterator.hasNext()){ + ControllerWrapper controllerWrapper = iterator.next(); + if(!applicationContext.containsBean(controllerWrapper.getBeanName())){ + iterator.remove(); + } + Object controllerBean = applicationContext.getBean(controllerWrapper.getBeanName()); + Set requestMappingInfos = registry(registryInfo, controllerBean.getClass()); + if(requestMappingInfos.isEmpty()){ + iterator.remove(); + } else { + for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { + LOG.info("插件[{}]注册接口: {}", pluginId, requestMappingInfo.toString()); + } + } + } + } + + @Override + public ListenerRunMode runMode() { + return ListenerRunMode.PLUGIN; + } + + + private Set registry(SpringPluginRegistryInfo pluginRegistryInfo, Class aClass) + throws Exception { + ConfigurableApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginSpringApplication() + .getApplicationContext(); + Object object = pluginApplicationContext.getBean(aClass); + + Method[] methods = aClass.getMethods(); + Set requestMappingInfos = new HashSet<>(); + for (Method method : methods) { + if (isHaveRequestMapping(method)) { + RequestMappingInfo requestMappingInfo = (RequestMappingInfo) + getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass); + requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method); + requestMappingInfos.add(requestMappingInfo); + } + } + return requestMappingInfos; + } + + /** + * 方法上是否存在 @RequestMapping 注解 + * @param method method + * @return boolean + */ + private boolean isHaveRequestMapping(Method method){ + return AnnotationUtils.findAnnotation(method, RequestMapping.class) != null; + } + + private static class ChangeRestPathPostProcessor implements BeanPostProcessor { + + private final static Logger LOG = LoggerFactory.getLogger(ChangeRestPathPostProcessor.class); + private final static String COMMON_ERROR = "无法统一处理该 Controller 统一请求路径前缀"; + + private final SpringPluginRegistryInfo registryInfo; + + + + private ChangeRestPathPostProcessor(SpringPluginRegistryInfo registryInfo) { + this.registryInfo = registryInfo; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + Class aClass = bean.getClass(); + Controller controller = AnnotationUtils.findAnnotation(aClass, Controller.class); + if(controller == null){ + return bean; + } + RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class); + if(requestMapping != null){ + changePathForClass(beanName, aClass, requestMapping); + } + return bean; + } + + private void changePathForClass(String beanName, Class aClass, RequestMapping requestMapping){ + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + String pathPrefix = CommonUtils.getPluginRestPrefix(registryInfo.getConfiguration(), pluginId); + + if(StringUtils.isNullOrEmpty(pathPrefix)){ + LOG.error("插件 [{}] Controller类 [{}] 未发现 path 配置, {}", + pluginId, aClass.getSimpleName(), COMMON_ERROR); + return; + } + Set definePaths = new HashSet<>(); + definePaths.addAll(Arrays.asList(requestMapping.path())); + definePaths.addAll(Arrays.asList(requestMapping.value())); + try { + Map memberValues = ClassUtils.getAnnotationsUpdater(requestMapping); + if(memberValues == null){ + LOG.error("插件 [{}] Controller 类 [{}] 无法反射获取注解属性, {}", + pluginId, aClass.getSimpleName(), COMMON_ERROR); + return; + } + String[] newPath = new String[definePaths.size()]; + int i = 0; + for (String definePath : definePaths) { + // 解决插件启用、禁用后, 路径前缀重复的问题。 + if(definePath.contains(pathPrefix)){ + newPath[i++] = definePath; + } else { + newPath[i++] = CommonUtils.restJoiningPath(pathPrefix, definePath); + } + } + if(newPath.length == 0){ + newPath = new String[]{ pathPrefix }; + } + memberValues.put("path", newPath); + memberValues.put("value", newPath); + + List controllerWrappers = this.registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + if(controllerWrappers == null){ + controllerWrappers = new ArrayList<>(); + this.registryInfo.addRegistryInfo(PROCESS_CONTROLLERS, controllerWrappers); + } + ControllerWrapper controllerWrapper = new ControllerWrapper(); + controllerWrapper.setPathPrefix(newPath); + controllerWrapper.setBeanName(beanName); + controllerWrappers.add(controllerWrapper); + } catch (Exception e) { + LOG.error("插件 [{}] Controller 类[{}] 注册异常. {}", pluginId, aClass.getName(), e.getMessage(), e); + } + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java new file mode 100644 index 0000000..a711e87 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java @@ -0,0 +1,42 @@ +package com.gitee.starblues.spring.listener; + + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.Order; +import com.gitee.starblues.utils.OrderPriority; + +/** + * @author starBlues + * @version 1.0 + */ +public interface PluginSpringApplicationRunListener extends Order { + + default void starting(SpringPluginRegistryInfo registryInfo) throws Exception{ + } + + default void environmentPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ + } + + default void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ + } + + default void started(SpringPluginRegistryInfo registryInfo) throws Exception{ + } + + default void failed(SpringPluginRegistryInfo registryInfo, Throwable exception) throws Exception{ + } + + default void stop(SpringPluginRegistryInfo registryInfo) throws Exception{ + + } + + @Override + default OrderPriority order() { + return OrderPriority.getMiddlePriority(); + } + + + ListenerRunMode runMode(); + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java new file mode 100644 index 0000000..aacf89c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java @@ -0,0 +1,94 @@ +package com.gitee.starblues.spring.listener; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginSpringApplicationRunListeners implements PluginSpringApplicationRunListener{ + + private final static Logger LOGGER = LoggerFactory.getLogger(PluginSpringApplicationRunListeners.class); + + + private final List runListeners = new ArrayList<>(); + private final ListenerRunMode listenerRunMode; + + public PluginSpringApplicationRunListeners(ListenerRunMode listenerRunMode) { + this.listenerRunMode = listenerRunMode; + } + + public void addListener(PluginSpringApplicationRunListener listener){ + if(listener != null){ + runListeners.add(listener); + } + } + + @Override + public void starting(SpringPluginRegistryInfo registryInfo) throws Exception{ + publicListener(listener -> listener.starting(registryInfo)); + } + + @Override + public void environmentPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ + publicListener(listener -> listener.environmentPrepared(registryInfo)); + } + + @Override + public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ + publicListener(listener -> listener.refreshPrepared(registryInfo)); + } + + @Override + public void started(SpringPluginRegistryInfo registryInfo) throws Exception{ + publicListener(listener -> listener.started(registryInfo)); + } + + @Override + public void failed(SpringPluginRegistryInfo registryInfo, Throwable exception) { + try { + publicListener(listener -> listener.failed(registryInfo, exception)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void stop(SpringPluginRegistryInfo registryInfo) throws Exception { + try { + publicListener(listener -> listener.stop(registryInfo)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public ListenerRunMode runMode() { + return ListenerRunMode.ALL; + } + + private void publicListener(Consumer consumer) throws Exception{ + for (PluginSpringApplicationRunListener listener : runListeners) { + ListenerRunMode listenerRunMode = listener.runMode(); + if(listenerRunMode == ListenerRunMode.ALL || listenerRunMode == this.listenerRunMode){ + try { + consumer.accept(listener); + } catch (Exception e){ + LOGGER.error("监听者 <{}> 执行失败. {}", listener.getClass().getName(), e.getMessage(), e); + throw e; + } + } + } + } + + @FunctionalInterface + private interface Consumer{ + void accept(T t) throws Exception; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java new file mode 100644 index 0000000..60d7d91 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java @@ -0,0 +1,62 @@ +package com.gitee.starblues.spring.oneself; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.listener.*; +import org.springframework.boot.context.event.*; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class OneselfApplicationContextListener implements ApplicationListener { + + private final PluginSpringApplicationRunListeners listeners; + + private final SpringPluginRegistryInfo registryInfo; + + public OneselfApplicationContextListener(SpringPluginRegistryInfo registryInfo){ + this.registryInfo = registryInfo; + listeners = new PluginSpringApplicationRunListeners(ListenerRunMode.ONESELF); + addListeners(); + } + + + public void addListeners(){ + listeners.addListener(new ClassScannerListener()); + listeners.addListener(new NecessaryBeanRegistryListener()); + listeners.addListener(new InvokeOtherPluginRegistryListener()); + } + + + @Override + public void onApplicationEvent(ApplicationEvent event) { + try { + if(event instanceof ApplicationStartingEvent){ + listeners.starting(registryInfo); + } + if(event instanceof ApplicationEnvironmentPreparedEvent){ + listeners.environmentPrepared(registryInfo); + } + if(event instanceof ApplicationContextInitializedEvent){ + listeners.refreshPrepared(registryInfo); + } + if(event instanceof ApplicationPreparedEvent){ + listeners.refreshPrepared(registryInfo); + } + if(event instanceof ApplicationStartedEvent){ + listeners.started(registryInfo); + } + if(event instanceof ApplicationFailedEvent){ + listeners.failed(registryInfo, ((ApplicationFailedEvent)event).getException()); + } + } catch (Exception e){ + e.printStackTrace(); + } + + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java index fcf5ee4..1707e3d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java @@ -1,46 +1,22 @@ package com.gitee.starblues.spring.oneself; -import com.gitee.starblues.spring.PluginSpringApplication; -import org.springframework.context.ConfigurableApplicationContext; + +import org.springframework.context.support.GenericApplicationContext; /** * 插件可主运行的 PluginSpringApplication 实现, 插件如果需要自动运行, 则使用该类进行引导启动 * @author starBlues * @version 3.0.0 */ -public class OneselfPluginSpringApplication implements PluginSpringApplication { - - private final OneselfSpringApplication oneselfSpringApplication; - - private ConfigurableApplicationContext applicationContext; - - public OneselfPluginSpringApplication(Class ...primarySources) { - this.oneselfSpringApplication = new OneselfSpringApplication(this, primarySources); - } - - /** - * 插件自主运行时, 引导入口 - * @param primarySources primarySources - * @return ConfigurableApplicationContext - */ - public static ConfigurableApplicationContext run(Class ...primarySources){ - return new OneselfPluginSpringApplication(primarySources).run(); +public class OneselfPluginSpringApplication { + + public static GenericApplicationContext run(Class ...primarySources){ + try { + return new OneselfSpringApplication(primarySources).run(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } } - - @Override - public ConfigurableApplicationContext run() { - applicationContext = oneselfSpringApplication.run(); - return this.applicationContext; - } - - @Override - public void close() { - applicationContext.close(); - } - - @Override - public ConfigurableApplicationContext getApplicationContext() { - return applicationContext; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java index 0f0452c..dba258e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -5,12 +5,10 @@ import com.gitee.starblues.core.descriptor.*; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.integration.DefaultIntegrationConfiguration; -import com.gitee.starblues.spring.DefaultSpringPluginRegistryInfo; import com.gitee.starblues.spring.PluginSpringApplication; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.AbstractProcessorFactory; -import com.gitee.starblues.spring.processor.DefaultProcessorFactory; -import com.gitee.starblues.spring.processor.ProcessorRunMode; +import com.gitee.starblues.spring.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.processor.SpringPluginProcessorFactory; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,6 +16,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.io.ResourceLoader; @@ -33,23 +32,26 @@ import java.util.Map; * @version 3.0.0 * @see SpringApplication */ -public class OneselfSpringApplication extends SpringApplication { +public class OneselfSpringApplication extends SpringApplication implements PluginSpringApplication{ private final static Logger LOG = LoggerFactory.getLogger(OneselfSpringApplication.class); private final Class primarySource; - private final PluginSpringApplication springApplication; private final PluginWrapper pluginWrapper; - public OneselfSpringApplication(PluginSpringApplication springApplication, Class... primarySources) { - this(springApplication, null, primarySources); + private final SpringPluginProcessor springPluginProcessor; + + private SpringPluginRegistryInfo registryInfo; + + private GenericApplicationContext applicationContext; + + public OneselfSpringApplication(Class... primarySources) { + this(null, primarySources); } - public OneselfSpringApplication(PluginSpringApplication springApplication, - ResourceLoader resourceLoader, Class... primarySources) { + public OneselfSpringApplication(ResourceLoader resourceLoader, Class... primarySources) { super(resourceLoader, primarySources); - this.springApplication = springApplication; if(primarySources.length > 0){ primarySource = primarySources[0]; } else { @@ -57,13 +59,34 @@ public class OneselfSpringApplication extends SpringApplication { } // 运行之前, 从当前插件的 classpath 下获取插件引导信息 pluginWrapper = tryGetPluginWrapper(); + this.springPluginProcessor = new SpringPluginProcessorFactory(SpringPluginProcessor.RunMode.ONESELF); } + @Override - protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { - super.configureProfiles(environment, args); + public GenericApplicationContext run() throws Exception { + return (GenericApplicationContext) super.run(); + } + + @Override + public void close(){ + if(applicationContext != null){ + try { + springPluginProcessor.close(registryInfo); + } catch (Exception e) { + e.printStackTrace(); + } finally { + applicationContext.close(); + } + } } + @Override + public GenericApplicationContext getApplicationContext() { + return applicationContext; + } + + @Override protected void bindToSpringApplication(ConfigurableEnvironment environment) { super.bindToSpringApplication(environment); @@ -75,50 +98,57 @@ public class OneselfSpringApplication extends SpringApplication { env.put("server.servlet.context-path", contextPath); LOG.info("当前应用接口前缀为: {}", contextPath); environment.getPropertySources().addFirst(new MapPropertySource("springPluginRegistryInfo", env)); + } + @Override + protected ConfigurableApplicationContext createApplicationContext() { + ConfigurableApplicationContext applicationContext = super.createApplicationContext(); + try { + this.applicationContext = (GenericApplicationContext) applicationContext; + springPluginProcessor.init(this.applicationContext); + } catch (Exception e) { + e.printStackTrace(); + } + return applicationContext; } @Override protected void refresh(ConfigurableApplicationContext applicationContext) { - AutoIntegrationConfiguration configuration = getConfiguration(applicationContext); - // 刷新之前 - AbstractProcessorFactory processorFactory = - new DefaultProcessorFactory(applicationContext, configuration, ProcessorRunMode.ONESELF); - SpringPluginRegistryInfo springPluginRegistryInfo = create(applicationContext, configuration); - processorFactory.registryOfBefore(springPluginRegistryInfo); - super.refresh(applicationContext); + try { + AutoIntegrationConfiguration configuration = bindIntegrationConfiguration(applicationContext); + registryInfo = new OneselfSpringPluginRegistryInfo(pluginWrapper, this, + applicationContext, configuration); + springPluginProcessor.refreshBefore(registryInfo); + } catch (Exception e) { + throw new RuntimeException(e); + } + try { + super.refresh(applicationContext); + springPluginProcessor.refreshAfter(registryInfo); + } catch (Exception e){ + try { + springPluginProcessor.failure(registryInfo); + } catch (Exception exception) { + throw new RuntimeException(e); + } + } + } - private AutoIntegrationConfiguration getConfiguration(ConfigurableApplicationContext applicationContext){ + private AutoIntegrationConfiguration bindIntegrationConfiguration( + ConfigurableApplicationContext applicationContext){ Binder binder = Binder.get(applicationContext.getEnvironment()); - AutoIntegrationConfiguration autoIntegrationConfiguration = + AutoIntegrationConfiguration configuration = binder.bind("plugin", Bindable.of(AutoIntegrationConfiguration.class)) .orElseGet(() -> null); - if(autoIntegrationConfiguration != null){ - return autoIntegrationConfiguration; + if(configuration == null){ + configuration = new AutoIntegrationConfiguration(); } - return new AutoIntegrationConfiguration(); + applicationContext.getBeanFactory().registerSingleton("integrationConfiguration", + configuration); + return configuration; } - private SpringPluginRegistryInfo create(ConfigurableApplicationContext applicationContext, - AutoIntegrationConfiguration configuration){ - return new DefaultSpringPluginRegistryInfo(pluginWrapper, new PluginSpringApplication() { - @Override - public ConfigurableApplicationContext run() { - return springApplication.run(); - } - - @Override - public void close() { - springApplication.close(); - } - - @Override - public ConfigurableApplicationContext getApplicationContext() { - return applicationContext; - } - }, applicationContext, configuration); - } /** * 尝试从 classpath 获取插件引导信息, 如果不存在, 则生成空的 PluginWrapper diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java new file mode 100644 index 0000000..3eb227c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java @@ -0,0 +1,51 @@ +package com.gitee.starblues.spring.oneself; + +import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.DefaultRegistryInfo; +import com.gitee.starblues.spring.PluginSpringApplication; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class OneselfSpringPluginRegistryInfo extends DefaultRegistryInfo implements SpringPluginRegistryInfo { + + + private final PluginSpringApplication pluginSpringApplication; + private final PluginWrapper pluginWrapper; + private final ConfigurableApplicationContext applicationContext; + private final IntegrationConfiguration configuration; + + public OneselfSpringPluginRegistryInfo(PluginWrapper pluginWrapper, + PluginSpringApplication pluginSpringApplication, + ConfigurableApplicationContext applicationContext, + IntegrationConfiguration configuration) { + this.pluginWrapper = pluginWrapper; + this.pluginSpringApplication = pluginSpringApplication; + this.applicationContext = applicationContext; + this.configuration = configuration; + } + + @Override + public PluginWrapper getPluginWrapper() { + return pluginWrapper; + } + + @Override + public PluginSpringApplication getPluginSpringApplication() { + return pluginSpringApplication; + } + + @Override + public ConfigurableApplicationContext getMainApplicationContext() { + return applicationContext; + } + + @Override + public IntegrationConfiguration getConfiguration() { + return configuration; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java deleted file mode 100644 index 585000c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AbstractProcessorFactory.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.before.RegisterNecessaryBeanProcessor; -import com.gitee.starblues.utils.CommonUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ConfigurableApplicationContext; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -/** - * @author starBlues - * @version 3.0.0 - */ -public abstract class AbstractProcessorFactory implements BeforeRefreshProcessor, AfterRefreshProcessor{ - - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractProcessorFactory.class); - - private final List afterProcessors; - private final List beforeProcessors; - - protected final ProcessorRunMode processorRunMode; - - protected final IntegrationConfiguration configuration; - protected final ConfigurableApplicationContext mainApplicationContext; - - public AbstractProcessorFactory(ConfigurableApplicationContext mainApplicationContext, - IntegrationConfiguration configuration, - ProcessorRunMode processorRunMode) { - this.mainApplicationContext = mainApplicationContext; - this.configuration = configuration; - - this.processorRunMode = processorRunMode; - - List beforeProcessors = new ArrayList<>(); - List afterProcessors = new ArrayList<>(); - addDefaultBeforeProcessor(beforeProcessors); - addDefaultAfterProcessor(afterProcessors); - addDefaultCommonProcessor(beforeProcessors, afterProcessors); - - this.beforeProcessors = beforeProcessors.stream() - .filter(Objects::nonNull) - .sorted(CommonUtils.orderPriority(BeforeRefreshProcessor::orderOfBefore)) - .collect(Collectors.toList()); - this.afterProcessors = afterProcessors.stream() - .filter(Objects::nonNull) - .sorted(CommonUtils.orderPriority(AfterRefreshProcessor::orderOfAfter)) - .collect(Collectors.toList()); - } - - protected abstract void addDefaultBeforeProcessor(List beforeProcessors); - - protected abstract void addDefaultAfterProcessor(List afterProcessors); - - protected abstract void addDefaultCommonProcessor(List beforeProcessors, - List afterProcessors); - - protected void addDefaultCommonProcessor(List beforeProcessors, - List afterProcessors, - Object o){ - if(o instanceof BeforeRefreshProcessor){ - beforeProcessors.add((BeforeRefreshProcessor)o); - } - if(o instanceof AfterRefreshProcessor){ - afterProcessors.add((AfterRefreshProcessor)o); - } - } - - @Override - public void registryOfAfter(SpringPluginRegistryInfo registryInfo) { - for (AfterRefreshProcessor processor : afterProcessors) { - try { - processor.registryOfAfter(registryInfo); - } catch (Exception e){ - LOGGER.error("AfterRefreshProcessor: [{}] registry 异常", - processor.getClass().getName(), e); - } - } - } - - @Override - public void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) { - for (AfterRefreshProcessor processor : afterProcessors) { - try { - processor.unRegistryOfAfter(registryInfo); - } catch (Exception e){ - LOGGER.error("AfterRefreshProcessor: [{}] unRegistry 异常", - processor.getClass().getName(), e); - } - } - } - - @Override - public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { - for (BeforeRefreshProcessor processor : beforeProcessors) { - try { - processor.registryOfBefore(registryInfo); - } catch (Exception e){ - LOGGER.error("BeforeRefreshProcessor: [{}] registry 异常", - processor.getClass().getName(), e); - } - } - } - - @Override - public void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo) { - for (BeforeRefreshProcessor processor : beforeProcessors) { - try { - processor.unRegistryOfBefore(registryInfo); - } catch (Exception e){ - LOGGER.error("BeforeRefreshProcessor: [{}] unRegistry 异常", - processor.getClass().getName(), e); - } - } - } - - private boolean filterProcessorRunMode(ProcessorRunMode processorRunMode){ - if(processorRunMode == ProcessorRunMode.ALL){ - return true; - } - return processorRunMode == this.processorRunMode; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java deleted file mode 100644 index bff1e67..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/AfterRefreshProcessor.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.OrderPriority; - -/** - * ApplicationContext.refresh 刷新之前的处理扩展接口 - * @author starBlues - * @version 3.0.0 - */ -public interface AfterRefreshProcessor { - - /** - * 插件注册时调用 - * @param registryInfo 注册插件信息 - * @throws Exception Exception - */ - void registryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception; - - /** - * 插件卸载时调用 - * @param registryInfo 注册插件信息 - * @throws Exception Exception - */ - default void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception{ - - } - - /** - * 执行顺序 OrderPriority - * @return OrderPriority - */ - default OrderPriority orderOfAfter(){ - return OrderPriority.getMiddlePriority(); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java new file mode 100644 index 0000000..a2cf2d9 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.scanner.PluginClassPathBeanDefinitionScanner; +import com.gitee.starblues.utils.OrderPriority; +import com.gitee.starblues.utils.ScanUtils; + + +/** + * @author starBlues + * @version 1.0 + */ +public class BeanRegistryProcessor implements SpringPluginProcessor{ + + @Override + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { + PluginClassPathBeanDefinitionScanner scanner = new PluginClassPathBeanDefinitionScanner(registryInfo); + scanner.scan(ScanUtils.getScanBasePackages((registryInfo.getPluginWrapper().getPluginClass()))); + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority().down(10); + } + + @Override + public RunMode runMode() { + return RunMode.PLUGIN; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java deleted file mode 100644 index 32556d1..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeforeRefreshProcessor.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.OrderPriority; - -/** - * ApplicationContext.refresh 刷新之后的处理扩展接口 - * @author starBlues - * @version 3.0.0 - */ -public interface BeforeRefreshProcessor { - - /** - * 插件注册时调用 - * @param registryInfo 注册插件信息 - */ - void registryOfBefore(SpringPluginRegistryInfo registryInfo); - - /** - * 插件卸载时调用 - * @param registryInfo 注册插件信息 - */ - default void unRegistryOfBefore(SpringPluginRegistryInfo registryInfo){ - - } - - /** - * 执行顺序 OrderPriority - * @return OrderPriority - */ - default OrderPriority orderOfBefore(){ - return OrderPriority.getMiddlePriority(); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java new file mode 100644 index 0000000..0271123 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java @@ -0,0 +1,135 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; +import com.gitee.starblues.spring.processor.classgroup.ComposeClassGroup; +import com.gitee.starblues.spring.processor.classgroup.PluginClassGroup; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.OrderPriority; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.type.classreading.CachingMetadataReaderFactory; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.util.ClassUtils; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class ClassScannerProcessor implements SpringPluginProcessor{ + + static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; + + private final List pluginClassGroup = new ArrayList<>(); + + public ClassScannerProcessor(){ + } + + @Override + public void init(GenericApplicationContext mainApplicationContext) throws Exception { + addPluginClassGroup(); + } + + protected void addPluginClassGroup(){ + pluginClassGroup.add(new ComposeClassGroup()); + pluginClassGroup.add(new CallerClassGroup()); + } + + @Override + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception{ + ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); + ResourceLoader resourceLoader = new DefaultResourceLoader(pluginClassLoader); + ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(resourceLoader); + Set packageSearchPaths = getPackageSearchPaths(registryInfo); + MetadataReaderFactory metadataReaderFactory = getMetadataReaderFactory(registryInfo); + for (String packageSearchPath : packageSearchPaths) { + Resource[] resources = patternResolver.getResources(packageSearchPath); + for (Resource resource : resources) { + MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); + String className = metadataReader.getClassMetadata().getClassName(); + Class aClass = pluginClassLoader.loadClass(className); + groupClass(aClass, registryInfo); + } + } + } + + private void groupClass(Class aClass, SpringPluginRegistryInfo registryInfo){ + boolean filterResult = false; + for (PluginClassGroup classGroup : pluginClassGroup) { + String groupId = classGroup.groupId(); + if(ObjectUtils.isEmpty(groupId)){ + continue; + } + boolean filter = classGroup.filter(aClass); + if(filter){ + addClass(groupId, aClass, registryInfo); + filterResult = true; + } + } + if(!filterResult){ + addClass(PluginClassGroup.OTHER_CLASS_GROUP_ID, aClass, registryInfo); + } + } + + + private void addClass(String groupId, Class aClass, SpringPluginRegistryInfo registryInfo){ + List> classes = registryInfo.getRegistryInfo(groupId, ArrayList::new); + classes.add(aClass); + } + + + protected Set getPackageSearchPaths(SpringPluginRegistryInfo registryInfo) { + Class pluginClass = registryInfo.getPluginWrapper().getPluginClass(); + String[] scanBasePackages = getScanBasePackages(pluginClass); + Set packageSearchPaths = new HashSet<>(); + ConfigurableEnvironment environment = registryInfo.getPluginSpringApplication() + .getApplicationContext().getEnvironment(); + for (String scanBasePackage : scanBasePackages) { + String scanPackageName = ClassUtils.convertClassNameToResourcePath( + environment.resolveRequiredPlaceholders(scanBasePackage)); + scanPackageName = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + + scanPackageName + '/' + DEFAULT_RESOURCE_PATTERN; + packageSearchPaths.add(scanPackageName); + } + return packageSearchPaths; + } + + + protected String[] getScanBasePackages(Class pluginClass){ + SpringBootApplication springBootApplication = pluginClass.getAnnotation(SpringBootApplication.class); + if(springBootApplication != null){ + String[] scanBasePackages = springBootApplication.scanBasePackages(); + if(scanBasePackages.length > 0){ + return scanBasePackages; + } + } + return new String[]{ pluginClass.getPackage().getName() }; + } + + protected MetadataReaderFactory getMetadataReaderFactory(SpringPluginRegistryInfo registryInfo){ + ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); + return new CachingMetadataReaderFactory(pluginClassLoader); + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java deleted file mode 100644 index 86a0ba2..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/DefaultProcessorFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.processor.before.RegisterNecessaryBeanProcessor; -import org.springframework.context.ConfigurableApplicationContext; - -import java.util.List; - -/** - * @author starBlues - * @version 1.0 - */ -public class DefaultProcessorFactory extends AbstractProcessorFactory{ - - public DefaultProcessorFactory(ConfigurableApplicationContext mainApplicationContext, - IntegrationConfiguration configuration, - ProcessorRunMode processorRunMode) { - super(mainApplicationContext, configuration, processorRunMode); - } - - @Override - protected void addDefaultBeforeProcessor(List beforeProcessors) { - beforeProcessors.add(new RegisterNecessaryBeanProcessor()); - } - - @Override - protected void addDefaultAfterProcessor(List afterProcessors){ - - } - - @Override - protected void addDefaultCommonProcessor(List beforeProcessors, - List afterProcessors) { - addPluginControllerProcessor(beforeProcessors, afterProcessors); - } - - private void addPluginControllerProcessor(List beforeProcessors, - List afterProcessors){ - if(configuration != null && configuration.enablePluginRestController() - && processorRunMode == ProcessorRunMode.PLUGIN){ - addDefaultCommonProcessor(beforeProcessors, afterProcessors, - new PluginControllerProcessor(mainApplicationContext)); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java new file mode 100644 index 0000000..c8de5a6 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.realize.PluginUtils; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * 框架 bean 注册 + * @author starBlues + * @version 1.0 + */ +public class FrameDefineBeanRegistryProcessor implements SpringPluginProcessor{ + + @Override + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + PluginDescriptor pluginDescriptor = registryInfo.getPluginWrapper().getPluginDescriptor(); + ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); + beanFactory.registerSingleton("pluginDescriptor", pluginDescriptor); + beanFactory.registerSingleton("pluginUtils", new PluginUtils(applicationContext)); + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java new file mode 100644 index 0000000..fd4f732 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java @@ -0,0 +1,123 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.annotation.Caller; +import com.gitee.starblues.annotation.Supplier; +import com.gitee.starblues.factory.SpringBeanRegister; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; +import com.gitee.starblues.spring.processor.invoke.InvokeBeanFactory; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.processor.scanner.PluginClassPathBeanDefinitionScanner; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ScanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.type.filter.AnnotationTypeFilter; + +import java.util.List; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ + + + @Override + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + InvokeCallerBeanDefinitionScanner scanner = new InvokeCallerBeanDefinitionScanner(registryInfo); + scanner.doScan(ScanUtils.getScanBasePackages(registryInfo.getPluginWrapper().getPluginClass())); + // 注册发现 supper bean 的后置处理器 + applicationContext.registerBean(FindSupperBeanPostProcessor.class, registryInfo); + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } + + + private static class InvokeCallerBeanDefinitionScanner extends PluginClassPathBeanDefinitionScanner { + + private final SpringPluginRegistryInfo registryInfo; + + public InvokeCallerBeanDefinitionScanner(SpringPluginRegistryInfo registryInfo) { + super(registryInfo, false); + setResourceLoader(new DefaultResourceLoader(registryInfo.getPluginWrapper().getPluginClassLoader())); + this.registryInfo = registryInfo; + addIncludeFilter(new AnnotationTypeFilter(Caller.class)); + addExcludeFilter((metadataReader, metadataReaderFactory) -> { + String className = metadataReader.getClassMetadata().getClassName(); + return className.endsWith("package-info"); + }); + } + + + @Override + protected Set doScan(String... basePackages) { + Set holders = super.doScan(basePackages); + ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); + for (BeanDefinitionHolder holder : holders) { + AbstractBeanDefinition definition = (AbstractBeanDefinition) holder.getBeanDefinition(); + try { + Class aClass = pluginClassLoader.loadClass(definition.getBeanClassName()); + Caller caller = AnnotationUtils.findAnnotation(aClass, Caller.class); + if(caller == null){ + continue; + } + // 是调用方 + definition.getPropertyValues().add("callerAnnotation", caller); + definition.getPropertyValues().add("callerInterface", aClass); + definition.getPropertyValues().add("registryInfo", registryInfo); + definition.setBeanClass(InvokeBeanFactory.class); + definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + return holders; + } + + @Override + protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { + return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); + } + + } + + + private static class FindSupperBeanPostProcessor implements BeanPostProcessor { + + private final SpringPluginRegistryInfo registryInfo; + + private FindSupperBeanPostProcessor(SpringPluginRegistryInfo registryInfo) { + this.registryInfo = registryInfo; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + Supplier supplier = AnnotationUtils.findAnnotation(bean.getClass(), Supplier.class); + if(supplier != null){ + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + InvokeSupperCache.add(pluginId, new InvokeSupperCache.Cache(supplier.value(), beanName, + applicationContext)); + } + return bean; + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java new file mode 100644 index 0000000..3e59aee --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.integration.application.EmptyPluginApplication; +import com.gitee.starblues.integration.application.PluginApplication; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class OneselfBeanRegistryProcessor implements SpringPluginProcessor{ + + @Override + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { + ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); + PluginApplication pluginApplication = new EmptyPluginApplication(); + beanFactory.registerSingleton("pluginApplication", pluginApplication); + beanFactory.registerSingleton("pluginOperator", pluginApplication.getPluginOperator()); + beanFactory.registerSingleton("pluginUser", pluginApplication.getPluginUser()); + } + + @Override + public RunMode runMode() { + return RunMode.ONESELF; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java similarity index 82% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java index 87705f5..97772b2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java @@ -4,7 +4,10 @@ import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.PluginSpringApplication; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.*; +import com.gitee.starblues.utils.ClassUtils; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ReflectionUtils; import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,6 +15,7 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -20,51 +24,45 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl import java.lang.reflect.Method; import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; /** - * 插件 controller 处理者 * @author starBlues - * @version 3.0.0 + * @version 1.0 */ -public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterRefreshProcessor { +public class PluginControllerRegistryProcessor implements SpringPluginProcessor{ - private final static Logger LOG = LoggerFactory.getLogger(PluginControllerProcessor.class); + private final static Logger LOG = LoggerFactory.getLogger(PluginControllerRegistryProcessor.class); private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; - private final RequestMappingHandlerMapping requestMappingHandlerMapping; - private final Method getMappingForMethod; + private GenericApplicationContext mainApplicationContext; + private RequestMappingHandlerMapping requestMappingHandlerMapping; + private Method getMappingForMethod; - public PluginControllerProcessor(ConfigurableApplicationContext mainApplicationContext){ + private final AtomicBoolean canRegistered = new AtomicBoolean(false); + + + @Override + public void init(GenericApplicationContext mainApplicationContext) throws Exception { this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); - if(this.getMappingForMethod != null){ - this.getMappingForMethod.setAccessible(true); - } if(getMappingForMethod == null){ LOG.warn("RequestMappingHandlerMapping 类中没有发现 方法, 无法注册插件接口. " + "请检查当前环境是否为 web 环境"); } + this.getMappingForMethod.setAccessible(true); + canRegistered.set(true); } @Override - public void registryOfBefore(SpringPluginRegistryInfo registryInfo) { - ConfigurableApplicationContext mainApplicationContext = registryInfo.getMainApplicationContext(); - - - if(getMappingForMethod == null){ - return; - } - IntegrationConfiguration configuration = registryInfo.getConfiguration(); - if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) - && !configuration.enablePluginIdRestPathPrefix()){ - // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { + if(!canRegistered.get()){ return; } - PluginSpringApplication pluginSpringApplication = registryInfo.getPluginSpringApplication(); AnnotationConfigApplicationContext applicationContext = (AnnotationConfigApplicationContext)pluginSpringApplication.getApplicationContext(); @@ -73,8 +71,14 @@ public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterR } @Override - public void registryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception { - if(getMappingForMethod == null){ + public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + if(!canRegistered.get()){ + return; + } + IntegrationConfiguration configuration = registryInfo.getConfiguration(); + if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) + && !configuration.enablePluginIdRestPathPrefix()){ + // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 return; } String pluginId = registryInfo.getPluginWrapper().getPluginId(); @@ -104,29 +108,10 @@ public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterR } @Override - public void unRegistryOfAfter(SpringPluginRegistryInfo registryInfo) throws Exception { - List controllerWrappers = registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); - if(ObjectUtils.isEmpty(controllerWrappers)){ - return; - } - for (ControllerWrapper controllerBeanWrapper : controllerWrappers) { - if(controllerBeanWrapper == null){ - continue; - } - unregister(controllerBeanWrapper); - } - registryInfo.removeRegistryInfo(PROCESS_CONTROLLERS); + public RunMode runMode() { + return RunMode.PLUGIN; } - private void unregister(ControllerWrapper controllerBeanWrapper) { - Set requestMappingInfos = controllerBeanWrapper.getRequestMappingInfos(); - if(ObjectUtils.isEmpty(requestMappingInfos)){ - return; - } - for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { - requestMappingHandlerMapping.unregisterMapping(requestMappingInfo); - } - } private Set registry(SpringPluginRegistryInfo pluginRegistryInfo, Class aClass) throws Exception { @@ -156,7 +141,6 @@ public class PluginControllerProcessor implements BeforeRefreshProcessor, AfterR return AnnotationUtils.findAnnotation(method, RequestMapping.class) != null; } - private static class ChangeRestPathPostProcessor implements BeanPostProcessor { private final static Logger LOG = LoggerFactory.getLogger(ChangeRestPathPostProcessor.class); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java new file mode 100644 index 0000000..83f0ca4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java @@ -0,0 +1,49 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.Order; +import com.gitee.starblues.utils.OrderPriority; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public interface SpringPluginProcessor extends Order { + + default void init(GenericApplicationContext mainApplicationContext) throws Exception{}; + + default void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception{} + default void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception{} + + default void failure(SpringPluginRegistryInfo registryInfo) throws Exception{} + + default void close(SpringPluginRegistryInfo registryInfo) throws Exception{} + + @Override + default OrderPriority order(){ + return OrderPriority.getLowPriority(); + } + + + RunMode runMode(); + + + enum RunMode{ + /** + * 全部运行 + */ + ALL, + + /** + * 插件环境运行 + */ + PLUGIN, + + /** + * 插件独立运行 + */ + ONESELF + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java new file mode 100644 index 0000000..4aa7e03 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java @@ -0,0 +1,104 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.OrderPriority; +import com.gitee.starblues.utils.SpringBeanUtils; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author starBlues + * @version 1.0 + */ +public class SpringPluginProcessorFactory implements SpringPluginProcessor{ + + private final SpringPluginProcessor.RunMode runMode; + + private List processors; + + public SpringPluginProcessorFactory(SpringPluginProcessor.RunMode runMode) { + this.runMode = runMode; + } + + @Override + public void init(GenericApplicationContext mainApplicationContext) throws Exception { + List processors = getDefaultProcessors(); + if(runMode == RunMode.PLUGIN){ + List extendProcessors = SpringBeanUtils.getBeans(mainApplicationContext, + SpringPluginProcessor.class); + processors.addAll(extendProcessors); + } + this.processors = processors.stream() + .filter(p->{ + RunMode runMode = p.runMode(); + return runMode == RunMode.ALL || runMode == this.runMode; + }) + .sorted(CommonUtils.orderPriority(SpringPluginProcessor::order)) + .collect(Collectors.toList()); + for (SpringPluginProcessor processor : this.processors) { + processor.init(mainApplicationContext); + } + } + + private List getDefaultProcessors(){ + List processors = new ArrayList<>(); + //processors.add(new ClassScannerProcessor()); + processors.add(new BeanRegistryProcessor()); + processors.add(new FrameDefineBeanRegistryProcessor()); + processors.add(new InvokeOtherPluginProcessor()); + processors.add(new PluginControllerRegistryProcessor()); + processors.add(new OneselfBeanRegistryProcessor()); + return processors; + } + + + @Override + public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { + for (SpringPluginProcessor processor : processors) { + processor.refreshBefore(registryInfo); + } + } + + @Override + public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + for (SpringPluginProcessor processor : processors) { + processor.refreshAfter(registryInfo); + } + } + + @Override + public void failure(SpringPluginRegistryInfo registryInfo) throws Exception { + for (SpringPluginProcessor processor : processors) { + try { + processor.failure(registryInfo); + } catch (Exception e){ + e.printStackTrace(); + } + } + } + + @Override + public void close(SpringPluginRegistryInfo registryInfo) throws Exception { + for (SpringPluginProcessor processor : processors) { + try { + processor.close(registryInfo); + } catch (Exception e){ + e.printStackTrace(); + } + } + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java new file mode 100644 index 0000000..10b058b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java @@ -0,0 +1,24 @@ +package com.gitee.starblues.spring.processor.classgroup; + +import com.gitee.starblues.annotation.Caller; +import org.springframework.core.annotation.AnnotationUtils; + +/** + * @author starBlues + * @version 1.0 + */ +public class CallerClassGroup extends PluginClassGroup{ + + public final static String ID = getFullId("CallerClassGroup"); + + @Override + public String groupId() { + return ID; + } + + @Override + public boolean filter(Class aClass) { + return AnnotationUtils.findAnnotation(aClass, Caller.class) != null; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java new file mode 100644 index 0000000..ad69846 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java @@ -0,0 +1,24 @@ +package com.gitee.starblues.spring.processor.classgroup; + +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.stereotype.Component; + +/** + * @author starBlues + * @version 1.0 + */ +public class ComposeClassGroup extends PluginClassGroup{ + + public final static String ID = getFullId("ComposeClassGroup"); + + @Override + public String groupId() { + return ID; + } + + @Override + public boolean filter(Class aClass) { + return AnnotationUtils.findAnnotation(aClass, Component.class) != null; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java new file mode 100644 index 0000000..336a003 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java @@ -0,0 +1,35 @@ +package com.gitee.starblues.spring.processor.classgroup; + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class PluginClassGroup { + + protected static String ID_PREFIX = "PluginClassGroup_"; + + public static String OTHER_CLASS_GROUP_ID = ID_PREFIX + "otherClass"; + + /** + * 得到全id + * @param groupId groupId + * @return String + */ + static String getFullId(String groupId){ + return ID_PREFIX + groupId; + } + + /** + * 组id + * @return 组id + */ + public abstract String groupId(); + + /** + * 过滤类。 + * @param aClass 类 + * @return 返回true.说明符合该分组器。false不符合该分组器 + */ + public abstract boolean filter(Class aClass); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java new file mode 100644 index 0000000..e13e988 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java @@ -0,0 +1,50 @@ +package com.gitee.starblues.spring.processor.invoke; + +import com.gitee.starblues.annotation.Caller; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.springframework.beans.factory.FactoryBean; + +import java.lang.reflect.Proxy; + +/** + * @author starBlues + * @version 1.0 + */ +public class InvokeBeanFactory implements FactoryBean { + + private SpringPluginRegistryInfo registryInfo; + private Class callerInterface; + private Caller callerAnnotation; + + @Override + @SuppressWarnings("unchecked") + public T getObject() throws Exception { + ClassLoader classLoader = callerInterface.getClassLoader(); + Class[] interfaces = new Class[]{callerInterface}; + InvokeProxyHandler proxy = new InvokeProxyHandler(callerAnnotation); + return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy); + } + + @Override + public Class getObjectType() { + return callerInterface; + } + + @Override + public boolean isSingleton() { + return true; + } + + public void setRegistryInfo(SpringPluginRegistryInfo registryInfo) { + this.registryInfo = registryInfo; + } + + public void setCallerInterface(Class callerInterface) { + this.callerInterface = callerInterface; + } + + public void setCallerAnnotation(Caller callerAnnotation) { + this.callerAnnotation = callerAnnotation; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java new file mode 100644 index 0000000..4e3e365 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java @@ -0,0 +1,144 @@ +package com.gitee.starblues.spring.processor.invoke; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.gitee.starblues.annotation.Caller; +import com.gitee.starblues.annotation.Supplier; +import org.pf4j.util.StringUtils; +import org.springframework.util.ClassUtils; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Objects; + +/** + * @author starBlues + * @version 1.0 + */ +public class InvokeProxyHandler implements InvocationHandler { + + private final Caller callerAnnotation; + + private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + public InvokeProxyHandler(Caller callerAnnotation) { + this.callerAnnotation = callerAnnotation; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String pluginId = callerAnnotation.pluginId(); + Object supplierObject = InvokeSupperCache.getSupperBean(pluginId, callerAnnotation.value()); + if (supplierObject == null) { + if (StringUtils.isNullOrEmpty(pluginId)) { + throw new Exception("Not found '" + callerAnnotation.value() + "' supplier object"); + } else { + throw new Exception("Not found '" + callerAnnotation.value() + "' supplier object in plugin '" + + pluginId + "'"); + } + } + Caller.Method callerMethod = method.getAnnotation(Caller.Method.class); + if (args == null) { + args = new Object[]{}; + } + if (callerMethod == null) { + return notAnnotationInvoke(method, supplierObject, args); + } else { + return annotationInvoke(method, callerMethod, supplierObject, args); + } + } + + + + /** + * 有注解的调用 + * @param method 调用接口的方法 + * @param callerMethod 调用者方法注解 + * @param supplierObject 调用者对象 + * @param args 传入参数 + * @return 返回值 + * @throws Throwable 异常 + */ + private Object annotationInvoke(Method method, Caller.Method callerMethod, + Object supplierObject, Object[] args) throws Throwable{ + + String callerMethodName = callerMethod.value(); + Class supplierClass = supplierObject.getClass(); + Method[] methods = supplierClass.getMethods(); + Method supplierMethod = null; + for (Method m : methods) { + Supplier.Method supplierMethodAnnotation = m.getAnnotation(Supplier.Method.class); + if(supplierMethodAnnotation == null){ + continue; + } + if(Objects.equals(supplierMethodAnnotation.value(), callerMethodName)){ + supplierMethod = m; + break; + } + } + if(supplierMethod == null){ + // 如果为空, 说明没有找到被调用者的注解, 则走没有注解的代理调用。 + return notAnnotationInvoke(method, supplierObject, args); + } + Class[] parameterTypes = supplierMethod.getParameterTypes(); + if(parameterTypes.length != args.length){ + // 参数不匹配 + return notAnnotationInvoke(method, supplierObject, args); + } + Object[] supplierArgs = new Object[args.length]; + for (int i = 0; i < parameterTypes.length; i++) { + Class parameterType = parameterTypes[i]; + Object arg = args[i]; + if(parameterType == arg.getClass()){ + supplierArgs[i] = arg; + } else { + // 类型不匹配, 尝试使用json序列化 + String json = OBJECT_MAPPER.writeValueAsString(arg); + Object serializeObject = OBJECT_MAPPER.readValue(json, parameterType); + supplierArgs[i] = serializeObject; + } + } + Object invokeReturn = supplierMethod.invoke(supplierObject, supplierArgs); + return getReturnObject(invokeReturn, method); + } + + /** + * 没有注解调用 + * @param method 调用接口的方法 + * @param supplierObject 提供者对象 + * @param args 传入参数 + * @return 返回值 + * @throws Throwable 异常 + */ + private Object notAnnotationInvoke(Method method, Object supplierObject, Object[] args) throws Throwable{ + String name = method.getName(); + Class[] argClasses = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + argClasses[i] = args[i].getClass(); + } + Class supplierClass = supplierObject.getClass(); + Method supplierMethod = supplierClass.getMethod(name, argClasses); + Object invokeReturn = supplierMethod.invoke(supplierObject, args); + return getReturnObject(invokeReturn, method); + } + + + /** + * 得到返回值对象 + * @param invokeReturn 反射调用后返回的对象 + * @param method 调用接口的方法 + * @return 返回值对象 + * @throws Throwable Throwable + */ + private Object getReturnObject(Object invokeReturn, Method method) throws Throwable{ + if(invokeReturn == null){ + return null; + } + Class returnType = method.getReturnType(); + if(ClassUtils.isAssignable(invokeReturn.getClass(),returnType)){ + return invokeReturn; + } else { + String json = OBJECT_MAPPER.writeValueAsString(invokeReturn); + return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructType(method.getGenericReturnType()) ); + } + } +} \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java new file mode 100644 index 0000000..66b4c35 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java @@ -0,0 +1,80 @@ +package com.gitee.starblues.spring.processor.invoke; + +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class InvokeSupperCache { + + private static final Map> INVOKE_SUPPLIER_CACHE = new ConcurrentHashMap<>(); + + static Object getSupperBean(String pluginId, String supperKey){ + if(!ObjectUtils.isEmpty(pluginId)){ + Map cacheMap = INVOKE_SUPPLIER_CACHE.get(pluginId); + if(cacheMap == null){ + return null; + } + return getSupperBean(cacheMap.get(supperKey)); + } + for (Map value : INVOKE_SUPPLIER_CACHE.values()) { + Object supperBean = getSupperBean(value.get(supperKey)); + if(supperBean != null){ + return supperBean; + } + } + return null; + } + + private static Object getSupperBean(Cache cache){ + if(cache == null){ + return null; + } + GenericApplicationContext applicationContext = cache.getApplicationContext(); + if(applicationContext.containsBean(cache.getBeanName())){ + return applicationContext.getBean(cache.getBeanName()); + } + return null; + } + + public static void add(String pluginId, Cache cache){ + Map supperCache = INVOKE_SUPPLIER_CACHE.computeIfAbsent(pluginId, k -> new HashMap<>()); + supperCache.put(cache.getSupperKey(), cache); + } + + public static void remove(String pluginId){ + INVOKE_SUPPLIER_CACHE.remove(pluginId); + } + + public static class Cache{ + private final String supperKey; + private final String beanName; + private final GenericApplicationContext applicationContext; + + public Cache(String supperKey, String beanName, GenericApplicationContext applicationContext) { + this.supperKey = supperKey; + this.beanName = beanName; + this.applicationContext = applicationContext; + } + + public String getSupperKey() { + return supperKey; + } + + public String getBeanName() { + return beanName; + } + + public GenericApplicationContext getApplicationContext() { + return applicationContext; + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java new file mode 100644 index 0000000..bea92fe --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java @@ -0,0 +1,23 @@ +package com.gitee.starblues.spring.processor.scanner; + +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; + + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { + + public PluginClassPathBeanDefinitionScanner(SpringPluginRegistryInfo registryInfo) { + this(registryInfo, true); + } + + public PluginClassPathBeanDefinitionScanner(SpringPluginRegistryInfo registryInfo, boolean useDefaultFilters) { + super(registryInfo.getPluginSpringApplication().getApplicationContext(), useDefaultFilters, + registryInfo.getPluginSpringApplication().getApplicationContext().getEnvironment(), + registryInfo.getPluginSpringApplication().getResourceLoader()); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java new file mode 100644 index 0000000..663132a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java @@ -0,0 +1,16 @@ +package com.gitee.starblues.utils; + +/** + * @author starBlues + * @version 1.0 + */ +public interface Order { + + /** + * 排序, 数字越大越先执行 + * @return OrderPriority + */ + OrderPriority order(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java index ffc0ff6..d056975 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java @@ -2,6 +2,7 @@ package com.gitee.starblues.utils; import org.pf4j.PluginWrapper; +import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.util.ClassUtils; import java.io.File; @@ -45,6 +46,22 @@ public class ScanUtils { } } + /** + * 得到扫描的包 + * @param pluginClass 插件入口class + * @return 包集合 + */ + public static String[] getScanBasePackages(Class pluginClass){ + SpringBootApplication springBootApplication = pluginClass.getAnnotation(SpringBootApplication.class); + if(springBootApplication != null){ + String[] scanBasePackages = springBootApplication.scanBasePackages(); + if(scanBasePackages.length > 0){ + return scanBasePackages; + } + } + return new String[]{ pluginClass.getPackage().getName() }; + } + /** * 扫描windows环境下的类。包括子包中的类 * @param basePackage 包名 -- Gitee From bd2eb3aad6c2126137cc2688556136c6062d98e6 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Wed, 8 Dec 2021 13:38:51 +0800 Subject: [PATCH 15/37] 3.0.0-v3-add-extract --- .../gitee/starblues/annotation/Extract.java | 11 +- .../gitee/starblues/annotation/Supplier.java | 5 + .../pipe/PluginPipeProcessorFactory.java | 2 +- .../pipe/bean/inset/ExtractFactoryInset.java | 2 +- .../integration/IntegrationExtendPoint.java | 6 + .../DefaultPluginSpringApplication.java | 2 +- .../OneselfApplicationContextListener.java | 62 -------- .../oneself/OneselfSpringApplication.java | 2 +- .../processor/ClassScannerProcessor.java | 135 ------------------ .../processor/InvokeOtherPluginProcessor.java | 52 +++---- .../OneselfBeanRegistryProcessor.java | 4 + .../PluginControllerRegistryProcessor.java | 2 +- .../processor/SpringPluginProcessor.java | 2 +- .../SpringPluginProcessorFactory.java | 8 +- .../extract/ExtractBeanProcessor.java | 49 +++++++ .../processor}/extract/ExtractCoordinate.java | 2 +- .../processor}/extract/ExtractFactory.java | 34 +++-- .../extract/PluginExtractPipeProcessor.java | 2 +- 18 files changed, 131 insertions(+), 251 deletions(-) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{factory/process/pipe => spring/processor}/extract/ExtractCoordinate.java (97%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{factory/process/pipe => spring/processor}/extract/ExtractFactory.java (88%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{factory/process/pipe => spring/processor}/extract/PluginExtractPipeProcessor.java (97%) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java index 05c57eb..b7c6678 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java @@ -1,6 +1,7 @@ package com.gitee.starblues.annotation; -import com.gitee.starblues.utils.OrderPriority; +import org.springframework.core.annotation.AliasFor; +import org.springframework.stereotype.Component; import java.lang.annotation.*; @@ -12,8 +13,16 @@ import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented +@Component public @interface Extract { + /** + * 指定 Component Bean 名称 + * @return component name + */ + @AliasFor(annotation = Component.class) + String value() default ""; + /** * 业务 * @return 业务标志 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java index 04858f7..2a3b995 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java @@ -1,5 +1,8 @@ package com.gitee.starblues.annotation; +import org.springframework.core.annotation.AliasFor; +import org.springframework.stereotype.Component; + import java.lang.annotation.*; /** @@ -11,12 +14,14 @@ import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented +@Component public @interface Supplier { /** * 全局唯一key.全局不能重复 * @return String */ + @AliasFor(annotation = Component.class) String value(); /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java index ec43b32..9127fcb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java @@ -3,7 +3,7 @@ package com.gitee.starblues.factory.process.pipe; import com.gitee.starblues.extension.ExtensionInitializer; import com.gitee.starblues.factory.PluginRegistryInfo; import com.gitee.starblues.factory.process.pipe.classs.PluginClassProcess; -import com.gitee.starblues.factory.process.pipe.extract.PluginExtractPipeProcessor; +import com.gitee.starblues.spring.processor.extract.PluginExtractPipeProcessor; import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java index 26db0af..9f6bdfe 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java @@ -1,7 +1,7 @@ package com.gitee.starblues.factory.process.pipe.bean.inset; import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.extract.ExtractFactory; +import com.gitee.starblues.spring.processor.extract.ExtractFactory; /** * ExtractFactory 扩展工厂注册者 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java index 987dc68..9ed07ec 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java @@ -11,6 +11,7 @@ import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; import com.gitee.starblues.spring.DefaultSpringPlugin; import com.gitee.starblues.spring.SpringPlugin; +import com.gitee.starblues.spring.processor.extract.ExtractFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.support.GenericApplicationContext; @@ -73,4 +74,9 @@ public class IntegrationExtendPoint { return new DefaultMainResourcePatternDefiner(configuration.mainPackage()); } + @Bean + public ExtractFactory extractFactory(){ + return ExtractFactory.getInstant(); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java index f6e7268..f71f867 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java @@ -89,7 +89,7 @@ public class DefaultPluginSpringApplication implements PluginSpringApplication{ throw new RuntimeException("已经运行了PluginSpringApplication, 无法再运行"); } try { - springPluginProcessor.init(mainApplicationContext); + springPluginProcessor.initialize(mainApplicationContext); processEnvironment(); addPluginEnvironment(); addDefaultProcessor(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java deleted file mode 100644 index 60d7d91..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfApplicationContextListener.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.gitee.starblues.spring.oneself; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.listener.*; -import org.springframework.boot.context.event.*; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.support.GenericApplicationContext; - -/** - * @author starBlues - * @version 1.0 - */ -public class OneselfApplicationContextListener implements ApplicationListener { - - private final PluginSpringApplicationRunListeners listeners; - - private final SpringPluginRegistryInfo registryInfo; - - public OneselfApplicationContextListener(SpringPluginRegistryInfo registryInfo){ - this.registryInfo = registryInfo; - listeners = new PluginSpringApplicationRunListeners(ListenerRunMode.ONESELF); - addListeners(); - } - - - public void addListeners(){ - listeners.addListener(new ClassScannerListener()); - listeners.addListener(new NecessaryBeanRegistryListener()); - listeners.addListener(new InvokeOtherPluginRegistryListener()); - } - - - @Override - public void onApplicationEvent(ApplicationEvent event) { - try { - if(event instanceof ApplicationStartingEvent){ - listeners.starting(registryInfo); - } - if(event instanceof ApplicationEnvironmentPreparedEvent){ - listeners.environmentPrepared(registryInfo); - } - if(event instanceof ApplicationContextInitializedEvent){ - listeners.refreshPrepared(registryInfo); - } - if(event instanceof ApplicationPreparedEvent){ - listeners.refreshPrepared(registryInfo); - } - if(event instanceof ApplicationStartedEvent){ - listeners.started(registryInfo); - } - if(event instanceof ApplicationFailedEvent){ - listeners.failed(registryInfo, ((ApplicationFailedEvent)event).getException()); - } - } catch (Exception e){ - e.printStackTrace(); - } - - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java index dba258e..9019ec2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java @@ -105,7 +105,7 @@ public class OneselfSpringApplication extends SpringApplication implements Plugi ConfigurableApplicationContext applicationContext = super.createApplicationContext(); try { this.applicationContext = (GenericApplicationContext) applicationContext; - springPluginProcessor.init(this.applicationContext); + springPluginProcessor.initialize(this.applicationContext); } catch (Exception e) { e.printStackTrace(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java deleted file mode 100644 index 0271123..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/ClassScannerProcessor.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; -import com.gitee.starblues.spring.processor.classgroup.ComposeClassGroup; -import com.gitee.starblues.spring.processor.classgroup.PluginClassGroup; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.OrderPriority; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.type.classreading.CachingMetadataReaderFactory; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.util.ClassUtils; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author starBlues - * @version 1.0 - */ -public class ClassScannerProcessor implements SpringPluginProcessor{ - - static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; - - private final List pluginClassGroup = new ArrayList<>(); - - public ClassScannerProcessor(){ - } - - @Override - public void init(GenericApplicationContext mainApplicationContext) throws Exception { - addPluginClassGroup(); - } - - protected void addPluginClassGroup(){ - pluginClassGroup.add(new ComposeClassGroup()); - pluginClassGroup.add(new CallerClassGroup()); - } - - @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception{ - ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); - ResourceLoader resourceLoader = new DefaultResourceLoader(pluginClassLoader); - ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(resourceLoader); - Set packageSearchPaths = getPackageSearchPaths(registryInfo); - MetadataReaderFactory metadataReaderFactory = getMetadataReaderFactory(registryInfo); - for (String packageSearchPath : packageSearchPaths) { - Resource[] resources = patternResolver.getResources(packageSearchPath); - for (Resource resource : resources) { - MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); - String className = metadataReader.getClassMetadata().getClassName(); - Class aClass = pluginClassLoader.loadClass(className); - groupClass(aClass, registryInfo); - } - } - } - - private void groupClass(Class aClass, SpringPluginRegistryInfo registryInfo){ - boolean filterResult = false; - for (PluginClassGroup classGroup : pluginClassGroup) { - String groupId = classGroup.groupId(); - if(ObjectUtils.isEmpty(groupId)){ - continue; - } - boolean filter = classGroup.filter(aClass); - if(filter){ - addClass(groupId, aClass, registryInfo); - filterResult = true; - } - } - if(!filterResult){ - addClass(PluginClassGroup.OTHER_CLASS_GROUP_ID, aClass, registryInfo); - } - } - - - private void addClass(String groupId, Class aClass, SpringPluginRegistryInfo registryInfo){ - List> classes = registryInfo.getRegistryInfo(groupId, ArrayList::new); - classes.add(aClass); - } - - - protected Set getPackageSearchPaths(SpringPluginRegistryInfo registryInfo) { - Class pluginClass = registryInfo.getPluginWrapper().getPluginClass(); - String[] scanBasePackages = getScanBasePackages(pluginClass); - Set packageSearchPaths = new HashSet<>(); - ConfigurableEnvironment environment = registryInfo.getPluginSpringApplication() - .getApplicationContext().getEnvironment(); - for (String scanBasePackage : scanBasePackages) { - String scanPackageName = ClassUtils.convertClassNameToResourcePath( - environment.resolveRequiredPlaceholders(scanBasePackage)); - scanPackageName = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + - scanPackageName + '/' + DEFAULT_RESOURCE_PATTERN; - packageSearchPaths.add(scanPackageName); - } - return packageSearchPaths; - } - - - protected String[] getScanBasePackages(Class pluginClass){ - SpringBootApplication springBootApplication = pluginClass.getAnnotation(SpringBootApplication.class); - if(springBootApplication != null){ - String[] scanBasePackages = springBootApplication.scanBasePackages(); - if(scanBasePackages.length > 0){ - return scanBasePackages; - } - } - return new String[]{ pluginClass.getPackage().getName() }; - } - - protected MetadataReaderFactory getMetadataReaderFactory(SpringPluginRegistryInfo registryInfo){ - ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); - return new CachingMetadataReaderFactory(pluginClassLoader); - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority(); - } - - @Override - public RunMode runMode() { - return RunMode.ALL; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java index fd4f732..86838fd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java @@ -2,28 +2,22 @@ package com.gitee.starblues.spring.processor; import com.gitee.starblues.annotation.Caller; import com.gitee.starblues.annotation.Supplier; -import com.gitee.starblues.factory.SpringBeanRegister; import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; import com.gitee.starblues.spring.processor.invoke.InvokeBeanFactory; import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; import com.gitee.starblues.spring.processor.scanner.PluginClassPathBeanDefinitionScanner; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ScanUtils; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; -import java.util.List; +import java.util.Map; import java.util.Set; /** @@ -32,15 +26,27 @@ import java.util.Set; */ public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ - @Override public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); InvokeCallerBeanDefinitionScanner scanner = new InvokeCallerBeanDefinitionScanner(registryInfo); scanner.doScan(ScanUtils.getScanBasePackages(registryInfo.getPluginWrapper().getPluginClass())); - // 注册发现 supper bean 的后置处理器 - applicationContext.registerBean(FindSupperBeanPostProcessor.class, registryInfo); + } + + @Override + public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() + .getApplicationContext(); + Map supplierBeans = applicationContext.getBeansWithAnnotation(Supplier.class); + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + supplierBeans.forEach((k,v)->{ + Supplier supplier = AnnotationUtils.findAnnotation(v.getClass(), Supplier.class); + String supperKey = k; + if(supplier != null && !ObjectUtils.isEmpty(supplier.value())){ + supperKey = supplier.value(); + } + InvokeSupperCache.add(pluginId, new InvokeSupperCache.Cache(supperKey, k, applicationContext)); + }); + } @Override @@ -98,26 +104,4 @@ public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ } - private static class FindSupperBeanPostProcessor implements BeanPostProcessor { - - private final SpringPluginRegistryInfo registryInfo; - - private FindSupperBeanPostProcessor(SpringPluginRegistryInfo registryInfo) { - this.registryInfo = registryInfo; - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - Supplier supplier = AnnotationUtils.findAnnotation(bean.getClass(), Supplier.class); - if(supplier != null){ - String pluginId = registryInfo.getPluginWrapper().getPluginId(); - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); - InvokeSupperCache.add(pluginId, new InvokeSupperCache.Cache(supplier.value(), beanName, - applicationContext)); - } - return bean; - } - } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java index 3e59aee..0208151 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java @@ -1,14 +1,17 @@ package com.gitee.starblues.spring.processor; +import com.gitee.starblues.integration.IntegrationExtendPoint; import com.gitee.starblues.integration.application.EmptyPluginApplication; import com.gitee.starblues.integration.application.PluginApplication; import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.extract.ExtractFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; /** * @author starBlues * @version 1.0 + * @see IntegrationExtendPoint */ public class OneselfBeanRegistryProcessor implements SpringPluginProcessor{ @@ -21,6 +24,7 @@ public class OneselfBeanRegistryProcessor implements SpringPluginProcessor{ beanFactory.registerSingleton("pluginApplication", pluginApplication); beanFactory.registerSingleton("pluginOperator", pluginApplication.getPluginOperator()); beanFactory.registerSingleton("pluginUser", pluginApplication.getPluginUser()); + beanFactory.registerSingleton("extractFactory", ExtractFactory.getInstant()); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java index 97772b2..9d3a385 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java @@ -45,7 +45,7 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor @Override - public void init(GenericApplicationContext mainApplicationContext) throws Exception { + public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java index 83f0ca4..ba580ab 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java @@ -11,7 +11,7 @@ import org.springframework.context.support.GenericApplicationContext; */ public interface SpringPluginProcessor extends Order { - default void init(GenericApplicationContext mainApplicationContext) throws Exception{}; + default void initialize(GenericApplicationContext mainApplicationContext) throws Exception{}; default void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception{} default void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception{} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java index 4aa7e03..84e4970 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java @@ -1,6 +1,7 @@ package com.gitee.starblues.spring.processor; import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.extract.ExtractBeanProcessor; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.OrderPriority; import com.gitee.starblues.utils.SpringBeanUtils; @@ -25,7 +26,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor{ } @Override - public void init(GenericApplicationContext mainApplicationContext) throws Exception { + public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { List processors = getDefaultProcessors(); if(runMode == RunMode.PLUGIN){ List extendProcessors = SpringBeanUtils.getBeans(mainApplicationContext, @@ -40,17 +41,18 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor{ .sorted(CommonUtils.orderPriority(SpringPluginProcessor::order)) .collect(Collectors.toList()); for (SpringPluginProcessor processor : this.processors) { - processor.init(mainApplicationContext); + processor.initialize(mainApplicationContext); } } private List getDefaultProcessors(){ List processors = new ArrayList<>(); - //processors.add(new ClassScannerProcessor()); processors.add(new BeanRegistryProcessor()); processors.add(new FrameDefineBeanRegistryProcessor()); processors.add(new InvokeOtherPluginProcessor()); + processors.add(new ExtractBeanProcessor()); processors.add(new PluginControllerRegistryProcessor()); + processors.add(new OneselfBeanRegistryProcessor()); return processors; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java new file mode 100644 index 0000000..97ffb48 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java @@ -0,0 +1,49 @@ +package com.gitee.starblues.spring.processor.extract; + +import com.gitee.starblues.annotation.Extract; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.SpringPluginProcessor; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.Map; + +/** + * Extract 扩展Bean注册处理者 + * @author starBlues + * @version 1.0 + */ +public class ExtractBeanProcessor implements SpringPluginProcessor { + + private final ExtractFactory extractFactory = ExtractFactory.getInstant(); + + @Override + public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { + // 获取主程序的扩展 + Map extractMap = mainApplicationContext.getBeansWithAnnotation(Extract.class); + if(ObjectUtils.isEmpty(extractMap)){ + return; + } + for (Object extract : extractMap.values()) { + extractFactory.addOfMain(extract); + } + } + + @Override + public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + Map extractMap = applicationContext.getBeansWithAnnotation(Extract.class); + if(ObjectUtils.isEmpty(extractMap)){ + return; + } + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + for (Object extract : extractMap.values()) { + extractFactory.add(pluginId, extract); + } + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractCoordinate.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractCoordinate.java similarity index 97% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractCoordinate.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractCoordinate.java index a23407e..fb0e424 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractCoordinate.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractCoordinate.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.factory.process.pipe.extract; +package com.gitee.starblues.spring.processor.extract; import com.gitee.starblues.annotation.Extract; import org.pf4j.util.StringUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractFactory.java similarity index 88% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractFactory.java index 7a6278f..9f93b4b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/ExtractFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractFactory.java @@ -1,10 +1,13 @@ -package com.gitee.starblues.factory.process.pipe.extract; +package com.gitee.starblues.spring.processor.extract; import com.gitee.starblues.annotation.Extract; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import org.springframework.util.ClassUtils; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; /** * 扩展工厂 @@ -51,7 +54,8 @@ public class ExtractFactory { if(extract == null){ return; } - Map extractObjects = extractMap.computeIfAbsent(pluginId, k -> new ConcurrentHashMap<>()); + Map extractObjects = extractMap.computeIfAbsent(pluginId, k -> + new ConcurrentHashMap<>()); ExtractWrapper extractWrapper = new ExtractWrapper(extractObject, extract.order()); extractObjects.put(new ExtractCoordinate(extract, extractObject.getClass()), extractWrapper); } @@ -70,6 +74,7 @@ public class ExtractFactory { * @param 扩展的泛型 * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 */ + @SuppressWarnings("unchecked") public T getExtractByCoordinate(ExtractCoordinate coordinate){ Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); int currentOrder = Integer.MIN_VALUE; @@ -98,6 +103,7 @@ public class ExtractFactory { * @param 扩展的泛型 * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 */ + @SuppressWarnings("unchecked") public T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate){ Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); Map extractCoordinates = extractMap.get(pluginId); @@ -144,17 +150,17 @@ public class ExtractFactory { if(interfaceClass == null){ return Collections.emptyList(); } - List extracts = new ArrayList<>(); + List extracts = new ArrayList<>(); for (Map value : extractMap.values()) { for (ExtractWrapper extractWrapper : value.values()) { Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet( extractWrapper.getObject().getClass()); if(allInterfacesForClassAsSet.contains(interfaceClass)){ - extracts.add((T)extractWrapper.getObject()); + extracts.add(extractWrapper); } } } - return extracts; + return sort(extracts); } /** @@ -169,7 +175,7 @@ public class ExtractFactory { if(interfaceClass == null){ return Collections.emptyList(); } - List extracts = new ArrayList<>(); + List extracts = new ArrayList<>(); Map extractCoordinateObjectMap = extractMap.get(pluginId); if(extractCoordinateObjectMap == null || extractCoordinateObjectMap.isEmpty()){ return Collections.emptyList(); @@ -178,10 +184,10 @@ public class ExtractFactory { Object object = wrapper.getObject(); Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(object.getClass()); if(allInterfacesForClassAsSet.contains(interfaceClass)){ - extracts.add((T)object); + extracts.add(wrapper); } } - return extracts; + return sort(extracts); } /** @@ -218,6 +224,18 @@ public class ExtractFactory { return extractObject.getClass().getAnnotation(Extract.class); } + @SuppressWarnings("unchecked") + private List sort(List extractWrappers){ + if(ObjectUtils.isEmpty(extractWrappers)){ + return new ArrayList<>(0); + } + return extractWrappers.stream() + .sorted(Comparator.comparing(ExtractWrapper::getOrder, + Comparator.nullsLast(Comparator.reverseOrder()))) + .map(extractWrapper -> (T) extractWrapper.getObject()) + .collect(Collectors.toList()); + } + /** * 扩展对象包装类型 **/ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/PluginExtractPipeProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java similarity index 97% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/PluginExtractPipeProcessor.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java index a7c3f81..4293f03 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/extract/PluginExtractPipeProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.factory.process.pipe.extract; +package com.gitee.starblues.spring.processor.extract; import com.gitee.starblues.annotation.Extract; import com.gitee.starblues.factory.PluginRegistryInfo; -- Gitee From 42ebf2f024681854d83a9621b34eb3667034f195 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Wed, 8 Dec 2021 14:20:18 +0800 Subject: [PATCH 16/37] add Interceptors --- .../annotation/invoke/InvokeBean.java | 26 ---- .../annotation/invoke/InvokeParam.java | 21 --- .../pipe/PluginInterceptorsPipeProcessor.java | 4 +- .../PluginInterceptorsProcessor.java | 126 ++++++++++++++++++ .../SpringPluginProcessorFactory.java | 1 + .../PluginInterceptorRegister.java | 2 +- .../PluginInterceptorRegistration.java | 8 +- .../PluginInterceptorRegistry.java | 19 +-- .../com/gitee/starblues/utils/Assert.java | 2 - .../com/gitee/starblues/utils/ClassUtils.java | 4 +- .../starblues/utils/ReflectionUtils.java | 16 ++- 11 files changed, 157 insertions(+), 72 deletions(-) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{factory/process/pipe => spring/processor}/interceptor/PluginInterceptorRegister.java (80%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{factory/process/pipe => spring/processor}/interceptor/PluginInterceptorRegistration.java (96%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/{factory/process/pipe => spring/processor}/interceptor/PluginInterceptorRegistry.java (98%) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java deleted file mode 100644 index 60b8fd4..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeBean.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.annotation.invoke; - -import java.lang.annotation.*; - -/** - * @author starBlues - * @version 1.0 - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface InvokeBean { - - /** - * bean 名称 - * @return String - */ - String value(); - - /** - * 可指定具体,插件id. 可选. 如果不填, 默认会进行所有插件扫描 - * @return String - */ - String pluginId(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java deleted file mode 100644 index eda3df3..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/invoke/InvokeParam.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gitee.starblues.annotation.invoke; - -import java.lang.annotation.*; - -/** - * @author starBlues - * @version 1.0 - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface InvokeParam { - - /** - * 自定义参数名称 - * @return 参数名称 - */ - String value(); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java index 9783987..fa628e9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java @@ -1,8 +1,8 @@ package com.gitee.starblues.factory.process.pipe; import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.interceptor.PluginInterceptorRegister; -import com.gitee.starblues.factory.process.pipe.interceptor.PluginInterceptorRegistry; +import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegister; +import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegistry; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.utils.ClassUtils; import com.gitee.starblues.utils.CommonUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java new file mode 100644 index 0000000..662cd86 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java @@ -0,0 +1,126 @@ +package com.gitee.starblues.spring.processor; + +import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegister; +import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegistry; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.utils.ClassUtils; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.SpringBeanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.web.context.request.WebRequestInterceptor; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.handler.AbstractHandlerMapping; +import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginInterceptorsProcessor implements SpringPluginProcessor{ + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final static String INTERCEPTORS = "pluginHandlerInterceptors"; + + private AbstractHandlerMapping handlerMapping; + + + @Override + public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { + handlerMapping = SpringBeanUtils.getExistBean(mainApplicationContext, + AbstractHandlerMapping.class); + if(handlerMapping == null){ + logger.warn("Not found AbstractHandlerMapping, Plugin interceptor can't use"); + } + } + + @Override + public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + if(handlerMapping == null){ + return; + } + GenericApplicationContext pluginApplicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + List interceptorRegisters = SpringBeanUtils.getBeans(pluginApplicationContext, + PluginInterceptorRegister.class); + List interceptorsObjects = new ArrayList<>(); + List adaptedInterceptors = getAdaptedInterceptors(); + if(adaptedInterceptors == null){ + return; + } + IntegrationConfiguration configuration = registryInfo.getConfiguration(); + String pluginId = registryInfo.getPluginWrapper().getPluginId(); + String pluginRestPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginId); + + for (PluginInterceptorRegister interceptorRegister : interceptorRegisters) { + PluginInterceptorRegistry interceptorRegistry = new PluginInterceptorRegistry(pluginRestPrefix); + interceptorRegister.registry(interceptorRegistry); + List interceptors = interceptorRegistry.getInterceptors(); + if(interceptors == null || interceptors.isEmpty()){ + continue; + } + for (Object interceptor : interceptors) { + HandlerInterceptor handlerInterceptor = adaptInterceptor(interceptor); + adaptedInterceptors.add(handlerInterceptor); + interceptorsObjects.add(handlerInterceptor); + } + } + registryInfo.addRegistryInfo(INTERCEPTORS, interceptorsObjects); + } + + @Override + public void close(SpringPluginRegistryInfo registryInfo) throws Exception { + if(handlerMapping == null){ + return; + } + List interceptorsObjects = registryInfo.getRegistryInfo(INTERCEPTORS); + if(interceptorsObjects == null || interceptorsObjects.isEmpty()){ + return; + } + List adaptedInterceptors = getAdaptedInterceptors(); + if(adaptedInterceptors == null){ + return; + } + for (HandlerInterceptor interceptor : interceptorsObjects) { + adaptedInterceptors.remove(interceptor); + } + } + + @Override + public RunMode runMode() { + return RunMode.PLUGIN; + } + + /** + * 得到拦截器存储者 + * @return List + */ + private List getAdaptedInterceptors(){ + try { + return ClassUtils.getReflectionField(handlerMapping, "adaptedInterceptors", List.class); + } catch (IllegalAccessException e) { + logger.error("Can't get 'adaptedInterceptors' from AbstractHandlerMapping, so " + + "You can't use HandlerInterceptor. {} ", e.getMessage()); + return null; + } + } + + /** + * 转换拦截器 + * @param interceptor interceptor + * @return HandlerInterceptor + */ + private HandlerInterceptor adaptInterceptor(Object interceptor) { + if (interceptor instanceof HandlerInterceptor) { + return (HandlerInterceptor) interceptor; + } else if (interceptor instanceof WebRequestInterceptor) { + return new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor); + } else { + throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName()); + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java index 84e4970..630be34 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java @@ -51,6 +51,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor{ processors.add(new FrameDefineBeanRegistryProcessor()); processors.add(new InvokeOtherPluginProcessor()); processors.add(new ExtractBeanProcessor()); + processors.add(new PluginInterceptorsProcessor()); processors.add(new PluginControllerRegistryProcessor()); processors.add(new OneselfBeanRegistryProcessor()); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegister.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegister.java similarity index 80% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegister.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegister.java index 56fcba3..3623c10 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegister.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegister.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.factory.process.pipe.interceptor; +package com.gitee.starblues.spring.processor.interceptor; /** * 插件拦截器注册者 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegistration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistration.java similarity index 96% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegistration.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistration.java index ee8647e..799e4fc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegistration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistration.java @@ -1,7 +1,7 @@ -package com.gitee.starblues.factory.process.pipe.interceptor; +package com.gitee.starblues.spring.processor.interceptor; import com.gitee.starblues.utils.CommonUtils; -import org.pf4j.util.StringUtils; +import com.gitee.starblues.utils.ObjectUtils; import org.springframework.lang.Nullable; import org.springframework.util.PathMatcher; import org.springframework.web.servlet.HandlerInterceptor; @@ -68,7 +68,7 @@ public class PluginInterceptorRegistration { } // 局部的 for (String pattern : patterns) { - if(StringUtils.isNullOrEmpty(pattern)){ + if(ObjectUtils.isEmpty(pattern)){ continue; } this.includePatterns.add(CommonUtils.joiningPath(pluginRestApiPrefix, pattern)); @@ -86,7 +86,7 @@ public class PluginInterceptorRegistration { this.excludePatterns.addAll(Arrays.asList(patterns)); } for (String pattern : patterns) { - if(StringUtils.isNullOrEmpty(pattern)){ + if(ObjectUtils.isEmpty(pattern)){ continue; } this.excludePatterns.add(CommonUtils.joiningPath(pluginRestApiPrefix, pattern)); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegistry.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistry.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegistry.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistry.java index f95ecc8..59ed222 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/interceptor/PluginInterceptorRegistry.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistry.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.factory.process.pipe.interceptor; +package com.gitee.starblues.spring.processor.interceptor; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; @@ -68,6 +68,15 @@ public class PluginInterceptorRegistry { .collect(Collectors.toList()); } + private static final Comparator INTERCEPTOR_ORDER_COMPARATOR = + OrderComparator.INSTANCE.withSourceProvider(object -> { + if (object instanceof PluginInterceptorRegistration) { + return (Ordered) ((PluginInterceptorRegistration) object)::getOrder; + } + return null; + }); + + public enum Type{ /** @@ -82,14 +91,6 @@ public class PluginInterceptorRegistry { } - private static final Comparator INTERCEPTOR_ORDER_COMPARATOR = - OrderComparator.INSTANCE.withSourceProvider(object -> { - if (object instanceof PluginInterceptorRegistration) { - return (Ordered) ((PluginInterceptorRegistration) object)::getOrder; - } - return null; - }); - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java index 1991d5e..20bec8f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java @@ -1,8 +1,6 @@ package com.gitee.starblues.utils; -import sun.awt.geom.AreaOp; - import java.util.function.Supplier; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java index eb346ce..7aba7af 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java @@ -79,9 +79,7 @@ public class ClassUtils { if (field == null) { return null; } - if(!field.isAccessible()){ - field.setAccessible(true); - } + field.setAccessible(true); Object fieldObject = field.get(o); return (T) fieldObject; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 546acbf..b202aa0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -39,12 +39,20 @@ public abstract class ReflectionUtils { if(declaredFields.length == 0){ return null; } - for (Field field : declaredFields) { - if ((fieldName == null || fieldName.equals(field.getName())) && - (fieldType == null || fieldType.equals(field.getType()))) { - return field; + while (true){ + for (Field field : declaredFields) { + if ((fieldName == null || fieldName.equals(field.getName())) && + (fieldType == null || fieldType.equals(field.getType()))) { + return field; + } } + clazz = clazz.getSuperclass(); + if(clazz == null){ + break; + } + declaredFields = clazz.getDeclaredFields(); } + return null; } -- Gitee From 6ac96f32008323a8c89f7bdcb1688f1654bf8b53 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sun, 26 Dec 2021 18:21:30 +0800 Subject: [PATCH 17/37] 3.0.0 version2 --- pom.xml | 1 + springboot-plugin-bootstrap/pom.xml | 52 +++ .../bootstrap/ConfigurePluginEnvironment.java | 42 ++ .../bootstrap/PluginApplicationContext.java | 23 + .../bootstrap/PluginListableBeanFactory.java | 14 + .../bootstrap/PluginSpringApplication.java | 64 +++ .../bootstrap/SpringPluginBootstrap.java | 31 ++ .../starblues/core/DefaultPluginManager.java | 10 +- .../classloader/AbstractResourceLoader.java | 4 +- .../core/classloader/ClassPathLoader.java | 1 + .../DefaultMainResourceMatcher.java | 17 +- .../DefaultMainResourcePatternDefiner.java | 14 +- .../EmptyMainResourcePatternDefiner.java | 7 +- .../core/classloader/JarResourceLoader.java | 1 + .../MainResourcePatternDefiner.java | 4 +- .../core/classloader/PluginClassLoader.java | 11 +- .../AbstractExecutableArchiveLauncher.java | 8 + .../core/launcher/AbstractLauncher.java | 59 +++ .../core/launcher/ClasspathLauncher.java | 26 ++ .../JavaMainResourcePatternDefiner.java | 40 ++ .../starblues/core/launcher/Launcher.java | 17 + .../core/launcher/MainMethodRunner.java | 17 + .../core/launcher/MainProgramLauncher.java | 67 +++ .../starblues/core/launcher/MethodRunner.java | 53 +++ .../core/launcher/SpringBootstrap.java | 14 + .../core/launcher/SpringMainBootstrap.java | 69 +++ .../core/launcher/archive/Archive.java | 155 ++++++ .../launcher/archive/ExplodedArchive.java | 314 +++++++++++++ .../core/launcher/archive/JarFileArchive.java | 287 ++++++++++++ .../core/launcher/jar/AbstractJarFile.java | 61 +++ .../core/launcher/jar/AsciiBytes.java | 237 ++++++++++ .../starblues/core/launcher/jar/Bytes.java | 21 + .../jar/CentralDirectoryEndRecord.java | 228 +++++++++ .../jar/CentralDirectoryFileHeader.java | 170 +++++++ .../launcher/jar/CentralDirectoryParser.java | 80 ++++ .../launcher/jar/CentralDirectoryVisitor.java | 15 + .../core/launcher/jar/FileHeader.java | 46 ++ .../starblues/core/launcher/jar/Handler.java | 442 ++++++++++++++++++ .../starblues/core/launcher/jar/JarEntry.java | 103 ++++ .../launcher/jar/JarEntryCertification.java | 41 ++ .../core/launcher/jar/JarEntryFilter.java | 19 + .../starblues/core/launcher/jar/JarFile.java | 431 +++++++++++++++++ .../core/launcher/jar/JarFileEntries.java | 389 +++++++++++++++ .../core/launcher/jar/JarFileWrapper.java | 109 +++++ .../core/launcher/jar/JarURLConnection.java | 366 +++++++++++++++ .../core/launcher/jar/RandomAccessData.java | 57 +++ .../launcher/jar/RandomAccessDataFile.java | 234 ++++++++++ .../core/launcher/jar/StringSequence.java | 139 ++++++ .../launcher/jar/ZipInflaterInputStream.java | 70 +++ .../launcher/plugin/CacheRegistryInfo.java | 50 ++ .../plugin/DefaultPluginInteractive.java | 31 ++ .../plugin/DefaultPluginLauncherManager.java | 45 ++ .../plugin/DefaultPluginRegistryInfo.java | 36 ++ .../launcher/plugin/PluginInteractive.java | 16 + .../core/launcher/plugin/PluginLauncher.java | 68 +++ .../plugin/PluginLauncherManager.java | 18 + .../plugin/PluginLauncherStorage.java | 48 ++ .../launcher/plugin/PluginMethodRunner.java | 44 ++ .../launcher/plugin/PluginRegistryInfo.java | 15 + .../core/launcher/plugin/RegistryInfo.java | 45 ++ .../core/loader/DefaultPluginLoader.java | 28 +- .../core/scanner/BasePluginScanner.java | 4 + .../integration/IntegrationExtendPoint.java | 10 +- .../operator/DefaultPluginOperator.java | 15 +- .../starblues/spring/ApplicationContext.java | 12 + .../DefaultPluginSpringApplication.java | 2 + .../GenericApplicationContextReflection.java | 274 +++++++++++ .../spring/MainApplicationContext.java | 13 + .../MainApplicationContextReflection.java | 24 + .../PluginLocalConfigFileProcessor.java | 19 +- .../extract/ExtractBeanProcessor.java | 16 +- .../starblues/utils/ReflectionUtils.java | 24 +- .../main/resources/META-INF/spring.factories | 1 - 73 files changed, 5487 insertions(+), 51 deletions(-) create mode 100644 springboot-plugin-bootstrap/pom.xml create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java diff --git a/pom.xml b/pom.xml index a41e02c..b0761ce 100644 --- a/pom.xml +++ b/pom.xml @@ -13,6 +13,7 @@ springboot-plugin-framework + springboot-plugin-bootstrap springboot-plugin-framework-extension springboot-plugin-framework-example diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml new file mode 100644 index 0000000..c8760dc --- /dev/null +++ b/springboot-plugin-bootstrap/pom.xml @@ -0,0 +1,52 @@ + + + + springboot-plugin-framework-parent + com.gitee.starblues + 3.0.0-RELEASE + + 4.0.0 + + springboot-plugin-bootstrap + 插件引导模块 + + + 1.8 + UTF-8 + 3.8.1 + + 2.4.1 + + + + + org.springframework.boot + spring-boot + ${spring-boot-version} + provided + + + com.gitee.starblues + springboot-plugin-framework + 3.0.0-RELEASE + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + + \ No newline at end of file diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java new file mode 100644 index 0000000..ede8c0a --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -0,0 +1,42 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author starBlues + * @version 1.0 + */ +class ConfigurePluginEnvironment { + + private final static String PLUGIN_PROPERTY_NAME = "pluginPropertySources"; + + private final static String SPRING_CONFIG_NAME = "spring.config.name"; + private final static String SPRING_ADMIN_JMX_NAME = "spring.application.admin.jmx-name"; + private final static String SPRING_ADMIN_JMX_VALUE = "org.springframework.boot:type=Admin,name="; + + private final PluginDescriptor pluginDescriptor; + + ConfigurePluginEnvironment(PluginDescriptor pluginDescriptor) { + this.pluginDescriptor = Assert.isNotNull(pluginDescriptor, "pluginDescriptor 不能为空"); + } + + void configureEnvironment(ConfigurableEnvironment environment, String[] args) { + Map env = new HashMap<>(); + String pluginId = pluginDescriptor.getPluginId(); + String configFileName = pluginDescriptor.getConfigFileName(); + if(!ObjectUtils.isEmpty(configFileName)){ + env.put(SPRING_CONFIG_NAME, PluginFileUtils.getFileName(configFileName)); + } + env.put(SPRING_ADMIN_JMX_NAME, SPRING_ADMIN_JMX_VALUE + pluginId); + environment.getPropertySources().addLast(new MapPropertySource(PLUGIN_PROPERTY_NAME, env)); + } + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java new file mode 100644 index 0000000..4814d4e --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java @@ -0,0 +1,23 @@ +package com.gitee.starblues.bootstrap; + +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.io.ResourceLoader; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginApplicationContext extends AnnotationConfigApplicationContext { + + public PluginApplicationContext(DefaultListableBeanFactory beanFactory, + ResourceLoader resourceLoader) { + super(beanFactory); + setResourceLoader(resourceLoader); + } + + @Override + public String getApplicationName() { + return "jpa-plugin1"; + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java new file mode 100644 index 0000000..1e89976 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -0,0 +1,14 @@ +package com.gitee.starblues.bootstrap; + +import org.springframework.beans.factory.support.DefaultListableBeanFactory; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginListableBeanFactory extends DefaultListableBeanFactory { + + public PluginListableBeanFactory() { + } + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java new file mode 100644 index 0000000..fc43d48 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -0,0 +1,64 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.launcher.plugin.PluginInteractive; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.ResourceLoader; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginSpringApplication extends SpringApplication { + + private final PluginDescriptor pluginDescriptor; + + private final ConfigurableApplicationContext applicationContext; + private final DefaultListableBeanFactory beanFactory; + private final ResourceLoader resourceLoader; + private final ConfigurePluginEnvironment configurePluginEnvironment; + + public PluginSpringApplication(PluginInteractive pluginInteractive, Class... primarySources) { + super(primarySources); + this.pluginDescriptor = pluginInteractive.getPluginDescriptor(); + this.resourceLoader = new DefaultResourceLoader(getPluginClassLoader()); + this.beanFactory = new PluginListableBeanFactory(); + this.applicationContext = new PluginApplicationContext(beanFactory, resourceLoader); + this.configurePluginEnvironment = new ConfigurePluginEnvironment(pluginDescriptor); + setDefaultConfig(); + } + + private void setDefaultConfig(){ + setResourceLoader(resourceLoader); + setBannerMode(Banner.Mode.OFF); + setEnvironment(new StandardEnvironment()); + } + + @Override + protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { + super.configureEnvironment(environment, args); + configurePluginEnvironment.configureEnvironment(environment, args); + } + + @Override + protected ConfigurableApplicationContext createApplicationContext() { + return applicationContext; + } + + private ClassLoader getPluginClassLoader(){ + return PluginSpringApplication.class.getClassLoader(); + } + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java new file mode 100644 index 0000000..8353179 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.core.launcher.plugin.PluginInteractive; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class SpringPluginBootstrap { + + private PluginInteractive pluginInteractive; + + public ConfigurableApplicationContext run(Class primarySources, String[] args){ + return run(new Class[]{ primarySources }, args); + } + + public ConfigurableApplicationContext run(Class[] primarySources, String[] args){ + return start(primarySources, args); + } + + private ConfigurableApplicationContext start(Class[] primarySources, String[] args){ + PluginSpringApplication springApplication = new PluginSpringApplication(pluginInteractive, primarySources); + return springApplication.run(args); + } + + public final void setPluginInteractive(PluginInteractive pluginInteractive) { + this.pluginInteractive = pluginInteractive; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 13dfe93..5c66a2f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -43,7 +43,11 @@ public class DefaultPluginManager implements PluginManager{ public DefaultPluginManager(RealizeProvider realizeProvider, List pluginRootDirs) { this.provider = Assert.isNotNull(realizeProvider, "参数 realizeProvider 不能为空"); - this.pluginRootDirs = Assert.isNotEmpty(pluginRootDirs, "参数 pluginRootDirs 不能为空"); + if(pluginRootDirs == null){ + this.pluginRootDirs = Collections.emptyList(); + } else { + this.pluginRootDirs = pluginRootDirs; + } } public void setConfiguration(PluginConfiguration configuration) { @@ -64,6 +68,10 @@ public class DefaultPluginManager implements PluginManager{ throw new RuntimeException("已经加载过了插件, 不能在重复调用: loadPlugins"); } try { + if(ObjectUtils.isEmpty(pluginRootDirs)){ + log.warn("插件根目录为空, 无法发现插件."); + return Collections.emptyList(); + } List scanPluginPaths = provider.getPluginScanner().scan(pluginRootDirs); if(ObjectUtils.isEmpty(scanPluginPaths)){ StringBuilder warn = new StringBuilder("\n\n路径 {} 中未发现插件.\n"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index 3e8048e..35f5516 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -38,7 +38,9 @@ public abstract class AbstractResourceLoader { * @throws Exception 初始异常 */ public void init() throws Exception{ - + // 添加root 路径 + Resource rootResource = new Resource("root", baseUrl, baseUrl, null); + resourceCache.put("/", rootResource); } protected boolean existResource(String name){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java index 996b6b1..8c644eb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -27,6 +27,7 @@ public class ClassPathLoader extends AbstractResourceLoader{ @Override public void init() throws Exception { + super.init(); File file = new File(url.toURI()); load(file, null); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java index 17dfa14..4db8f2d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java @@ -23,7 +23,7 @@ public class DefaultMainResourceMatcher implements MainResourceMatcher{ @Override public boolean match(String resourceUrl) { - Set resourcePatterns = mainResourcePatternDefiner.getResourcePatterns(); + Set resourcePatterns = mainResourcePatternDefiner.getIncludeResourcePatterns(); return match(resourcePatterns, resourceUrl); } @@ -34,6 +34,20 @@ public class DefaultMainResourceMatcher implements MainResourceMatcher{ } private boolean match(Collection patterns, String url){ + if(ObjectUtils.isEmpty(patterns) || ObjectUtils.isEmpty(url)){ + return false; + } + url = formatUrl(url); + for (String pattern : patterns) { + boolean match = pathMatcher.match(pattern, url); + if(match){ + return !excludeMatch(mainResourcePatternDefiner.getExcludeResourcePatterns(), url); + } + } + return false; + } + + private boolean excludeMatch(Collection patterns, String url){ if(ObjectUtils.isEmpty(patterns) || ObjectUtils.isEmpty(url)){ return false; } @@ -47,6 +61,7 @@ public class DefaultMainResourceMatcher implements MainResourceMatcher{ return false; } + private String formatUrl(String url){ url = url.replace("\\", AntPathMatcher.DEFAULT_PATH_SEPARATOR); if(url.startsWith(AntPathMatcher.DEFAULT_PATH_SEPARATOR)){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java index f9e5b4e..d8db0c4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java @@ -25,11 +25,17 @@ public class DefaultMainResourcePatternDefiner implements MainResourcePatternDef initDefaultSpringFactories(); } + @Override - public Set getResourcePatterns() { + public Set getIncludeResourcePatterns() { return resourcePatterns; } + @Override + public Set getExcludeResourcePatterns() { + return null; + } + @Override public Set getSpringFactoriesPatterns() { return springFactoriesPatterns; @@ -50,7 +56,6 @@ public class DefaultMainResourcePatternDefiner implements MainResourcePatternDef // aop resourcePatterns.add("org/aspectj/**"); - resourcePatterns.add("org/aopalliance/**"); // === spring-boot-starter === // logback-classic @@ -67,9 +72,6 @@ public class DefaultMainResourcePatternDefiner implements MainResourcePatternDef resourcePatterns.add("META-INF/spring.factories"); - // spring - resourcePatterns.add("org/springframework/**"); - // spring-boot resourcePatterns.add("org/springframework/boot/**"); // spring-boot-autoconfigure @@ -86,8 +88,6 @@ public class DefaultMainResourcePatternDefiner implements MainResourcePatternDef } private void initDefaultSpringFactories() { - springFactoriesPatterns.add("**/spring-boot/**"); - springFactoriesPatterns.add("**/spring-beans/**"); // 当前框架名称 springFactoriesPatterns.add("**/springboot-plugin-framework/**"); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java index a8338f7..987f1d4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java @@ -10,7 +10,12 @@ import java.util.Set; public class EmptyMainResourcePatternDefiner implements MainResourcePatternDefiner { @Override - public Set getResourcePatterns() { + public Set getIncludeResourcePatterns() { + return null; + } + + @Override + public Set getExcludeResourcePatterns() { return null; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index 44302b5..e026fd6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -25,6 +25,7 @@ public class JarResourceLoader extends AbstractResourceLoader{ @Override public void init() throws Exception { + super.init(); // 解析 try (InputStream fileInputStream = sourceUrl.openStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java index 64fe72f..65af2ac 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java @@ -13,9 +13,11 @@ public interface MainResourcePatternDefiner { * 资源名称. * @return 资源名称集合 */ - Set getResourcePatterns(); + Set getIncludeResourcePatterns(); + Set getExcludeResourcePatterns(); + /** * spring spi 定义 * @return spring spi 集合 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index f61feab..20ac03b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -44,9 +44,10 @@ public class PluginClassLoader extends AbstractPluginClassLoader implements Reso MainResourcePatternDefiner patternDefiner = Assert.isNotNull(mainResourcePatternDefiner, "参数 mainResourcePatternDefiner 不能为空"); setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); + System.out.println("PluginClassLoader=" + this); } - protected void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ + public void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ this.mainResourceMatcher = Assert.isNotNull(mainResourceMatcher, "参数 mainResourceMatcher 不能为空"); } @@ -55,6 +56,12 @@ public class PluginClassLoader extends AbstractPluginClassLoader implements Reso resourceLoaderFactory.addResource(file); } + public void addResource(Path path) { + resourceLoaderFactory.addResource(path); + } + + + public String getPluginId() { return pluginId; } @@ -197,7 +204,7 @@ public class PluginClassLoader extends AbstractPluginClassLoader implements Reso private String formatResourceName(String resourceName){ if(ObjectUtils.isEmpty(resourceName)) { - return resourceName; + return ResourceUtils.PACKAGE_SPLIT; } String[] split = resourceName.split("/"); StringBuilder newPath = new StringBuilder(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java new file mode 100644 index 0000000..4c59727 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java @@ -0,0 +1,8 @@ +package com.gitee.starblues.core.launcher; + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class AbstractExecutableArchiveLauncher { +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java new file mode 100644 index 0000000..a2d08d2 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java @@ -0,0 +1,59 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.core.launcher.archive.Archive; +import com.gitee.starblues.core.launcher.jar.JarFile; + +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class AbstractLauncher implements Launcher { + + @Override + public R run(String... args) throws Exception { + JarFile.registerUrlProtocolHandler(); + ClassLoader classLoader = createClassLoader(getClassPathArchivesIterator()); + Thread thread = Thread.currentThread(); + ClassLoader oldClassLoader = thread.getContextClassLoader(); + try { + thread.setContextClassLoader(classLoader); + return launch(classLoader, args); + } finally { + thread.setContextClassLoader(oldClassLoader); + } + } + + protected Iterator getClassPathArchivesIterator() throws Exception { + return Collections.emptyListIterator(); + } + + protected ClassLoader createClassLoader(Iterator archives) throws Exception { + List urls = new ArrayList<>(50); + while (archives.hasNext()) { + urls.add(archives.next().getUrl()); + } + return createClassLoader(urls.toArray(new URL[0])); + } + + protected ClassLoader createClassLoader(URL[] urls) throws Exception { + return new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); + } + + /** + * 子类实现具体的启动方法 + * @param classLoader 当前的 ClassLoader + * @param args 启动参数 + * @return 启动返回值 + * @throws Exception 启动异常 + */ + protected abstract R launch(ClassLoader classLoader, String... args) throws Exception; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java new file mode 100644 index 0000000..a199e21 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java @@ -0,0 +1,26 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.core.launcher.archive.Archive; + +import java.util.Iterator; + +/** + * @author starBlues + * @version 1.0 + */ +public class ClasspathLauncher extends AbstractLauncher{ + + + + + @Override + protected Iterator getClassPathArchivesIterator() throws Exception { + return super.getClassPathArchivesIterator(); + } + + @Override + protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { + Thread.currentThread().setContextClassLoader(classLoader); + return classLoader; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java new file mode 100644 index 0000000..e4054bc --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java @@ -0,0 +1,40 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; + +import java.util.HashSet; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class JavaMainResourcePatternDefiner implements MainResourcePatternDefiner { + + private final Set includes = new HashSet<>(); + + public JavaMainResourcePatternDefiner(){ + // == java == + includes.add("java/**"); + includes.add("javax/**"); + includes.add("sun/**"); + includes.add("org/xml/**"); + includes.add("jdk/**"); + includes.add("org/w3c/**"); + } + + @Override + public Set getIncludeResourcePatterns() { + return includes; + } + + @Override + public Set getExcludeResourcePatterns() { + return null; + } + + @Override + public Set getSpringFactoriesPatterns() { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java new file mode 100644 index 0000000..87b973c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java @@ -0,0 +1,17 @@ +package com.gitee.starblues.core.launcher; + +/** + * @author starBlues + * @version 1.0 + */ +public interface Launcher { + + /** + * 启动运行 + * @param args 启动传入的参数 + * @return 启动后的返回值 + * @throws Exception 启动异常 + */ + R run(String... args) throws Exception; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java new file mode 100644 index 0000000..b4a5293 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java @@ -0,0 +1,17 @@ +package com.gitee.starblues.core.launcher; + +/** + * @author starBlues + * @version 1.0 + */ +public class MainMethodRunner extends MethodRunner{ + + public MainMethodRunner(String mainClass, String mainRunMethod, String[] args) { + super(mainClass, mainRunMethod, args); + } + + @Override + protected Object getInstance(Class mainClass) throws Exception { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java new file mode 100644 index 0000000..d12f0dc --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java @@ -0,0 +1,67 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.core.classloader.PluginClassLoader; +import com.gitee.starblues.core.launcher.archive.Archive; +import com.gitee.starblues.core.launcher.archive.ExplodedArchive; +import com.gitee.starblues.core.launcher.archive.JarFileArchive; +import com.gitee.starblues.utils.PluginFileUtils; + +import java.io.File; +import java.lang.management.ManagementFactory; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class MainProgramLauncher extends AbstractLauncher{ + + private final SpringBootstrap springBootstrap; + + public MainProgramLauncher(SpringBootstrap springBootstrap) { + this.springBootstrap = springBootstrap; + } + + @Override + protected ClassLoader createClassLoader(URL[] urls) throws Exception { + PluginClassLoader pluginClassLoader = new PluginClassLoader( + "main", null, MainProgramLauncher.class.getClassLoader(), + new JavaMainResourcePatternDefiner() + ); + for (URL url : urls) { + pluginClassLoader.addResource(Paths.get(url.toURI())); + } + + return pluginClassLoader; + } + + @Override + protected Iterator getClassPathArchivesIterator() throws Exception { + // TODO 生产环境下待定 + String classPath = ManagementFactory.getRuntimeMXBean().getClassPath(); + String[] split = classPath.split(";"); + List archives = new ArrayList<>(); + for (String s : split) { + Path path = Paths.get(s); + File file = path.toFile(); + if(PluginFileUtils.isJarFile(path)){ + archives.add(new JarFileArchive(file)); + } else { + archives.add(new ExplodedArchive(file)); + } + } + return archives.iterator(); + } + + @Override + protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { + MethodRunner run = new MethodRunner(springBootstrap.getClass().getName(), "run", args); + run.run(classLoader); + return classLoader; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java new file mode 100644 index 0000000..91dde0a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java @@ -0,0 +1,53 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ReflectionUtils; + +import java.lang.reflect.Method; +import java.util.StringJoiner; + +/** + * @author starBlues + * @version 1.0 + */ +public class MethodRunner { + + protected final String className; + protected final String runMethodName; + + protected final String[] args; + + public MethodRunner(String className, String runMethodName, String[] args) { + this.className = Assert.isNotEmpty(className, "className 不能为空"); + this.runMethodName = Assert.isNotEmpty(runMethodName, "runMethod 不能为空"); + this.args = (args != null) ? args.clone() : null; + } + + public Object run() throws Exception { + return run(null); + } + + public Object run(ClassLoader classLoader) throws Exception { + if(classLoader == null){ + classLoader = Thread.currentThread().getContextClassLoader(); + } + Class runClass = Class.forName(this.className, false, classLoader); + return runMethod(runClass); + } + + protected Object runMethod(Class runClass) throws Exception { + Method runMethod = ReflectionUtils.findMethod(runClass, runMethodName, String[].class); + if(runMethod == null) { + throw new NoSuchMethodException(runClass.getName() + "." + runMethodName + "(String[] args)"); + } + Object instance = getInstance(runClass); + runMethod.setAccessible(true); + runMethod.invoke(instance, new Object[] { this.args }); + return instance; + } + + protected Object getInstance(Class runClass) throws Exception { + return runClass.getConstructor().newInstance(); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java new file mode 100644 index 0000000..5d63a45 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java @@ -0,0 +1,14 @@ +package com.gitee.starblues.core.launcher; + +/** + * @author starBlues + * @version 1.0 + */ +public interface SpringBootstrap { + + String RUN_METHOD_NAME = "run"; + + + void run(String[] args) throws Exception; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java new file mode 100644 index 0000000..d797b80 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java @@ -0,0 +1,69 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.utils.Assert; + +import java.util.concurrent.CountDownLatch; + +/** + * @author starBlues + * @version 1.0 + */ +public class SpringMainBootstrap { + + private static final String MAIN_RUN_METHOD = "main"; + + private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1); + + private static SpringBootstrap springBootstrap; + + public static void launch(Class bootstrapClass, String[] args) { + try { + SpringBootstrap springBootstrap = bootstrapClass.getConstructor().newInstance(); + launch(springBootstrap, args); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void launch(SpringBootstrap springBootstrap, String[] args) { + SpringMainBootstrap.springBootstrap = Assert.isNotNull(springBootstrap, "springBootBootstrap 不能为空"); + MainMethodRunner mainMethodRunner = new MainMethodRunner(SpringMainBootstrap.class.getName(), + MAIN_RUN_METHOD, args); + Thread launchThread = new Thread(new Runner(mainMethodRunner)); + launchThread.start(); + try { + COUNT_DOWN_LATCH.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private static void main(String[] args) throws Exception { + Assert.isNotNull(springBootstrap, "springBootstrap 不能为空"); + MainProgramLauncher launcher = new MainProgramLauncher(springBootstrap); + launcher.run(args); + } + + + private static class Runner implements Runnable{ + + private final MainMethodRunner mainMethodRunner; + + private Runner(MainMethodRunner mainMethodRunner) { + this.mainMethodRunner = mainMethodRunner; + } + + @Override + public void run() { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + try { + mainMethodRunner.run(contextClassLoader); + } catch (Exception e) { + e.printStackTrace(); + } finally { + COUNT_DOWN_LATCH.countDown(); + } + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java new file mode 100644 index 0000000..25af38b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java @@ -0,0 +1,155 @@ +package com.gitee.starblues.core.launcher.archive; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; +import java.util.function.Consumer; +import java.util.jar.Manifest; + +/** + * @author starBlues + * @version 1.0 + */ +public interface Archive extends Iterable, AutoCloseable { + + /** + * Returns a URL that can be used to load the archive. + * @return the archive URL + * @throws MalformedURLException if the URL is malformed + */ + URL getUrl() throws MalformedURLException; + + /** + * Returns the manifest of the archive. + * @return the manifest + * @throws IOException if the manifest cannot be read + */ + Manifest getManifest() throws IOException; + + /** + * Returns nested {@link Archive}s for entries that match the specified filters. + * @param searchFilter filter used to limit when additional sub-entry searching is + * required or {@code null} if all entries should be considered. + * @param includeFilter filter used to determine which entries should be included in + * the result or {@code null} if all entries should be included + * @return the nested archives + * @throws IOException on IO error + * @since 2.3.0 + */ + default Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) + throws IOException { + EntryFilter combinedFilter = (entry) -> (searchFilter == null || searchFilter.matches(entry)) + && (includeFilter == null || includeFilter.matches(entry)); + List nestedArchives = getNestedArchives(combinedFilter); + return nestedArchives.iterator(); + } + + /** + * Returns nested {@link Archive}s for entries that match the specified filter. + * @param filter the filter used to limit entries + * @return nested archives + * @throws IOException if nested archives cannot be read + * @deprecated since 2.3.0 for removal in 2.5.0 in favor of + * {@link #getNestedArchives(EntryFilter, EntryFilter)} + */ + @Deprecated + default List getNestedArchives(EntryFilter filter) throws IOException { + throw new IllegalStateException("Unexpected call to getNestedArchives(filter)"); + } + + /** + * Return a new iterator for the archive entries. + * @see java.lang.Iterable#iterator() + * @deprecated since 2.3.0 for removal in 2.5.0 in favor of using + * {@link org.springframework.boot.loader.jar.JarFile} to access entries and + * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. + */ + @Deprecated + @Override + Iterator iterator(); + + /** + * Performs the given action for each element of the {@code Iterable} until all + * elements have been processed or the action throws an exception. + * @see Iterable#forEach + * @deprecated since 2.3.0 for removal in 2.5.0 in favor of using + * {@link org.springframework.boot.loader.jar.JarFile} to access entries and + * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. + */ + @Deprecated + @Override + default void forEach(Consumer action) { + Objects.requireNonNull(action); + for (Entry entry : this) { + action.accept(entry); + } + } + + /** + * Creates a {@link Spliterator} over the elements described by this {@code Iterable}. + * @see Iterable#spliterator + * @deprecated since 2.3.0 for removal in 2.5.0 in favor of using + * {@link org.springframework.boot.loader.jar.JarFile} to access entries and + * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. + */ + @Deprecated + @Override + default Spliterator spliterator() { + return Spliterators.spliteratorUnknownSize(iterator(), 0); + } + + /** + * Return if the archive is exploded (already unpacked). + * @return if the archive is exploded + * @since 2.3.0 + */ + default boolean isExploded() { + return false; + } + + /** + * Closes the {@code Archive}, releasing any open resources. + * @throws Exception if an error occurs during close processing + * @since 2.2.0 + */ + @Override + default void close() throws Exception { + + } + + /** + * Represents a single entry in the archive. + */ + interface Entry { + + /** + * Returns {@code true} if the entry represents a directory. + * @return if the entry is a directory + */ + boolean isDirectory(); + + /** + * Returns the name of the entry. + * @return the name of the entry + */ + String getName(); + + } + + /** + * Strategy interface to filter {@link Entry Entries}. + */ + @FunctionalInterface + interface EntryFilter { + + /** + * Apply the jar entry filter. + * @param entry the entry to filter + * @return {@code true} if the filter matches + */ + boolean matches(Entry entry); + + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java new file mode 100644 index 0000000..2a174f0 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java @@ -0,0 +1,314 @@ +package com.gitee.starblues.core.launcher.archive; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.*; +import java.util.jar.Manifest; + +/** + * @author starBlues + * @version 1.0 + */ +public class ExplodedArchive implements Archive { + + private static final Set SKIPPED_NAMES = new HashSet<>(Arrays.asList(".", "..")); + + private final File root; + + private final boolean recursive; + + private File manifestFile; + + private Manifest manifest; + + /** + * Create a new {@link ExplodedArchive} instance. + * @param root the root directory + */ + public ExplodedArchive(File root) { + this(root, true); + } + + /** + * Create a new {@link ExplodedArchive} instance. + * @param root the root directory + * @param recursive if recursive searching should be used to locate the manifest. + * Defaults to {@code true}, directories with a large tree might want to set this to + * {@code false}. + */ + public ExplodedArchive(File root, boolean recursive) { + if (!root.exists() || !root.isDirectory()) { + throw new IllegalArgumentException("Invalid source directory " + root); + } + this.root = root; + this.recursive = recursive; + this.manifestFile = getManifestFile(root); + } + + private File getManifestFile(File root) { + File metaInf = new File(root, "META-INF"); + return new File(metaInf, "MANIFEST.MF"); + } + + @Override + public URL getUrl() throws MalformedURLException { + return this.root.toURI().toURL(); + } + + @Override + public Manifest getManifest() throws IOException { + if (this.manifest == null && this.manifestFile.exists()) { + try (FileInputStream inputStream = new FileInputStream(this.manifestFile)) { + this.manifest = new Manifest(inputStream); + } + } + return this.manifest; + } + + @Override + public Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException { + return new ArchiveIterator(this.root, this.recursive, searchFilter, includeFilter); + } + + @Override + @Deprecated + public Iterator iterator() { + return new EntryIterator(this.root, this.recursive, null, null); + } + + protected Archive getNestedArchive(Entry entry) throws IOException { + File file = ((FileEntry) entry).getFile(); + return (file.isDirectory() ? new ExplodedArchive(file) : new SimpleJarFileArchive((FileEntry) entry)); + } + + @Override + public boolean isExploded() { + return true; + } + + @Override + public String toString() { + try { + return getUrl().toString(); + } + catch (Exception ex) { + return "exploded archive"; + } + } + + /** + * File based {@link Entry} {@link Iterator}. + */ + private abstract static class AbstractIterator implements Iterator { + + private static final Comparator entryComparator = Comparator.comparing(File::getAbsolutePath); + + private final File root; + + private final boolean recursive; + + private final EntryFilter searchFilter; + + private final EntryFilter includeFilter; + + private final Deque> stack = new LinkedList<>(); + + private FileEntry current; + + private String rootUrl; + + AbstractIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { + this.root = root; + this.rootUrl = this.root.toURI().getPath(); + this.recursive = recursive; + this.searchFilter = searchFilter; + this.includeFilter = includeFilter; + this.stack.add(listFiles(root)); + this.current = poll(); + } + + @Override + public boolean hasNext() { + return this.current != null; + } + + @Override + public T next() { + FileEntry entry = this.current; + if (entry == null) { + throw new NoSuchElementException(); + } + this.current = poll(); + return adapt(entry); + } + + private FileEntry poll() { + while (!this.stack.isEmpty()) { + while (this.stack.peek().hasNext()) { + File file = this.stack.peek().next(); + if (SKIPPED_NAMES.contains(file.getName())) { + continue; + } + FileEntry entry = getFileEntry(file); + if (isListable(entry)) { + this.stack.addFirst(listFiles(file)); + } + if (this.includeFilter == null || this.includeFilter.matches(entry)) { + return entry; + } + } + this.stack.poll(); + } + return null; + } + + private FileEntry getFileEntry(File file) { + URI uri = file.toURI(); + String name = uri.getPath().substring(this.rootUrl.length()); + try { + return new FileEntry(name, file, uri.toURL()); + } + catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + } + + private boolean isListable(FileEntry entry) { + return entry.isDirectory() && (this.recursive || entry.getFile().getParentFile().equals(this.root)) + && (this.searchFilter == null || this.searchFilter.matches(entry)) + && (this.includeFilter == null || !this.includeFilter.matches(entry)); + } + + private Iterator listFiles(File file) { + File[] files = file.listFiles(); + if (files == null) { + return Collections.emptyIterator(); + } + Arrays.sort(files, entryComparator); + return Arrays.asList(files).iterator(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException("remove"); + } + + protected abstract T adapt(FileEntry entry); + + } + + private static class EntryIterator extends AbstractIterator { + + EntryIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { + super(root, recursive, searchFilter, includeFilter); + } + + @Override + protected Entry adapt(FileEntry entry) { + return entry; + } + + } + + private static class ArchiveIterator extends AbstractIterator { + + ArchiveIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { + super(root, recursive, searchFilter, includeFilter); + } + + @Override + protected Archive adapt(FileEntry entry) { + File file = entry.getFile(); + return (file.isDirectory() ? new ExplodedArchive(file) : new SimpleJarFileArchive(entry)); + } + + } + + /** + * {@link Entry} backed by a File. + */ + private static class FileEntry implements Entry { + + private final String name; + + private final File file; + + private final URL url; + + FileEntry(String name, File file, URL url) { + this.name = name; + this.file = file; + this.url = url; + } + + File getFile() { + return this.file; + } + + @Override + public boolean isDirectory() { + return this.file.isDirectory(); + } + + @Override + public String getName() { + return this.name; + } + + URL getUrl() { + return this.url; + } + + } + + /** + * {@link Archive} implementation backed by a simple JAR file that doesn't itself + * contain nested archives. + */ + private static class SimpleJarFileArchive implements Archive { + + private final URL url; + + SimpleJarFileArchive(FileEntry file) { + this.url = file.getUrl(); + } + + @Override + public URL getUrl() throws MalformedURLException { + return this.url; + } + + @Override + public Manifest getManifest() throws IOException { + return null; + } + + @Override + public Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) + throws IOException { + return Collections.emptyIterator(); + } + + @Override + @Deprecated + public Iterator iterator() { + return Collections.emptyIterator(); + } + + @Override + public String toString() { + try { + return getUrl().toString(); + } + catch (Exception ex) { + return "jar archive"; + } + } + + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java new file mode 100644 index 0000000..54a6e01 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java @@ -0,0 +1,287 @@ +package com.gitee.starblues.core.launcher.archive; + +import com.gitee.starblues.core.launcher.jar.JarFile; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.*; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.UUID; +import java.util.jar.JarEntry; +import java.util.jar.Manifest; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarFileArchive implements Archive { + + private static final String UNPACK_MARKER = "UNPACK:"; + + private static final int BUFFER_SIZE = 32 * 1024; + + private static final FileAttribute[] NO_FILE_ATTRIBUTES = {}; + + private static final EnumSet DIRECTORY_PERMISSIONS = EnumSet.of(PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE); + + private static final EnumSet FILE_PERMISSIONS = EnumSet.of(PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE); + + private final JarFile jarFile; + + private URL url; + + private Path tempUnpackDirectory; + + public JarFileArchive(File file) throws IOException { + this(file, file.toURI().toURL()); + } + + public JarFileArchive(File file, URL url) throws IOException { + this(new JarFile(file)); + this.url = url; + } + + public JarFileArchive(JarFile jarFile) { + this.jarFile = jarFile; + } + + @Override + public URL getUrl() throws MalformedURLException { + if (this.url != null) { + return this.url; + } + return this.jarFile.getUrl(); + } + + @Override + public Manifest getManifest() throws IOException { + return this.jarFile.getManifest(); + } + + @Override + public Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException { + return new NestedArchiveIterator(this.jarFile.iterator(), searchFilter, includeFilter); + } + + @Override + @Deprecated + public Iterator iterator() { + return new EntryIterator(this.jarFile.iterator(), null, null); + } + + @Override + public void close() throws IOException { + this.jarFile.close(); + } + + protected Archive getNestedArchive(Entry entry) throws IOException { + JarEntry jarEntry = ((JarFileEntry) entry).getJarEntry(); + if (jarEntry.getComment().startsWith(UNPACK_MARKER)) { + return getUnpackedNestedArchive(jarEntry); + } + try { + JarFile jarFile = this.jarFile.getNestedJarFile(jarEntry); + return new JarFileArchive(jarFile); + } + catch (Exception ex) { + throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex); + } + } + + private Archive getUnpackedNestedArchive(JarEntry jarEntry) throws IOException { + String name = jarEntry.getName(); + if (name.lastIndexOf('/') != -1) { + name = name.substring(name.lastIndexOf('/') + 1); + } + Path path = getTempUnpackDirectory().resolve(name); + if (!Files.exists(path) || Files.size(path) != jarEntry.getSize()) { + unpack(jarEntry, path); + } + return new JarFileArchive(path.toFile(), path.toUri().toURL()); + } + + private Path getTempUnpackDirectory() { + if (this.tempUnpackDirectory == null) { + Path tempDirectory = Paths.get(System.getProperty("java.io.tmpdir")); + this.tempUnpackDirectory = createUnpackDirectory(tempDirectory); + } + return this.tempUnpackDirectory; + } + + private Path createUnpackDirectory(Path parent) { + int attempts = 0; + while (attempts++ < 1000) { + String fileName = Paths.get(this.jarFile.getName()).getFileName().toString(); + Path unpackDirectory = parent.resolve(fileName + "-spring-boot-libs-" + UUID.randomUUID()); + try { + createDirectory(unpackDirectory); + return unpackDirectory; + } + catch (IOException ex) { + } + } + throw new IllegalStateException("Failed to create unpack directory in directory '" + parent + "'"); + } + + private void unpack(JarEntry entry, Path path) throws IOException { + createFile(path); + path.toFile().deleteOnExit(); + try (InputStream inputStream = this.jarFile.getInputStream(entry); + OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING)) { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + outputStream.flush(); + } + } + + private void createDirectory(Path path) throws IOException { + Files.createDirectory(path, getFileAttributes(path.getFileSystem(), DIRECTORY_PERMISSIONS)); + } + + private void createFile(Path path) throws IOException { + Files.createFile(path, getFileAttributes(path.getFileSystem(), FILE_PERMISSIONS)); + } + + private FileAttribute[] getFileAttributes(FileSystem fileSystem, EnumSet ownerReadWrite) { + if (!fileSystem.supportedFileAttributeViews().contains("posix")) { + return NO_FILE_ATTRIBUTES; + } + return new FileAttribute[] { PosixFilePermissions.asFileAttribute(ownerReadWrite) }; + } + + @Override + public String toString() { + try { + return getUrl().toString(); + } + catch (Exception ex) { + return "jar archive"; + } + } + + /** + * Abstract base class for iterator implementations. + */ + private abstract static class AbstractIterator implements Iterator { + + private final Iterator iterator; + + private final EntryFilter searchFilter; + + private final EntryFilter includeFilter; + + private Entry current; + + AbstractIterator(Iterator iterator, EntryFilter searchFilter, EntryFilter includeFilter) { + this.iterator = iterator; + this.searchFilter = searchFilter; + this.includeFilter = includeFilter; + this.current = poll(); + } + + @Override + public boolean hasNext() { + return this.current != null; + } + + @Override + public T next() { + T result = adapt(this.current); + this.current = poll(); + return result; + } + + private Entry poll() { + while (this.iterator.hasNext()) { + JarFileEntry candidate = new JarFileEntry(this.iterator.next()); + if ((this.searchFilter == null || this.searchFilter.matches(candidate)) + && (this.includeFilter == null || this.includeFilter.matches(candidate))) { + return candidate; + } + } + return null; + } + + protected abstract T adapt(Entry entry); + + } + + /** + * {@link Archive.Entry} iterator implementation backed by {@link JarEntry}. + */ + private static class EntryIterator extends AbstractIterator { + + EntryIterator(Iterator iterator, EntryFilter searchFilter, EntryFilter includeFilter) { + super(iterator, searchFilter, includeFilter); + } + + @Override + protected Entry adapt(Entry entry) { + return entry; + } + + } + + /** + * Nested {@link Archive} iterator implementation backed by {@link JarEntry}. + */ + private class NestedArchiveIterator extends AbstractIterator { + + NestedArchiveIterator(Iterator iterator, EntryFilter searchFilter, EntryFilter includeFilter) { + super(iterator, searchFilter, includeFilter); + } + + @Override + protected Archive adapt(Entry entry) { + try { + return getNestedArchive(entry); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + } + + /** + * {@link Archive.Entry} implementation backed by a {@link JarEntry}. + */ + private static class JarFileEntry implements Entry { + + private final JarEntry jarEntry; + + JarFileEntry(JarEntry jarEntry) { + this.jarEntry = jarEntry; + } + + JarEntry getJarEntry() { + return this.jarEntry; + } + + @Override + public boolean isDirectory() { + return this.jarEntry.isDirectory(); + } + + @Override + public String getName() { + return this.jarEntry.getName(); + } + + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java new file mode 100644 index 0000000..1ce258b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java @@ -0,0 +1,61 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.Permission; + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class AbstractJarFile extends java.util.jar.JarFile{ + + /** + * Create a new {@link AbstractJarFile}. + * @param file the root jar file. + * @throws IOException on IO error + */ + AbstractJarFile(File file) throws IOException { + super(file); + } + + /** + * Return a URL that can be used to access this JAR file. NOTE: the specified URL + * cannot be serialized and or cloned. + * @return the URL + * @throws MalformedURLException if the URL is malformed + */ + abstract URL getUrl() throws MalformedURLException; + + /** + * Return the {@link JarFileType} of this instance. + * @return the jar file type + */ + abstract JarFileType getType(); + + /** + * Return the security permission for this JAR. + * @return the security permission. + */ + abstract Permission getPermission(); + + /** + * Return an {@link InputStream} for the entire jar contents. + * @return the contents input stream + * @throws IOException on IO error + */ + abstract InputStream getInputStream() throws IOException; + + /** + * The type of a {@link JarFile}. + */ + enum JarFileType { + + DIRECT, NESTED_DIRECTORY, NESTED_JAR + + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java new file mode 100644 index 0000000..20ba4ba --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java @@ -0,0 +1,237 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.nio.charset.StandardCharsets; + +/** + * @author starBlues + * @version 1.0 + */ +public class AsciiBytes { + + private static final String EMPTY_STRING = ""; + + private static final int[] INITIAL_BYTE_BITMASK = { 0x7F, 0x1F, 0x0F, 0x07 }; + + private static final int SUBSEQUENT_BYTE_BITMASK = 0x3F; + + private final byte[] bytes; + + private final int offset; + + private final int length; + + private String string; + + private int hash; + + /** + * Create a new {@link AsciiBytes} from the specified String. + * @param string the source string + */ + AsciiBytes(String string) { + this(string.getBytes(StandardCharsets.UTF_8)); + this.string = string; + } + + /** + * Create a new {@link AsciiBytes} from the specified bytes. NOTE: underlying bytes + * are not expected to change. + * @param bytes the source bytes + */ + AsciiBytes(byte[] bytes) { + this(bytes, 0, bytes.length); + } + + /** + * Create a new {@link AsciiBytes} from the specified bytes. NOTE: underlying bytes + * are not expected to change. + * @param bytes the source bytes + * @param offset the offset + * @param length the length + */ + AsciiBytes(byte[] bytes, int offset, int length) { + if (offset < 0 || length < 0 || (offset + length) > bytes.length) { + throw new IndexOutOfBoundsException(); + } + this.bytes = bytes; + this.offset = offset; + this.length = length; + } + + int length() { + return this.length; + } + + boolean startsWith(AsciiBytes prefix) { + if (this == prefix) { + return true; + } + if (prefix.length > this.length) { + return false; + } + for (int i = 0; i < prefix.length; i++) { + if (this.bytes[i + this.offset] != prefix.bytes[i + prefix.offset]) { + return false; + } + } + return true; + } + + boolean endsWith(AsciiBytes postfix) { + if (this == postfix) { + return true; + } + if (postfix.length > this.length) { + return false; + } + for (int i = 0; i < postfix.length; i++) { + if (this.bytes[this.offset + (this.length - 1) - i] != postfix.bytes[postfix.offset + (postfix.length - 1) + - i]) { + return false; + } + } + return true; + } + + AsciiBytes substring(int beginIndex) { + return substring(beginIndex, this.length); + } + + AsciiBytes substring(int beginIndex, int endIndex) { + int length = endIndex - beginIndex; + if (this.offset + length > this.bytes.length) { + throw new IndexOutOfBoundsException(); + } + return new AsciiBytes(this.bytes, this.offset + beginIndex, length); + } + + boolean matches(CharSequence name, char suffix) { + int charIndex = 0; + int nameLen = name.length(); + int totalLen = nameLen + ((suffix != 0) ? 1 : 0); + for (int i = this.offset; i < this.offset + this.length; i++) { + int b = this.bytes[i]; + int remainingUtfBytes = getNumberOfUtfBytes(b) - 1; + b &= INITIAL_BYTE_BITMASK[remainingUtfBytes]; + for (int j = 0; j < remainingUtfBytes; j++) { + b = (b << 6) + (this.bytes[++i] & SUBSEQUENT_BYTE_BITMASK); + } + char c = getChar(name, suffix, charIndex++); + if (b <= 0xFFFF) { + if (c != b) { + return false; + } + } + else { + if (c != ((b >> 0xA) + 0xD7C0)) { + return false; + } + c = getChar(name, suffix, charIndex++); + if (c != ((b & 0x3FF) + 0xDC00)) { + return false; + } + } + } + return charIndex == totalLen; + } + + private char getChar(CharSequence name, char suffix, int index) { + if (index < name.length()) { + return name.charAt(index); + } + if (index == name.length()) { + return suffix; + } + return 0; + } + + private int getNumberOfUtfBytes(int b) { + if ((b & 0x80) == 0) { + return 1; + } + int numberOfUtfBytes = 0; + while ((b & 0x80) != 0) { + b <<= 1; + numberOfUtfBytes++; + } + return numberOfUtfBytes; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + if (obj.getClass() == AsciiBytes.class) { + AsciiBytes other = (AsciiBytes) obj; + if (this.length == other.length) { + for (int i = 0; i < this.length; i++) { + if (this.bytes[this.offset + i] != other.bytes[other.offset + i]) { + return false; + } + } + return true; + } + } + return false; + } + + @Override + public int hashCode() { + int hash = this.hash; + if (hash == 0 && this.bytes.length > 0) { + for (int i = this.offset; i < this.offset + this.length; i++) { + int b = this.bytes[i]; + int remainingUtfBytes = getNumberOfUtfBytes(b) - 1; + b &= INITIAL_BYTE_BITMASK[remainingUtfBytes]; + for (int j = 0; j < remainingUtfBytes; j++) { + b = (b << 6) + (this.bytes[++i] & SUBSEQUENT_BYTE_BITMASK); + } + if (b <= 0xFFFF) { + hash = 31 * hash + b; + } + else { + hash = 31 * hash + ((b >> 0xA) + 0xD7C0); + hash = 31 * hash + ((b & 0x3FF) + 0xDC00); + } + } + this.hash = hash; + } + return hash; + } + + @Override + public String toString() { + if (this.string == null) { + if (this.length == 0) { + this.string = EMPTY_STRING; + } + else { + this.string = new String(this.bytes, this.offset, this.length, StandardCharsets.UTF_8); + } + } + return this.string; + } + + static String toString(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + static int hashCode(CharSequence charSequence) { + // We're compatible with String's hashCode() + if (charSequence instanceof StringSequence) { + // ... but save making an unnecessary String for StringSequence + return charSequence.hashCode(); + } + return charSequence.toString().hashCode(); + } + + static int hashCode(int hash, char suffix) { + return (suffix != 0) ? (31 * hash + suffix) : hash; + } + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java new file mode 100644 index 0000000..da137ec --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java @@ -0,0 +1,21 @@ +package com.gitee.starblues.core.launcher.jar; + +/** + * @author starBlues + * @version 1.0 + */ +public class Bytes { + + private Bytes() { + } + + static long littleEndianValue(byte[] bytes, int offset, int length) { + long value = 0; + for (int i = length - 1; i >= 0; i--) { + value = ((value << 8) | (bytes[offset + i] & 0xFF)); + } + return value; + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java new file mode 100644 index 0000000..17c36ce --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java @@ -0,0 +1,228 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.IOException; + +/** + * @author starBlues + * @version 1.0 + */ +public class CentralDirectoryEndRecord { + + private static final int MINIMUM_SIZE = 22; + + private static final int MAXIMUM_COMMENT_LENGTH = 0xFFFF; + + private static final int ZIP64_MAGICCOUNT = 0xFFFF; + + private static final int MAXIMUM_SIZE = MINIMUM_SIZE + MAXIMUM_COMMENT_LENGTH; + + private static final int SIGNATURE = 0x06054b50; + + private static final int COMMENT_LENGTH_OFFSET = 20; + + private static final int READ_BLOCK_SIZE = 256; + + private final Zip64End zip64End; + + private byte[] block; + + private int offset; + + private int size; + + /** + * Create a new {@link CentralDirectoryEndRecord} instance from the specified + * {@link RandomAccessData}, searching backwards from the end until a valid block is + * located. + * @param data the source data + * @throws IOException in case of I/O errors + */ + CentralDirectoryEndRecord(RandomAccessData data) throws IOException { + this.block = createBlockFromEndOfData(data, READ_BLOCK_SIZE); + this.size = MINIMUM_SIZE; + this.offset = this.block.length - this.size; + while (!isValid()) { + this.size++; + if (this.size > this.block.length) { + if (this.size >= MAXIMUM_SIZE || this.size > data.getSize()) { + throw new IOException( + "Unable to find ZIP central directory records after reading " + this.size + " bytes"); + } + this.block = createBlockFromEndOfData(data, this.size + READ_BLOCK_SIZE); + } + this.offset = this.block.length - this.size; + } + int startOfCentralDirectoryEndRecord = (int) (data.getSize() - this.size); + this.zip64End = isZip64() ? new Zip64End(data, startOfCentralDirectoryEndRecord) : null; + } + + private byte[] createBlockFromEndOfData(RandomAccessData data, int size) throws IOException { + int length = (int) Math.min(data.getSize(), size); + return data.read(data.getSize() - length, length); + } + + private boolean isValid() { + if (this.block.length < MINIMUM_SIZE || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { + return false; + } + // Total size must be the structure size + comment + long commentLength = Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2); + return this.size == MINIMUM_SIZE + commentLength; + } + + private boolean isZip64() { + return (int) Bytes.littleEndianValue(this.block, this.offset + 10, 2) == ZIP64_MAGICCOUNT; + } + + /** + * Returns the location in the data that the archive actually starts. For most files + * the archive data will start at 0, however, it is possible to have prefixed bytes + * (often used for startup scripts) at the beginning of the data. + * @param data the source data + * @return the offset within the data where the archive begins + */ + long getStartOfArchive(RandomAccessData data) { + long length = Bytes.littleEndianValue(this.block, this.offset + 12, 4); + long specifiedOffset = Bytes.littleEndianValue(this.block, this.offset + 16, 4); + long zip64EndSize = (this.zip64End != null) ? this.zip64End.getSize() : 0L; + int zip64LocSize = (this.zip64End != null) ? Zip64Locator.ZIP64_LOCSIZE : 0; + long actualOffset = data.getSize() - this.size - length - zip64EndSize - zip64LocSize; + return actualOffset - specifiedOffset; + } + + /** + * Return the bytes of the "Central directory" based on the offset indicated in this + * record. + * @param data the source data + * @return the central directory data + */ + RandomAccessData getCentralDirectory(RandomAccessData data) { + if (this.zip64End != null) { + return this.zip64End.getCentralDirectory(data); + } + long offset = Bytes.littleEndianValue(this.block, this.offset + 16, 4); + long length = Bytes.littleEndianValue(this.block, this.offset + 12, 4); + return data.getSubsection(offset, length); + } + + /** + * Return the number of ZIP entries in the file. + * @return the number of records in the zip + */ + int getNumberOfRecords() { + if (this.zip64End != null) { + return this.zip64End.getNumberOfRecords(); + } + long numberOfRecords = Bytes.littleEndianValue(this.block, this.offset + 10, 2); + return (int) numberOfRecords; + } + + String getComment() { + int commentLength = (int) Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2); + AsciiBytes comment = new AsciiBytes(this.block, this.offset + COMMENT_LENGTH_OFFSET + 2, commentLength); + return comment.toString(); + } + + /** + * A Zip64 end of central directory record. + * + * @see Chapter + * 4.3.14 of Zip64 specification + */ + private static final class Zip64End { + + private static final int ZIP64_ENDTOT = 32; // total number of entries + + private static final int ZIP64_ENDSIZ = 40; // central directory size in bytes + + private static final int ZIP64_ENDOFF = 48; // offset of first CEN header + + private final Zip64Locator locator; + + private final long centralDirectoryOffset; + + private final long centralDirectoryLength; + + private final int numberOfRecords; + + private Zip64End(RandomAccessData data, int centralDirectoryEndOffset) throws IOException { + this(data, new Zip64Locator(data, centralDirectoryEndOffset)); + } + + private Zip64End(RandomAccessData data, Zip64Locator locator) throws IOException { + this.locator = locator; + byte[] block = data.read(locator.getZip64EndOffset(), 56); + this.centralDirectoryOffset = Bytes.littleEndianValue(block, ZIP64_ENDOFF, 8); + this.centralDirectoryLength = Bytes.littleEndianValue(block, ZIP64_ENDSIZ, 8); + this.numberOfRecords = (int) Bytes.littleEndianValue(block, ZIP64_ENDTOT, 8); + } + + /** + * Return the size of this zip 64 end of central directory record. + * @return size of this zip 64 end of central directory record + */ + private long getSize() { + return this.locator.getZip64EndSize(); + } + + /** + * Return the bytes of the "Central directory" based on the offset indicated in + * this record. + * @param data the source data + * @return the central directory data + */ + private RandomAccessData getCentralDirectory(RandomAccessData data) { + return data.getSubsection(this.centralDirectoryOffset, this.centralDirectoryLength); + } + + /** + * Return the number of entries in the zip64 archive. + * @return the number of records in the zip + */ + private int getNumberOfRecords() { + return this.numberOfRecords; + } + + } + + /** + * A Zip64 end of central directory locator. + * + * @see Chapter + * 4.3.15 of Zip64 specification + */ + private static final class Zip64Locator { + + static final int ZIP64_LOCSIZE = 20; // locator size + static final int ZIP64_LOCOFF = 8; // offset of zip64 end + + private final long zip64EndOffset; + + private final int offset; + + private Zip64Locator(RandomAccessData data, int centralDirectoryEndOffset) throws IOException { + this.offset = centralDirectoryEndOffset - ZIP64_LOCSIZE; + byte[] block = data.read(this.offset, ZIP64_LOCSIZE); + this.zip64EndOffset = Bytes.littleEndianValue(block, ZIP64_LOCOFF, 8); + } + + /** + * Return the size of the zip 64 end record located by this zip64 end locator. + * @return size of the zip 64 end record located by this zip64 end locator + */ + private long getZip64EndSize() { + return this.offset - this.zip64EndOffset; + } + + /** + * Return the offset to locate {@link Zip64End}. + * @return offset of the Zip64 end of central directory record + */ + private long getZip64EndOffset() { + return this.zip64EndOffset; + } + + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java new file mode 100644 index 0000000..f098adf --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java @@ -0,0 +1,170 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.IOException; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoField; +import java.time.temporal.ChronoUnit; +import java.time.temporal.ValueRange; + +/** + * @author starBlues + * @version 1.0 + */ +public class CentralDirectoryFileHeader implements FileHeader { + + private static final AsciiBytes SLASH = new AsciiBytes("/"); + + private static final byte[] NO_EXTRA = {}; + + private static final AsciiBytes NO_COMMENT = new AsciiBytes(""); + + private byte[] header; + + private int headerOffset; + + private AsciiBytes name; + + private byte[] extra; + + private AsciiBytes comment; + + private long localHeaderOffset; + + CentralDirectoryFileHeader() { + } + + CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, byte[] extra, AsciiBytes comment, + long localHeaderOffset) { + this.header = header; + this.headerOffset = headerOffset; + this.name = name; + this.extra = extra; + this.comment = comment; + this.localHeaderOffset = localHeaderOffset; + } + + void load(byte[] data, int dataOffset, RandomAccessData variableData, int variableOffset, JarEntryFilter filter) + throws IOException { + // Load fixed part + this.header = data; + this.headerOffset = dataOffset; + long nameLength = Bytes.littleEndianValue(data, dataOffset + 28, 2); + long extraLength = Bytes.littleEndianValue(data, dataOffset + 30, 2); + long commentLength = Bytes.littleEndianValue(data, dataOffset + 32, 2); + this.localHeaderOffset = Bytes.littleEndianValue(data, dataOffset + 42, 4); + // Load variable part + dataOffset += 46; + if (variableData != null) { + data = variableData.read(variableOffset + 46, nameLength + extraLength + commentLength); + dataOffset = 0; + } + this.name = new AsciiBytes(data, dataOffset, (int) nameLength); + if (filter != null) { + this.name = filter.apply(this.name); + } + this.extra = NO_EXTRA; + this.comment = NO_COMMENT; + if (extraLength > 0) { + this.extra = new byte[(int) extraLength]; + System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, this.extra.length); + } + if (commentLength > 0) { + this.comment = new AsciiBytes(data, (int) (dataOffset + nameLength + extraLength), (int) commentLength); + } + } + + AsciiBytes getName() { + return this.name; + } + + @Override + public boolean hasName(CharSequence name, char suffix) { + return this.name.matches(name, suffix); + } + + boolean isDirectory() { + return this.name.endsWith(SLASH); + } + + @Override + public int getMethod() { + return (int) Bytes.littleEndianValue(this.header, this.headerOffset + 10, 2); + } + + long getTime() { + long datetime = Bytes.littleEndianValue(this.header, this.headerOffset + 12, 4); + return decodeMsDosFormatDateTime(datetime); + } + + /** + * Decode MS-DOS Date Time details. See + * Microsoft's documentation for more details of the format. + * @param datetime the date and time + * @return the date and time as milliseconds since the epoch + */ + private long decodeMsDosFormatDateTime(long datetime) { + int year = getChronoValue(((datetime >> 25) & 0x7f) + 1980, ChronoField.YEAR); + int month = getChronoValue((datetime >> 21) & 0x0f, ChronoField.MONTH_OF_YEAR); + int day = getChronoValue((datetime >> 16) & 0x1f, ChronoField.DAY_OF_MONTH); + int hour = getChronoValue((datetime >> 11) & 0x1f, ChronoField.HOUR_OF_DAY); + int minute = getChronoValue((datetime >> 5) & 0x3f, ChronoField.MINUTE_OF_HOUR); + int second = getChronoValue((datetime << 1) & 0x3e, ChronoField.SECOND_OF_MINUTE); + return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()).toInstant() + .truncatedTo(ChronoUnit.SECONDS).toEpochMilli(); + } + + long getCrc() { + return Bytes.littleEndianValue(this.header, this.headerOffset + 16, 4); + } + + @Override + public long getCompressedSize() { + return Bytes.littleEndianValue(this.header, this.headerOffset + 20, 4); + } + + @Override + public long getSize() { + return Bytes.littleEndianValue(this.header, this.headerOffset + 24, 4); + } + + byte[] getExtra() { + return this.extra; + } + + boolean hasExtra() { + return this.extra.length > 0; + } + + AsciiBytes getComment() { + return this.comment; + } + + @Override + public long getLocalHeaderOffset() { + return this.localHeaderOffset; + } + + @Override + public CentralDirectoryFileHeader clone() { + byte[] header = new byte[46]; + System.arraycopy(this.header, this.headerOffset, header, 0, header.length); + return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, this.localHeaderOffset); + } + + static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, int offset, JarEntryFilter filter) + throws IOException { + CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); + byte[] bytes = data.read(offset, 46); + fileHeader.load(bytes, 0, data, offset, filter); + return fileHeader; + } + + private static int getChronoValue(long value, ChronoField field) { + ValueRange range = field.range(); + return Math.toIntExact(Math.min(Math.max(value, range.getMinimum()), range.getMaximum())); + } + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java new file mode 100644 index 0000000..33420cd --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java @@ -0,0 +1,80 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class CentralDirectoryParser { + + private static final int CENTRAL_DIRECTORY_HEADER_BASE_SIZE = 46; + + private final List visitors = new ArrayList<>(); + + T addVisitor(T visitor) { + this.visitors.add(visitor); + return visitor; + } + + /** + * Parse the source data, triggering {@link CentralDirectoryVisitor visitors}. + * @param data the source data + * @param skipPrefixBytes if prefix bytes should be skipped + * @return the actual archive data without any prefix bytes + * @throws IOException on error + */ + RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException { + CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data); + if (skipPrefixBytes) { + data = getArchiveData(endRecord, data); + } + RandomAccessData centralDirectoryData = endRecord.getCentralDirectory(data); + visitStart(endRecord, centralDirectoryData); + parseEntries(endRecord, centralDirectoryData); + visitEnd(); + return data; + } + + private void parseEntries(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) + throws IOException { + byte[] bytes = centralDirectoryData.read(0, centralDirectoryData.getSize()); + CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); + int dataOffset = 0; + for (int i = 0; i < endRecord.getNumberOfRecords(); i++) { + fileHeader.load(bytes, dataOffset, null, 0, null); + visitFileHeader(dataOffset, fileHeader); + dataOffset += CENTRAL_DIRECTORY_HEADER_BASE_SIZE + fileHeader.getName().length() + + fileHeader.getComment().length() + fileHeader.getExtra().length; + } + } + + private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, RandomAccessData data) { + long offset = endRecord.getStartOfArchive(data); + if (offset == 0) { + return data; + } + return data.getSubsection(offset, data.getSize() - offset); + } + + private void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { + for (CentralDirectoryVisitor visitor : this.visitors) { + visitor.visitStart(endRecord, centralDirectoryData); + } + } + + private void visitFileHeader(int dataOffset, CentralDirectoryFileHeader fileHeader) { + for (CentralDirectoryVisitor visitor : this.visitors) { + visitor.visitFileHeader(fileHeader, dataOffset); + } + } + + private void visitEnd() { + for (CentralDirectoryVisitor visitor : this.visitors) { + visitor.visitEnd(); + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java new file mode 100644 index 0000000..f7b29f3 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java @@ -0,0 +1,15 @@ +package com.gitee.starblues.core.launcher.jar; + +/** + * @author starBlues + * @version 1.0 + */ +public interface CentralDirectoryVisitor { + + void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData); + + void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset); + + void visitEnd(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java new file mode 100644 index 0000000..2dc9142 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java @@ -0,0 +1,46 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.util.zip.ZipEntry; + +/** + * @author starBlues + * @version 1.0 + */ +public interface FileHeader { + + /** + * Returns {@code true} if the header has the given name. + * @param name the name to test + * @param suffix an additional suffix (or {@code 0}) + * @return {@code true} if the header has the given name + */ + boolean hasName(CharSequence name, char suffix); + + /** + * Return the offset of the load file header within the archive data. + * @return the local header offset + */ + long getLocalHeaderOffset(); + + /** + * Return the compressed size of the entry. + * @return the compressed size. + */ + long getCompressedSize(); + + /** + * Return the uncompressed size of the entry. + * @return the uncompressed size. + */ + long getSize(); + + /** + * Return the method used to compress the data. + * @return the zip compression method + * @see ZipEntry#STORED + * @see ZipEntry#DEFLATED + */ + int getMethod(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java new file mode 100644 index 0000000..23ba9c7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java @@ -0,0 +1,442 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.File; +import java.io.IOException; +import java.lang.ref.SoftReference; +import java.net.*; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +/** + * @author starBlues + * @version 1.0 + */ +public class Handler extends URLStreamHandler { + + // NOTE: in order to be found as a URL protocol handler, this class must be public, + // must be named Handler and must be in a package ending '.jar' + + private static final String JAR_PROTOCOL = "jar:"; + + private static final String FILE_PROTOCOL = "file:"; + + private static final String TOMCAT_WARFILE_PROTOCOL = "war:file:"; + + private static final String SEPARATOR = "!/"; + + private static final Pattern SEPARATOR_PATTERN = Pattern.compile(SEPARATOR, Pattern.LITERAL); + + private static final String CURRENT_DIR = "/./"; + + private static final Pattern CURRENT_DIR_PATTERN = Pattern.compile(CURRENT_DIR, Pattern.LITERAL); + + private static final String PARENT_DIR = "/../"; + + private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; + + private static final String[] FALLBACK_HANDLERS = { "sun.net.www.protocol.jar.Handler" }; + + private static URL jarContextUrl; + + private static SoftReference> rootFileCache; + + static { + rootFileCache = new SoftReference<>(null); + } + + private final JarFile jarFile; + + private URLStreamHandler fallbackHandler; + + public Handler() { + this(null); + } + + public Handler(JarFile jarFile) { + this.jarFile = jarFile; + } + + @Override + protected URLConnection openConnection(URL url) throws IOException { + if (this.jarFile != null && isUrlInJarFile(url, this.jarFile)) { + return JarURLConnection.get(url, this.jarFile); + } + try { + return JarURLConnection.get(url, getRootJarFileFromUrl(url)); + } + catch (Exception ex) { + return openFallbackConnection(url, ex); + } + } + + private boolean isUrlInJarFile(URL url, JarFile jarFile) throws MalformedURLException { + // Try the path first to save building a new url string each time + return url.getPath().startsWith(jarFile.getUrl().getPath()) + && url.toString().startsWith(jarFile.getUrlString()); + } + + private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException { + try { + URLConnection connection = openFallbackTomcatConnection(url); + connection = (connection != null) ? connection : openFallbackContextConnection(url); + return (connection != null) ? connection : openFallbackHandlerConnection(url); + } + catch (Exception ex) { + if (reason instanceof IOException) { + log(false, "Unable to open fallback handler", ex); + throw (IOException) reason; + } + log(true, "Unable to open fallback handler", ex); + if (reason instanceof RuntimeException) { + throw (RuntimeException) reason; + } + throw new IllegalStateException(reason); + } + } + + /** + * Attempt to open a Tomcat formatted 'jar:war:file:...' URL. This method allows us to + * use our own nested JAR support to open the content rather than the logic in + * {@code sun.net.www.protocol.jar.URLJarFile} which will extract the nested jar to + * the temp folder to that its content can be accessed. + * @param url the URL to open + * @return a {@link URLConnection} or {@code null} + */ + private URLConnection openFallbackTomcatConnection(URL url) { + String file = url.getFile(); + if (isTomcatWarUrl(file)) { + file = file.substring(TOMCAT_WARFILE_PROTOCOL.length()); + file = file.replaceFirst("\\*/", "!/"); + try { + URLConnection connection = openConnection(new URL("jar:file:" + file)); + connection.getInputStream().close(); + return connection; + } + catch (IOException ex) { + } + } + return null; + } + + private boolean isTomcatWarUrl(String file) { + if (file.startsWith(TOMCAT_WARFILE_PROTOCOL) || !file.contains("*/")) { + try { + URLConnection connection = new URL(file).openConnection(); + if (connection.getClass().getName().startsWith("org.apache.catalina")) { + return true; + } + } + catch (Exception ex) { + } + } + return false; + } + + /** + * Attempt to open a fallback connection by using a context URL captured before the + * jar handler was replaced with our own version. Since this method doesn't use + * reflection it won't trigger "illegal reflective access operation has occurred" + * warnings on Java 13+. + * @param url the URL to open + * @return a {@link URLConnection} or {@code null} + */ + private URLConnection openFallbackContextConnection(URL url) { + try { + if (jarContextUrl != null) { + return new URL(jarContextUrl, url.toExternalForm()).openConnection(); + } + } + catch (Exception ex) { + } + return null; + } + + /** + * Attempt to open a fallback connection by using reflection to access Java's default + * jar {@link URLStreamHandler}. + * @param url the URL to open + * @return the {@link URLConnection} + * @throws Exception if not connection could be opened + */ + private URLConnection openFallbackHandlerConnection(URL url) throws Exception { + URLStreamHandler fallbackHandler = getFallbackHandler(); + return new URL(null, url.toExternalForm(), fallbackHandler).openConnection(); + } + + private URLStreamHandler getFallbackHandler() { + if (this.fallbackHandler != null) { + return this.fallbackHandler; + } + for (String handlerClassName : FALLBACK_HANDLERS) { + try { + Class handlerClass = Class.forName(handlerClassName); + this.fallbackHandler = (URLStreamHandler) handlerClass.getDeclaredConstructor().newInstance(); + return this.fallbackHandler; + } + catch (Exception ex) { + // Ignore + } + } + throw new IllegalStateException("Unable to find fallback handler"); + } + + private void log(boolean warning, String message, Exception cause) { + try { + Level level = warning ? Level.WARNING : Level.FINEST; + Logger.getLogger(getClass().getName()).log(level, message, cause); + } + catch (Exception ex) { + if (warning) { + System.err.println("WARNING: " + message); + } + } + } + + @Override + protected void parseURL(URL context, String spec, int start, int limit) { + if (spec.regionMatches(true, 0, JAR_PROTOCOL, 0, JAR_PROTOCOL.length())) { + setFile(context, getFileFromSpec(spec.substring(start, limit))); + } + else { + setFile(context, getFileFromContext(context, spec.substring(start, limit))); + } + } + + private String getFileFromSpec(String spec) { + int separatorIndex = spec.lastIndexOf("!/"); + if (separatorIndex == -1) { + throw new IllegalArgumentException("No !/ in spec '" + spec + "'"); + } + try { + new URL(spec.substring(0, separatorIndex)); + return spec; + } + catch (MalformedURLException ex) { + throw new IllegalArgumentException("Invalid spec URL '" + spec + "'", ex); + } + } + + private String getFileFromContext(URL context, String spec) { + String file = context.getFile(); + if (spec.startsWith("/")) { + return trimToJarRoot(file) + SEPARATOR + spec.substring(1); + } + if (file.endsWith("/")) { + return file + spec; + } + int lastSlashIndex = file.lastIndexOf('/'); + if (lastSlashIndex == -1) { + throw new IllegalArgumentException("No / found in context URL's file '" + file + "'"); + } + return file.substring(0, lastSlashIndex + 1) + spec; + } + + private String trimToJarRoot(String file) { + int lastSeparatorIndex = file.lastIndexOf(SEPARATOR); + if (lastSeparatorIndex == -1) { + throw new IllegalArgumentException("No !/ found in context URL's file '" + file + "'"); + } + return file.substring(0, lastSeparatorIndex); + } + + private void setFile(URL context, String file) { + String path = normalize(file); + String query = null; + int queryIndex = path.lastIndexOf('?'); + if (queryIndex != -1) { + query = path.substring(queryIndex + 1); + path = path.substring(0, queryIndex); + } + setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, context.getRef()); + } + + private String normalize(String file) { + if (!file.contains(CURRENT_DIR) && !file.contains(PARENT_DIR)) { + return file; + } + int afterLastSeparatorIndex = file.lastIndexOf(SEPARATOR) + SEPARATOR.length(); + String afterSeparator = file.substring(afterLastSeparatorIndex); + afterSeparator = replaceParentDir(afterSeparator); + afterSeparator = replaceCurrentDir(afterSeparator); + return file.substring(0, afterLastSeparatorIndex) + afterSeparator; + } + + private String replaceParentDir(String file) { + int parentDirIndex; + while ((parentDirIndex = file.indexOf(PARENT_DIR)) >= 0) { + int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1); + if (precedingSlashIndex >= 0) { + file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3); + } + else { + file = file.substring(parentDirIndex + 4); + } + } + return file; + } + + private String replaceCurrentDir(String file) { + return CURRENT_DIR_PATTERN.matcher(file).replaceAll("/"); + } + + @Override + protected int hashCode(URL u) { + return hashCode(u.getProtocol(), u.getFile()); + } + + private int hashCode(String protocol, String file) { + int result = (protocol != null) ? protocol.hashCode() : 0; + int separatorIndex = file.indexOf(SEPARATOR); + if (separatorIndex == -1) { + return result + file.hashCode(); + } + String source = file.substring(0, separatorIndex); + String entry = canonicalize(file.substring(separatorIndex + 2)); + try { + result += new URL(source).hashCode(); + } + catch (MalformedURLException ex) { + result += source.hashCode(); + } + result += entry.hashCode(); + return result; + } + + @Override + protected boolean sameFile(URL u1, URL u2) { + if (!u1.getProtocol().equals("jar") || !u2.getProtocol().equals("jar")) { + return false; + } + int separator1 = u1.getFile().indexOf(SEPARATOR); + int separator2 = u2.getFile().indexOf(SEPARATOR); + if (separator1 == -1 || separator2 == -1) { + return super.sameFile(u1, u2); + } + String nested1 = u1.getFile().substring(separator1 + SEPARATOR.length()); + String nested2 = u2.getFile().substring(separator2 + SEPARATOR.length()); + if (!nested1.equals(nested2)) { + String canonical1 = canonicalize(nested1); + String canonical2 = canonicalize(nested2); + if (!canonical1.equals(canonical2)) { + return false; + } + } + String root1 = u1.getFile().substring(0, separator1); + String root2 = u2.getFile().substring(0, separator2); + try { + return super.sameFile(new URL(root1), new URL(root2)); + } + catch (MalformedURLException ex) { + // Continue + } + return super.sameFile(u1, u2); + } + + private String canonicalize(String path) { + return SEPARATOR_PATTERN.matcher(path).replaceAll("/"); + } + + public JarFile getRootJarFileFromUrl(URL url) throws IOException { + String spec = url.getFile(); + int separatorIndex = spec.indexOf(SEPARATOR); + if (separatorIndex == -1) { + throw new MalformedURLException("Jar URL does not contain !/ separator"); + } + String name = spec.substring(0, separatorIndex); + return getRootJarFile(name); + } + + private JarFile getRootJarFile(String name) throws IOException { + try { + if (!name.startsWith(FILE_PROTOCOL)) { + throw new IllegalStateException("Not a file URL"); + } + File file = new File(URI.create(name)); + Map cache = rootFileCache.get(); + JarFile result = (cache != null) ? cache.get(file) : null; + if (result == null) { + result = new JarFile(file); + addToRootFileCache(file, result); + } + return result; + } + catch (Exception ex) { + throw new IOException("Unable to open root Jar file '" + name + "'", ex); + } + } + + /** + * Add the given {@link JarFile} to the root file cache. + * @param sourceFile the source file to add + * @param jarFile the jar file. + */ + static void addToRootFileCache(File sourceFile, JarFile jarFile) { + Map cache = rootFileCache.get(); + if (cache == null) { + cache = new ConcurrentHashMap<>(); + rootFileCache = new SoftReference<>(cache); + } + cache.put(sourceFile, jarFile); + } + + /** + * If possible, capture a URL that is configured with the original jar handler so that + * we can use it as a fallback context later. We can only do this if we know that we + * can reset the handlers after. + */ + static void captureJarContextUrl() { + if (canResetCachedUrlHandlers()) { + String handlers = System.getProperty(PROTOCOL_HANDLER, ""); + try { + System.clearProperty(PROTOCOL_HANDLER); + try { + resetCachedUrlHandlers(); + jarContextUrl = new URL("jar:file:context.jar!/"); + URLConnection connection = jarContextUrl.openConnection(); + if (connection instanceof JarURLConnection) { + jarContextUrl = null; + } + } + catch (Exception ex) { + } + } + finally { + if (handlers == null) { + System.clearProperty(PROTOCOL_HANDLER); + } + else { + System.setProperty(PROTOCOL_HANDLER, handlers); + } + } + resetCachedUrlHandlers(); + } + } + + private static boolean canResetCachedUrlHandlers() { + try { + resetCachedUrlHandlers(); + return true; + } + catch (Error ex) { + return false; + } + } + + private static void resetCachedUrlHandlers() { + URL.setURLStreamHandlerFactory(null); + } + + /** + * Set if a generic static exception can be thrown when a URL cannot be connected. + * This optimization is used during class loading to save creating lots of exceptions + * which are then swallowed. + * @param useFastConnectionExceptions if fast connection exceptions can be used. + */ + public static void setUseFastConnectionExceptions(boolean useFastConnectionExceptions) { + JarURLConnection.setUseFastExceptions(useFastConnectionExceptions); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java new file mode 100644 index 0000000..c20b388 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java @@ -0,0 +1,103 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.CodeSigner; +import java.security.cert.Certificate; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarEntry extends java.util.jar.JarEntry implements FileHeader { + + private final int index; + + private final AsciiBytes name; + + private final AsciiBytes headerName; + + private final JarFile jarFile; + + private long localHeaderOffset; + + private volatile JarEntryCertification certification; + + JarEntry(JarFile jarFile, int index, CentralDirectoryFileHeader header, AsciiBytes nameAlias) { + super((nameAlias != null) ? nameAlias.toString() : header.getName().toString()); + this.index = index; + this.name = (nameAlias != null) ? nameAlias : header.getName(); + this.headerName = header.getName(); + this.jarFile = jarFile; + this.localHeaderOffset = header.getLocalHeaderOffset(); + setCompressedSize(header.getCompressedSize()); + setMethod(header.getMethod()); + setCrc(header.getCrc()); + setComment(header.getComment().toString()); + setSize(header.getSize()); + setTime(header.getTime()); + if (header.hasExtra()) { + setExtra(header.getExtra()); + } + } + + int getIndex() { + return this.index; + } + + AsciiBytes getAsciiBytesName() { + return this.name; + } + + @Override + public boolean hasName(CharSequence name, char suffix) { + return this.headerName.matches(name, suffix); + } + + /** + * Return a {@link URL} for this {@link JarEntry}. + * @return the URL for the entry + * @throws MalformedURLException if the URL is not valid + */ + URL getUrl() throws MalformedURLException { + return new URL(this.jarFile.getUrl(), getName()); + } + + @Override + public Attributes getAttributes() throws IOException { + Manifest manifest = this.jarFile.getManifest(); + return (manifest != null) ? manifest.getAttributes(getName()) : null; + } + + @Override + public Certificate[] getCertificates() { + return getCertification().getCertificates(); + } + + @Override + public CodeSigner[] getCodeSigners() { + return getCertification().getCodeSigners(); + } + + private JarEntryCertification getCertification() { + if (!this.jarFile.isSigned()) { + return JarEntryCertification.NONE; + } + JarEntryCertification certification = this.certification; + if (certification == null) { + certification = this.jarFile.getCertification(this); + this.certification = certification; + } + return certification; + } + + @Override + public long getLocalHeaderOffset() { + return this.localHeaderOffset; + } + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java new file mode 100644 index 0000000..6f10107 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java @@ -0,0 +1,41 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.security.CodeSigner; +import java.security.cert.Certificate; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarEntryCertification { + + static final JarEntryCertification NONE = new JarEntryCertification(null, null); + + private final Certificate[] certificates; + + private final CodeSigner[] codeSigners; + + JarEntryCertification(Certificate[] certificates, CodeSigner[] codeSigners) { + this.certificates = certificates; + this.codeSigners = codeSigners; + } + + Certificate[] getCertificates() { + return (this.certificates != null) ? this.certificates.clone() : null; + } + + CodeSigner[] getCodeSigners() { + return (this.codeSigners != null) ? this.codeSigners.clone() : null; + } + + static JarEntryCertification from(java.util.jar.JarEntry certifiedEntry) { + Certificate[] certificates = (certifiedEntry != null) ? certifiedEntry.getCertificates() : null; + CodeSigner[] codeSigners = (certifiedEntry != null) ? certifiedEntry.getCodeSigners() : null; + if (certificates == null && codeSigners == null) { + return NONE; + } + return new JarEntryCertification(certificates, codeSigners); + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java new file mode 100644 index 0000000..9da34f9 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java @@ -0,0 +1,19 @@ +package com.gitee.starblues.core.launcher.jar; + +/** + * @author starBlues + * @version 1.0 + */ +public interface JarEntryFilter { + + /** + * Apply the jar entry filter. + * @param name the current entry name. This may be different that the original entry + * name if a previous filter has been applied + * @return the new name of the entry or {@code null} if the entry should not be + * included. + */ + AsciiBytes apply(AsciiBytes name); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java new file mode 100644 index 0000000..8b8160b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java @@ -0,0 +1,431 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.File; +import java.io.FilePermission; +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.SoftReference; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; +import java.security.Permission; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Supplier; +import java.util.jar.Manifest; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import java.util.zip.ZipEntry; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarFile extends AbstractJarFile implements Iterable { + + + private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; + + private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; + + private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader"; + + private static final AsciiBytes META_INF = new AsciiBytes("META-INF/"); + + private static final AsciiBytes SIGNATURE_FILE_EXTENSION = new AsciiBytes(".SF"); + + private static final String READ_ACTION = "read"; + + private final RandomAccessDataFile rootFile; + + private final String pathFromRoot; + + private final RandomAccessData data; + + private final JarFileType type; + + private URL url; + + private String urlString; + + private JarFileEntries entries; + + private Supplier manifestSupplier; + + private SoftReference manifest; + + private boolean signed; + + private String comment; + + private volatile boolean closed; + + /** + * Create a new {@link JarFile} backed by the specified file. + * @param file the root jar file + * @throws IOException if the file cannot be read + */ + public JarFile(File file) throws IOException { + this(new RandomAccessDataFile(file)); + } + + /** + * Create a new {@link JarFile} backed by the specified file. + * @param file the root jar file + * @throws IOException if the file cannot be read + */ + JarFile(RandomAccessDataFile file) throws IOException { + this(file, "", file, JarFileType.DIRECT); + } + + /** + * Private constructor used to create a new {@link JarFile} either directly or from a + * nested entry. + * @param rootFile the root jar file + * @param pathFromRoot the name of this file + * @param data the underlying data + * @param type the type of the jar file + * @throws IOException if the file cannot be read + */ + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarFileType type) + throws IOException { + this(rootFile, pathFromRoot, data, null, type, null); + } + + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarEntryFilter filter, + JarFileType type, Supplier manifestSupplier) throws IOException { + super(rootFile.getFile()); + super.close(); + this.rootFile = rootFile; + this.pathFromRoot = pathFromRoot; + CentralDirectoryParser parser = new CentralDirectoryParser(); + this.entries = parser.addVisitor(new JarFileEntries(this, filter)); + this.type = type; + parser.addVisitor(centralDirectoryVisitor()); + try { + this.data = parser.parse(data, filter == null); + } + catch (RuntimeException ex) { + close(); + throw ex; + } + this.manifestSupplier = (manifestSupplier != null) ? manifestSupplier : () -> { + try (InputStream inputStream = getInputStream(MANIFEST_NAME)) { + if (inputStream == null) { + return null; + } + return new Manifest(inputStream); + } + catch (IOException ex) { + throw new RuntimeException(ex); + } + }; + } + + private CentralDirectoryVisitor centralDirectoryVisitor() { + return new CentralDirectoryVisitor() { + + @Override + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { + JarFile.this.comment = endRecord.getComment(); + } + + @Override + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { + AsciiBytes name = fileHeader.getName(); + if (name.startsWith(META_INF) && name.endsWith(SIGNATURE_FILE_EXTENSION)) { + JarFile.this.signed = true; + } + } + + @Override + public void visitEnd() { + } + + }; + } + + @Override + Permission getPermission() { + return new FilePermission(this.rootFile.getFile().getPath(), READ_ACTION); + } + + protected final RandomAccessDataFile getRootJarFile() { + return this.rootFile; + } + + RandomAccessData getData() { + return this.data; + } + + @Override + public Manifest getManifest() throws IOException { + Manifest manifest = (this.manifest != null) ? this.manifest.get() : null; + if (manifest == null) { + try { + manifest = this.manifestSupplier.get(); + } + catch (RuntimeException ex) { + throw new IOException(ex); + } + this.manifest = new SoftReference<>(manifest); + } + return manifest; + } + + @Override + public Enumeration entries() { + return new JarEntryEnumeration(this.entries.iterator()); + } + + @Override + public Stream stream() { + Spliterator spliterator = Spliterators.spliterator(iterator(), size(), + Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL); + return StreamSupport.stream(spliterator, false); + } + + /** + * Return an iterator for the contained entries. + * @see java.lang.Iterable#iterator() + * @since 2.3.0 + */ + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public Iterator iterator() { + return (Iterator) this.entries.iterator(this::ensureOpen); + } + + public JarEntry getJarEntry(CharSequence name) { + return this.entries.getEntry(name); + } + + @Override + public JarEntry getJarEntry(String name) { + return (JarEntry) getEntry(name); + } + + public boolean containsEntry(String name) { + return this.entries.containsEntry(name); + } + + @Override + public ZipEntry getEntry(String name) { + ensureOpen(); + return this.entries.getEntry(name); + } + + @Override + InputStream getInputStream() throws IOException { + return this.data.getInputStream(); + } + + @Override + public synchronized InputStream getInputStream(ZipEntry entry) throws IOException { + ensureOpen(); + if (entry instanceof JarEntry) { + return this.entries.getInputStream((JarEntry) entry); + } + return getInputStream((entry != null) ? entry.getName() : null); + } + + InputStream getInputStream(String name) throws IOException { + return this.entries.getInputStream(name); + } + + /** + * Return a nested {@link JarFile} loaded from the specified entry. + * @param entry the zip entry + * @return a {@link JarFile} for the entry + * @throws IOException if the nested jar file cannot be read + */ + public synchronized JarFile getNestedJarFile(ZipEntry entry) throws IOException { + return getNestedJarFile((JarEntry) entry); + } + + /** + * Return a nested {@link JarFile} loaded from the specified entry. + * @param entry the zip entry + * @return a {@link JarFile} for the entry + * @throws IOException if the nested jar file cannot be read + */ + public synchronized JarFile getNestedJarFile(JarEntry entry) throws IOException { + try { + return createJarFileFromEntry(entry); + } + catch (Exception ex) { + throw new IOException("Unable to open nested jar file '" + entry.getName() + "'", ex); + } + } + + private JarFile createJarFileFromEntry(JarEntry entry) throws IOException { + if (entry.isDirectory()) { + return createJarFileFromDirectoryEntry(entry); + } + return createJarFileFromFileEntry(entry); + } + + private JarFile createJarFileFromDirectoryEntry(JarEntry entry) throws IOException { + AsciiBytes name = entry.getAsciiBytesName(); + JarEntryFilter filter = (candidate) -> { + if (candidate.startsWith(name) && !candidate.equals(name)) { + return candidate.substring(name.length()); + } + return null; + }; + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName().substring(0, name.length() - 1), + this.data, filter, JarFileType.NESTED_DIRECTORY, this.manifestSupplier); + } + + private JarFile createJarFileFromFileEntry(JarEntry entry) throws IOException { + if (entry.getMethod() != ZipEntry.STORED) { + throw new IllegalStateException( + "Unable to open nested entry '" + entry.getName() + "'. It has been compressed and nested " + + "jar files must be stored without compression. Please check the " + + "mechanism used to create your executable jar file"); + } + RandomAccessData entryData = this.entries.getEntryData(entry.getName()); + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), entryData, + JarFileType.NESTED_JAR); + } + + @Override + public String getComment() { + ensureOpen(); + return this.comment; + } + + @Override + public int size() { + ensureOpen(); + return this.entries.getSize(); + } + + @Override + public void close() throws IOException { + if (this.closed) { + return; + } + this.closed = true; + if (this.type == JarFileType.DIRECT) { + this.rootFile.close(); + } + } + + private void ensureOpen() { + if (this.closed) { + throw new IllegalStateException("zip file closed"); + } + } + + boolean isClosed() { + return this.closed; + } + + String getUrlString() throws MalformedURLException { + if (this.urlString == null) { + this.urlString = getUrl().toString(); + } + return this.urlString; + } + + @Override + public URL getUrl() throws MalformedURLException { + if (this.url == null) { + String file = this.rootFile.getFile().toURI() + this.pathFromRoot + "!/"; + file = file.replace("file:////", "file://"); // Fix UNC paths + this.url = new URL("jar", "", -1, file, new Handler(this)); + } + return this.url; + } + + @Override + public String toString() { + return getName(); + } + + @Override + public String getName() { + return this.rootFile.getFile() + this.pathFromRoot; + } + + boolean isSigned() { + return this.signed; + } + + JarEntryCertification getCertification(JarEntry entry) { + try { + return this.entries.getCertification(entry); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + public void clearCache() { + this.entries.clearCache(); + } + + protected String getPathFromRoot() { + return this.pathFromRoot; + } + + @Override + JarFileType getType() { + return this.type; + } + + /** + * Register a {@literal 'java.protocol.handler.pkgs'} property so that a + * {@link URLStreamHandler} will be located to deal with jar URLs. + */ + public static void registerUrlProtocolHandler() { + Handler.captureJarContextUrl(); + String handlers = System.getProperty(PROTOCOL_HANDLER, ""); + System.setProperty(PROTOCOL_HANDLER, + ((handlers == null || handlers.isEmpty()) ? HANDLERS_PACKAGE : handlers + "|" + HANDLERS_PACKAGE)); + resetCachedUrlHandlers(); + } + + /** + * Reset any cached handlers just in case a jar protocol has already been used. We + * reset the handler by trying to set a null {@link URLStreamHandlerFactory} which + * should have no effect other than clearing the handlers cache. + */ + private static void resetCachedUrlHandlers() { + try { + URL.setURLStreamHandlerFactory(null); + } + catch (Error ex) { + // Ignore + } + } + + /** + * An {@link Enumeration} on {@linkplain java.util.jar.JarEntry jar entries}. + */ + private static class JarEntryEnumeration implements Enumeration { + + private final Iterator iterator; + + JarEntryEnumeration(Iterator iterator) { + this.iterator = iterator; + } + + @Override + public boolean hasMoreElements() { + return this.iterator.hasNext(); + } + + @Override + public java.util.jar.JarEntry nextElement() { + return this.iterator.next(); + } + + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java new file mode 100644 index 0000000..8090b30 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java @@ -0,0 +1,389 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.jar.Attributes; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarFileEntries implements CentralDirectoryVisitor, Iterable { + + private static final Runnable NO_VALIDATION = () -> { + }; + + private static final String META_INF_PREFIX = "META-INF/"; + + private static final Attributes.Name MULTI_RELEASE = new Attributes.Name("Multi-Release"); + + private static final int BASE_VERSION = 8; + + private static final int RUNTIME_VERSION; + + static { + int version; + try { + Object runtimeVersion = Runtime.class.getMethod("version").invoke(null); + version = (int) runtimeVersion.getClass().getMethod("major").invoke(runtimeVersion); + } + catch (Throwable ex) { + version = BASE_VERSION; + } + RUNTIME_VERSION = version; + } + + private static final long LOCAL_FILE_HEADER_SIZE = 30; + + private static final char SLASH = '/'; + + private static final char NO_SUFFIX = 0; + + protected static final int ENTRY_CACHE_SIZE = 25; + + private final JarFile jarFile; + + private final JarEntryFilter filter; + + private RandomAccessData centralDirectoryData; + + private int size; + + private int[] hashCodes; + + private int[] centralDirectoryOffsets; + + private int[] positions; + + private Boolean multiReleaseJar; + + private JarEntryCertification[] certifications; + + private final Map entriesCache = Collections + .synchronizedMap(new LinkedHashMap(16, 0.75f, true) { + + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() >= ENTRY_CACHE_SIZE; + } + + }); + + JarFileEntries(JarFile jarFile, JarEntryFilter filter) { + this.jarFile = jarFile; + this.filter = filter; + if (RUNTIME_VERSION == BASE_VERSION) { + this.multiReleaseJar = false; + } + } + + @Override + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { + int maxSize = endRecord.getNumberOfRecords(); + this.centralDirectoryData = centralDirectoryData; + this.hashCodes = new int[maxSize]; + this.centralDirectoryOffsets = new int[maxSize]; + this.positions = new int[maxSize]; + } + + @Override + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { + AsciiBytes name = applyFilter(fileHeader.getName()); + if (name != null) { + add(name, dataOffset); + } + } + + private void add(AsciiBytes name, int dataOffset) { + this.hashCodes[this.size] = name.hashCode(); + this.centralDirectoryOffsets[this.size] = dataOffset; + this.positions[this.size] = this.size; + this.size++; + } + + @Override + public void visitEnd() { + sort(0, this.size - 1); + int[] positions = this.positions; + this.positions = new int[positions.length]; + for (int i = 0; i < this.size; i++) { + this.positions[positions[i]] = i; + } + } + + int getSize() { + return this.size; + } + + private void sort(int left, int right) { + // Quick sort algorithm, uses hashCodes as the source but sorts all arrays + if (left < right) { + int pivot = this.hashCodes[left + (right - left) / 2]; + int i = left; + int j = right; + while (i <= j) { + while (this.hashCodes[i] < pivot) { + i++; + } + while (this.hashCodes[j] > pivot) { + j--; + } + if (i <= j) { + swap(i, j); + i++; + j--; + } + } + if (left < j) { + sort(left, j); + } + if (right > i) { + sort(i, right); + } + } + } + + private void swap(int i, int j) { + swap(this.hashCodes, i, j); + swap(this.centralDirectoryOffsets, i, j); + swap(this.positions, i, j); + } + + private void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + @Override + public Iterator iterator() { + return new EntryIterator(NO_VALIDATION); + } + + Iterator iterator(Runnable validator) { + return new EntryIterator(validator); + } + + boolean containsEntry(CharSequence name) { + return getEntry(name, FileHeader.class, true) != null; + } + + JarEntry getEntry(CharSequence name) { + return getEntry(name, JarEntry.class, true); + } + + InputStream getInputStream(String name) throws IOException { + FileHeader entry = getEntry(name, FileHeader.class, false); + return getInputStream(entry); + } + + InputStream getInputStream(FileHeader entry) throws IOException { + if (entry == null) { + return null; + } + InputStream inputStream = getEntryData(entry).getInputStream(); + if (entry.getMethod() == ZipEntry.DEFLATED) { + inputStream = new ZipInflaterInputStream(inputStream, (int) entry.getSize()); + } + return inputStream; + } + + RandomAccessData getEntryData(String name) throws IOException { + FileHeader entry = getEntry(name, FileHeader.class, false); + if (entry == null) { + return null; + } + return getEntryData(entry); + } + + private RandomAccessData getEntryData(FileHeader entry) throws IOException { + // aspectjrt-1.7.4.jar has a different ext bytes length in the + // local directory to the central directory. We need to re-read + // here to skip them + RandomAccessData data = this.jarFile.getData(); + byte[] localHeader = data.read(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE); + long nameLength = Bytes.littleEndianValue(localHeader, 26, 2); + long extraLength = Bytes.littleEndianValue(localHeader, 28, 2); + return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE + nameLength + extraLength, + entry.getCompressedSize()); + } + + private T getEntry(CharSequence name, Class type, boolean cacheEntry) { + T entry = doGetEntry(name, type, cacheEntry, null); + if (!isMetaInfEntry(name) && isMultiReleaseJar()) { + int version = RUNTIME_VERSION; + AsciiBytes nameAlias = (entry instanceof JarEntry) ? ((JarEntry) entry).getAsciiBytesName() + : new AsciiBytes(name.toString()); + while (version > BASE_VERSION) { + T versionedEntry = doGetEntry("META-INF/versions/" + version + "/" + name, type, cacheEntry, nameAlias); + if (versionedEntry != null) { + return versionedEntry; + } + version--; + } + } + return entry; + } + + private boolean isMetaInfEntry(CharSequence name) { + return name.toString().startsWith(META_INF_PREFIX); + } + + private boolean isMultiReleaseJar() { + Boolean multiRelease = this.multiReleaseJar; + if (multiRelease != null) { + return multiRelease; + } + try { + Manifest manifest = this.jarFile.getManifest(); + if (manifest == null) { + multiRelease = false; + } + else { + Attributes attributes = manifest.getMainAttributes(); + multiRelease = attributes.containsKey(MULTI_RELEASE); + } + } + catch (IOException ex) { + multiRelease = false; + } + this.multiReleaseJar = multiRelease; + return multiRelease; + } + + private T doGetEntry(CharSequence name, Class type, boolean cacheEntry, + AsciiBytes nameAlias) { + int hashCode = AsciiBytes.hashCode(name); + T entry = getEntry(hashCode, name, NO_SUFFIX, type, cacheEntry, nameAlias); + if (entry == null) { + hashCode = AsciiBytes.hashCode(hashCode, SLASH); + entry = getEntry(hashCode, name, SLASH, type, cacheEntry, nameAlias); + } + return entry; + } + + private T getEntry(int hashCode, CharSequence name, char suffix, Class type, + boolean cacheEntry, AsciiBytes nameAlias) { + int index = getFirstIndex(hashCode); + while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { + T entry = getEntry(index, type, cacheEntry, nameAlias); + if (entry.hasName(name, suffix)) { + return entry; + } + index++; + } + return null; + } + + @SuppressWarnings("unchecked") + private T getEntry(int index, Class type, boolean cacheEntry, AsciiBytes nameAlias) { + try { + FileHeader cached = this.entriesCache.get(index); + FileHeader entry = (cached != null) ? cached : CentralDirectoryFileHeader + .fromRandomAccessData(this.centralDirectoryData, this.centralDirectoryOffsets[index], this.filter); + if (CentralDirectoryFileHeader.class.equals(entry.getClass()) && type.equals(JarEntry.class)) { + entry = new JarEntry(this.jarFile, index, (CentralDirectoryFileHeader) entry, nameAlias); + } + if (cacheEntry && cached != entry) { + this.entriesCache.put(index, entry); + } + return (T) entry; + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + private int getFirstIndex(int hashCode) { + int index = Arrays.binarySearch(this.hashCodes, 0, this.size, hashCode); + if (index < 0) { + return -1; + } + while (index > 0 && this.hashCodes[index - 1] == hashCode) { + index--; + } + return index; + } + + void clearCache() { + this.entriesCache.clear(); + } + + private AsciiBytes applyFilter(AsciiBytes name) { + return (this.filter != null) ? this.filter.apply(name) : name; + } + + JarEntryCertification getCertification(JarEntry entry) throws IOException { + JarEntryCertification[] certifications = this.certifications; + if (certifications == null) { + certifications = new JarEntryCertification[this.size]; + // We fallback to use JarInputStream to obtain the certs. This isn't that + // fast, but hopefully doesn't happen too often. + try (JarInputStream certifiedJarStream = new JarInputStream(this.jarFile.getData().getInputStream())) { + java.util.jar.JarEntry certifiedEntry = null; + while ((certifiedEntry = certifiedJarStream.getNextJarEntry()) != null) { + // Entry must be closed to trigger a read and set entry certificates + certifiedJarStream.closeEntry(); + int index = getEntryIndex(certifiedEntry.getName()); + if (index != -1) { + certifications[index] = JarEntryCertification.from(certifiedEntry); + } + } + } + this.certifications = certifications; + } + JarEntryCertification certification = certifications[entry.getIndex()]; + return (certification != null) ? certification : JarEntryCertification.NONE; + } + + private int getEntryIndex(CharSequence name) { + int hashCode = AsciiBytes.hashCode(name); + int index = getFirstIndex(hashCode); + while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { + FileHeader candidate = getEntry(index, FileHeader.class, false, null); + if (candidate.hasName(name, NO_SUFFIX)) { + return index; + } + index++; + } + return -1; + } + + /** + * Iterator for contained entries. + */ + private final class EntryIterator implements Iterator { + + private final Runnable validator; + + private int index = 0; + + private EntryIterator(Runnable validator) { + this.validator = validator; + validator.run(); + } + + @Override + public boolean hasNext() { + this.validator.run(); + return this.index < JarFileEntries.this.size; + } + + @Override + public JarEntry next() { + this.validator.run(); + if (!hasNext()) { + throw new NoSuchElementException(); + } + int entryIndex = JarFileEntries.this.positions[this.index]; + this.index++; + return getEntry(entryIndex, JarEntry.class, false, null); + } + + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java new file mode 100644 index 0000000..6aca9c2 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java @@ -0,0 +1,109 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.Permission; +import java.util.Enumeration; +import java.util.jar.JarEntry; +import java.util.jar.Manifest; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarFileWrapper extends AbstractJarFile { + + private final JarFile parent; + + JarFileWrapper(JarFile parent) throws IOException { + super(parent.getRootJarFile().getFile()); + this.parent = parent; + super.close(); + } + + @Override + URL getUrl() throws MalformedURLException { + return this.parent.getUrl(); + } + + @Override + JarFileType getType() { + return this.parent.getType(); + } + + @Override + Permission getPermission() { + return this.parent.getPermission(); + } + + @Override + public Manifest getManifest() throws IOException { + return this.parent.getManifest(); + } + + @Override + public Enumeration entries() { + return this.parent.entries(); + } + + @Override + public Stream stream() { + return this.parent.stream(); + } + + @Override + public JarEntry getJarEntry(String name) { + return this.parent.getJarEntry(name); + } + + @Override + public ZipEntry getEntry(String name) { + return this.parent.getEntry(name); + } + + @Override + InputStream getInputStream() throws IOException { + return this.parent.getInputStream(); + } + + @Override + public synchronized InputStream getInputStream(ZipEntry ze) throws IOException { + return this.parent.getInputStream(ze); + } + + @Override + public String getComment() { + return this.parent.getComment(); + } + + @Override + public int size() { + return this.parent.size(); + } + + @Override + public String toString() { + return this.parent.toString(); + } + + @Override + public String getName() { + return this.parent.getName(); + } + + static JarFile unwrap(java.util.jar.JarFile jarFile) { + if (jarFile instanceof JarFile) { + return (JarFile) jarFile; + } + if (jarFile instanceof JarFileWrapper) { + return unwrap(((JarFileWrapper) jarFile).parent); + } + throw new IllegalStateException("Not a JarFile or Wrapper"); + } + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java new file mode 100644 index 0000000..77cb617 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java @@ -0,0 +1,366 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.*; +import java.net.*; +import java.security.Permission; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarURLConnection extends java.net.JarURLConnection { + + private static ThreadLocal useFastExceptions = new ThreadLocal<>(); + + private static final FileNotFoundException FILE_NOT_FOUND_EXCEPTION = new FileNotFoundException( + "Jar file or entry not found"); + + private static final IllegalStateException NOT_FOUND_CONNECTION_EXCEPTION = new IllegalStateException( + FILE_NOT_FOUND_EXCEPTION); + + private static final String SEPARATOR = "!/"; + + private static final URL EMPTY_JAR_URL; + + static { + try { + EMPTY_JAR_URL = new URL("jar:", null, 0, "file:!/", new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL u) throws IOException { + // Stub URLStreamHandler to prevent the wrong JAR Handler from being + // Instantiated and cached. + return null; + } + }); + } + catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + } + + private static final JarEntryName EMPTY_JAR_ENTRY_NAME = new JarEntryName(new StringSequence("")); + + private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection.notFound(); + + private final AbstractJarFile jarFile; + + private Permission permission; + + private URL jarFileUrl; + + private final JarEntryName jarEntryName; + + private java.util.jar.JarEntry jarEntry; + + private JarURLConnection(URL url, AbstractJarFile jarFile, JarEntryName jarEntryName) throws IOException { + // What we pass to super is ultimately ignored + super(EMPTY_JAR_URL); + this.url = url; + this.jarFile = jarFile; + this.jarEntryName = jarEntryName; + } + + @Override + public void connect() throws IOException { + if (this.jarFile == null) { + throw FILE_NOT_FOUND_EXCEPTION; + } + if (!this.jarEntryName.isEmpty() && this.jarEntry == null) { + this.jarEntry = this.jarFile.getJarEntry(getEntryName()); + if (this.jarEntry == null) { + throwFileNotFound(this.jarEntryName, this.jarFile); + } + } + this.connected = true; + } + + @Override + public java.util.jar.JarFile getJarFile() throws IOException { + connect(); + return this.jarFile; + } + + @Override + public URL getJarFileURL() { + if (this.jarFile == null) { + throw NOT_FOUND_CONNECTION_EXCEPTION; + } + if (this.jarFileUrl == null) { + this.jarFileUrl = buildJarFileUrl(); + } + return this.jarFileUrl; + } + + private URL buildJarFileUrl() { + try { + String spec = this.jarFile.getUrl().getFile(); + if (spec.endsWith(SEPARATOR)) { + spec = spec.substring(0, spec.length() - SEPARATOR.length()); + } + if (!spec.contains(SEPARATOR)) { + return new URL(spec); + } + return new URL("jar:" + spec); + } + catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + } + + @Override + public java.util.jar.JarEntry getJarEntry() throws IOException { + if (this.jarEntryName == null || this.jarEntryName.isEmpty()) { + return null; + } + connect(); + return this.jarEntry; + } + + @Override + public String getEntryName() { + if (this.jarFile == null) { + throw NOT_FOUND_CONNECTION_EXCEPTION; + } + return this.jarEntryName.toString(); + } + + @Override + public InputStream getInputStream() throws IOException { + if (this.jarFile == null) { + throw FILE_NOT_FOUND_EXCEPTION; + } + if (this.jarEntryName.isEmpty() && this.jarFile.getType() == JarFile.JarFileType.DIRECT) { + throw new IOException("no entry name specified"); + } + connect(); + InputStream inputStream = (this.jarEntryName.isEmpty() ? this.jarFile.getInputStream() + : this.jarFile.getInputStream(this.jarEntry)); + if (inputStream == null) { + throwFileNotFound(this.jarEntryName, this.jarFile); + } + return inputStream; + } + + private void throwFileNotFound(Object entry, AbstractJarFile jarFile) throws FileNotFoundException { + if (Boolean.TRUE.equals(useFastExceptions.get())) { + throw FILE_NOT_FOUND_EXCEPTION; + } + throw new FileNotFoundException("JAR entry " + entry + " not found in " + jarFile.getName()); + } + + @Override + public int getContentLength() { + long length = getContentLengthLong(); + if (length > Integer.MAX_VALUE) { + return -1; + } + return (int) length; + } + + @Override + public long getContentLengthLong() { + if (this.jarFile == null) { + return -1; + } + try { + if (this.jarEntryName.isEmpty()) { + return this.jarFile.size(); + } + java.util.jar.JarEntry entry = getJarEntry(); + return (entry != null) ? (int) entry.getSize() : -1; + } + catch (IOException ex) { + return -1; + } + } + + @Override + public Object getContent() throws IOException { + connect(); + return this.jarEntryName.isEmpty() ? this.jarFile : super.getContent(); + } + + @Override + public String getContentType() { + return (this.jarEntryName != null) ? this.jarEntryName.getContentType() : null; + } + + @Override + public Permission getPermission() throws IOException { + if (this.jarFile == null) { + throw FILE_NOT_FOUND_EXCEPTION; + } + if (this.permission == null) { + this.permission = this.jarFile.getPermission(); + } + return this.permission; + } + + @Override + public long getLastModified() { + if (this.jarFile == null || this.jarEntryName.isEmpty()) { + return 0; + } + try { + java.util.jar.JarEntry entry = getJarEntry(); + return (entry != null) ? entry.getTime() : 0; + } + catch (IOException ex) { + return 0; + } + } + + static void setUseFastExceptions(boolean useFastExceptions) { + JarURLConnection.useFastExceptions.set(useFastExceptions); + } + + static JarURLConnection get(URL url, JarFile jarFile) throws IOException { + StringSequence spec = new StringSequence(url.getFile()); + int index = indexOfRootSpec(spec, jarFile.getPathFromRoot()); + if (index == -1) { + return (Boolean.TRUE.equals(useFastExceptions.get()) ? NOT_FOUND_CONNECTION + : new JarURLConnection(url, null, EMPTY_JAR_ENTRY_NAME)); + } + int separator; + while ((separator = spec.indexOf(SEPARATOR, index)) > 0) { + JarEntryName entryName = JarEntryName.get(spec.subSequence(index, separator)); + JarEntry jarEntry = jarFile.getJarEntry(entryName.toCharSequence()); + if (jarEntry == null) { + return JarURLConnection.notFound(jarFile, entryName); + } + jarFile = jarFile.getNestedJarFile(jarEntry); + index = separator + SEPARATOR.length(); + } + JarEntryName jarEntryName = JarEntryName.get(spec, index); + if (Boolean.TRUE.equals(useFastExceptions.get()) && !jarEntryName.isEmpty() + && !jarFile.containsEntry(jarEntryName.toString())) { + return NOT_FOUND_CONNECTION; + } + return new JarURLConnection(url, new JarFileWrapper(jarFile), jarEntryName); + } + + private static int indexOfRootSpec(StringSequence file, String pathFromRoot) { + int separatorIndex = file.indexOf(SEPARATOR); + if (separatorIndex < 0 || !file.startsWith(pathFromRoot, separatorIndex)) { + return -1; + } + return separatorIndex + SEPARATOR.length() + pathFromRoot.length(); + } + + private static JarURLConnection notFound() { + try { + return notFound(null, null); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) throws IOException { + if (Boolean.TRUE.equals(useFastExceptions.get())) { + return NOT_FOUND_CONNECTION; + } + return new JarURLConnection(null, jarFile, jarEntryName); + } + + /** + * A JarEntryName parsed from a URL String. + */ + static class JarEntryName { + + private final StringSequence name; + + private String contentType; + + JarEntryName(StringSequence spec) { + this.name = decode(spec); + } + + private StringSequence decode(StringSequence source) { + if (source.isEmpty() || (source.indexOf('%') < 0)) { + return source; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length()); + write(source.toString(), bos); + // AsciiBytes is what is used to store the JarEntries so make it symmetric + return new StringSequence(AsciiBytes.toString(bos.toByteArray())); + } + + private void write(String source, ByteArrayOutputStream outputStream) { + int length = source.length(); + for (int i = 0; i < length; i++) { + int c = source.charAt(i); + if (c > 127) { + try { + String encoded = URLEncoder.encode(String.valueOf((char) c), "UTF-8"); + write(encoded, outputStream); + } + catch (UnsupportedEncodingException ex) { + throw new IllegalStateException(ex); + } + } + else { + if (c == '%') { + if ((i + 2) >= length) { + throw new IllegalArgumentException( + "Invalid encoded sequence \"" + source.substring(i) + "\""); + } + c = decodeEscapeSequence(source, i); + i += 2; + } + outputStream.write(c); + } + } + } + + private char decodeEscapeSequence(String source, int i) { + int hi = Character.digit(source.charAt(i + 1), 16); + int lo = Character.digit(source.charAt(i + 2), 16); + if (hi == -1 || lo == -1) { + throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); + } + return ((char) ((hi << 4) + lo)); + } + + CharSequence toCharSequence() { + return this.name; + } + + @Override + public String toString() { + return this.name.toString(); + } + + boolean isEmpty() { + return this.name.isEmpty(); + } + + String getContentType() { + if (this.contentType == null) { + this.contentType = deduceContentType(); + } + return this.contentType; + } + + private String deduceContentType() { + // Guess the content type, don't bother with streams as mark is not supported + String type = isEmpty() ? "x-java/jar" : null; + type = (type != null) ? type : guessContentTypeFromName(toString()); + type = (type != null) ? type : "content/unknown"; + return type; + } + + static JarEntryName get(StringSequence spec) { + return get(spec, 0); + } + + static JarEntryName get(StringSequence spec, int beginIndex) { + if (spec.length() <= beginIndex) { + return EMPTY_JAR_ENTRY_NAME; + } + return new JarEntryName(spec.subSequence(beginIndex)); + } + + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java new file mode 100644 index 0000000..578828a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java @@ -0,0 +1,57 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; + +/** + * @author starBlues + * @version 1.0 + */ +public interface RandomAccessData { + + + /** + * Returns an {@link InputStream} that can be used to read the underlying data. The + * caller is responsible close the underlying stream. + * @return a new input stream that can be used to read the underlying data. + * @throws IOException if the stream cannot be opened + */ + InputStream getInputStream() throws IOException; + + /** + * Returns a new {@link RandomAccessData} for a specific subsection of this data. + * @param offset the offset of the subsection + * @param length the length of the subsection + * @return the subsection data + */ + RandomAccessData getSubsection(long offset, long length); + + /** + * Reads all the data and returns it as a byte array. + * @return the data + * @throws IOException if the data cannot be read + */ + byte[] read() throws IOException; + + /** + * Reads the {@code length} bytes of data starting at the given {@code offset}. + * @param offset the offset from which data should be read + * @param length the number of bytes to be read + * @return the data + * @throws IOException if the data cannot be read + * @throws IndexOutOfBoundsException if offset is beyond the end of the file or + * subsection + * @throws EOFException if offset plus length is greater than the length of the file + * or subsection + */ + byte[] read(long offset, long length) throws IOException; + + /** + * Returns the size of the data. + * @return the size + */ + long getSize(); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java new file mode 100644 index 0000000..8f35b8a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java @@ -0,0 +1,234 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.*; + +/** + * @author starBlues + * @version 1.0 + */ +public class RandomAccessDataFile implements RandomAccessData{ + + private final FileAccess fileAccess; + + private final long offset; + + private final long length; + + /** + * Create a new {@link RandomAccessDataFile} backed by the specified file. + * @param file the underlying file + * @throws IllegalArgumentException if the file is null or does not exist + */ + public RandomAccessDataFile(File file) { + if (file == null) { + throw new IllegalArgumentException("File must not be null"); + } + this.fileAccess = new FileAccess(file); + this.offset = 0L; + this.length = file.length(); + } + + /** + * Private constructor used to create a {@link #getSubsection(long, long) subsection}. + * @param fileAccess provides access to the underlying file + * @param offset the offset of the section + * @param length the length of the section + */ + private RandomAccessDataFile(FileAccess fileAccess, long offset, long length) { + this.fileAccess = fileAccess; + this.offset = offset; + this.length = length; + } + + /** + * Returns the underlying File. + * @return the underlying file + */ + public File getFile() { + return this.fileAccess.file; + } + + @Override + public InputStream getInputStream() throws IOException { + return new DataInputStream(); + } + + @Override + public RandomAccessData getSubsection(long offset, long length) { + if (offset < 0 || length < 0 || offset + length > this.length) { + throw new IndexOutOfBoundsException(); + } + return new RandomAccessDataFile(this.fileAccess, this.offset + offset, length); + } + + @Override + public byte[] read() throws IOException { + return read(0, this.length); + } + + @Override + public byte[] read(long offset, long length) throws IOException { + if (offset > this.length) { + throw new IndexOutOfBoundsException(); + } + if (offset + length > this.length) { + throw new EOFException(); + } + byte[] bytes = new byte[(int) length]; + read(bytes, offset, 0, bytes.length); + return bytes; + } + + private int readByte(long position) throws IOException { + if (position >= this.length) { + return -1; + } + return this.fileAccess.readByte(this.offset + position); + } + + private int read(byte[] bytes, long position, int offset, int length) throws IOException { + if (position > this.length) { + return -1; + } + return this.fileAccess.read(bytes, this.offset + position, offset, length); + } + + @Override + public long getSize() { + return this.length; + } + + public void close() throws IOException { + this.fileAccess.close(); + } + + /** + * {@link InputStream} implementation for the {@link RandomAccessDataFile}. + */ + private class DataInputStream extends InputStream { + + private int position; + + @Override + public int read() throws IOException { + int read = RandomAccessDataFile.this.readByte(this.position); + if (read > -1) { + moveOn(1); + } + return read; + } + + @Override + public int read(byte[] b) throws IOException { + return read(b, 0, (b != null) ? b.length : 0); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (b == null) { + throw new NullPointerException("Bytes must not be null"); + } + return doRead(b, off, len); + } + + /** + * Perform the actual read. + * @param b the bytes to read or {@code null} when reading a single byte + * @param off the offset of the byte array + * @param len the length of data to read + * @return the number of bytes read into {@code b} or the actual read byte if + * {@code b} is {@code null}. Returns -1 when the end of the stream is reached + * @throws IOException in case of I/O errors + */ + int doRead(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return 0; + } + int cappedLen = cap(len); + if (cappedLen <= 0) { + return -1; + } + return (int) moveOn(RandomAccessDataFile.this.read(b, this.position, off, cappedLen)); + } + + @Override + public long skip(long n) throws IOException { + return (n <= 0) ? 0 : moveOn(cap(n)); + } + + /** + * Cap the specified value such that it cannot exceed the number of bytes + * remaining. + * @param n the value to cap + * @return the capped value + */ + private int cap(long n) { + return (int) Math.min(RandomAccessDataFile.this.length - this.position, n); + } + + /** + * Move the stream position forwards the specified amount. + * @param amount the amount to move + * @return the amount moved + */ + private long moveOn(int amount) { + this.position += amount; + return amount; + } + + } + + private static final class FileAccess { + + private final Object monitor = new Object(); + + private final File file; + + private RandomAccessFile randomAccessFile; + + private FileAccess(File file) { + this.file = file; + openIfNecessary(); + } + + private int read(byte[] bytes, long position, int offset, int length) throws IOException { + synchronized (this.monitor) { + openIfNecessary(); + this.randomAccessFile.seek(position); + return this.randomAccessFile.read(bytes, offset, length); + } + } + + private void openIfNecessary() { + if (this.randomAccessFile == null) { + try { + this.randomAccessFile = new RandomAccessFile(this.file, "r"); + } + catch (FileNotFoundException ex) { + throw new IllegalArgumentException( + String.format("File %s must exist", this.file.getAbsolutePath())); + } + } + } + + private void close() throws IOException { + synchronized (this.monitor) { + if (this.randomAccessFile != null) { + this.randomAccessFile.close(); + this.randomAccessFile = null; + } + } + } + + private int readByte(long position) throws IOException { + synchronized (this.monitor) { + openIfNecessary(); + this.randomAccessFile.seek(position); + return this.randomAccessFile.read(); + } + } + + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java new file mode 100644 index 0000000..c8d1986 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java @@ -0,0 +1,139 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.util.Objects; + +/** + * @author starBlues + * @version 1.0 + */ +public class StringSequence implements CharSequence { + + private final String source; + + private final int start; + + private final int end; + + private int hash; + + StringSequence(String source) { + this(source, 0, (source != null) ? source.length() : -1); + } + + StringSequence(String source, int start, int end) { + Objects.requireNonNull(source, "Source must not be null"); + if (start < 0) { + throw new StringIndexOutOfBoundsException(start); + } + if (end > source.length()) { + throw new StringIndexOutOfBoundsException(end); + } + this.source = source; + this.start = start; + this.end = end; + } + + StringSequence subSequence(int start) { + return subSequence(start, length()); + } + + @Override + public StringSequence subSequence(int start, int end) { + int subSequenceStart = this.start + start; + int subSequenceEnd = this.start + end; + if (subSequenceStart > this.end) { + throw new StringIndexOutOfBoundsException(start); + } + if (subSequenceEnd > this.end) { + throw new StringIndexOutOfBoundsException(end); + } + if (start == 0 && subSequenceEnd == this.end) { + return this; + } + return new StringSequence(this.source, subSequenceStart, subSequenceEnd); + } + + /** + * Returns {@code true} if the sequence is empty. Public to be compatible with JDK 15. + * @return {@code true} if {@link #length()} is {@code 0}, otherwise {@code false} + */ + public boolean isEmpty() { + return length() == 0; + } + + @Override + public int length() { + return this.end - this.start; + } + + @Override + public char charAt(int index) { + return this.source.charAt(this.start + index); + } + + int indexOf(char ch) { + return this.source.indexOf(ch, this.start) - this.start; + } + + int indexOf(String str) { + return this.source.indexOf(str, this.start) - this.start; + } + + int indexOf(String str, int fromIndex) { + return this.source.indexOf(str, this.start + fromIndex) - this.start; + } + + boolean startsWith(String prefix) { + return startsWith(prefix, 0); + } + + boolean startsWith(String prefix, int offset) { + int prefixLength = prefix.length(); + int length = length(); + if (length - prefixLength - offset < 0) { + return false; + } + return this.source.startsWith(prefix, this.start + offset); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof CharSequence)) { + return false; + } + CharSequence other = (CharSequence) obj; + int n = length(); + if (n != other.length()) { + return false; + } + int i = 0; + while (n-- != 0) { + if (charAt(i) != other.charAt(i)) { + return false; + } + i++; + } + return true; + } + + @Override + public int hashCode() { + int hash = this.hash; + if (hash == 0 && length() > 0) { + for (int i = this.start; i < this.end; i++) { + hash = 31 * hash + this.source.charAt(i); + } + this.hash = hash; + } + return hash; + } + + @Override + public String toString() { + return this.source.substring(this.start, this.end); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java new file mode 100644 index 0000000..f856a9a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java @@ -0,0 +1,70 @@ +package com.gitee.starblues.core.launcher.jar; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + +/** + * @author starBlues + * @version 1.0 + */ +public class ZipInflaterInputStream extends InflaterInputStream { + + private int available; + + private boolean extraBytesWritten; + + ZipInflaterInputStream(InputStream inputStream, int size) { + super(inputStream, new Inflater(true), getInflaterBufferSize(size)); + this.available = size; + } + + @Override + public int available() throws IOException { + if (this.available < 0) { + return super.available(); + } + return this.available; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int result = super.read(b, off, len); + if (result != -1) { + this.available -= result; + } + return result; + } + + @Override + public void close() throws IOException { + super.close(); + this.inf.end(); + } + + @Override + protected void fill() throws IOException { + try { + super.fill(); + } + catch (EOFException ex) { + if (this.extraBytesWritten) { + throw ex; + } + this.len = 1; + this.buf[0] = 0x0; + this.extraBytesWritten = true; + this.inf.setInput(this.buf, 0, this.len); + } + } + + private static int getInflaterBufferSize(long size) { + size += 2; // inflater likes some space + size = (size > 65536) ? 8192 : size; + size = (size <= 0) ? 4096 : size; + return (int) size; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java new file mode 100644 index 0000000..bd91eb6 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java @@ -0,0 +1,50 @@ +package com.gitee.starblues.core.launcher.plugin; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** + * @author starBlues + * @version 1.0 + */ +public class CacheRegistryInfo implements RegistryInfo { + + private final Map registryInfo = new ConcurrentHashMap<>(); + + @Override + public void addRegistryInfo(String key, Object value) { + registryInfo.put(key, value); + } + + @SuppressWarnings("unchecked") + @Override + public T getRegistryInfo(String key) { + Object o = registryInfo.get(key); + if(o == null){ + return null; + } + return (T) o; + } + + @Override + public T getRegistryInfo(String key, Supplier notExistCreate) { + T t = getRegistryInfo(key); + if(t != null){ + return t; + } + t = notExistCreate.get(); + registryInfo.put(key, t); + return t; + } + + @Override + public void removeRegistryInfo(String key) { + registryInfo.remove(key); + } + + @Override + public void clearRegistryInfo() { + registryInfo.clear(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java new file mode 100644 index 0000000..f2b9e18 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.MainApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultPluginInteractive implements PluginInteractive{ + + private final PluginDescriptor pluginDescriptor; + private final MainApplicationContext mainApplicationContext; + + public DefaultPluginInteractive(PluginDescriptor pluginDescriptor, MainApplicationContext mainApplicationContext) { + this.pluginDescriptor = pluginDescriptor; + this.mainApplicationContext = mainApplicationContext; + } + + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginDescriptor; + } + + @Override + public MainApplicationContext getMainApplicationContext() { + return mainApplicationContext; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java new file mode 100644 index 0000000..fec145b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java @@ -0,0 +1,45 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.MainApplicationContextReflection; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultPluginLauncherManager implements PluginLauncherManager{ + + private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); + + private final MainApplicationContext mainApplicationContext; + + public DefaultPluginLauncherManager(GenericApplicationContext mainGenericApplicationContext, + IntegrationConfiguration configuration) { + this.mainApplicationContext = new MainApplicationContextReflection(mainGenericApplicationContext, configuration); + } + + @Override + public synchronized void start(PluginDescriptor pluginDescriptor) throws Exception{ + if(pluginRegistryInfoMap.containsKey(pluginDescriptor.getPluginId())){ + throw new Exception("已经存在插件 : " + pluginDescriptor.getPluginId()); + } + PluginInteractive pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, + mainApplicationContext); + PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive); + Object pluginApplicationContext = pluginLauncher.run(); + PluginRegistryInfo pluginRegistryInfo = new DefaultPluginRegistryInfo(pluginApplicationContext, + pluginLauncher); + pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), pluginRegistryInfo); + } + + @Override + public synchronized void stop(String pluginId) throws Exception{ + + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java new file mode 100644 index 0000000..c70d8ec --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java @@ -0,0 +1,36 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.GenericApplicationContextReflection; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultPluginRegistryInfo extends CacheRegistryInfo implements PluginRegistryInfo{ + + private final ApplicationContext applicationContext; + private final PluginLauncher pluginLauncher; + + public DefaultPluginRegistryInfo(Object pluginApplicationContext, + PluginLauncher pluginLauncher) { + this.applicationContext = new GenericApplicationContextReflection(pluginApplicationContext); + this.pluginLauncher = pluginLauncher; + } + + @Override + public ApplicationContext getApplicationContext() { + return applicationContext; + } + + @Override + public PluginLauncher getPluginLauncher() { + return pluginLauncher; + } + + @Override + public void clearRegistryInfo() { + super.clearRegistryInfo(); + pluginLauncher.clear(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java new file mode 100644 index 0000000..f34622c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java @@ -0,0 +1,16 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.spring.MainApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public interface PluginInteractive { + + PluginDescriptor getPluginDescriptor(); + + MainApplicationContext getMainApplicationContext(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java new file mode 100644 index 0000000..9cd0904 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -0,0 +1,68 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.ResourceClear; +import com.gitee.starblues.core.classloader.PluginClassLoader; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.launcher.*; + +import java.io.File; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginLauncher extends AbstractLauncher implements ResourceClear { + + private final PluginInteractive pluginInteractive; + private final PluginDescriptor pluginDescriptor; + + public PluginLauncher(PluginInteractive pluginInteractive) { + this.pluginInteractive = pluginInteractive; + this.pluginDescriptor = pluginInteractive.getPluginDescriptor(); + } + + @Override + protected ClassLoader createClassLoader(URL[] urls) throws Exception { + String pluginLibDir = pluginDescriptor.getPluginLibDir(); + Path pluginPath = pluginDescriptor.getPluginPath(); + PluginClassLoader pluginClassLoader = new PluginClassLoader( + "plugin", pluginPath, MainProgramLauncher.class.getClassLoader(), + new JavaMainResourcePatternDefiner(){ + @Override + public Set getIncludeResourcePatterns() { + Set includeResourcePatterns = super.getIncludeResourcePatterns(); + includeResourcePatterns.add("com/gitee/starblues/**"); + return includeResourcePatterns; + } + } + ); + File file = new File(pluginLibDir); + if(file.exists() && file.isDirectory()){ + File[] listFiles = file.listFiles(); + if(listFiles != null){ + for (File listFile : listFiles) { + pluginClassLoader.addResource(listFile); + } + } + + } + pluginClassLoader.addResource(Paths.get("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-bootstrap\\target\\classes")); + + return pluginClassLoader; + } + + + @Override + protected Object launch(ClassLoader classLoader, String... args) throws Exception { + return new PluginMethodRunner(pluginInteractive).run(classLoader); + } + + @Override + public void clear() { + + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java new file mode 100644 index 0000000..0451c49 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java @@ -0,0 +1,18 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; + +/** + * @author starBlues + * @version 1.0 + */ +public interface PluginLauncherManager { + + + void start(PluginDescriptor pluginDescriptor) throws Exception; + + + void stop(String pluginId) throws Exception; + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java new file mode 100644 index 0000000..c6d44b0 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java @@ -0,0 +1,48 @@ +package com.gitee.starblues.core.launcher.plugin; + +import java.util.function.Supplier; + +/** + * @author starBlues + * @version 1.0 + */ +public interface PluginLauncherStorage { + + + void add(String key, Object value); + + /** + * 添加注册的信息 + * @param key 注册信息key + * @param value 注册信息值 + */ + void addRegistryInfo(String key, Object value); + + /** + * 得到注册信息 + * @param key 注册信息key + * @return 注册信息的值 + */ + T getRegistryInfo(String key); + + /** + * 得到注册信息 + * @param key 注册信息key + * @param notExistCreate 不存在的话, 进行创建操作 + * @return 注册信息的值 + */ + T getRegistryInfo(String key, Supplier notExistCreate); + + + /** + * 移除注册信息 + * @param key 注册信息key + */ + void removeRegistryInfo(String key); + + /** + * 清除全部的注册信息 + */ + void clearRegistryInfo(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java new file mode 100644 index 0000000..118f6f6 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java @@ -0,0 +1,44 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.launcher.MethodRunner; +import com.gitee.starblues.utils.ReflectionUtils; + +import java.lang.reflect.Method; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginMethodRunner extends MethodRunner { + + private static final String PLUGIN_RUN_METHOD_NAME = "run"; + + private final PluginInteractive pluginInteractive; + + public PluginMethodRunner(PluginInteractive pluginInteractive) { + super(pluginInteractive.getPluginDescriptor().getPluginClass(), PLUGIN_RUN_METHOD_NAME, new String[]{}); + this.pluginInteractive = pluginInteractive; + } + + @Override + protected Object runMethod(Class runClass) throws Exception { + Method runMethod = ReflectionUtils.findMethod(runClass, runMethodName, Class.class, String[].class); + if(runMethod == null) { + throw new NoSuchMethodException(runClass.getName() + "." + runMethodName + + "(Class arg0, String[] arg1)"); + } + Object instance = getInstance(runClass); + setPluginInteractive(instance); + runMethod.setAccessible(true); + return runMethod.invoke(instance, runClass, this.args); + } + + private void setPluginInteractive(Object launchObject) throws Exception { + if(launchObject == null){ + return; + } + ReflectionUtils.setAttribute(launchObject, "setPluginInteractive", pluginInteractive); + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java new file mode 100644 index 0000000..5496e60 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java @@ -0,0 +1,15 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.spring.ApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public interface PluginRegistryInfo { + + ApplicationContext getApplicationContext(); + + PluginLauncher getPluginLauncher(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java new file mode 100644 index 0000000..8cfc5c0 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java @@ -0,0 +1,45 @@ +package com.gitee.starblues.core.launcher.plugin; +import java.util.function.Supplier; + +/** + * @author starBlues + * @version 1.0 + */ +public interface RegistryInfo { + + + /** + * 添加注册的信息 + * @param key 注册信息key + * @param value 注册信息值 + */ + void addRegistryInfo(String key, Object value); + + /** + * 得到注册信息 + * @param key 注册信息key + * @return 注册信息的值 + */ + T getRegistryInfo(String key); + + /** + * 得到注册信息 + * @param key 注册信息key + * @param notExistCreate 不存在的话, 进行创建操作 + * @return 注册信息的值 + */ + T getRegistryInfo(String key, Supplier notExistCreate); + + + /** + * 移除注册信息 + * @param key 注册信息key + */ + void removeRegistryInfo(String key); + + /** + * 清除全部的注册信息 + */ + void clearRegistryInfo(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java index 334940d..cb40692 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java @@ -5,6 +5,7 @@ import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; import org.springframework.util.ClassUtils; @@ -37,7 +38,7 @@ public class DefaultPluginLoader implements PluginLoader{ public PluginWrapperInside load(PluginDescriptor descriptor) throws Exception { Assert.isNotNull(descriptor, "参数 PluginDescriptor 不能为空"); PluginClassLoader classLoader = getClassLoader(descriptor); - installLib(classLoader, descriptor.getPluginLibDir()); + installLib(classLoader, descriptor); Class bootstrapClass = classLoader.loadClass(descriptor.getPluginClass()); PluginWrapperInside pluginWrapperInside = new PluginWrapperInside( descriptor.getPluginId(), @@ -75,11 +76,16 @@ public class DefaultPluginLoader implements PluginLoader{ return pnClassLoader; } - protected void installLib(PluginClassLoader classLoader, String lib){ - if(ObjectUtils.isEmpty(lib)){ + protected void installLib(PluginClassLoader classLoader, PluginDescriptor descriptor){ + String pluginLibDir = descriptor.getPluginLibDir(); + + if(ObjectUtils.isEmpty(pluginLibDir)){ + return; + } + File file = getExistLibFile(descriptor); + if(file == null){ return; } - File file = new File(lib); addJarFile(classLoader, file); if(file.isDirectory()){ File[] files = file.listFiles(); @@ -92,6 +98,20 @@ public class DefaultPluginLoader implements PluginLoader{ } } + private File getExistLibFile(PluginDescriptor descriptor){ + String pluginLibDir = descriptor.getPluginLibDir(); + File file = new File(pluginLibDir); + if(file.exists()){ + return file; + } + String relativePath = CommonUtils.joiningFilePath(descriptor.getPluginPath().toString(), pluginLibDir); + file = new File(relativePath); + if(file.exists()){ + return file; + } + return null; + } + private void addJarFile(PluginClassLoader pnClassLoader, File file){ if(!file.exists()){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java index 40f3ab6..0bfd072 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java @@ -5,6 +5,7 @@ import com.gitee.starblues.utils.ObjectUtils; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** @@ -22,6 +23,9 @@ public class BasePluginScanner implements PluginScanner{ @Override public List scan(List rootDir) { + if(ObjectUtils.isEmpty(rootDir)){ + return Collections.emptyList(); + } List pluginPaths = new ArrayList<>(); if(pathResolve == null){ return pluginPaths; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java index 9ed07ec..d1db186 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java @@ -40,23 +40,15 @@ public class IntegrationExtendPoint { @Bean @ConditionalOnMissingBean - public PluginOperator createPluginOperator(RealizeProvider realizeProvider, - SpringPlugin springPlugin) { + public PluginOperator createPluginOperator(RealizeProvider realizeProvider) { PluginOperator pluginOperator = new DefaultPluginOperator( applicationContext, - springPlugin, realizeProvider, configuration ); return new PluginOperatorWrapper(pluginOperator, configuration); } - @Bean - @ConditionalOnMissingBean - public SpringPlugin createSpringPlugin(){ - return new DefaultSpringPlugin(applicationContext); - } - @Bean @ConditionalOnMissingBean public RealizeProvider realizeProvider(MainResourcePatternDefiner mainResourcePatternDefiner) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 453fb0c..8150999 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -4,11 +4,12 @@ import com.gitee.starblues.core.DefaultPluginManager; import com.gitee.starblues.core.PluginManager; import com.gitee.starblues.core.RealizeProvider; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.launcher.plugin.*; import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; -import com.gitee.starblues.spring.SpringPlugin; +import com.gitee.starblues.spring.*; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; import org.slf4j.Logger; @@ -30,20 +31,17 @@ public class DefaultPluginOperator implements PluginOperator { private final AtomicBoolean isInit = new AtomicBoolean(false); - private final GenericApplicationContext applicationContext; private final IntegrationConfiguration configuration; - private final SpringPlugin springPlugin; private final PluginManager pluginManager; + private final PluginLauncherManager pluginLauncherManager; public DefaultPluginOperator(GenericApplicationContext applicationContext, - SpringPlugin springPlugin, RealizeProvider realizeProvider, IntegrationConfiguration configuration) { - this.applicationContext = applicationContext; this.configuration = configuration; - this.springPlugin = springPlugin; this.pluginManager = new DefaultPluginManager(realizeProvider, configuration.pluginPath()); + this.pluginLauncherManager = new DefaultPluginLauncherManager(applicationContext, configuration); } @@ -76,8 +74,9 @@ public class DefaultPluginOperator implements PluginOperator { boolean isFoundException = false; for (PluginDescriptor descriptor : pluginDescriptors) { try { - pluginManager.start(descriptor.getPluginId()); - springPlugin.registry(pluginManager.getPluginWrapper(descriptor.getPluginId())); + //pluginManager.start(descriptor.getPluginId()); + pluginLauncherManager.start(descriptor); + //springPlugin.registry(pluginManager.getPluginWrapper(descriptor.getPluginId())); log.info("启动插件[{}@{}]成功", descriptor.getPluginId(), descriptor.getPluginVersion()); } catch (Exception e){ log.error("启动插件[{}]失败. {}", descriptor.getPluginId(), e.getMessage(), e); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java new file mode 100644 index 0000000..4675aac --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java @@ -0,0 +1,12 @@ +package com.gitee.starblues.spring; + +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; + +/** + * @author starBlues + * @version 1.0 + */ +public interface ApplicationContext extends AutowireCapableBeanFactory, ListableBeanFactory { + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java index f71f867..667325f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java @@ -15,6 +15,7 @@ import com.gitee.starblues.utils.PluginFileUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; import org.springframework.context.support.GenericApplicationContext; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; @@ -140,6 +141,7 @@ public class DefaultPluginSpringApplication implements PluginSpringApplication{ private void addDefaultProcessor() { // 注册 ConfigurationPropertiesBindingPostProcessor, 用于将配置信息绑定到Bean上 ConfigurationPropertiesBindingPostProcessor.register(applicationContext); + applicationContext.register(PropertySourcesPlaceholderConfigurer.class); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java new file mode 100644 index 0000000..690f8ac --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java @@ -0,0 +1,274 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.utils.ReflectionUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.config.NamedBeanHolder; +import org.springframework.core.ResolvableType; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.Set; +import java.util.StringJoiner; + +/** + * @author starBlues + * @version 1.0 + */ +public class GenericApplicationContextReflection implements ApplicationContext { + + private final Object genericApplicationContext; + private final Class mainApplicationContextClass; + + public GenericApplicationContextReflection(Object genericApplicationContext) { + this.genericApplicationContext = genericApplicationContext; + this.mainApplicationContextClass = genericApplicationContext.getClass(); + } + + @Override + public boolean containsBeanDefinition(String beanName) { + return invokeReturn("containsBeanDefinition", beanName); + } + + @Override + public int getBeanDefinitionCount() { + return invokeReturn("getBeanDefinitionCount"); + } + + @Override + public String[] getBeanDefinitionNames() { + return invokeReturn("getBeanDefinitionNames"); + } + + @Override + public String[] getBeanNamesForType(ResolvableType type) { + return invokeReturn("getBeanNamesForType", type); + } + + @Override + public String[] getBeanNamesForType(Class type) { + return invokeReturn("getBeanNamesForType", type); + } + + @Override + public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { + return invokeReturn("getBeanNamesForType", includeNonSingletons, allowEagerInit); + } + + @Override + public Map getBeansOfType(Class type) throws BeansException { + return invokeReturn("getBeansOfType", type); + } + + @Override + public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { + return invokeReturn("getBeansOfType", type, includeNonSingletons, allowEagerInit); + } + + @Override + public String[] getBeanNamesForAnnotation(Class annotationType) { + return invokeReturn("getBeanNamesForAnnotation", annotationType); + } + + @Override + public Map getBeansWithAnnotation(Class annotationType) throws BeansException { + return invokeReturn("getBeansWithAnnotation", annotationType); + } + + @Override + public A findAnnotationOnBean(String beanName, Class annotationType) throws NoSuchBeanDefinitionException { + return invokeReturn("findAnnotationOnBean", beanName, annotationType); + } + + @Override + public T createBean(Class beanClass) throws BeansException { + prohibitCall("createBean"); + return null; + } + + @Override + public void autowireBean(Object existingBean) throws BeansException { + prohibitCall("autowireBean"); + } + + @Override + public Object configureBean(Object existingBean, String beanName) throws BeansException { + prohibitCall("configureBean"); + return null; + } + + @Override + public Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { + prohibitCall("createBean"); + return null; + } + + @Override + public Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { + prohibitCall("autowire"); + return null; + } + + @Override + public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException { + prohibitCall("autowireBeanProperties"); + } + + @Override + public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException { + prohibitCall("applyBeanPropertyValues"); + } + + @Override + public Object initializeBean(Object existingBean, String beanName) throws BeansException { + prohibitCall("initializeBean"); + return null; + } + + @Override + public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { + prohibitCall("applyBeanPostProcessorsBeforeInitialization"); + return null; + } + + @Override + public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { + prohibitCall("applyBeanPostProcessorsAfterInitialization"); + return null; + } + + @Override + public void destroyBean(Object existingBean) { + prohibitCall("destroyBean"); + } + + @Override + public NamedBeanHolder resolveNamedBean(Class requiredType) throws BeansException { + prohibitCall("resolveNamedBean"); + return null; + } + + @Override + public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName) throws BeansException { + return null; + } + + @Override + public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName, Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { + return null; + } + + @Override + public Object getBean(String name) throws BeansException { + return invokeReturn("getBean", name); + } + + @Override + public T getBean(String name, Class requiredType) throws BeansException { + return invokeReturn("getBean", name, requiredType); + } + + @Override + public Object getBean(String name, Object... args) throws BeansException { + return invokeReturn("getBean", name, args); + } + + @Override + public T getBean(Class requiredType) throws BeansException { + return invokeReturn("getBean", requiredType); + } + + @Override + public T getBean(Class requiredType, Object... args) throws BeansException { + return invokeReturn("getBean", requiredType, args); + } + + @Override + public boolean containsBean(String name) { + return invokeReturn("containsBean", name); + } + + @Override + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return invokeReturn("isSingleton", name); + } + + @Override + public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + return invokeReturn("isPrototype", name); + } + + @Override + public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { + return invokeReturn("isTypeMatch", name, typeToMatch); + } + + @Override + public boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { + return invokeReturn("isTypeMatch", name, typeToMatch); + } + + @Override + public Class getType(String name) throws NoSuchBeanDefinitionException { + return invokeReturn("getType", name); + } + + @Override + public String[] getAliases(String name) { + return invokeReturn("getAliases", name); + } + + + private T invokeReturn(String methodName, Object... params){ + return invoke(true, methodName, params); + } + + private void invokeNoReturn(String methodName, Object... params){ + invoke(false, methodName, params); + } + + @SuppressWarnings("unchecked") + private T invoke(boolean haveReturn, String methodName, Object... params){ + Class[] paramTypes = new Class[params.length]; + for (int i = 0; i < params.length; i++) { + paramTypes[i] = params[i].getClass(); + } + Method method = ReflectionUtils.findMethod(mainApplicationContextClass, methodName, paramTypes); + if(method == null){ + throw new RuntimeException("Not found method : " + methodToString(methodName, paramTypes)); + } + try { + if(haveReturn){ + return (T) method.invoke(genericApplicationContext, params); + } else { + method.invoke(genericApplicationContext, params); + return null; + } + } catch (Exception e) { + throw new RuntimeException("Cannot call method : " + methodToString(methodName, paramTypes)); + } + } + + private String methodToString(String name, Class[] argTypes) { + StringJoiner sj = new StringJoiner(", ", getName() + "." + name + "(", ")"); + if (argTypes != null) { + for (Class c : argTypes) { + sj.add((c == null) ? "null" : c.getName()); + } + } + return sj.toString(); + } + + private String getName() { + return mainApplicationContextClass.getName(); + } + + private void prohibitCall(String name){ + throw new IllegalStateException("Prohibit call: " + name); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java new file mode 100644 index 0000000..8c0ee5d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java @@ -0,0 +1,13 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.integration.IntegrationConfiguration; + +/** + * @author starBlues + * @version 1.0 + */ +public interface MainApplicationContext extends ApplicationContext { + + IntegrationConfiguration getConfiguration(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java new file mode 100644 index 0000000..7a2ba15 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java @@ -0,0 +1,24 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.integration.IntegrationConfiguration; + +/** + * @author starBlues + * @version 1.0 + */ +public class MainApplicationContextReflection extends GenericApplicationContextReflection implements MainApplicationContext { + + private final IntegrationConfiguration configuration; + + public MainApplicationContextReflection(Object mainGenericApplicationContext, + IntegrationConfiguration configuration) { + super(mainGenericApplicationContext); + this.configuration = configuration; + } + + @Override + public IntegrationConfiguration getConfiguration() { + return configuration; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java index 7282343..8a7fb64 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java @@ -15,8 +15,10 @@ import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; +import org.springframework.boot.env.PropertiesPropertySourceLoader; import org.springframework.boot.env.PropertySourceLoader; import org.springframework.boot.env.RandomValuePropertySource; +import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.boot.logging.DeferredLog; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ConfigurationClassPostProcessor; @@ -47,6 +49,8 @@ import java.util.stream.Stream; */ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcessor { + private static final String ENVIRONMENT_NAME = "defaultPluginProperties"; + private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"; @@ -248,12 +252,17 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso this.environment = environment; this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment); this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(null); - this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, - this.resourceLoader.getClassLoader()); + this.propertySourceLoaders = new ArrayList<>(); + initPropertySourceLoader(); + } + + private void initPropertySourceLoader(){ + this.propertySourceLoaders.add(new YamlPropertySourceLoader()); + this.propertySourceLoaders.add(new PropertiesPropertySourceLoader()); } void load() { - FilteredPropertySource.apply(this.environment, DefaultPropertiesPropertySource.NAME, LOAD_FILTERED_PROPERTY, + FilteredPropertySource.apply(this.environment, ENVIRONMENT_NAME, LOAD_FILTERED_PROPERTY, this::loadWithFilteredProperties); } @@ -703,8 +712,8 @@ public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcesso private void addLoadedPropertySource(MutablePropertySources destination, String lastAdded, PropertySource source) { if (lastAdded == null) { - if (destination.contains(DefaultPropertiesPropertySource.NAME)) { - destination.addBefore(DefaultPropertiesPropertySource.NAME, source); + if (destination.contains(ENVIRONMENT_NAME)) { + destination.addBefore(ENVIRONMENT_NAME, source); } else { destination.addLast(source); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java index 97ffb48..0036afd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java @@ -19,14 +19,14 @@ public class ExtractBeanProcessor implements SpringPluginProcessor { @Override public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { - // 获取主程序的扩展 - Map extractMap = mainApplicationContext.getBeansWithAnnotation(Extract.class); - if(ObjectUtils.isEmpty(extractMap)){ - return; - } - for (Object extract : extractMap.values()) { - extractFactory.addOfMain(extract); - } +// // 获取主程序的扩展 +// Map extractMap = mainApplicationContext.getBeansWithAnnotation(Extract.class); +// if(ObjectUtils.isEmpty(extractMap)){ +// return; +// } +// for (Object extract : extractMap.values()) { +// extractFactory.addOfMain(extract); +// } } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index b202aa0..1563e19 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -122,6 +122,16 @@ public abstract class ReflectionUtils { return null; } + public static void setAttribute(Object bean, String setMethodName, Object setObject) throws Exception { + Class aClass = bean.getClass(); + Method setMethod = ReflectionUtils.findMethod(aClass, setMethodName, setObject.getClass()); + + if(setMethod == null){ + throw new Exception("Not found method[" + setMethodName + "] of :" + aClass.getName()); + } + setMethod.invoke(bean, setObject); + } + private static Method[] getDeclaredMethods(Class clazz, boolean defensive) { Assert.isNotNull(clazz, "Class must not be null"); Method[] result = new Method[]{}; @@ -163,8 +173,18 @@ public abstract class ReflectionUtils { } private static boolean hasSameParams(Method method, Class[] paramTypes) { - return (paramTypes.length == method.getParameterCount() && - Arrays.equals(paramTypes, method.getParameterTypes())); + if(paramTypes.length != method.getParameterCount()){ + return false; + } + Class[] parameterTypes = method.getParameterTypes(); + for (int i = 0; i < paramTypes.length; i++) { + Class paramType = paramTypes[i]; + Class methodParamType = parameterTypes[i]; + if(!methodParamType.isAssignableFrom(paramType)){ + return false; + } + } + return true; } } diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories index 3c901ff..cc6e350 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring.factories +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring.factories @@ -1,3 +1,2 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ com.gitee.starblues.integration.SpringBootPluginStarter \ No newline at end of file -- Gitee From 46e9fe6d8c5f1b6ada82371791d02dffa0986307 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Wed, 29 Dec 2021 14:07:41 +0800 Subject: [PATCH 18/37] submit invoke --- pom.xml | 2 +- springboot-plugin-bootstrap/pom.xml | 22 ++- .../bootstrap/DefaultSpringPluginHook.java | 33 ++++ .../EmptyMainApplicationContext.java | 174 ++++++++++++++++++ .../bootstrap/PluginApplicationContext.java | 22 ++- .../bootstrap/PluginListableBeanFactory.java | 47 ++++- .../bootstrap/PluginSpringApplication.java | 60 ++++-- .../bootstrap/SpringPluginBootstrap.java | 81 +++++++- .../processor/DefaultProcessorContext.java | 92 +++++++++ .../processor/FrameDefineBeanProcessor.java | 27 +++ .../processor/InvokeOtherPluginProcessor.java | 46 ++--- .../PluginControllerRegistryProcessor.java | 118 ++++++------ .../bootstrap/processor/ProcessorContext.java | 74 ++++++++ .../processor/ProcessorException.java | 28 +++ .../processor/SpringPluginProcessor.java | 56 ++++++ .../SpringPluginProcessorFactory.java | 136 ++++++++++++++ .../processor/invoke/InvokeBeanFactory.java | 15 +- .../processor/invoke/InvokeProxyHandler.java | 16 +- .../PluginClassPathBeanDefinitionScanner.java | 24 +++ .../bootstrap/utils/AnnotationUtils.java | 47 +++++ .../core/classloader/PluginClassLoader.java | 2 - .../plugin/DefaultPluginInteractive.java | 21 ++- .../plugin/DefaultPluginLauncherManager.java | 19 +- .../plugin/DefaultPluginRegistryInfo.java | 3 +- .../launcher/plugin/PluginInteractive.java | 6 + .../core/launcher/plugin/PluginLauncher.java | 1 + .../launcher/plugin/PluginMethodRunner.java | 8 +- .../launcher/plugin/PluginRegistryInfo.java | 2 +- .../application/AutoPluginApplication.java | 23 ++- .../application/DefaultPluginApplication.java | 32 ++-- .../starblues/spring/ApplicationContext.java | 6 +- .../spring/ApplicationContextProxy.java | 22 +++ .../spring/CglibProxyInvokeFactory.java | 56 ++++++ .../DefaultPluginSpringApplication.java | 16 -- .../spring/DiffProxyInvokeFactory.java | 34 ++++ .../GenericApplicationContextReflection.java | 133 +------------ .../spring/MainApplicationContext.java | 9 +- .../MainApplicationContextReflection.java | 41 ++++- .../gitee/starblues/spring/ProxyInvoke.java | 73 ++++++++ .../starblues/spring/ProxyInvokeFactory.java | 11 ++ .../starblues/spring/SpringPluginHook.java | 11 ++ .../spring/listener/BeanRegistryListener.java | 61 ------ .../spring/listener/ClassScannerListener.java | 132 ------------- .../InvokeOtherPluginRegistryListener.java | 54 ------ .../spring/listener/ListenerRunMode.java | 24 --- .../NecessaryBeanRegistryListener.java | 36 ---- .../PluginSpringApplicationRunListener.java | 42 ----- .../PluginSpringApplicationRunListeners.java | 94 ---------- .../SpringPluginProcessorFactory.java | 1 - .../invoke/DefaultInvokeSupperCache.java | 62 +++++++ .../processor/invoke/InvokeSupperCache.java | 73 +------- .../spring/processor/invoke/SupperCache.java | 33 ++++ .../com/gitee/starblues/utils/ClassUtils.java | 3 - .../starblues/utils/ReflectionUtils.java | 56 +++++- 54 files changed, 1480 insertions(+), 840 deletions(-) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/InvokeOtherPluginProcessor.java (66%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java (68%) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/invoke/InvokeBeanFactory.java (74%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/invoke/InvokeProxyHandler.java (90%) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java diff --git a/pom.xml b/pom.xml index b0761ce..ad021fd 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ springboot-plugin-framework springboot-plugin-bootstrap - springboot-plugin-framework-extension + springboot-plugin-framework-example diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index c8760dc..7fc8a38 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -17,22 +17,40 @@ UTF-8 3.8.1 - 2.4.1 + 2.5.0 + 5.3.2 + 2.11.3 org.springframework.boot spring-boot - ${spring-boot-version} + ${spring-boot.version} provided + + org.springframework + spring-webmvc + ${spring.version} + provided + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + com.gitee.starblues springboot-plugin-framework 3.0.0-RELEASE provided + + org.slf4j + slf4j-api + 1.7.32 + diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java new file mode 100644 index 0000000..5101056 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -0,0 +1,33 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.SpringPluginHook; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultSpringPluginHook implements SpringPluginHook { + + private final SpringPluginProcessor springPluginProcessor; + private final ProcessorContext processorContext; + + public DefaultSpringPluginHook(SpringPluginProcessor springPluginProcessor, + ProcessorContext processorContext) { + this.springPluginProcessor = springPluginProcessor; + this.processorContext = processorContext; + } + + @Override + public Object getGenericApplicationContext() { + return processorContext.getApplicationContext(); + } + + @Override + public void close() throws Exception{ + springPluginProcessor.close(processorContext); + processorContext.getApplicationContext().close(); + processorContext.clearRegistryInfo(); + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java new file mode 100644 index 0000000..3f71aaa --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java @@ -0,0 +1,174 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.spring.MainApplicationContext; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.core.ResolvableType; + +import java.lang.annotation.Annotation; +import java.util.Map; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class EmptyMainApplicationContext implements MainApplicationContext { + + + @Override + public Object resolveDependency(Object descriptor, String requestingBeanName) throws BeansException { + return null; + } + + @Override + public Object resolveDependency(Object descriptor, String requestingBeanName, Set autowiredBeanNames, Object typeConverter) throws BeansException { + return null; + } + + @Override + public boolean containsBeanDefinition(String beanName) { + return false; + } + + @Override + public int getBeanDefinitionCount() { + return 0; + } + + @Override + public String[] getBeanDefinitionNames() { + return new String[0]; + } + + @Override + public ObjectProvider getBeanProvider(Class requiredType, boolean allowEagerInit) { + return null; + } + + @Override + public ObjectProvider getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) { + return null; + } + + @Override + public String[] getBeanNamesForType(ResolvableType type) { + return new String[0]; + } + + @Override + public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { + return new String[0]; + } + + @Override + public String[] getBeanNamesForType(Class type) { + return new String[0]; + } + + @Override + public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { + return new String[0]; + } + + @Override + public Map getBeansOfType(Class type) throws BeansException { + return null; + } + + @Override + public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { + return null; + } + + @Override + public String[] getBeanNamesForAnnotation(Class annotationType) { + return new String[0]; + } + + @Override + public Map getBeansWithAnnotation(Class annotationType) throws BeansException { + return null; + } + + @Override + public A findAnnotationOnBean(String beanName, Class annotationType) throws NoSuchBeanDefinitionException { + return null; + } + + @Override + public Object getBean(String name) throws BeansException { + return null; + } + + @Override + public T getBean(String name, Class requiredType) throws BeansException { + return null; + } + + @Override + public Object getBean(String name, Object... args) throws BeansException { + return null; + } + + @Override + public T getBean(Class requiredType) throws BeansException { + return null; + } + + @Override + public T getBean(Class requiredType, Object... args) throws BeansException { + return null; + } + + @Override + public ObjectProvider getBeanProvider(Class requiredType) { + return null; + } + + @Override + public ObjectProvider getBeanProvider(ResolvableType requiredType) { + return null; + } + + @Override + public boolean containsBean(String name) { + return false; + } + + @Override + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return false; + } + + @Override + public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + return false; + } + + @Override + public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { + return false; + } + + @Override + public boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { + return false; + } + + @Override + public Class getType(String name) throws NoSuchBeanDefinitionException { + return null; + } + + @Override + public Class getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { + return null; + } + + @Override + public String[] getAliases(String name) { + return new String[0]; + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java index 4814d4e..d9787c2 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java @@ -1,5 +1,8 @@ package com.gitee.starblues.bootstrap; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.ResourceLoader; @@ -10,14 +13,27 @@ import org.springframework.core.io.ResourceLoader; */ public class PluginApplicationContext extends AnnotationConfigApplicationContext { + private final PluginDescriptor pluginDescriptor; + public PluginApplicationContext(DefaultListableBeanFactory beanFactory, - ResourceLoader resourceLoader) { + ProcessorContext processorContext) { super(beanFactory); - setResourceLoader(resourceLoader); + setResourceLoader(processorContext.getResourceLoader()); + this.pluginDescriptor = processorContext.getPluginDescriptor(); } @Override public String getApplicationName() { - return "jpa-plugin1"; + return pluginDescriptor.getPluginId(); + } + + @Override + public void refresh() throws BeansException, IllegalStateException { + super.refresh(); + } + + @Override + public void close() { + super.close(); } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java index 1e89976..c24b6b1 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -1,6 +1,18 @@ package com.gitee.starblues.bootstrap; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.utils.ObjectUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.lang.Nullable; + +import java.util.Set; /** * @author starBlues @@ -8,7 +20,40 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; */ public class PluginListableBeanFactory extends DefaultListableBeanFactory { - public PluginListableBeanFactory() { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final static String NO_SUCH_BEAN_EXCEPTION_NAME = "NoSuchBeanDefinitionException"; + + private final MainApplicationContext applicationContext; + + public PluginListableBeanFactory(MainApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Override + public Object resolveDependency(DependencyDescriptor descriptor, + @Nullable String requestingBeanName, + @Nullable Set autowiredBeanNames, + @Nullable TypeConverter typeConverter) throws BeansException { + + try { + return super.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); + } catch (BeansException e){ + return resolveDependencyFromMain(descriptor); + } + } + + private Object resolveDependencyFromMain(DependencyDescriptor descriptor){ + String dependencyName = descriptor.getDependencyName(); + if(!ObjectUtils.isEmpty(dependencyName) && applicationContext.containsBean(dependencyName)){ + return applicationContext.getBean(dependencyName); + } else { + try { + return applicationContext.getBean(descriptor.getDependencyType()); + } catch (Exception e){ + throw new NoSuchBeanDefinitionException(descriptor.getDependencyType()); + } + } } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java index fc43d48..d558911 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -1,42 +1,45 @@ package com.gitee.starblues.bootstrap; -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.launcher.plugin.PluginInteractive; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; -import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; -import java.util.HashMap; -import java.util.Map; - /** * @author starBlues * @version 1.0 */ public class PluginSpringApplication extends SpringApplication { - private final PluginDescriptor pluginDescriptor; + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final SpringPluginProcessor springPluginProcessor; + private final ProcessorContext processorContext; - private final ConfigurableApplicationContext applicationContext; + private final GenericApplicationContext applicationContext; private final DefaultListableBeanFactory beanFactory; private final ResourceLoader resourceLoader; private final ConfigurePluginEnvironment configurePluginEnvironment; - public PluginSpringApplication(PluginInteractive pluginInteractive, Class... primarySources) { + public PluginSpringApplication(SpringPluginProcessor springPluginProcessor, + ProcessorContext processorContext, + Class... primarySources) { super(primarySources); - this.pluginDescriptor = pluginInteractive.getPluginDescriptor(); - this.resourceLoader = new DefaultResourceLoader(getPluginClassLoader()); - this.beanFactory = new PluginListableBeanFactory(); - this.applicationContext = new PluginApplicationContext(beanFactory, resourceLoader); - this.configurePluginEnvironment = new ConfigurePluginEnvironment(pluginDescriptor); + this.springPluginProcessor = springPluginProcessor; + this.processorContext = processorContext; + this.resourceLoader = processorContext.getResourceLoader(); + this.beanFactory = new PluginListableBeanFactory(processorContext.getMainApplicationContext()); + this.applicationContext = new PluginApplicationContext(beanFactory, processorContext); + this.configurePluginEnvironment = new ConfigurePluginEnvironment(processorContext.getPluginDescriptor()); setDefaultConfig(); } @@ -44,6 +47,7 @@ public class PluginSpringApplication extends SpringApplication { setResourceLoader(resourceLoader); setBannerMode(Banner.Mode.OFF); setEnvironment(new StandardEnvironment()); + setWebApplicationType(WebApplicationType.NONE); } @Override @@ -57,8 +61,26 @@ public class PluginSpringApplication extends SpringApplication { return applicationContext; } - private ClassLoader getPluginClassLoader(){ - return PluginSpringApplication.class.getClassLoader(); + @Override + public ConfigurableApplicationContext run(String... args) { + try { + processorContext.setApplicationContext(this.applicationContext); + springPluginProcessor.initialize(processorContext); + return super.run(args); + } catch (Exception e) { + springPluginProcessor.failure(processorContext); + logger.error("启动插件[{}]失败. {}", + processorContext.getPluginDescriptor().getPluginId(), + e.getMessage(), e); + throw new RuntimeException(e); + } + } + + @Override + protected void refresh(ConfigurableApplicationContext applicationContext) { + springPluginProcessor.refreshBefore(processorContext); + super.refresh(applicationContext); + springPluginProcessor.refreshAfter(processorContext); } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java index 8353179..d3cfe22 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java @@ -1,7 +1,23 @@ package com.gitee.starblues.bootstrap; +import com.gitee.starblues.bootstrap.processor.DefaultProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessorFactory; +import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.EmptyPluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; -import org.springframework.context.ConfigurableApplicationContext; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.spring.processor.invoke.DefaultInvokeSupperCache; + +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; /** * @author starBlues @@ -9,23 +25,74 @@ import org.springframework.context.ConfigurableApplicationContext; */ public abstract class SpringPluginBootstrap { - private PluginInteractive pluginInteractive; + private SpringPluginProcessor.RunMode runMode = SpringPluginProcessor.RunMode.ONESELF; + + private volatile PluginInteractive pluginInteractive; + + private final List customPluginProcessors = new ArrayList<>(); - public ConfigurableApplicationContext run(Class primarySources, String[] args){ + public SpringPluginHook run(String[] args){ + return run(this.getClass(), args); + } + + public SpringPluginHook run(Class primarySources, String[] args){ return run(new Class[]{ primarySources }, args); } - public ConfigurableApplicationContext run(Class[] primarySources, String[] args){ + public SpringPluginHook run(Class[] primarySources, String[] args){ return start(primarySources, args); } - private ConfigurableApplicationContext start(Class[] primarySources, String[] args){ - PluginSpringApplication springApplication = new PluginSpringApplication(pluginInteractive, primarySources); - return springApplication.run(args); + private SpringPluginHook start(Class[] primarySources, String[] args){ + createPluginInteractive(); + SpringPluginProcessor springPluginProcessor = new SpringPluginProcessorFactory(runMode, customPluginProcessors); + ProcessorContext processorContext = new DefaultProcessorContext( + pluginInteractive, + this.getClass() + ); + PluginSpringApplication springApplication = new PluginSpringApplication( + springPluginProcessor, + processorContext, + primarySources); + springApplication.run(args); + return new DefaultSpringPluginHook(springPluginProcessor, processorContext); } public final void setPluginInteractive(PluginInteractive pluginInteractive) { this.pluginInteractive = pluginInteractive; + this.runMode = SpringPluginProcessor.RunMode.PLUGIN; + } + + public final void addSpringPluginProcessor(SpringPluginProcessor springPluginProcessor){ + if(springPluginProcessor != null){ + customPluginProcessors.add(springPluginProcessor); + } + } + + private void createPluginInteractive(){ + if(pluginInteractive != null){ + return; + } + PluginDescriptor pluginDescriptor = createPluginDescriptor(); + MainApplicationContext mainApplicationContext = new EmptyMainApplicationContext(); + pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, mainApplicationContext, + new AutoIntegrationConfiguration(), + new DefaultInvokeSupperCache()); + } + + private PluginDescriptor createPluginDescriptor(){ + PluginDescriptor pluginDescriptor; + try { + PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); + pluginDescriptor = pluginDescriptorLoader.load( + Paths.get(this.getClass().getResource("/").toURI())); + if(pluginDescriptor == null){ + pluginDescriptor = new EmptyPluginDescriptor(); + } + } catch (Exception e){ + pluginDescriptor = new EmptyPluginDescriptor(); + } + return pluginDescriptor; } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java new file mode 100644 index 0000000..0468199 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -0,0 +1,92 @@ +package com.gitee.starblues.bootstrap.processor; + +import com.gitee.starblues.bootstrap.SpringPluginBootstrap; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.launcher.plugin.CacheRegistryInfo; +import com.gitee.starblues.core.launcher.plugin.PluginInteractive; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.ResourceLoader; +import org.springframework.util.ClassUtils; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultProcessorContext extends CacheRegistryInfo implements ProcessorContext{ + + private final PluginInteractive pluginInteractive; + private final Class runnerClass; + private final MainApplicationContext mainApplicationContext; + private final ClassLoader classLoader; + private final ResourceLoader resourceLoader; + + private final IntegrationConfiguration configuration; + + private GenericApplicationContext applicationContext; + + public DefaultProcessorContext(PluginInteractive pluginInteractive, + Class runnerClass) { + this.pluginInteractive = pluginInteractive; + this.runnerClass = runnerClass; + this.classLoader = getPluginClassLoader(); + this.resourceLoader = new DefaultResourceLoader(this.classLoader); + this.mainApplicationContext = pluginInteractive.getMainApplicationContext(); + this.configuration = pluginInteractive.getConfiguration(); + } + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginInteractive.getPluginDescriptor(); + } + + @Override + public Class getRunnerClass() { + return runnerClass; + } + + @Override + public PluginInteractive getPluginInteractive() { + return pluginInteractive; + } + + @Override + public MainApplicationContext getMainApplicationContext() { + return mainApplicationContext; + } + + @Override + public IntegrationConfiguration getConfiguration() { + return configuration; + } + + @Override + public GenericApplicationContext getApplicationContext() { + if(applicationContext == null){ + throw new IllegalStateException("GenericApplicationContext 未初始化!"); + } + return applicationContext; + } + + @Override + public ClassLoader getClassLoader() { + return classLoader; + } + + @Override + public ResourceLoader getResourceLoader() { + return resourceLoader; + } + + @Override + public void setApplicationContext(GenericApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + + protected ClassLoader getPluginClassLoader(){ + return ClassUtils.getDefaultClassLoader(); + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java new file mode 100644 index 0000000..9541deb --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java @@ -0,0 +1,27 @@ +package com.gitee.starblues.bootstrap.processor; + + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class FrameDefineBeanProcessor implements SpringPluginProcessor { + + @Override + public void refreshBefore(ProcessorContext context) throws ProcessorException { + ConfigurableApplicationContext applicationContext = context.getApplicationContext(); + PluginDescriptor pluginDescriptor = context.getPluginDescriptor(); + ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); + beanFactory.registerSingleton("pluginDescriptor", pluginDescriptor); + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java similarity index 66% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java index 86838fd..9121254 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/InvokeOtherPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java @@ -1,11 +1,13 @@ -package com.gitee.starblues.spring.processor; +package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.annotation.Caller; import com.gitee.starblues.annotation.Supplier; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.invoke.InvokeBeanFactory; +import com.gitee.starblues.bootstrap.processor.invoke.InvokeBeanFactory; +import com.gitee.starblues.bootstrap.processor.scanner.PluginClassPathBeanDefinitionScanner; +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.GenericApplicationContextReflection; import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; -import com.gitee.starblues.spring.processor.scanner.PluginClassPathBeanDefinitionScanner; +import com.gitee.starblues.spring.processor.invoke.SupperCache; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ScanUtils; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; @@ -14,7 +16,6 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; import java.util.Map; @@ -24,29 +25,29 @@ import java.util.Set; * @author starBlues * @version 1.0 */ -public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ +public class InvokeOtherPluginProcessor implements SpringPluginProcessor { @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - InvokeCallerBeanDefinitionScanner scanner = new InvokeCallerBeanDefinitionScanner(registryInfo); - scanner.doScan(ScanUtils.getScanBasePackages(registryInfo.getPluginWrapper().getPluginClass())); + public void refreshBefore(ProcessorContext context) throws ProcessorException { + InvokeCallerBeanDefinitionScanner scanner = new InvokeCallerBeanDefinitionScanner(context); + scanner.doScan(ScanUtils.getScanBasePackages(context.getRunnerClass())); } @Override - public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); + public void refreshAfter(ProcessorContext context) throws ProcessorException { + GenericApplicationContext applicationContext = context.getApplicationContext(); Map supplierBeans = applicationContext.getBeansWithAnnotation(Supplier.class); - String pluginId = registryInfo.getPluginWrapper().getPluginId(); + String pluginId = context.getPluginDescriptor().getPluginId(); + ApplicationContext applicationContextReflection = new GenericApplicationContextReflection(applicationContext); + InvokeSupperCache invokeSupperCache = context.getPluginInteractive().getInvokeSupperCache(); supplierBeans.forEach((k,v)->{ Supplier supplier = AnnotationUtils.findAnnotation(v.getClass(), Supplier.class); String supperKey = k; if(supplier != null && !ObjectUtils.isEmpty(supplier.value())){ supperKey = supplier.value(); } - InvokeSupperCache.add(pluginId, new InvokeSupperCache.Cache(supperKey, k, applicationContext)); + invokeSupperCache.add(pluginId, new SupperCache(supperKey, k, applicationContextReflection)); }); - } @Override @@ -57,12 +58,12 @@ public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ private static class InvokeCallerBeanDefinitionScanner extends PluginClassPathBeanDefinitionScanner { - private final SpringPluginRegistryInfo registryInfo; + private final ProcessorContext context; - public InvokeCallerBeanDefinitionScanner(SpringPluginRegistryInfo registryInfo) { - super(registryInfo, false); - setResourceLoader(new DefaultResourceLoader(registryInfo.getPluginWrapper().getPluginClassLoader())); - this.registryInfo = registryInfo; + public InvokeCallerBeanDefinitionScanner(ProcessorContext context) { + super(context, false); + setResourceLoader(context.getResourceLoader()); + this.context = context; addIncludeFilter(new AnnotationTypeFilter(Caller.class)); addExcludeFilter((metadataReader, metadataReaderFactory) -> { String className = metadataReader.getClassMetadata().getClassName(); @@ -74,7 +75,8 @@ public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ @Override protected Set doScan(String... basePackages) { Set holders = super.doScan(basePackages); - ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); + ClassLoader pluginClassLoader = context.getClassLoader(); + InvokeSupperCache invokeSupperCache = context.getPluginInteractive().getInvokeSupperCache(); for (BeanDefinitionHolder holder : holders) { AbstractBeanDefinition definition = (AbstractBeanDefinition) holder.getBeanDefinition(); try { @@ -86,7 +88,7 @@ public class InvokeOtherPluginProcessor implements SpringPluginProcessor{ // 是调用方 definition.getPropertyValues().add("callerAnnotation", caller); definition.getPropertyValues().add("callerInterface", aClass); - definition.getPropertyValues().add("registryInfo", registryInfo); + definition.getPropertyValues().add("invokeSupperCache", invokeSupperCache); definition.setBeanClass(InvokeBeanFactory.class); definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE); } catch (ClassNotFoundException e) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java similarity index 68% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java index 86d412b..d7b878f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginControllerRegistryListener.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java @@ -1,24 +1,21 @@ -package com.gitee.starblues.spring.listener; +package com.gitee.starblues.bootstrap.processor; +import com.gitee.starblues.bootstrap.utils.AnnotationUtils; import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.PluginSpringApplication; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.utils.ClassUtils; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ReflectionUtils; -import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @@ -28,34 +25,24 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ -public class PluginControllerRegistryListener implements PluginSpringApplicationRunListener { +public class PluginControllerRegistryProcessor implements SpringPluginProcessor { + + private final static Logger LOG = LoggerFactory.getLogger(PluginControllerRegistryProcessor.class); - private final static Logger LOG = LoggerFactory.getLogger(PluginControllerRegistryListener.class); private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; - private final GenericApplicationContext mainApplicationContext; private RequestMappingHandlerMapping requestMappingHandlerMapping; private Method getMappingForMethod; private final AtomicBoolean canRegistered = new AtomicBoolean(false); - public PluginControllerRegistryListener(GenericApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - } @Override - public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { - - IntegrationConfiguration configuration = registryInfo.getConfiguration(); - if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) - && !configuration.enablePluginIdRestPathPrefix()){ - // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 - return; - } - + public void initialize(ProcessorContext processorContext) throws ProcessorException { + MainApplicationContext mainApplicationContext = processorContext.getMainApplicationContext(); this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); @@ -64,28 +51,38 @@ public class PluginControllerRegistryListener implements PluginSpringApplication "请检查当前环境是否为 web 环境"); } this.getMappingForMethod.setAccessible(true); - - PluginSpringApplication pluginSpringApplication = registryInfo.getPluginSpringApplication(); - AnnotationConfigApplicationContext applicationContext = - (AnnotationConfigApplicationContext)pluginSpringApplication.getApplicationContext(); - applicationContext.registerBean("changeRestPathPostProcessor", - ChangeRestPathPostProcessor.class, ()-> new ChangeRestPathPostProcessor(registryInfo)); canRegistered.set(true); } @Override - public void started(SpringPluginRegistryInfo registryInfo) throws Exception { + public void refreshBefore(ProcessorContext processorContext) throws ProcessorException { + if(!canRegistered.get()){ + return; + } + GenericApplicationContext applicationContext = processorContext.getApplicationContext(); + applicationContext.registerBean("changeRestPathPostProcessor", + ChangeRestPathPostProcessor.class, ()-> new ChangeRestPathPostProcessor(processorContext)); + } + + @Override + public void refreshAfter(ProcessorContext processorContext) throws ProcessorException { if(!canRegistered.get()){ return; } - String pluginId = registryInfo.getPluginWrapper().getPluginId(); - List controllerWrappers = registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + IntegrationConfiguration configuration = processorContext.getConfiguration(); + if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) + && !configuration.enablePluginIdRestPathPrefix()){ + // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 + return; + } + String pluginId = processorContext.getPluginDescriptor().getPluginId(); + List controllerWrappers = processorContext.getRegistryInfo(PROCESS_CONTROLLERS); if(ObjectUtils.isEmpty(controllerWrappers)){ LOG.warn("插件 [{}] 没有发现可注册的 Controller", pluginId); return; } - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + GenericApplicationContext applicationContext = processorContext.getApplicationContext(); Iterator iterator = controllerWrappers.iterator(); while (iterator.hasNext()){ @@ -94,7 +91,7 @@ public class PluginControllerRegistryListener implements PluginSpringApplication iterator.remove(); } Object controllerBean = applicationContext.getBean(controllerWrapper.getBeanName()); - Set requestMappingInfos = registry(registryInfo, controllerBean.getClass()); + Set requestMappingInfos = registry(applicationContext, controllerBean.getClass()); if(requestMappingInfos.isEmpty()){ iterator.remove(); } else { @@ -106,25 +103,27 @@ public class PluginControllerRegistryListener implements PluginSpringApplication } @Override - public ListenerRunMode runMode() { - return ListenerRunMode.PLUGIN; + public RunMode runMode() { + return RunMode.PLUGIN; } - private Set registry(SpringPluginRegistryInfo pluginRegistryInfo, Class aClass) - throws Exception { - ConfigurableApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginSpringApplication() - .getApplicationContext(); + private Set registry(GenericApplicationContext pluginApplicationContext, Class aClass) + throws ProcessorException { Object object = pluginApplicationContext.getBean(aClass); - Method[] methods = aClass.getMethods(); + Method[] methods = aClass.getDeclaredMethods(); Set requestMappingInfos = new HashSet<>(); for (Method method : methods) { if (isHaveRequestMapping(method)) { - RequestMappingInfo requestMappingInfo = (RequestMappingInfo) - getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass); - requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method); - requestMappingInfos.add(requestMappingInfo); + try { + RequestMappingInfo requestMappingInfo = (RequestMappingInfo) + getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass); + requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method); + requestMappingInfos.add(requestMappingInfo); + } catch (Exception e){ + throw new ProcessorException(e.getMessage()); + } } } return requestMappingInfos; @@ -144,33 +143,33 @@ public class PluginControllerRegistryListener implements PluginSpringApplication private final static Logger LOG = LoggerFactory.getLogger(ChangeRestPathPostProcessor.class); private final static String COMMON_ERROR = "无法统一处理该 Controller 统一请求路径前缀"; - private final SpringPluginRegistryInfo registryInfo; + private final ProcessorContext processorContext; - private ChangeRestPathPostProcessor(SpringPluginRegistryInfo registryInfo) { - this.registryInfo = registryInfo; + private ChangeRestPathPostProcessor(ProcessorContext processorContext) { + this.processorContext = processorContext; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class aClass = bean.getClass(); - Controller controller = AnnotationUtils.findAnnotation(aClass, Controller.class); - if(controller == null){ - return bean; - } - RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class); - if(requestMapping != null){ + RequestMapping requestMapping = AnnotationUtils.findAnnotation(aClass, RequestMapping.class); + boolean isController = AnnotationUtils.existOr(aClass, new Class[]{ + Controller.class, RestController.class + }); + if(requestMapping != null && isController){ changePathForClass(beanName, aClass, requestMapping); } return bean; } private void changePathForClass(String beanName, Class aClass, RequestMapping requestMapping){ - String pluginId = registryInfo.getPluginWrapper().getPluginId(); - String pathPrefix = CommonUtils.getPluginRestPrefix(registryInfo.getConfiguration(), pluginId); + String pluginId = processorContext.getPluginDescriptor().getPluginId(); + IntegrationConfiguration configuration = processorContext.getConfiguration(); + String pathPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginId); - if(StringUtils.isNullOrEmpty(pathPrefix)){ + if(ObjectUtils.isEmpty(pathPrefix)){ LOG.error("插件 [{}] Controller类 [{}] 未发现 path 配置, {}", pluginId, aClass.getSimpleName(), COMMON_ERROR); return; @@ -201,10 +200,10 @@ public class PluginControllerRegistryListener implements PluginSpringApplication memberValues.put("path", newPath); memberValues.put("value", newPath); - List controllerWrappers = this.registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); + List controllerWrappers = processorContext.getRegistryInfo(PROCESS_CONTROLLERS); if(controllerWrappers == null){ controllerWrappers = new ArrayList<>(); - this.registryInfo.addRegistryInfo(PROCESS_CONTROLLERS, controllerWrappers); + processorContext.addRegistryInfo(PROCESS_CONTROLLERS, controllerWrappers); } ControllerWrapper controllerWrapper = new ControllerWrapper(); controllerWrapper.setPathPrefix(newPath); @@ -216,5 +215,4 @@ public class PluginControllerRegistryListener implements PluginSpringApplication } } - } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java new file mode 100644 index 0000000..a190c38 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -0,0 +1,74 @@ +package com.gitee.starblues.bootstrap.processor; + + +import com.gitee.starblues.bootstrap.SpringPluginBootstrap; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.launcher.plugin.PluginInteractive; +import com.gitee.starblues.core.launcher.plugin.RegistryInfo; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.io.ResourceLoader; + +/** + * @author starBlues + * @version 1.0 + */ +public interface ProcessorContext extends RegistryInfo { + + /** + * 得到插件信息 PluginDescriptor + * @return PluginDescriptor + */ + PluginDescriptor getPluginDescriptor(); + + /** + * 得到启动的class类 + * @return Class + */ + Class getRunnerClass(); + + /** + * 得到 PluginInteractive + * @return PluginInteractive + */ + PluginInteractive getPluginInteractive(); + + /** + * 得到主程序的 ApplicationContext + * @return MainApplicationContext + */ + MainApplicationContext getMainApplicationContext(); + + /** + * 得到当前框架的集成配置 + * @return IntegrationConfiguration + */ + IntegrationConfiguration getConfiguration(); + + + /** + * 得到当前插件的 ApplicationContext + * @return GenericApplicationContext + */ + GenericApplicationContext getApplicationContext(); + + /** + * 得到当前插件的 ClassLoader + * @return ClassLoader + */ + ClassLoader getClassLoader(); + + /** + * 得到插件的资源loader + * @return ResourceLoader + */ + ResourceLoader getResourceLoader(); + + /** + * set 当前插件的 ApplicationContext + * @param applicationContext GenericApplicationContext + */ + void setApplicationContext(GenericApplicationContext applicationContext); + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java new file mode 100644 index 0000000..7ccb83f --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java @@ -0,0 +1,28 @@ +package com.gitee.starblues.bootstrap.processor; + +/** + * @author starBlues + * @version 1.0 + */ +public class ProcessorException extends RuntimeException{ + + public ProcessorException() { + super(); + } + + public ProcessorException(String message) { + super(message); + } + + public ProcessorException(String message, Throwable cause) { + super(message, cause); + } + + public ProcessorException(Throwable cause) { + super(cause); + } + + protected ProcessorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java new file mode 100644 index 0000000..06675ae --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java @@ -0,0 +1,56 @@ +package com.gitee.starblues.bootstrap.processor; + +import com.gitee.starblues.utils.Order; +import com.gitee.starblues.utils.OrderPriority; + +/** + * @author starBlues + * @version 1.0 + */ +public interface SpringPluginProcessor extends Order { + + default void initialize(ProcessorContext context) throws ProcessorException{ + + } + + default void refreshBefore(ProcessorContext context) throws ProcessorException{ + + } + + default void refreshAfter(ProcessorContext context) throws ProcessorException{ + + } + + default void failure(ProcessorContext context) throws ProcessorException{ + + } + + default void close(ProcessorContext context) throws ProcessorException{ + + } + + @Override + default OrderPriority order(){ + return OrderPriority.getLowPriority(); + } + + RunMode runMode(); + + enum RunMode{ + /** + * 全部运行 + */ + ALL, + + /** + * 插件环境运行 + */ + PLUGIN, + + /** + * 插件独立运行 + */ + ONESELF + } + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java new file mode 100644 index 0000000..c8f97dc --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java @@ -0,0 +1,136 @@ +package com.gitee.starblues.bootstrap.processor; + +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.OrderPriority; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author starBlues + * @version 1.0 + */ +public class SpringPluginProcessorFactory implements SpringPluginProcessor { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final RunMode runMode; + + private List processors; + + public SpringPluginProcessorFactory(RunMode runMode) { + this(runMode, null); + } + + public SpringPluginProcessorFactory(RunMode runMode, List processors) { + this.runMode = runMode; + if(!ObjectUtils.isEmpty(processors)){ + this.processors = processors; + } else { + this.processors = new ArrayList<>(); + } + } + + public void addSpringPluginProcessor(SpringPluginProcessor springPluginProcessor){ + if(springPluginProcessor != null){ + this.processors.add(springPluginProcessor); + } + } + + private List getDefaultProcessors(){ + List processors = new ArrayList<>(); + processors.add(new FrameDefineBeanProcessor()); + processors.add(new PluginControllerRegistryProcessor()); + processors.add(new InvokeOtherPluginProcessor()); + return processors; + } + + @Override + public void initialize(ProcessorContext processorContext) throws ProcessorException { + List processors = getDefaultProcessors(); + processors.addAll(this.processors); + this.processors = processors.stream() + .filter(p->{ + RunMode runMode = p.runMode(); + return runMode == RunMode.ALL || runMode == this.runMode; + }) + .sorted(CommonUtils.orderPriority(SpringPluginProcessor::order)) + .collect(Collectors.toList()); + for (SpringPluginProcessor processor : this.processors) { + try { + processor.initialize(processorContext); + } catch (Exception e){ + processException(processor, "initialize", e, true); + } + } + } + + @Override + public void refreshBefore(ProcessorContext context) throws ProcessorException { + for (SpringPluginProcessor processor : processors) { + try { + processor.refreshBefore(context); + } catch (Exception e){ + processException(processor, "refreshBefore", e, true); + } + } + } + + @Override + public void refreshAfter(ProcessorContext context) throws ProcessorException { + for (SpringPluginProcessor processor : processors) { + try { + processor.refreshAfter(context); + } catch (Exception e){ + processException(processor, "refreshAfter", e, true); + } + } + } + + @Override + public void failure(ProcessorContext context) throws ProcessorException { + for (SpringPluginProcessor processor : processors) { + try { + processor.failure(context); + } catch (Exception e){ + processException(processor, "failure", e, false); + } + } + } + + @Override + public void close(ProcessorContext context) throws ProcessorException { + for (SpringPluginProcessor processor : processors) { + try { + processor.close(context); + } catch (Exception e){ + processException(processor, "close", e, false); + } + } + } + + @Override + public OrderPriority order() { + return OrderPriority.getHighPriority(); + } + + @Override + public RunMode runMode() { + return RunMode.ALL; + } + + private void processException(SpringPluginProcessor processor, String executeType, + Exception e, boolean isThrow){ + String error = "Processor[" + processor.getClass().getName() + "] execute[" + executeType + "] failure : " + + e.getMessage(); + if(isThrow){ + throw new ProcessorException(error, e); + } else { + logger.error(error, e); + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java similarity index 74% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java index e13e988..2e586c2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java @@ -1,7 +1,9 @@ -package com.gitee.starblues.spring.processor.invoke; +package com.gitee.starblues.bootstrap.processor.invoke; import com.gitee.starblues.annotation.Caller; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; import org.springframework.beans.factory.FactoryBean; import java.lang.reflect.Proxy; @@ -12,16 +14,16 @@ import java.lang.reflect.Proxy; */ public class InvokeBeanFactory implements FactoryBean { - private SpringPluginRegistryInfo registryInfo; private Class callerInterface; private Caller callerAnnotation; + private InvokeSupperCache invokeSupperCache; @Override @SuppressWarnings("unchecked") public T getObject() throws Exception { ClassLoader classLoader = callerInterface.getClassLoader(); Class[] interfaces = new Class[]{callerInterface}; - InvokeProxyHandler proxy = new InvokeProxyHandler(callerAnnotation); + InvokeProxyHandler proxy = new InvokeProxyHandler(callerAnnotation, invokeSupperCache); return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy); } @@ -35,10 +37,6 @@ public class InvokeBeanFactory implements FactoryBean { return true; } - public void setRegistryInfo(SpringPluginRegistryInfo registryInfo) { - this.registryInfo = registryInfo; - } - public void setCallerInterface(Class callerInterface) { this.callerInterface = callerInterface; } @@ -47,4 +45,7 @@ public class InvokeBeanFactory implements FactoryBean { this.callerAnnotation = callerAnnotation; } + public void setInvokeSupperCache(InvokeSupperCache invokeSupperCache) { + this.invokeSupperCache = invokeSupperCache; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java similarity index 90% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java index 4e3e365..2415716 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeProxyHandler.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java @@ -1,10 +1,10 @@ -package com.gitee.starblues.spring.processor.invoke; +package com.gitee.starblues.bootstrap.processor.invoke; import com.fasterxml.jackson.databind.ObjectMapper; import com.gitee.starblues.annotation.Caller; import com.gitee.starblues.annotation.Supplier; -import org.pf4j.util.StringUtils; -import org.springframework.util.ClassUtils; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.utils.ObjectUtils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -19,17 +19,19 @@ public class InvokeProxyHandler implements InvocationHandler { private final Caller callerAnnotation; private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private final InvokeSupperCache invokeSupperCache; - public InvokeProxyHandler(Caller callerAnnotation) { + public InvokeProxyHandler(Caller callerAnnotation, InvokeSupperCache invokeSupperCache) { this.callerAnnotation = callerAnnotation; + this.invokeSupperCache = invokeSupperCache; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String pluginId = callerAnnotation.pluginId(); - Object supplierObject = InvokeSupperCache.getSupperBean(pluginId, callerAnnotation.value()); + Object supplierObject = invokeSupperCache.getSupperBean(pluginId, callerAnnotation.value()); if (supplierObject == null) { - if (StringUtils.isNullOrEmpty(pluginId)) { + if (ObjectUtils.isEmpty(pluginId)) { throw new Exception("Not found '" + callerAnnotation.value() + "' supplier object"); } else { throw new Exception("Not found '" + callerAnnotation.value() + "' supplier object in plugin '" + @@ -134,7 +136,7 @@ public class InvokeProxyHandler implements InvocationHandler { return null; } Class returnType = method.getReturnType(); - if(ClassUtils.isAssignable(invokeReturn.getClass(),returnType)){ + if(invokeReturn.getClass().isAssignableFrom(returnType)){ return invokeReturn; } else { String json = OBJECT_MAPPER.writeValueAsString(invokeReturn); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java new file mode 100644 index 0000000..86347bb --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java @@ -0,0 +1,24 @@ +package com.gitee.starblues.bootstrap.processor.scanner; + +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; + + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { + + public PluginClassPathBeanDefinitionScanner(ProcessorContext processorContext) { + this(processorContext, true); + } + + public PluginClassPathBeanDefinitionScanner(ProcessorContext processorContext, boolean useDefaultFilters) { + super(processorContext.getApplicationContext(), useDefaultFilters, + processorContext.getApplicationContext().getEnvironment(), + processorContext.getResourceLoader()); + } + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java new file mode 100644 index 0000000..a09624b --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java @@ -0,0 +1,47 @@ +package com.gitee.starblues.bootstrap.utils; + + +import org.springframework.core.annotation.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +/** + * @author starBlues + * @version 1.0 + */ +public class AnnotationUtils { + + + private AnnotationUtils(){} + + public static A findAnnotation(Method method, Class annotationType) { + return org.springframework.core.annotation.AnnotationUtils.findAnnotation(method, annotationType); + } + + + public static A findAnnotation(Class clazz, Class annotationType) { + return org.springframework.core.annotation.AnnotationUtils.findAnnotation(clazz, annotationType); + } + + public static boolean existOr(Class clazz, Class[] annotationTypes) { + for (Class annotationType : annotationTypes) { + A annotation = findAnnotation(clazz, annotationType); + if(annotation != null){ + return true; + } + } + return false; + } + + public static boolean existAnd(Class clazz, Class[] annotationTypes) { + for (Class annotationType : annotationTypes) { + A annotation = findAnnotation(clazz, annotationType); + if(annotation == null){ + return false; + } + } + return true; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index 20ac03b..ebe0375 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -9,7 +9,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; @@ -44,7 +43,6 @@ public class PluginClassLoader extends AbstractPluginClassLoader implements Reso MainResourcePatternDefiner patternDefiner = Assert.isNotNull(mainResourcePatternDefiner, "参数 mainResourcePatternDefiner 不能为空"); setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); - System.out.println("PluginClassLoader=" + this); } public void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java index f2b9e18..955e291 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java @@ -1,8 +1,10 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; /** * @author starBlues @@ -12,10 +14,17 @@ public class DefaultPluginInteractive implements PluginInteractive{ private final PluginDescriptor pluginDescriptor; private final MainApplicationContext mainApplicationContext; + private final IntegrationConfiguration configuration; + private final InvokeSupperCache invokeSupperCache; - public DefaultPluginInteractive(PluginDescriptor pluginDescriptor, MainApplicationContext mainApplicationContext) { + public DefaultPluginInteractive(PluginDescriptor pluginDescriptor, + MainApplicationContext mainApplicationContext, + IntegrationConfiguration configuration, + InvokeSupperCache invokeSupperCache) { this.pluginDescriptor = pluginDescriptor; this.mainApplicationContext = mainApplicationContext; + this.configuration = configuration; + this.invokeSupperCache = invokeSupperCache; } @@ -28,4 +37,14 @@ public class DefaultPluginInteractive implements PluginInteractive{ public MainApplicationContext getMainApplicationContext() { return mainApplicationContext; } + + @Override + public IntegrationConfiguration getConfiguration() { + return configuration; + } + + @Override + public InvokeSupperCache getInvokeSupperCache() { + return invokeSupperCache; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java index fec145b..9928fbe 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java @@ -2,8 +2,11 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.ApplicationContextProxy; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.MainApplicationContextReflection; +import com.gitee.starblues.spring.processor.invoke.DefaultInvokeSupperCache; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; import org.springframework.context.support.GenericApplicationContext; import java.util.Map; @@ -18,10 +21,14 @@ public class DefaultPluginLauncherManager implements PluginLauncherManager{ private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); private final MainApplicationContext mainApplicationContext; + private final IntegrationConfiguration configuration; + private final InvokeSupperCache invokeSupperCache; public DefaultPluginLauncherManager(GenericApplicationContext mainGenericApplicationContext, IntegrationConfiguration configuration) { - this.mainApplicationContext = new MainApplicationContextReflection(mainGenericApplicationContext, configuration); + this.configuration = configuration; + this.mainApplicationContext = new MainApplicationContextReflection(mainGenericApplicationContext); + this.invokeSupperCache = new DefaultInvokeSupperCache(); } @Override @@ -30,16 +37,16 @@ public class DefaultPluginLauncherManager implements PluginLauncherManager{ throw new Exception("已经存在插件 : " + pluginDescriptor.getPluginId()); } PluginInteractive pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, - mainApplicationContext); + mainApplicationContext, configuration, invokeSupperCache); PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive); Object pluginApplicationContext = pluginLauncher.run(); - PluginRegistryInfo pluginRegistryInfo = new DefaultPluginRegistryInfo(pluginApplicationContext, - pluginLauncher); - pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), pluginRegistryInfo); +// PluginRegistryInfo pluginRegistryInfo = new DefaultPluginRegistryInfo(pluginApplicationContext, +// pluginLauncher); +// pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), pluginRegistryInfo); } @Override public synchronized void stop(String pluginId) throws Exception{ - + invokeSupperCache.remove(pluginId); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java index c70d8ec..c0ca10a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java @@ -2,6 +2,7 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.GenericApplicationContextReflection; +import org.springframework.context.support.GenericApplicationContext; /** * @author starBlues @@ -12,7 +13,7 @@ public class DefaultPluginRegistryInfo extends CacheRegistryInfo implements Plug private final ApplicationContext applicationContext; private final PluginLauncher pluginLauncher; - public DefaultPluginRegistryInfo(Object pluginApplicationContext, + public DefaultPluginRegistryInfo(GenericApplicationContext pluginApplicationContext, PluginLauncher pluginLauncher) { this.applicationContext = new GenericApplicationContextReflection(pluginApplicationContext); this.pluginLauncher = pluginLauncher; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java index f34622c..d62d779 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java @@ -1,7 +1,9 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; /** * @author starBlues @@ -13,4 +15,8 @@ public interface PluginInteractive { MainApplicationContext getMainApplicationContext(); + IntegrationConfiguration getConfiguration(); + + InvokeSupperCache getInvokeSupperCache(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 9cd0904..8e94d55 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -36,6 +36,7 @@ public class PluginLauncher extends AbstractLauncher implements Resource public Set getIncludeResourcePatterns() { Set includeResourcePatterns = super.getIncludeResourcePatterns(); includeResourcePatterns.add("com/gitee/starblues/**"); + includeResourcePatterns.add("org/springframework/web/**"); return includeResourcePatterns; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java index 118f6f6..a916c67 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java @@ -30,7 +30,13 @@ public class PluginMethodRunner extends MethodRunner { Object instance = getInstance(runClass); setPluginInteractive(instance); runMethod.setAccessible(true); - return runMethod.invoke(instance, runClass, this.args); + try { + return runMethod.invoke(instance, runClass, this.args); + } catch (Exception e){ + String error = "Invoke failure: " + + ReflectionUtils.methodToString(runClass, runMethodName, runMethod.getParameterTypes()); + throw new Exception(error); + } } private void setPluginInteractive(Object launchObject) throws Exception { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java index 5496e60..158c055 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java @@ -8,7 +8,7 @@ import com.gitee.starblues.spring.ApplicationContext; */ public interface PluginRegistryInfo { - ApplicationContext getApplicationContext(); + Object getApplicationContext(); PluginLauncher getPluginLauncher(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java index 7a2705f..aedf7b7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java @@ -2,9 +2,12 @@ package com.gitee.starblues.integration.application; import com.gitee.starblues.integration.IntegrationExtendPoint; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import org.springframework.beans.factory.InitializingBean; +import com.gitee.starblues.integration.operator.PluginOperator; +import com.gitee.starblues.integration.user.PluginUser; +import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Import; /** @@ -15,7 +18,7 @@ import org.springframework.context.annotation.Import; */ @Import(IntegrationExtendPoint.class) public class AutoPluginApplication extends DefaultPluginApplication - implements PluginApplication, InitializingBean, ApplicationContextAware { + implements PluginApplication, ApplicationContextAware, ApplicationListener { private ApplicationContext applicationContext; private PluginInitializerListener pluginInitializerListener; @@ -45,13 +48,19 @@ public class AutoPluginApplication extends DefaultPluginApplication /** * Spring boot bean属性被Set完后调用。会自动初始化插件 - * @throws Exception 初始化异常 */ @Override - public void afterPropertiesSet() throws Exception { - if(applicationContext == null){ - throw new Exception("Auto initialize failed. ApplicationContext Not injected."); - } + public void onApplicationEvent(ApplicationStartedEvent event) { super.initialize(applicationContext, pluginInitializerListener); } + + @Override + public PluginOperator getPluginOperator() { + return createPluginOperator(applicationContext); + } + + @Override + public PluginUser getPluginUser() { + return createPluginUser(applicationContext); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index 1362976..7ef3dc8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -1,18 +1,10 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.core.DefaultRealizeProvider; -import com.gitee.starblues.core.RealizeProvider; -import com.gitee.starblues.core.classloader.DefaultMainResourcePatternDefiner; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; -import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.operator.DefaultPluginOperator; import com.gitee.starblues.integration.operator.PluginOperator; -import com.gitee.starblues.integration.user.DefaultPluginUser; +import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.user.PluginUser; -import com.gitee.starblues.spring.DefaultSpringPlugin; -import com.gitee.starblues.spring.SpringPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -49,8 +41,8 @@ public class DefaultPluginApplication extends AbstractPluginApplication { } // 检查Configuration IntegrationConfiguration configuration = getConfiguration(applicationContext); - pluginUser = createPluginUser(applicationContext); - pluginOperator = createPluginOperator(applicationContext); + createPluginUser(applicationContext); + createPluginOperator(applicationContext); try { if(!(pluginOperator instanceof PluginOperatorWrapper)){ pluginOperator = new PluginOperatorWrapper(pluginOperator, configuration); @@ -59,26 +51,30 @@ public class DefaultPluginApplication extends AbstractPluginApplication { pluginOperator.initPlugins(listener); beInitialized.set(true); } catch (Exception e) { - e.printStackTrace(); + LOG.error("初始化插件异常." + e.getMessage()); } } /** * 创建插件使用者。子类可扩展 * @param applicationContext Spring ApplicationContext - * @return PluginUser */ - protected PluginUser createPluginUser(ApplicationContext applicationContext){ - return applicationContext.getBean(PluginUser.class); + protected synchronized PluginUser createPluginUser(ApplicationContext applicationContext){ + if(pluginUser == null){ + pluginUser = applicationContext.getBean(PluginUser.class); + } + return pluginUser; } /** * 创建插件操作者。子类可扩展 * @param applicationContext Spring ApplicationContext - * @return PluginOperator */ - protected PluginOperator createPluginOperator(ApplicationContext applicationContext){ - return applicationContext.getBean(PluginOperator.class); + protected synchronized PluginOperator createPluginOperator(ApplicationContext applicationContext){ + if(pluginOperator == null){ + pluginOperator = applicationContext.getBean(PluginOperator.class); + } + return pluginOperator; } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java index 4675aac..66548ff 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java @@ -1,12 +1,14 @@ package com.gitee.starblues.spring; +import org.springframework.beans.BeansException; import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; + +import java.util.Set; /** * @author starBlues * @version 1.0 */ -public interface ApplicationContext extends AutowireCapableBeanFactory, ListableBeanFactory { +public interface ApplicationContext extends ListableBeanFactory { } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java new file mode 100644 index 0000000..15f8635 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java @@ -0,0 +1,22 @@ +package com.gitee.starblues.spring; + +import org.springframework.context.support.GenericApplicationContext; + + +/** + * @author starBlues + * @version 1.0 + */ +public class ApplicationContextProxy { + + + + +// public static MainApplicationContext getMainApplicationContext(GenericApplicationContext applicationContext){ +// ProxyInvokeFactory proxyInvokeFactory = new DiffProxyInvokeFactory(applicationContext); +// return proxyInvokeFactory.getObject(MainApplicationContext.class); +// } + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java new file mode 100644 index 0000000..c0471af --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java @@ -0,0 +1,56 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.utils.ReflectionUtils; +import org.springframework.cglib.proxy.Enhancer; +import org.springframework.cglib.proxy.MethodInterceptor; +import org.springframework.cglib.proxy.MethodProxy; + +import java.lang.reflect.Method; + +/** + * @author starBlues + * @version 1.0 + */ +public class CglibProxyInvokeFactory implements ProxyInvokeFactory { + + private final Object source; + + public CglibProxyInvokeFactory(Object source) { + this.source = source; + } + + @Override + public T getObject(Class interfacesClass) { + Enhancer enhancer = new Enhancer(); + enhancer.setSuperclass(interfacesClass); + enhancer.setCallback(new MethodInvoke(source)); + enhancer.setClassLoader(interfacesClass.getClassLoader()); + try { + return (T)enhancer.create(); + } catch (Exception e){ + System.out.println(interfacesClass); + e.printStackTrace(); + return null; + } + } + + private static class MethodInvoke implements MethodInterceptor { + + private final Object source; + + private MethodInvoke(Object source) { + this.source = source; + } + + @Override + public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { + Method delegateMethod = ReflectionUtils.findMethod(source.getClass(), method.getName(), + method.getParameterTypes()); + if(delegateMethod == null){ + throw ReflectionUtils.getNoSuchMethodException(source.getClass(), method.getName(), + method.getParameterTypes()); + } + return delegateMethod.invoke(source, objects); + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java index 667325f..d54f24f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java @@ -5,7 +5,6 @@ import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.environment.PluginEnvironmentProcessor; import com.gitee.starblues.spring.environment.PluginLocalConfigFileProcessor; -import com.gitee.starblues.spring.listener.*; import com.gitee.starblues.spring.processor.SpringPluginProcessor; import com.gitee.starblues.spring.processor.SpringPluginProcessorFactory; import com.gitee.starblues.utils.Assert; @@ -106,21 +105,6 @@ public class DefaultPluginSpringApplication implements PluginSpringApplication{ } } - private PluginSpringApplicationRunListeners getRunListeners() { - PluginSpringApplicationRunListeners runListeners = new PluginSpringApplicationRunListeners(ListenerRunMode.PLUGIN); - addDefaultListeners(runListeners); - return runListeners; - } - - protected void addDefaultListeners(PluginSpringApplicationRunListeners runListeners){ - runListeners.addListener(new ClassScannerListener()); - runListeners.addListener(new BeanRegistryListener()); - runListeners.addListener(new NecessaryBeanRegistryListener()); - runListeners.addListener(new InvokeOtherPluginRegistryListener()); - runListeners.addListener(new PluginControllerRegistryListener(mainApplicationContext)); - } - - protected void processEnvironment() { List orderPluginEnvironmentProcessor = CommonUtils.order(environmentProcessors, Ordered::getOrder); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java new file mode 100644 index 0000000..a99f6f4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java @@ -0,0 +1,34 @@ +//package com.gitee.starblues.spring; +// +//import java.lang.reflect.Proxy; +// +///** +// * @author starBlues +// * @version 1.0 +// */ +//public class DiffProxyInvokeFactory implements ProxyInvokeFactory{ +// +// private final Object invokeSource; +// private final ClassLoader invokeClassLoader; +// +// public DiffProxyInvokeFactory(Object invokeSource) { +// this(invokeSource, null); +// } +// +// public DiffProxyInvokeFactory(Object invokeSource, ClassLoader invokeClassLoader) { +// this.invokeSource = invokeSource; +// if(invokeClassLoader == null){ +// this.invokeClassLoader = invokeSource.getClass().getClassLoader(); +// } else { +// this.invokeClassLoader = invokeClassLoader; +// } +// } +// +// @SuppressWarnings("unchecked") +// @Override +// public T getObject(Class interfacesClass) { +// Class[] interfaces = new Class[]{ interfacesClass }; +// ProxyInvoke proxy = new ProxyInvoke(invokeSource); +// return (T) Proxy.newProxyInstance(invokeClassLoader, interfaces, proxy); +// } +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java index 690f8ac..66439cd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java @@ -1,19 +1,12 @@ package com.gitee.starblues.spring; -import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.utils.ReflectionUtils; import org.springframework.beans.BeansException; -import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.DependencyDescriptor; -import org.springframework.beans.factory.config.NamedBeanHolder; import org.springframework.core.ResolvableType; import java.lang.annotation.Annotation; -import java.lang.reflect.Method; import java.util.Map; -import java.util.Set; -import java.util.StringJoiner; /** * @author starBlues @@ -21,12 +14,10 @@ import java.util.StringJoiner; */ public class GenericApplicationContextReflection implements ApplicationContext { - private final Object genericApplicationContext; - private final Class mainApplicationContextClass; + protected final Object genericApplicationContext; public GenericApplicationContextReflection(Object genericApplicationContext) { this.genericApplicationContext = genericApplicationContext; - this.mainApplicationContextClass = genericApplicationContext.getClass(); } @Override @@ -46,7 +37,8 @@ public class GenericApplicationContextReflection implements ApplicationContext { @Override public String[] getBeanNamesForType(ResolvableType type) { - return invokeReturn("getBeanNamesForType", type); + prohibitCall("getBeanNamesForType"); + return null; } @Override @@ -84,84 +76,6 @@ public class GenericApplicationContextReflection implements ApplicationContext { return invokeReturn("findAnnotationOnBean", beanName, annotationType); } - @Override - public T createBean(Class beanClass) throws BeansException { - prohibitCall("createBean"); - return null; - } - - @Override - public void autowireBean(Object existingBean) throws BeansException { - prohibitCall("autowireBean"); - } - - @Override - public Object configureBean(Object existingBean, String beanName) throws BeansException { - prohibitCall("configureBean"); - return null; - } - - @Override - public Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { - prohibitCall("createBean"); - return null; - } - - @Override - public Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { - prohibitCall("autowire"); - return null; - } - - @Override - public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException { - prohibitCall("autowireBeanProperties"); - } - - @Override - public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException { - prohibitCall("applyBeanPropertyValues"); - } - - @Override - public Object initializeBean(Object existingBean, String beanName) throws BeansException { - prohibitCall("initializeBean"); - return null; - } - - @Override - public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { - prohibitCall("applyBeanPostProcessorsBeforeInitialization"); - return null; - } - - @Override - public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { - prohibitCall("applyBeanPostProcessorsAfterInitialization"); - return null; - } - - @Override - public void destroyBean(Object existingBean) { - prohibitCall("destroyBean"); - } - - @Override - public NamedBeanHolder resolveNamedBean(Class requiredType) throws BeansException { - prohibitCall("resolveNamedBean"); - return null; - } - - @Override - public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName) throws BeansException { - return null; - } - - @Override - public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName, Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { - return null; - } - @Override public Object getBean(String name) throws BeansException { return invokeReturn("getBean", name); @@ -222,49 +136,16 @@ public class GenericApplicationContextReflection implements ApplicationContext { return invokeReturn("getAliases", name); } - - private T invokeReturn(String methodName, Object... params){ + protected T invokeReturn(String methodName, Object... params){ return invoke(true, methodName, params); } - private void invokeNoReturn(String methodName, Object... params){ + protected void invokeNoReturn(String methodName, Object... params){ invoke(false, methodName, params); } - @SuppressWarnings("unchecked") - private T invoke(boolean haveReturn, String methodName, Object... params){ - Class[] paramTypes = new Class[params.length]; - for (int i = 0; i < params.length; i++) { - paramTypes[i] = params[i].getClass(); - } - Method method = ReflectionUtils.findMethod(mainApplicationContextClass, methodName, paramTypes); - if(method == null){ - throw new RuntimeException("Not found method : " + methodToString(methodName, paramTypes)); - } - try { - if(haveReturn){ - return (T) method.invoke(genericApplicationContext, params); - } else { - method.invoke(genericApplicationContext, params); - return null; - } - } catch (Exception e) { - throw new RuntimeException("Cannot call method : " + methodToString(methodName, paramTypes)); - } - } - - private String methodToString(String name, Class[] argTypes) { - StringJoiner sj = new StringJoiner(", ", getName() + "." + name + "(", ")"); - if (argTypes != null) { - for (Class c : argTypes) { - sj.add((c == null) ? "null" : c.getName()); - } - } - return sj.toString(); - } - - private String getName() { - return mainApplicationContextClass.getName(); + protected T invoke(boolean haveReturn, String methodName, Object... params){ + return ReflectionUtils.invoke(genericApplicationContext, methodName, params); } private void prohibitCall(String name){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java index 8c0ee5d..51f8352 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java @@ -1,6 +1,6 @@ package com.gitee.starblues.spring; -import com.gitee.starblues.integration.IntegrationConfiguration; +import java.util.Set; /** * @author starBlues @@ -8,6 +8,11 @@ import com.gitee.starblues.integration.IntegrationConfiguration; */ public interface MainApplicationContext extends ApplicationContext { - IntegrationConfiguration getConfiguration(); + + Object resolveDependency(Object descriptor, String requestingBeanName); + + + Object resolveDependency(Object descriptor, String requestingBeanName, + Set autowiredBeanNames, Object typeConverter); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java index 7a2ba15..3e761fb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java @@ -1,6 +1,9 @@ package com.gitee.starblues.spring; -import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.utils.ReflectionUtils; + +import java.lang.reflect.Field; +import java.util.Set; /** * @author starBlues @@ -8,17 +11,41 @@ import com.gitee.starblues.integration.IntegrationConfiguration; */ public class MainApplicationContextReflection extends GenericApplicationContextReflection implements MainApplicationContext { - private final IntegrationConfiguration configuration; + private ClassLoader mainClassLoader; - public MainApplicationContextReflection(Object mainGenericApplicationContext, - IntegrationConfiguration configuration) { + public MainApplicationContextReflection(Object mainGenericApplicationContext) { super(mainGenericApplicationContext); - this.configuration = configuration; + this.mainClassLoader = mainGenericApplicationContext.getClass().getClassLoader(); + } + + public void setMainClassLoader(ClassLoader mainClassLoader) { + this.mainClassLoader = mainClassLoader; } @Override - public IntegrationConfiguration getConfiguration() { - return configuration; + public Object resolveDependency(Object descriptor, String requestingBeanName) { + + return null; } + @Override + public Object resolveDependency(Object descriptor, String requestingBeanName, + Set autowiredBeanNames, Object typeConverter) { + try { + Class descriptorClass = mainClassLoader.loadClass(descriptor.getClass().getName()); + Class typeConverterClass = mainClassLoader.loadClass(typeConverter.getClass().getName()); + + Object descriptorObject = descriptorClass.getConstructor(Field.class, boolean.class).newInstance( + ReflectionUtils.getField(descriptor, "field", Field.class), + ReflectionUtils.getField(descriptor, "required", boolean.class) + ); + + Object o = invokeReturn("getBeanFactory"); + return ReflectionUtils.invoke(o, "resolveDependency", descriptorObject, requestingBeanName, + autowiredBeanNames, typeConverterClass.getConstructor().newInstance()); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java new file mode 100644 index 0000000..f7f09a7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java @@ -0,0 +1,73 @@ +//package com.gitee.starblues.spring; +// +//import com.gitee.starblues.utils.ObjectUtils; +//import com.gitee.starblues.utils.ReflectionUtils; +// +//import java.lang.reflect.InvocationHandler; +//import java.lang.reflect.Method; +//import java.util.List; +//import java.util.Objects; +// +///** +// * @author starBlues +// * @version 1.0 +// */ +//public class ProxyInvoke implements InvocationHandler { +// +// private final Object source; +// +// public ProxyInvoke(Object source) { +// this.source = source; +// } +// +// @Override +// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { +// String name = method.getName(); +// Method invokeMethod = findMethod(name, args); +// Class[] parameterTypes = invokeMethod.getParameterTypes(); +// Object[] invokeArgs = new Object[args.length]; +// for (int i = 0; i < parameterTypes.length; i++) { +// Class parameterType = parameterTypes[i]; +// Object arg = args[i]; +// Class aClass = arg.getClass(); +// if(parameterType == aClass){ +// // 类型一致 +// invokeArgs[i] = arg; +// } else { +// // 类型不一致 +// ProxyInvokeFactory factory = new DiffProxyInvokeFactory( +// arg, parameterType.getClassLoader() +// ); +// invokeArgs[i] = factory.getObject(); +// } +// } +// return invokeMethod.invoke(source, invokeArgs); +// } +// +// private Method findMethod(String sourceMethodName, Object[] args) throws Exception{ +// List methods = ReflectionUtils.findMethods(source.getClass(), sourceMethodName); +// if(ObjectUtils.isEmpty(methods)){ +// throw new NoSuchMethodException("Not found method:" + sourceMethodName); +// } +// for (Method m : methods) { +// if (m.getParameterCount() != args.length) { +// continue; +// } +// Class[] parameterTypes = m.getParameterTypes(); +// int matchCount = 0; +// for (int j = 0; j < parameterTypes.length; j++) { +// Class parameterType = parameterTypes[j]; +// Class aClass = args[j].getClass(); +// if (Objects.equals(parameterType.getName(), aClass.getName())) { +// matchCount++; +// } +// } +// if(matchCount == parameterTypes.length){ +// return m; +// } +// } +// throw new NoSuchMethodException("Not found method:" + sourceMethodName); +// } +// +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java new file mode 100644 index 0000000..fef842d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java @@ -0,0 +1,11 @@ +package com.gitee.starblues.spring; + +/** + * @author starBlues + * @version 1.0 + */ +public interface ProxyInvokeFactory { + + T getObject(Class interfacesClass); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java new file mode 100644 index 0000000..8b4d070 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java @@ -0,0 +1,11 @@ +package com.gitee.starblues.spring; + +/** + * @author starBlues + * @version 1.0 + */ +public interface SpringPluginHook extends AutoCloseable{ + + Object getGenericApplicationContext(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java deleted file mode 100644 index 129f270..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/BeanRegistryListener.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.gitee.starblues.spring.listener; - -import com.gitee.starblues.annotation.Supplier; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.classgroup.ComposeClassGroup; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.OrderPriority; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; - -import java.util.List; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class BeanRegistryListener implements PluginSpringApplicationRunListener { - - @Override - public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); - SpringBeanRegister springBeanRegister = new SpringBeanRegister(applicationContext); - List> classes = registryInfo.getRegistryInfo(ComposeClassGroup.ID); - if(ObjectUtils.isEmpty(classes)){ - return; - } - for (Class aClass : classes) { - String beanName = springBeanRegister.register(aClass); - cacheInvokeSupplier(aClass, beanName, registryInfo); - } - } - - @Override - public void stop(SpringPluginRegistryInfo registryInfo) throws Exception { - InvokeSupperCache.remove(registryInfo.getPluginWrapper().getPluginId()); - } - - private void cacheInvokeSupplier(Class aClass, String beanName, SpringPluginRegistryInfo registryInfo){ - Supplier supplier = AnnotationUtils.findAnnotation(aClass, Supplier.class); - if(supplier == null){ - return; - } - String pluginId = registryInfo.getPluginWrapper().getPluginId(); - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); - InvokeSupperCache.add(pluginId, new InvokeSupperCache.Cache(supplier.value(), beanName, applicationContext)); - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority(); - } - - @Override - public ListenerRunMode runMode() { - return ListenerRunMode.PLUGIN; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java deleted file mode 100644 index e3fb331..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ClassScannerListener.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.gitee.starblues.spring.listener; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; -import com.gitee.starblues.spring.processor.classgroup.ComposeClassGroup; -import com.gitee.starblues.spring.processor.classgroup.PluginClassGroup; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.OrderPriority; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.type.classreading.CachingMetadataReaderFactory; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.util.ClassUtils; - -import java.util.*; - -/** - * @author starBlues - * @version 1.0 - */ -public class ClassScannerListener implements PluginSpringApplicationRunListener { - private final static Logger LOGGER = LoggerFactory.getLogger(ClassScannerListener.class); - - static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; - - private final List pluginClassGroup = new ArrayList<>(); - - public ClassScannerListener(){ - addPluginClassGroup(); - } - - protected void addPluginClassGroup(){ - pluginClassGroup.add(new ComposeClassGroup()); - pluginClassGroup.add(new CallerClassGroup()); - } - - - @Override - public void starting(SpringPluginRegistryInfo registryInfo) throws Exception{ - ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); - ResourceLoader resourceLoader = new DefaultResourceLoader(pluginClassLoader); - ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(resourceLoader); - Set packageSearchPaths = getPackageSearchPaths(registryInfo); - MetadataReaderFactory metadataReaderFactory = getMetadataReaderFactory(registryInfo); - for (String packageSearchPath : packageSearchPaths) { - Resource[] resources = patternResolver.getResources(packageSearchPath); - for (Resource resource : resources) { - MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); - String className = metadataReader.getClassMetadata().getClassName(); - Class aClass = pluginClassLoader.loadClass(className); - groupClass(aClass, registryInfo); - } - } - } - - private void groupClass(Class aClass, SpringPluginRegistryInfo registryInfo){ - boolean filterResult = false; - for (PluginClassGroup classGroup : pluginClassGroup) { - String groupId = classGroup.groupId(); - if(ObjectUtils.isEmpty(groupId)){ - continue; - } - boolean filter = classGroup.filter(aClass); - if(filter){ - addClass(groupId, aClass, registryInfo); - filterResult = true; - } - } - if(!filterResult){ - addClass(PluginClassGroup.OTHER_CLASS_GROUP_ID, aClass, registryInfo); - } - } - - - private void addClass(String groupId, Class aClass, SpringPluginRegistryInfo registryInfo){ - List> classes = registryInfo.getRegistryInfo(groupId, ArrayList::new); - classes.add(aClass); - } - - - protected Set getPackageSearchPaths(SpringPluginRegistryInfo registryInfo) { - Class pluginClass = registryInfo.getPluginWrapper().getPluginClass(); - String[] scanBasePackages = getScanBasePackages(pluginClass); - Set packageSearchPaths = new HashSet<>(); - ConfigurableEnvironment environment = registryInfo.getPluginSpringApplication() - .getApplicationContext().getEnvironment(); - for (String scanBasePackage : scanBasePackages) { - String scanPackageName = ClassUtils.convertClassNameToResourcePath( - environment.resolveRequiredPlaceholders(scanBasePackage)); - scanPackageName = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + - scanPackageName + '/' + DEFAULT_RESOURCE_PATTERN; - packageSearchPaths.add(scanPackageName); - } - return packageSearchPaths; - } - - - protected String[] getScanBasePackages(Class pluginClass){ - SpringBootApplication springBootApplication = pluginClass.getAnnotation(SpringBootApplication.class); - if(springBootApplication != null){ - String[] scanBasePackages = springBootApplication.scanBasePackages(); - if(scanBasePackages.length > 0){ - return scanBasePackages; - } - } - return new String[]{ pluginClass.getPackage().getName() }; - } - - protected MetadataReaderFactory getMetadataReaderFactory(SpringPluginRegistryInfo registryInfo){ - ClassLoader pluginClassLoader = registryInfo.getPluginWrapper().getPluginClassLoader(); - return new CachingMetadataReaderFactory(pluginClassLoader); - } - - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority(); - } - - @Override - public ListenerRunMode runMode() { - return ListenerRunMode.ALL; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java deleted file mode 100644 index 4296b57..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/InvokeOtherPluginRegistryListener.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.gitee.starblues.spring.listener; - -import com.gitee.starblues.annotation.Caller; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.classgroup.CallerClassGroup; -import com.gitee.starblues.spring.processor.invoke.InvokeBeanFactory; -import com.gitee.starblues.utils.ObjectUtils; -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; - -import java.util.List; - -/** - * @author starBlues - * @version 1.0 - */ -public class InvokeOtherPluginRegistryListener implements PluginSpringApplicationRunListener { - - - public InvokeOtherPluginRegistryListener() { - } - - @Override - public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { - List> classes = registryInfo.getRegistryInfo(CallerClassGroup.ID); - if(ObjectUtils.isEmpty(classes)){ - return; - } - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); - SpringBeanRegister springBeanRegister = new SpringBeanRegister(applicationContext); - for (Class aClass : classes) { - Caller caller = AnnotationUtils.findAnnotation(aClass, Caller.class); - if(caller == null){ - continue; - } - springBeanRegister.register(aClass, definition -> { - // 是调用方 - definition.getPropertyValues().add("callerAnnotation", caller); - definition.getPropertyValues().add("callerInterface", aClass); - definition.getPropertyValues().add("registryInfo", registryInfo); - definition.setBeanClass(InvokeBeanFactory.class); - definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE); - }); - } - } - - @Override - public ListenerRunMode runMode() { - return ListenerRunMode.ALL; - } - -} \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java deleted file mode 100644 index 9747a82..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/ListenerRunMode.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.starblues.spring.listener; - -/** - * @author starBlues - * @version 1.0 - */ -public enum ListenerRunMode { - - /** - * 全部运行 - */ - ALL, - - /** - * 插件环境运行 - */ - PLUGIN, - - /** - * 插件独立运行 - */ - ONESELF - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java deleted file mode 100644 index 8cbcf1d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/NecessaryBeanRegistryListener.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gitee.starblues.spring.listener; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.realize.PluginUtils; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.OrderPriority; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author starBlues - * @version 1.0 - */ -public class NecessaryBeanRegistryListener implements PluginSpringApplicationRunListener { - - @Override - public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception { - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); - PluginDescriptor pluginDescriptor = registryInfo.getPluginWrapper().getPluginDescriptor(); - applicationContext.getBeanFactory().registerSingleton("pluginDescriptor", - pluginDescriptor); - applicationContext.getBeanFactory().registerSingleton("pluginUtils", - new PluginUtils(applicationContext)); - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority().down(-10); - } - - @Override - public ListenerRunMode runMode() { - return ListenerRunMode.ALL; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java deleted file mode 100644 index a711e87..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListener.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.gitee.starblues.spring.listener; - - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.Order; -import com.gitee.starblues.utils.OrderPriority; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PluginSpringApplicationRunListener extends Order { - - default void starting(SpringPluginRegistryInfo registryInfo) throws Exception{ - } - - default void environmentPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ - } - - default void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ - } - - default void started(SpringPluginRegistryInfo registryInfo) throws Exception{ - } - - default void failed(SpringPluginRegistryInfo registryInfo, Throwable exception) throws Exception{ - } - - default void stop(SpringPluginRegistryInfo registryInfo) throws Exception{ - - } - - @Override - default OrderPriority order() { - return OrderPriority.getMiddlePriority(); - } - - - ListenerRunMode runMode(); - -} - diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java deleted file mode 100644 index aacf89c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/listener/PluginSpringApplicationRunListeners.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.gitee.starblues.spring.listener; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author starBlues - * @version 1.0 - */ -public class PluginSpringApplicationRunListeners implements PluginSpringApplicationRunListener{ - - private final static Logger LOGGER = LoggerFactory.getLogger(PluginSpringApplicationRunListeners.class); - - - private final List runListeners = new ArrayList<>(); - private final ListenerRunMode listenerRunMode; - - public PluginSpringApplicationRunListeners(ListenerRunMode listenerRunMode) { - this.listenerRunMode = listenerRunMode; - } - - public void addListener(PluginSpringApplicationRunListener listener){ - if(listener != null){ - runListeners.add(listener); - } - } - - @Override - public void starting(SpringPluginRegistryInfo registryInfo) throws Exception{ - publicListener(listener -> listener.starting(registryInfo)); - } - - @Override - public void environmentPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ - publicListener(listener -> listener.environmentPrepared(registryInfo)); - } - - @Override - public void refreshPrepared(SpringPluginRegistryInfo registryInfo) throws Exception{ - publicListener(listener -> listener.refreshPrepared(registryInfo)); - } - - @Override - public void started(SpringPluginRegistryInfo registryInfo) throws Exception{ - publicListener(listener -> listener.started(registryInfo)); - } - - @Override - public void failed(SpringPluginRegistryInfo registryInfo, Throwable exception) { - try { - publicListener(listener -> listener.failed(registryInfo, exception)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void stop(SpringPluginRegistryInfo registryInfo) throws Exception { - try { - publicListener(listener -> listener.stop(registryInfo)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public ListenerRunMode runMode() { - return ListenerRunMode.ALL; - } - - private void publicListener(Consumer consumer) throws Exception{ - for (PluginSpringApplicationRunListener listener : runListeners) { - ListenerRunMode listenerRunMode = listener.runMode(); - if(listenerRunMode == ListenerRunMode.ALL || listenerRunMode == this.listenerRunMode){ - try { - consumer.accept(listener); - } catch (Exception e){ - LOGGER.error("监听者 <{}> 执行失败. {}", listener.getClass().getName(), e.getMessage(), e); - throw e; - } - } - } - } - - @FunctionalInterface - private interface Consumer{ - void accept(T t) throws Exception; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java index 630be34..9774308 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java @@ -49,7 +49,6 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor{ List processors = new ArrayList<>(); processors.add(new BeanRegistryProcessor()); processors.add(new FrameDefineBeanRegistryProcessor()); - processors.add(new InvokeOtherPluginProcessor()); processors.add(new ExtractBeanProcessor()); processors.add(new PluginInterceptorsProcessor()); processors.add(new PluginControllerRegistryProcessor()); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java new file mode 100644 index 0000000..f74017a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java @@ -0,0 +1,62 @@ +package com.gitee.starblues.spring.processor.invoke; + +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.utils.ObjectUtils; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class DefaultInvokeSupperCache implements InvokeSupperCache{ + + private final Map> invokeSupplierCache = new ConcurrentHashMap<>(); + + @Override + public Object getSupperBean(String supperKey){ + return getSupperBean(null, supperKey); + } + + @Override + public Object getSupperBean(String pluginId, String supperKey){ + if(!ObjectUtils.isEmpty(pluginId)){ + Map cacheMap = invokeSupplierCache.get(pluginId); + if(cacheMap == null){ + return null; + } + return getSupperBean(cacheMap.get(supperKey)); + } + for (Map value : invokeSupplierCache.values()) { + Object supperBean = getSupperBean(value.get(supperKey)); + if(supperBean != null){ + return supperBean; + } + } + return null; + } + + @Override + public void add(String pluginId, SupperCache cache){ + Map supperCache = invokeSupplierCache.computeIfAbsent(pluginId, k -> new HashMap<>()); + supperCache.put(cache.getSupperKey(), cache); + } + + @Override + public void remove(String pluginId){ + invokeSupplierCache.remove(pluginId); + } + + private static Object getSupperBean(SupperCache cache){ + if(cache == null){ + return null; + } + ApplicationContext applicationContext = cache.getApplicationContext(); + if(applicationContext.containsBean(cache.getBeanName())){ + return applicationContext.getBean(cache.getBeanName()); + } + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java index 66b4c35..6a60ae9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java @@ -1,80 +1,17 @@ package com.gitee.starblues.spring.processor.invoke; -import com.gitee.starblues.utils.ObjectUtils; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** * @author starBlues * @version 1.0 */ -public class InvokeSupperCache { - - private static final Map> INVOKE_SUPPLIER_CACHE = new ConcurrentHashMap<>(); - - static Object getSupperBean(String pluginId, String supperKey){ - if(!ObjectUtils.isEmpty(pluginId)){ - Map cacheMap = INVOKE_SUPPLIER_CACHE.get(pluginId); - if(cacheMap == null){ - return null; - } - return getSupperBean(cacheMap.get(supperKey)); - } - for (Map value : INVOKE_SUPPLIER_CACHE.values()) { - Object supperBean = getSupperBean(value.get(supperKey)); - if(supperBean != null){ - return supperBean; - } - } - return null; - } - - private static Object getSupperBean(Cache cache){ - if(cache == null){ - return null; - } - GenericApplicationContext applicationContext = cache.getApplicationContext(); - if(applicationContext.containsBean(cache.getBeanName())){ - return applicationContext.getBean(cache.getBeanName()); - } - return null; - } - - public static void add(String pluginId, Cache cache){ - Map supperCache = INVOKE_SUPPLIER_CACHE.computeIfAbsent(pluginId, k -> new HashMap<>()); - supperCache.put(cache.getSupperKey(), cache); - } - - public static void remove(String pluginId){ - INVOKE_SUPPLIER_CACHE.remove(pluginId); - } - - public static class Cache{ - private final String supperKey; - private final String beanName; - private final GenericApplicationContext applicationContext; - - public Cache(String supperKey, String beanName, GenericApplicationContext applicationContext) { - this.supperKey = supperKey; - this.beanName = beanName; - this.applicationContext = applicationContext; - } - - public String getSupperKey() { - return supperKey; - } +public interface InvokeSupperCache { - public String getBeanName() { - return beanName; - } + Object getSupperBean(String pluginId, String supperKey); + Object getSupperBean(String supperKey); + void add(String pluginId, SupperCache cache); + void remove(String pluginId); - public GenericApplicationContext getApplicationContext() { - return applicationContext; - } - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java new file mode 100644 index 0000000..78dcb05 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java @@ -0,0 +1,33 @@ +package com.gitee.starblues.spring.processor.invoke; + +import com.gitee.starblues.spring.ApplicationContext; + +/** + * @author starBlues + * @version 1.0 + */ +public class SupperCache { + + private final String supperKey; + private final String beanName; + private final ApplicationContext applicationContext; + + public SupperCache(String supperKey, String beanName, ApplicationContext applicationContext) { + this.supperKey = supperKey; + this.beanName = beanName; + this.applicationContext = applicationContext; + } + + public String getSupperKey() { + return supperKey; + } + + public String getBeanName() { + return beanName; + } + + public ApplicationContext getApplicationContext() { + return applicationContext; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java index 7aba7af..b37ca66 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java @@ -1,8 +1,5 @@ package com.gitee.starblues.utils; - -import org.springframework.beans.factory.config.BeanPostProcessor; - import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 1563e19..9feeb34 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -5,10 +5,7 @@ package com.gitee.starblues.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; +import java.util.*; /** * 反射工具类 @@ -106,20 +103,53 @@ public abstract class ReflectionUtils { } public static Method findMethod(Class clazz, String name, Class... paramTypes) { + List methods = findMethods(clazz, name, paramTypes); + if(ObjectUtils.isEmpty(methods)){ + return null; + } else { + return methods.get(0); + } + } + + public static List findMethods(Class clazz, String name, Class... paramTypes){ Assert.isNotNull(clazz, "Class must not be null"); Assert.isNotEmpty(name, "Method name must not be null"); Class searchType = clazz; + List methodList = new ArrayList<>(); while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType, false)); for (Method method : methods) { if (name.equals(method.getName()) && (paramTypes == null || hasSameParams(method, paramTypes))) { - return method; + methodList.add(method); } } searchType = searchType.getSuperclass(); } - return null; + return methodList; + } + + @SuppressWarnings("unchecked") + public static T invoke(Object object, String methodName, Object... params) throws RuntimeException { + Class[] paramTypes = new Class[params.length]; + for (int i = 0; i < params.length; i++) { + paramTypes[i] = params[i].getClass(); + } + Class aClass = object.getClass(); + Method method = ReflectionUtils.findMethod(aClass, methodName, paramTypes); + if(method == null){ + throw new RuntimeException("Not found method : " + methodToString(aClass, methodName, paramTypes)); + } + try { + Object invoke = method.invoke(object, params); + if(invoke != null){ + return (T) invoke; + } else { + return null; + } + } catch (Exception e) { + throw new RuntimeException("Cannot call method : " + methodToString(aClass, methodName, paramTypes), e); + } } public static void setAttribute(Object bean, String setMethodName, Object setObject) throws Exception { @@ -187,4 +217,18 @@ public abstract class ReflectionUtils { return true; } + public static NoSuchMethodException getNoSuchMethodException(Class aClass, String name, Class[] argTypes) { + return new NoSuchMethodException("Not found method:" + methodToString(aClass, name, argTypes)); + } + + public static String methodToString(Class aClass, String name, Class[] argTypes) { + StringJoiner sj = new StringJoiner(", ", aClass.getName() + "." + name + "(", ")"); + if (argTypes != null) { + for (Class c : argTypes) { + sj.add((c == null) ? "null" : c.getName()); + } + } + return sj.toString(); + } + } -- Gitee From a56540d9745254720c3bcd90a6b293331c034847 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 30 Dec 2021 21:45:59 +0800 Subject: [PATCH 19/37] remove old version code --- .../bootstrap/DefaultSpringPluginHook.java | 20 +- .../EmptyMainApplicationContext.java | 153 +-- .../bootstrap/EmptySpringBeanFactory.java | 106 ++- .../bootstrap/PluginListableBeanFactory.java | 10 +- .../bootstrap/PluginOneselfInteractive.java | 80 ++ .../bootstrap/PluginSpringApplication.java | 14 +- .../bootstrap/SpringPluginBootstrap.java | 40 +- ...java => ComposeSpringPluginProcessor.java} | 22 +- .../processor/DefaultProcessorContext.java | 6 + .../processor/InvokeOtherPluginProcessor.java | 8 +- .../PluginControllerRegistryProcessor.java | 63 +- .../PluginInterceptorsProcessor.java | 35 +- .../bootstrap/processor/ProcessorContext.java | 8 + .../extract/ExtractBeanProcessor.java | 38 +- .../processor/extract/ExtractCoordinate.java | 106 +++ .../processor/extract/ExtractFactory.java | 3 +- .../PluginInterceptorRegister.java | 2 +- .../PluginInterceptorRegistration.java | 2 +- .../PluginInterceptorRegistry.java | 2 +- .../processor/invoke/InvokeBeanFactory.java | 4 +- .../processor/invoke/InvokeProxyHandler.java | 2 +- .../PluginClassPathBeanDefinitionScanner.java | 1 - .../bootstrap/utils/AnnotationUtils.java | 4 +- .../bootstrap/utils/SpringBeanUtils.java | 102 ++ .../plugin/DefaultPluginInteractive.java | 18 +- .../plugin/DefaultPluginLauncherManager.java | 11 +- .../plugin/DefaultPluginRegistryInfo.java | 4 +- .../launcher/plugin/PluginInteractive.java | 5 +- .../extension/AbstractExtension.java | 206 ++-- .../starblues/extension/ExtensionFactory.java | 122 +-- .../extension/ExtensionInitializer.java | 322 +++---- .../PluginControllerProcessorExtend.java | 72 +- .../support/SpringDocControllerProcessor.java | 142 +-- .../factory/DefaultPluginFactory.java | 202 ---- .../starblues/factory/PluginFactory.java | 45 - .../starblues/factory/PluginRegistryInfo.java | 346 ------- .../gitee/starblues/factory/PropertyKey.java | 12 - .../starblues/factory/SpringBeanRegister.java | 224 ----- .../pipe/PluginConfigBeanPipeProcessor.java | 64 -- .../process/pipe/PluginInfoContainers.java | 45 - .../pipe/PluginInterceptorsPipeProcessor.java | 129 --- .../pipe/PluginOneselfStopEventProcessor.java | 51 - ...PluginPipeApplicationContextProcessor.java | 129 --- .../process/pipe/PluginPipeProcessor.java | 37 - .../pipe/PluginPipeProcessorExtend.java | 26 - .../pipe/PluginPipeProcessorFactory.java | 85 -- .../pipe/PluginPreProcessorExtend.java | 25 - .../process/pipe/bean/BasicBeanRegistrar.java | 59 -- .../pipe/bean/ConfigBeanRegistrar.java | 40 - .../pipe/bean/ConfigFileBeanRegistrar.java | 100 -- .../pipe/bean/InvokeBeanRegistrar.java | 308 ------ .../pipe/bean/PluginBeanRegistrar.java | 27 - .../pipe/bean/PluginBeanRegistrarExtend.java | 15 - .../pipe/bean/PluginInsetBeanRegistrar.java | 44 - .../bean/SpringBootConfigFileRegistrar.java | 310 ------ .../AbstractConfigurationParser.java | 71 -- .../configuration/ConfigurationParser.java | 21 - .../configuration/PluginConfigDefinition.java | 55 -- .../YamlConfigurationParser.java | 59 -- .../pipe/bean/inset/ExtractFactoryInset.java | 22 - .../pipe/bean/inset/PluginInsetBean.java | 24 - .../pipe/bean/inset/PluginUtilsInset.java | 26 - .../PluginAnnotationBeanNameGenerator.java | 39 - .../process/pipe/classs/PluginClassGroup.java | 47 - .../pipe/classs/PluginClassGroupExtend.java | 18 - .../pipe/classs/PluginClassProcess.java | 105 -- .../pipe/classs/group/CallerGroup.java | 39 - .../pipe/classs/group/ComponentGroup.java | 71 -- .../pipe/classs/group/ConfigBeanGroup.java | 42 - .../classs/group/ConfigDefinitionGroup.java | 41 - .../pipe/classs/group/ControllerGroup.java | 38 - .../classs/group/OneselfListenerGroup.java | 38 - .../pipe/classs/group/RepositoryGroup.java | 36 - .../pipe/classs/group/SupplierGroup.java | 38 - .../pipe/classs/group/WebSocketGroup.java | 31 - .../process/pipe/loader/PluginResource.java | 171 ---- .../loader/PluginResourceLoadFactory.java | 92 -- .../pipe/loader/PluginResourceLoader.java | 45 - .../process/pipe/loader/ResourceWrapper.java | 66 -- .../pipe/loader/load/PluginClassLoader.java | 57 -- .../loader/load/PluginConfigFileLoader.java | 140 --- .../process/post/PluginPostProcessor.java | 39 - .../post/PluginPostProcessorExtend.java | 25 - .../post/PluginPostProcessorFactory.java | 77 -- .../bean/PluginControllerPostProcessor.java | 249 ----- .../post/bean/PluginInvokePostProcessor.java | 105 -- .../PluginOneselfStartEventProcessor.java | 74 -- .../post/bean/PluginWebSocketProcessor.java | 254 ----- .../post/bean/model/ControllerWrapper.java | 66 -- .../integration/IntegrationExtendPoint.java | 4 +- .../AbstractPluginApplication.java | 11 - .../application/DefaultPluginApplication.java | 58 +- .../application/EmptyPluginApplication.java | 6 - .../application/PluginApplication.java | 9 - .../listener/DefaultInitializerListener.java | 4 +- .../operator/PluginOperatorWrapper.java | 38 +- .../integration/user/DefaultPluginUser.java | 178 ++-- .../realize/ConfigDefinitionTip.java | 229 +++-- .../starblues/spring/ApplicationContext.java | 13 +- .../spring/ApplicationContextProxy.java | 32 +- .../CacheJdkSameTypeParamProxyFactory.java | 44 + .../spring/CglibProxyInvokeFactory.java | 56 -- .../DefaultPluginSpringApplication.java | 170 ---- .../starblues/spring/DefaultRegistryInfo.java | 51 - .../starblues/spring/DefaultSpringPlugin.java | 52 - .../DefaultSpringPluginRegistryInfo.java | 47 - .../spring/DiffProxyInvokeFactory.java | 34 - .../spring/GenericApplicationContext.java | 38 + .../spring/JdkSameTypeParamProxyFactory.java | 34 + .../spring/MainApplicationContext.java | 8 - .../spring/MainApplicationContextProxy.java | 16 + .../MainApplicationContextReflection.java | 51 - .../spring/PluginApplicationContext.java | 31 - .../spring/PluginBeanDefinitionLoader.java | 282 ------ .../spring/PluginListableBeanFactory.java | 41 - ...xyInvokeFactory.java => ProxyFactory.java} | 5 +- .../gitee/starblues/spring/ProxyInvoke.java | 73 -- .../gitee/starblues/spring/RegistryInfo.java | 47 - .../starblues/spring/SpringBeanFactory.java | 10 + .../gitee/starblues/spring/SpringPlugin.java | 35 - .../starblues/spring/SpringPluginHook.java | 2 +- .../spring/SpringPluginRegistryInfo.java | 38 - .../environment/FilteredPropertySource.java | 50 - .../PluginEnvironmentProcessor.java | 21 - .../PluginLocalConfigFileProcessor.java | 901 ------------------ .../spring/extract/DefaultExtractFactory.java | 56 ++ .../extract/DefaultOpExtractFactory.java | 194 ++++ .../spring/extract/EmptyExtractFactory.java | 47 + .../extract/ExtractCoordinate.java | 2 +- .../spring/extract/ExtractFactory.java | 81 ++ .../spring/extract/OpExtractFactory.java | 29 + .../invoke/DefaultInvokeSupperCache.java | 8 +- .../invoke/InvokeSupperCache.java | 2 +- .../{processor => }/invoke/SupperCache.java | 2 +- .../OneselfPluginSpringApplication.java | 22 - .../oneself/OneselfSpringApplication.java | 230 ----- .../OneselfSpringPluginRegistryInfo.java | 51 - .../processor/BeanRegistryProcessor.java | 30 - .../FrameDefineBeanRegistryProcessor.java | 30 - .../OneselfBeanRegistryProcessor.java | 34 - .../PluginControllerRegistryProcessor.java | 221 ----- .../processor/SpringPluginProcessor.java | 49 - .../SpringPluginProcessorFactory.java | 106 --- .../classgroup/CallerClassGroup.java | 24 - .../classgroup/ComposeClassGroup.java | 24 - .../classgroup/PluginClassGroup.java | 35 - .../extract/PluginExtractPipeProcessor.java | 62 -- .../PluginClassPathBeanDefinitionScanner.java | 23 - .../utils/CompareClassTypeUtils.java | 83 ++ .../starblues/utils/ReflectionUtils.java | 3 +- .../gitee/starblues/utils/ResourceUtils.java | 57 +- .../starblues/utils/SpringBeanUtilsV3.java | 105 ++ 152 files changed, 2040 insertions(+), 8666 deletions(-) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java (54%) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java rename springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/{SpringPluginProcessorFactory.java => ComposeSpringPluginProcessor.java} (87%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/PluginInterceptorsProcessor.java (76%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/extract/ExtractBeanProcessor.java (40%) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/extract/ExtractFactory.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/interceptor/PluginInterceptorRegister.java (80%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/interceptor/PluginInterceptorRegistration.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/spring => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap}/processor/interceptor/PluginInterceptorRegistry.java (98%) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/DefaultPluginFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PropertyKey.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/SpringBeanRegister.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginConfigBeanPipeProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginOneselfStopEventProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPreProcessorExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/BasicBeanRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigBeanRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/InvokeBeanRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrarExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginInsetBeanRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/SpringBootConfigFileRegistrar.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/AbstractConfigurationParser.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/ConfigurationParser.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/PluginConfigDefinition.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/YamlConfigurationParser.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginInsetBean.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/name/PluginAnnotationBeanNameGenerator.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroupExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassProcess.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/CallerGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ComponentGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigBeanGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigDefinitionGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ControllerGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/OneselfListenerGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/RepositoryGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/SupplierGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/WebSocketGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResource.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoadFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/ResourceWrapper.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginClassLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginConfigFileLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginControllerPostProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginInvokePostProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginOneselfStartEventProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginWebSocketProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{ProxyInvokeFactory.java => ProxyFactory.java} (63%) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{processor => }/extract/ExtractCoordinate.java (98%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{processor => }/invoke/DefaultInvokeSupperCache.java (84%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{processor => }/invoke/InvokeSupperCache.java (84%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/{processor => }/invoke/SupperCache.java (93%) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java index 5101056..0c8d80c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -2,6 +2,8 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.ApplicationContextProxy; import com.gitee.starblues.spring.SpringPluginHook; /** @@ -10,24 +12,24 @@ import com.gitee.starblues.spring.SpringPluginHook; */ public class DefaultSpringPluginHook implements SpringPluginHook { - private final SpringPluginProcessor springPluginProcessor; + private final SpringPluginProcessor pluginProcessor; private final ProcessorContext processorContext; - public DefaultSpringPluginHook(SpringPluginProcessor springPluginProcessor, + public DefaultSpringPluginHook(SpringPluginProcessor pluginProcessor, ProcessorContext processorContext) { - this.springPluginProcessor = springPluginProcessor; + this.pluginProcessor = pluginProcessor; this.processorContext = processorContext; } - @Override - public Object getGenericApplicationContext() { - return processorContext.getApplicationContext(); - } - @Override public void close() throws Exception{ - springPluginProcessor.close(processorContext); + pluginProcessor.close(processorContext); processorContext.getApplicationContext().close(); processorContext.clearRegistryInfo(); } + + @Override + public ApplicationContext getApplicationContext() { + return new ApplicationContextProxy(processorContext.getApplicationContext().getBeanFactory()); + } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java index 3f71aaa..00cbb67 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java @@ -1,6 +1,7 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.ObjectProvider; @@ -16,159 +17,15 @@ import java.util.Set; */ public class EmptyMainApplicationContext implements MainApplicationContext { + private final SpringBeanFactory springBeanFactory = new EmptySpringBeanFactory(); @Override - public Object resolveDependency(Object descriptor, String requestingBeanName) throws BeansException { - return null; + public SpringBeanFactory getSpringBeanFactory() { + return springBeanFactory; } @Override - public Object resolveDependency(Object descriptor, String requestingBeanName, Set autowiredBeanNames, Object typeConverter) throws BeansException { - return null; - } - - @Override - public boolean containsBeanDefinition(String beanName) { - return false; - } - - @Override - public int getBeanDefinitionCount() { - return 0; - } - - @Override - public String[] getBeanDefinitionNames() { - return new String[0]; - } - - @Override - public ObjectProvider getBeanProvider(Class requiredType, boolean allowEagerInit) { - return null; - } - - @Override - public ObjectProvider getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) { - return null; - } - - @Override - public String[] getBeanNamesForType(ResolvableType type) { - return new String[0]; - } - - @Override - public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { - return new String[0]; - } - - @Override - public String[] getBeanNamesForType(Class type) { - return new String[0]; - } - - @Override - public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - return new String[0]; - } - - @Override - public Map getBeansOfType(Class type) throws BeansException { - return null; - } - - @Override - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { - return null; - } - - @Override - public String[] getBeanNamesForAnnotation(Class annotationType) { - return new String[0]; - } - - @Override - public Map getBeansWithAnnotation(Class annotationType) throws BeansException { - return null; - } - - @Override - public A findAnnotationOnBean(String beanName, Class annotationType) throws NoSuchBeanDefinitionException { - return null; - } + public void close() throws Exception { - @Override - public Object getBean(String name) throws BeansException { - return null; - } - - @Override - public T getBean(String name, Class requiredType) throws BeansException { - return null; - } - - @Override - public Object getBean(String name, Object... args) throws BeansException { - return null; - } - - @Override - public T getBean(Class requiredType) throws BeansException { - return null; - } - - @Override - public T getBean(Class requiredType, Object... args) throws BeansException { - return null; - } - - @Override - public ObjectProvider getBeanProvider(Class requiredType) { - return null; - } - - @Override - public ObjectProvider getBeanProvider(ResolvableType requiredType) { - return null; - } - - @Override - public boolean containsBean(String name) { - return false; - } - - @Override - public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { - return false; - } - - @Override - public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { - return false; - } - - @Override - public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { - return false; - } - - @Override - public boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { - return false; - } - - @Override - public Class getType(String name) throws NoSuchBeanDefinitionException { - return null; - } - - @Override - public Class getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { - return null; - } - - @Override - public String[] getAliases(String name) { - return new String[0]; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java similarity index 54% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java index 66439cd..401adf3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContextReflection.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java @@ -1,8 +1,9 @@ -package com.gitee.starblues.spring; +package com.gitee.starblues.bootstrap; -import com.gitee.starblues.utils.ReflectionUtils; +import com.gitee.starblues.spring.SpringBeanFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.core.ResolvableType; import java.lang.annotation.Annotation; @@ -12,144 +13,149 @@ import java.util.Map; * @author starBlues * @version 1.0 */ -public class GenericApplicationContextReflection implements ApplicationContext { - - protected final Object genericApplicationContext; - - public GenericApplicationContextReflection(Object genericApplicationContext) { - this.genericApplicationContext = genericApplicationContext; - } - +public class EmptySpringBeanFactory implements SpringBeanFactory { @Override public boolean containsBeanDefinition(String beanName) { - return invokeReturn("containsBeanDefinition", beanName); + return false; } @Override public int getBeanDefinitionCount() { - return invokeReturn("getBeanDefinitionCount"); + return 0; } @Override public String[] getBeanDefinitionNames() { - return invokeReturn("getBeanDefinitionNames"); + return new String[0]; } @Override - public String[] getBeanNamesForType(ResolvableType type) { - prohibitCall("getBeanNamesForType"); + public ObjectProvider getBeanProvider(Class requiredType, boolean allowEagerInit) { + return null; + } + + @Override + public ObjectProvider getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) { return null; } + @Override + public String[] getBeanNamesForType(ResolvableType type) { + return new String[0]; + } + + @Override + public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { + return new String[0]; + } + @Override public String[] getBeanNamesForType(Class type) { - return invokeReturn("getBeanNamesForType", type); + return new String[0]; } @Override public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - return invokeReturn("getBeanNamesForType", includeNonSingletons, allowEagerInit); + return new String[0]; } @Override public Map getBeansOfType(Class type) throws BeansException { - return invokeReturn("getBeansOfType", type); + return null; } @Override public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { - return invokeReturn("getBeansOfType", type, includeNonSingletons, allowEagerInit); + return null; } @Override public String[] getBeanNamesForAnnotation(Class annotationType) { - return invokeReturn("getBeanNamesForAnnotation", annotationType); + return new String[0]; } @Override public Map getBeansWithAnnotation(Class annotationType) throws BeansException { - return invokeReturn("getBeansWithAnnotation", annotationType); + return null; } @Override public A findAnnotationOnBean(String beanName, Class annotationType) throws NoSuchBeanDefinitionException { - return invokeReturn("findAnnotationOnBean", beanName, annotationType); + return null; } @Override public Object getBean(String name) throws BeansException { - return invokeReturn("getBean", name); + return null; } @Override public T getBean(String name, Class requiredType) throws BeansException { - return invokeReturn("getBean", name, requiredType); + return null; } @Override public Object getBean(String name, Object... args) throws BeansException { - return invokeReturn("getBean", name, args); + return null; } @Override public T getBean(Class requiredType) throws BeansException { - return invokeReturn("getBean", requiredType); + return null; } @Override public T getBean(Class requiredType, Object... args) throws BeansException { - return invokeReturn("getBean", requiredType, args); + return null; + } + + @Override + public ObjectProvider getBeanProvider(Class requiredType) { + return null; + } + + @Override + public ObjectProvider getBeanProvider(ResolvableType requiredType) { + return null; } @Override public boolean containsBean(String name) { - return invokeReturn("containsBean", name); + return false; } @Override public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { - return invokeReturn("isSingleton", name); + return false; } @Override public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { - return invokeReturn("isPrototype", name); + return false; } @Override public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { - return invokeReturn("isTypeMatch", name, typeToMatch); + return false; } @Override public boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { - return invokeReturn("isTypeMatch", name, typeToMatch); + return false; } @Override public Class getType(String name) throws NoSuchBeanDefinitionException { - return invokeReturn("getType", name); + return null; } @Override - public String[] getAliases(String name) { - return invokeReturn("getAliases", name); - } - - protected T invokeReturn(String methodName, Object... params){ - return invoke(true, methodName, params); - } - - protected void invokeNoReturn(String methodName, Object... params){ - invoke(false, methodName, params); - } - - protected T invoke(boolean haveReturn, String methodName, Object... params){ - return ReflectionUtils.invoke(genericApplicationContext, methodName, params); + public Class getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { + return null; } - private void prohibitCall(String name){ - throw new IllegalStateException("Prohibit call: " + name); + @Override + public String[] getAliases(String name) { + return new String[0]; } - } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java index c24b6b1..f5deb3d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -2,6 +2,7 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,8 +23,6 @@ public class PluginListableBeanFactory extends DefaultListableBeanFactory { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final static String NO_SUCH_BEAN_EXCEPTION_NAME = "NoSuchBeanDefinitionException"; - private final MainApplicationContext applicationContext; public PluginListableBeanFactory(MainApplicationContext applicationContext) { @@ -45,11 +44,12 @@ public class PluginListableBeanFactory extends DefaultListableBeanFactory { private Object resolveDependencyFromMain(DependencyDescriptor descriptor){ String dependencyName = descriptor.getDependencyName(); - if(!ObjectUtils.isEmpty(dependencyName) && applicationContext.containsBean(dependencyName)){ - return applicationContext.getBean(dependencyName); + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + if(!ObjectUtils.isEmpty(dependencyName) && springBeanFactory.containsBean(dependencyName)){ + return springBeanFactory.getBean(dependencyName); } else { try { - return applicationContext.getBean(descriptor.getDependencyType()); + return springBeanFactory.getBean(descriptor.getDependencyType()); } catch (Exception e){ throw new NoSuchBeanDefinitionException(descriptor.getDependencyType()); } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java new file mode 100644 index 0000000..39e0816 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -0,0 +1,80 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.EmptyPluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +import com.gitee.starblues.core.launcher.plugin.PluginInteractive; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.extract.DefaultOpExtractFactory; +import com.gitee.starblues.spring.extract.OpExtractFactory; +import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; + +import java.nio.file.Paths; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginOneselfInteractive implements PluginInteractive { + + private final PluginDescriptor pluginDescriptor; + private final MainApplicationContext mainApplicationContext; + private final IntegrationConfiguration configuration; + private final InvokeSupperCache invokeSupperCache; + private final OpExtractFactory opExtractFactory; + + public PluginOneselfInteractive(){ + this.pluginDescriptor = createPluginDescriptor(); + this.mainApplicationContext = new EmptyMainApplicationContext(); + this.configuration = new AutoIntegrationConfiguration(); + this.invokeSupperCache = new DefaultInvokeSupperCache(); + this.opExtractFactory = new DefaultOpExtractFactory(); + } + + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginDescriptor; + } + + @Override + public MainApplicationContext getMainApplicationContext() { + return mainApplicationContext; + } + + @Override + public IntegrationConfiguration getConfiguration() { + return configuration; + } + + @Override + public InvokeSupperCache getInvokeSupperCache() { + return invokeSupperCache; + } + + @Override + public OpExtractFactory getOpExtractFactory() { + return opExtractFactory; + } + + + + private PluginDescriptor createPluginDescriptor(){ + PluginDescriptor pluginDescriptor; + try { + PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); + pluginDescriptor = pluginDescriptorLoader.load( + Paths.get(this.getClass().getResource("/").toURI())); + if(pluginDescriptor == null){ + pluginDescriptor = new EmptyPluginDescriptor(); + } + } catch (Exception e){ + pluginDescriptor = new EmptyPluginDescriptor(); + } + return pluginDescriptor; + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java index d558911..74a906a 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -22,7 +22,7 @@ public class PluginSpringApplication extends SpringApplication { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final SpringPluginProcessor springPluginProcessor; + private final SpringPluginProcessor pluginProcessor; private final ProcessorContext processorContext; private final GenericApplicationContext applicationContext; @@ -30,11 +30,11 @@ public class PluginSpringApplication extends SpringApplication { private final ResourceLoader resourceLoader; private final ConfigurePluginEnvironment configurePluginEnvironment; - public PluginSpringApplication(SpringPluginProcessor springPluginProcessor, + public PluginSpringApplication(SpringPluginProcessor pluginProcessor, ProcessorContext processorContext, Class... primarySources) { super(primarySources); - this.springPluginProcessor = springPluginProcessor; + this.pluginProcessor = pluginProcessor; this.processorContext = processorContext; this.resourceLoader = processorContext.getResourceLoader(); this.beanFactory = new PluginListableBeanFactory(processorContext.getMainApplicationContext()); @@ -65,10 +65,10 @@ public class PluginSpringApplication extends SpringApplication { public ConfigurableApplicationContext run(String... args) { try { processorContext.setApplicationContext(this.applicationContext); - springPluginProcessor.initialize(processorContext); + pluginProcessor.initialize(processorContext); return super.run(args); } catch (Exception e) { - springPluginProcessor.failure(processorContext); + pluginProcessor.failure(processorContext); logger.error("启动插件[{}]失败. {}", processorContext.getPluginDescriptor().getPluginId(), e.getMessage(), e); @@ -78,9 +78,9 @@ public class PluginSpringApplication extends SpringApplication { @Override protected void refresh(ConfigurableApplicationContext applicationContext) { - springPluginProcessor.refreshBefore(processorContext); + pluginProcessor.refreshBefore(processorContext); super.refresh(applicationContext); - springPluginProcessor.refreshAfter(processorContext); + pluginProcessor.refreshAfter(processorContext); } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java index d3cfe22..be76a89 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java @@ -1,9 +1,6 @@ package com.gitee.starblues.bootstrap; -import com.gitee.starblues.bootstrap.processor.DefaultProcessorContext; -import com.gitee.starblues.bootstrap.processor.ProcessorContext; -import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; -import com.gitee.starblues.bootstrap.processor.SpringPluginProcessorFactory; +import com.gitee.starblues.bootstrap.processor.*; import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; import com.gitee.starblues.core.descriptor.EmptyPluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; @@ -13,15 +10,17 @@ import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; -import com.gitee.starblues.spring.processor.invoke.DefaultInvokeSupperCache; +import com.gitee.starblues.spring.extract.DefaultOpExtractFactory; +import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** + * 插件引导抽象类。插件入口需集成本抽象类 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public abstract class SpringPluginBootstrap { @@ -45,17 +44,17 @@ public abstract class SpringPluginBootstrap { private SpringPluginHook start(Class[] primarySources, String[] args){ createPluginInteractive(); - SpringPluginProcessor springPluginProcessor = new SpringPluginProcessorFactory(runMode, customPluginProcessors); + SpringPluginProcessor pluginProcessor = new ComposeSpringPluginProcessor(runMode, customPluginProcessors); ProcessorContext processorContext = new DefaultProcessorContext( pluginInteractive, this.getClass() ); PluginSpringApplication springApplication = new PluginSpringApplication( - springPluginProcessor, + pluginProcessor, processorContext, primarySources); springApplication.run(args); - return new DefaultSpringPluginHook(springPluginProcessor, processorContext); + return new DefaultSpringPluginHook(pluginProcessor, processorContext); } public final void setPluginInteractive(PluginInteractive pluginInteractive) { @@ -69,30 +68,15 @@ public abstract class SpringPluginBootstrap { } } - private void createPluginInteractive(){ + protected void createPluginInteractive(){ if(pluginInteractive != null){ return; } - PluginDescriptor pluginDescriptor = createPluginDescriptor(); - MainApplicationContext mainApplicationContext = new EmptyMainApplicationContext(); - pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, mainApplicationContext, - new AutoIntegrationConfiguration(), - new DefaultInvokeSupperCache()); + createPluginInteractiveOfOneself(); } - private PluginDescriptor createPluginDescriptor(){ - PluginDescriptor pluginDescriptor; - try { - PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); - pluginDescriptor = pluginDescriptorLoader.load( - Paths.get(this.getClass().getResource("/").toURI())); - if(pluginDescriptor == null){ - pluginDescriptor = new EmptyPluginDescriptor(); - } - } catch (Exception e){ - pluginDescriptor = new EmptyPluginDescriptor(); - } - return pluginDescriptor; + protected void createPluginInteractiveOfOneself(){ + this.pluginInteractive = new PluginOneselfInteractive(); } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java similarity index 87% rename from springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index c8f97dc..6aa1545 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessorFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -14,7 +14,7 @@ import java.util.stream.Collectors; * @author starBlues * @version 1.0 */ -public class SpringPluginProcessorFactory implements SpringPluginProcessor { +public class ComposeSpringPluginProcessor implements SpringPluginProcessor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @@ -22,11 +22,11 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { private List processors; - public SpringPluginProcessorFactory(RunMode runMode) { + public ComposeSpringPluginProcessor(RunMode runMode) { this(runMode, null); } - public SpringPluginProcessorFactory(RunMode runMode, List processors) { + public ComposeSpringPluginProcessor(RunMode runMode, List processors) { this.runMode = runMode; if(!ObjectUtils.isEmpty(processors)){ this.processors = processors; @@ -46,6 +46,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { processors.add(new FrameDefineBeanProcessor()); processors.add(new PluginControllerRegistryProcessor()); processors.add(new InvokeOtherPluginProcessor()); + processors.add(new PluginInterceptorsProcessor()); return processors; } @@ -63,7 +64,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { for (SpringPluginProcessor processor : this.processors) { try { processor.initialize(processorContext); - } catch (Exception e){ + } catch (Throwable e){ processException(processor, "initialize", e, true); } } @@ -74,7 +75,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { for (SpringPluginProcessor processor : processors) { try { processor.refreshBefore(context); - } catch (Exception e){ + } catch (Throwable e){ processException(processor, "refreshBefore", e, true); } } @@ -85,7 +86,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { for (SpringPluginProcessor processor : processors) { try { processor.refreshAfter(context); - } catch (Exception e){ + } catch (Throwable e){ processException(processor, "refreshAfter", e, true); } } @@ -96,7 +97,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { for (SpringPluginProcessor processor : processors) { try { processor.failure(context); - } catch (Exception e){ + } catch (Throwable e){ processException(processor, "failure", e, false); } } @@ -107,7 +108,7 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { for (SpringPluginProcessor processor : processors) { try { processor.close(context); - } catch (Exception e){ + } catch (Throwable e){ processException(processor, "close", e, false); } } @@ -124,13 +125,12 @@ public class SpringPluginProcessorFactory implements SpringPluginProcessor { } private void processException(SpringPluginProcessor processor, String executeType, - Exception e, boolean isThrow){ + Throwable e, boolean isThrow) throws ProcessorException{ String error = "Processor[" + processor.getClass().getName() + "] execute[" + executeType + "] failure : " + e.getMessage(); + logger.error(error, e); if(isThrow){ throw new ProcessorException(error, e); - } else { - logger.error(error, e); } } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 0468199..9d04ff6 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -6,6 +6,7 @@ import com.gitee.starblues.core.launcher.plugin.CacheRegistryInfo; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; @@ -57,6 +58,11 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces return mainApplicationContext; } + @Override + public SpringBeanFactory getMainBeanFactory() { + return mainApplicationContext.getSpringBeanFactory(); + } + @Override public IntegrationConfiguration getConfiguration() { return configuration; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java index 9121254..fe64bac 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java @@ -5,9 +5,9 @@ import com.gitee.starblues.annotation.Supplier; import com.gitee.starblues.bootstrap.processor.invoke.InvokeBeanFactory; import com.gitee.starblues.bootstrap.processor.scanner.PluginClassPathBeanDefinitionScanner; import com.gitee.starblues.spring.ApplicationContext; -import com.gitee.starblues.spring.GenericApplicationContextReflection; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; -import com.gitee.starblues.spring.processor.invoke.SupperCache; +import com.gitee.starblues.spring.ApplicationContextProxy; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.invoke.SupperCache; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ScanUtils; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; @@ -38,7 +38,7 @@ public class InvokeOtherPluginProcessor implements SpringPluginProcessor { GenericApplicationContext applicationContext = context.getApplicationContext(); Map supplierBeans = applicationContext.getBeansWithAnnotation(Supplier.class); String pluginId = context.getPluginDescriptor().getPluginId(); - ApplicationContext applicationContextReflection = new GenericApplicationContextReflection(applicationContext); + ApplicationContext applicationContextReflection = new ApplicationContextProxy(applicationContext); InvokeSupperCache invokeSupperCache = context.getPluginInteractive().getInvokeSupperCache(); supplierBeans.forEach((k,v)->{ Supplier supplier = AnnotationUtils.findAnnotation(v.getClass(), Supplier.class); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java index d7b878f..6cadf9c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java @@ -1,9 +1,8 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; -import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; import com.gitee.starblues.utils.ClassUtils; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; @@ -42,8 +41,8 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor @Override public void initialize(ProcessorContext processorContext) throws ProcessorException { - MainApplicationContext mainApplicationContext = processorContext.getMainApplicationContext(); - this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); + SpringBeanFactory mainBeanFactory = processorContext.getMainBeanFactory(); + this.requestMappingHandlerMapping = mainBeanFactory.getBean(RequestMappingHandlerMapping.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); if(getMappingForMethod == null){ @@ -215,4 +214,60 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor } } + + private static class ControllerWrapper{ + + /** + * controller bean 名称 + */ + private String beanName; + + /** + * controller 路径前缀 + */ + private String[] pathPrefix; + + /** + * controller bean 类型 + */ + private Class beanClass; + + /** + * controller 的 RequestMappingInfo 集合 + */ + private Set requestMappingInfos; + + public Class getBeanClass() { + return beanClass; + } + + public void setBeanClass(Class beanClass) { + this.beanClass = beanClass; + } + + public String getBeanName() { + return beanName; + } + + public void setBeanName(String beanName) { + this.beanName = beanName; + } + + public String[] getPathPrefix() { + return pathPrefix; + } + + public void setPathPrefix(String[] pathPrefix) { + this.pathPrefix = pathPrefix; + } + + public Set getRequestMappingInfos() { + return requestMappingInfos; + } + + public void setRequestMappingInfos(Set requestMappingInfos) { + this.requestMappingInfos = requestMappingInfos; + } + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginInterceptorsProcessor.java similarity index 76% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginInterceptorsProcessor.java index 662cd86..35b2098 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginInterceptorsProcessor.java @@ -1,15 +1,15 @@ -package com.gitee.starblues.spring.processor; +package com.gitee.starblues.bootstrap.processor; -import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegister; -import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegistry; +import com.gitee.starblues.bootstrap.processor.interceptor.PluginInterceptorRegister; +import com.gitee.starblues.bootstrap.processor.interceptor.PluginInterceptorRegistry; +import com.gitee.starblues.bootstrap.utils.SpringBeanUtils; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; +import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.utils.ClassUtils; import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.SpringBeanUtils; +import com.gitee.starblues.utils.SpringBeanUtilsV3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.context.request.WebRequestInterceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.handler.AbstractHandlerMapping; @@ -22,7 +22,7 @@ import java.util.List; * @author starBlues * @version 1.0 */ -public class PluginInterceptorsProcessor implements SpringPluginProcessor{ +public class PluginInterceptorsProcessor implements SpringPluginProcessor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final static String INTERCEPTORS = "pluginHandlerInterceptors"; @@ -31,8 +31,9 @@ public class PluginInterceptorsProcessor implements SpringPluginProcessor{ @Override - public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { - handlerMapping = SpringBeanUtils.getExistBean(mainApplicationContext, + public void initialize(ProcessorContext context) throws ProcessorException { + MainApplicationContext applicationContext = context.getMainApplicationContext(); + handlerMapping = SpringBeanUtilsV3.getExistBean(applicationContext, AbstractHandlerMapping.class); if(handlerMapping == null){ logger.warn("Not found AbstractHandlerMapping, Plugin interceptor can't use"); @@ -40,20 +41,20 @@ public class PluginInterceptorsProcessor implements SpringPluginProcessor{ } @Override - public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { + public void refreshAfter(ProcessorContext context) throws ProcessorException { if(handlerMapping == null){ return; } - GenericApplicationContext pluginApplicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); - List interceptorRegisters = SpringBeanUtils.getBeans(pluginApplicationContext, + List interceptorRegisters = SpringBeanUtils.getBeans( + context.getApplicationContext(), PluginInterceptorRegister.class); List interceptorsObjects = new ArrayList<>(); List adaptedInterceptors = getAdaptedInterceptors(); if(adaptedInterceptors == null){ return; } - IntegrationConfiguration configuration = registryInfo.getConfiguration(); - String pluginId = registryInfo.getPluginWrapper().getPluginId(); + IntegrationConfiguration configuration = context.getConfiguration(); + String pluginId = context.getPluginDescriptor().getPluginId(); String pluginRestPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginId); for (PluginInterceptorRegister interceptorRegister : interceptorRegisters) { @@ -69,15 +70,15 @@ public class PluginInterceptorsProcessor implements SpringPluginProcessor{ interceptorsObjects.add(handlerInterceptor); } } - registryInfo.addRegistryInfo(INTERCEPTORS, interceptorsObjects); + context.addRegistryInfo(INTERCEPTORS, interceptorsObjects); } @Override - public void close(SpringPluginRegistryInfo registryInfo) throws Exception { + public void close(ProcessorContext context) throws ProcessorException { if(handlerMapping == null){ return; } - List interceptorsObjects = registryInfo.getRegistryInfo(INTERCEPTORS); + List interceptorsObjects = context.getRegistryInfo(INTERCEPTORS); if(interceptorsObjects == null || interceptorsObjects.isEmpty()){ return; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index a190c38..ed09026 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -7,6 +7,8 @@ import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.core.launcher.plugin.RegistryInfo; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; +import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ResourceLoader; @@ -40,6 +42,12 @@ public interface ProcessorContext extends RegistryInfo { */ MainApplicationContext getMainApplicationContext(); + /** + * 得到主程序的 SpringBeanFactory + * @return SpringBeanFactory + */ + SpringBeanFactory getMainBeanFactory(); + /** * 得到当前框架的集成配置 * @return IntegrationConfiguration diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractBeanProcessor.java similarity index 40% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractBeanProcessor.java index 0036afd..5325c92 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractBeanProcessor.java @@ -1,8 +1,10 @@ -package com.gitee.starblues.spring.processor.extract; +package com.gitee.starblues.bootstrap.processor.extract; import com.gitee.starblues.annotation.Extract; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.SpringPluginProcessor; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorException; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.extract.OpExtractFactory; import com.gitee.starblues.utils.ObjectUtils; import org.springframework.context.support.GenericApplicationContext; @@ -15,33 +17,27 @@ import java.util.Map; */ public class ExtractBeanProcessor implements SpringPluginProcessor { - private final ExtractFactory extractFactory = ExtractFactory.getInstant(); - - @Override - public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { -// // 获取主程序的扩展 -// Map extractMap = mainApplicationContext.getBeansWithAnnotation(Extract.class); -// if(ObjectUtils.isEmpty(extractMap)){ -// return; -// } -// for (Object extract : extractMap.values()) { -// extractFactory.addOfMain(extract); -// } - } - @Override - public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { - GenericApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); + public void refreshAfter(ProcessorContext context) throws ProcessorException { + GenericApplicationContext applicationContext = context.getApplicationContext(); Map extractMap = applicationContext.getBeansWithAnnotation(Extract.class); if(ObjectUtils.isEmpty(extractMap)){ return; } - String pluginId = registryInfo.getPluginWrapper().getPluginId(); + String pluginId = context.getPluginDescriptor().getPluginId(); + OpExtractFactory opExtractFactory = context.getPluginInteractive().getOpExtractFactory(); for (Object extract : extractMap.values()) { - extractFactory.add(pluginId, extract); + opExtractFactory.add(pluginId, extract); } } + @Override + public void close(ProcessorContext context) throws ProcessorException { + OpExtractFactory opExtractFactory = context.getPluginInteractive().getOpExtractFactory(); + String pluginId = context.getPluginDescriptor().getPluginId(); + opExtractFactory.remove(pluginId); + } + @Override public RunMode runMode() { return RunMode.ALL; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java new file mode 100644 index 0000000..958801c --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java @@ -0,0 +1,106 @@ +package com.gitee.starblues.bootstrap.processor.extract; + +import com.gitee.starblues.annotation.Extract; +import org.pf4j.util.StringUtils; + +import java.util.Objects; + +/** + * 执行器坐标 + * @author starBlues + * @version 2.4.4 + */ +public class ExtractCoordinate { + + private final String bus; + private final String scene; + private final String useCase; + private final Class extractClass; + + ExtractCoordinate(String bus, String scene, String useCase, Class extractClass) { + this.bus = bus; + this.scene = scene; + this.useCase = useCase; + this.extractClass = extractClass; + } + + + ExtractCoordinate(Extract extract, Class extractClass) { + this.bus = extract.bus(); + this.scene = extract.scene(); + this.useCase = extract.useCase(); + this.extractClass = extractClass; + } + + public static ExtractCoordinate build(String bus) { + return new ExtractCoordinate(bus, null, null, null); + } + + public static ExtractCoordinate build(String bus, String scene) { + return new ExtractCoordinate(bus, scene, null, null); + } + + public static ExtractCoordinate build(String bus, String scene, String useCase) { + return new ExtractCoordinate(bus, scene, useCase, null); + } + + public String getBus() { + return bus; + } + + public String getScene() { + return scene; + } + + public String getUseCase() { + return useCase; + } + + public Class getExtractClass() { + return extractClass; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ExtractCoordinate)) { + return false; + } + ExtractCoordinate that = (ExtractCoordinate) o; + if(StringUtils.isNotNullOrEmpty(bus) && + StringUtils.isNotNullOrEmpty(scene) && + StringUtils.isNotNullOrEmpty(useCase)){ + return Objects.equals(getBus(), that.getBus()) && + Objects.equals(getScene(), that.getScene()) && + Objects.equals(getUseCase(), that.getUseCase()); + } + + if(StringUtils.isNotNullOrEmpty(bus) && StringUtils.isNotNullOrEmpty(scene)){ + return Objects.equals(getBus(), that.getBus()) && + Objects.equals(getScene(), that.getScene()); + } + + if(StringUtils.isNotNullOrEmpty(bus)){ + return Objects.equals(getBus(), that.getBus()); + } + + return false; + } + + @Override + public int hashCode() { + return Objects.hash(getBus(), getScene(), getUseCase()); + } + + @Override + public String toString() { + return "ExtractCoordinate{" + + "bus='" + bus + '\'' + + ", scene='" + scene + '\'' + + ", useCase='" + useCase + '\'' + + '}'; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractFactory.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java index 9f93b4b..c002591 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java @@ -1,7 +1,6 @@ -package com.gitee.starblues.spring.processor.extract; +package com.gitee.starblues.bootstrap.processor.extract; import com.gitee.starblues.annotation.Extract; -import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import org.springframework.util.ClassUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegister.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java similarity index 80% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegister.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java index 3623c10..b997b9d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegister.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.processor.interceptor; +package com.gitee.starblues.bootstrap.processor.interceptor; /** * 插件拦截器注册者 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistration.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistration.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java index 799e4fc..4610c2f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistration.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.processor.interceptor; +package com.gitee.starblues.bootstrap.processor.interceptor; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistry.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistry.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java index 59ed222..c33e081 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/interceptor/PluginInterceptorRegistry.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.processor.interceptor; +package com.gitee.starblues.bootstrap.processor.interceptor; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java index 2e586c2..3c61711 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java @@ -1,9 +1,7 @@ package com.gitee.starblues.bootstrap.processor.invoke; import com.gitee.starblues.annotation.Caller; -import com.gitee.starblues.bootstrap.processor.ProcessorContext; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; import org.springframework.beans.factory.FactoryBean; import java.lang.reflect.Proxy; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java index 2415716..7dcd0bf 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java @@ -3,7 +3,7 @@ package com.gitee.starblues.bootstrap.processor.invoke; import com.fasterxml.jackson.databind.ObjectMapper; import com.gitee.starblues.annotation.Caller; import com.gitee.starblues.annotation.Supplier; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; import com.gitee.starblues.utils.ObjectUtils; import java.lang.reflect.InvocationHandler; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java index 86347bb..cb5fd0c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java @@ -1,7 +1,6 @@ package com.gitee.starblues.bootstrap.processor.scanner; import com.gitee.starblues.bootstrap.processor.ProcessorContext; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java index a09624b..03a89bb 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java @@ -1,14 +1,12 @@ package com.gitee.starblues.bootstrap.utils; -import org.springframework.core.annotation.*; - import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class AnnotationUtils { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java new file mode 100644 index 0000000..654f9e2 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java @@ -0,0 +1,102 @@ +package com.gitee.starblues.bootstrap.utils; + +import org.springframework.context.ApplicationContext; +import org.springframework.util.ClassUtils; + +import java.util.*; + +/** + * 插件bean工具类 + * @author starBlues + * @version 3.0.0 + */ +public class SpringBeanUtils { + + /** + * 得到ApplicationContext中的bean的实现 + * @param applicationContext ApplicationContext + * @param aClass 接口或者抽象类型bean类型 + * @param 接口或者抽象类型bean类型 + * @return 所有的实现对象 + */ + public static List getBeans(ApplicationContext applicationContext, Class aClass) { + Map beansOfTypeMap = applicationContext.getBeansOfType(aClass); + if(beansOfTypeMap.isEmpty()){ + return new ArrayList<>(); + } + return new ArrayList<>(beansOfTypeMap.values()); + } + + /** + * 得到某个接口的实现对象 + * @param sourceObject 遍历的对象 + * @param interfaceClass 接口类类型 + * @param 接口类型 + * @return 实现对象 + */ + public static T getObjectByInterfaceClass(Set sourceObject, Class interfaceClass){ + if(sourceObject == null || sourceObject.isEmpty()){ + return null; + } + for (Object configSingletonObject : sourceObject) { + Set> allInterfacesForClassAsSet = ClassUtils + .getAllInterfacesAsSet(configSingletonObject); + if(allInterfacesForClassAsSet.contains(interfaceClass)){ + return (T) configSingletonObject; + } + } + return null; + } + + /** + * 获取具体类的对象 + * @param sourceObject 源对象集合 + * @param aClass 对象对应的类类型 + * @param 类实现 + * @return T + */ + public static T getObjectClass(Set sourceObject, Class aClass){ + if(sourceObject == null || sourceObject.isEmpty()){ + return null; + } + for (Object configSingletonObject : sourceObject) { + if(Objects.equals(configSingletonObject.getClass(), aClass)){ + return (T) configSingletonObject; + } + } + return null; + } + + /** + * 得到存在的bean, 不存在则返回null + * @param applicationContext ApplicationContext容器 + * @param aClass bean 类型 + * @param bean 类型 + * @return 存在bean对象, 不存在返回null + */ + public static T getExistBean(ApplicationContext applicationContext, Class aClass){ + String[] beanNamesForType = applicationContext.getBeanNamesForType(aClass, false, false); + if(beanNamesForType.length > 0){ + return applicationContext.getBean(aClass); + } else { + return null; + } + } + + /** + * 得到存在的bean, 不存在则返回null + * @param applicationContext ApplicationContext容器 + * @param beanName bean 名称 + * @param 返回的bean类型 + * @return 存在bean对象, 不存在返回null + */ + public static T getExistBean(ApplicationContext applicationContext, String beanName){ + if(applicationContext.containsBean(beanName)){ + Object bean = applicationContext.getBean(beanName); + return (T) bean; + } else { + return null; + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java index 955e291..6285bf2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java @@ -2,9 +2,11 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.MainApplicationContext; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.extract.DefaultExtractFactory; +import com.gitee.starblues.spring.extract.ExtractFactory; +import com.gitee.starblues.spring.extract.OpExtractFactory; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; /** * @author starBlues @@ -16,6 +18,7 @@ public class DefaultPluginInteractive implements PluginInteractive{ private final MainApplicationContext mainApplicationContext; private final IntegrationConfiguration configuration; private final InvokeSupperCache invokeSupperCache; + private final OpExtractFactory opExtractFactory; public DefaultPluginInteractive(PluginDescriptor pluginDescriptor, MainApplicationContext mainApplicationContext, @@ -25,6 +28,12 @@ public class DefaultPluginInteractive implements PluginInteractive{ this.mainApplicationContext = mainApplicationContext; this.configuration = configuration; this.invokeSupperCache = invokeSupperCache; + this.opExtractFactory = createOpExtractFactory(); + } + + protected OpExtractFactory createOpExtractFactory(){ + DefaultExtractFactory defaultExtractFactory = (DefaultExtractFactory)ExtractFactory.getInstant(); + return (OpExtractFactory) defaultExtractFactory.getTarget(); } @@ -47,4 +56,9 @@ public class DefaultPluginInteractive implements PluginInteractive{ public InvokeSupperCache getInvokeSupperCache() { return invokeSupperCache; } + + @Override + public OpExtractFactory getOpExtractFactory() { + return opExtractFactory; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java index 9928fbe..f209870 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java @@ -2,11 +2,10 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.ApplicationContextProxy; import com.gitee.starblues.spring.MainApplicationContext; -import com.gitee.starblues.spring.MainApplicationContextReflection; -import com.gitee.starblues.spring.processor.invoke.DefaultInvokeSupperCache; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.MainApplicationContextProxy; +import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; import org.springframework.context.support.GenericApplicationContext; import java.util.Map; @@ -27,7 +26,9 @@ public class DefaultPluginLauncherManager implements PluginLauncherManager{ public DefaultPluginLauncherManager(GenericApplicationContext mainGenericApplicationContext, IntegrationConfiguration configuration) { this.configuration = configuration; - this.mainApplicationContext = new MainApplicationContextReflection(mainGenericApplicationContext); + this.mainApplicationContext = new MainApplicationContextProxy( + mainGenericApplicationContext.getBeanFactory(), + mainGenericApplicationContext); this.invokeSupperCache = new DefaultInvokeSupperCache(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java index c0ca10a..152b1e2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java @@ -1,7 +1,7 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.spring.ApplicationContext; -import com.gitee.starblues.spring.GenericApplicationContextReflection; +import com.gitee.starblues.spring.MainApplicationContextProxy; import org.springframework.context.support.GenericApplicationContext; /** @@ -15,7 +15,7 @@ public class DefaultPluginRegistryInfo extends CacheRegistryInfo implements Plug public DefaultPluginRegistryInfo(GenericApplicationContext pluginApplicationContext, PluginLauncher pluginLauncher) { - this.applicationContext = new GenericApplicationContextReflection(pluginApplicationContext); + this.applicationContext = new MainApplicationContextProxy(pluginApplicationContext, null); this.pluginLauncher = pluginLauncher; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java index d62d779..876ef7c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java @@ -3,7 +3,8 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; -import com.gitee.starblues.spring.processor.invoke.InvokeSupperCache; +import com.gitee.starblues.spring.extract.OpExtractFactory; +import com.gitee.starblues.spring.invoke.InvokeSupperCache; /** * @author starBlues @@ -19,4 +20,6 @@ public interface PluginInteractive { InvokeSupperCache getInvokeSupperCache(); + OpExtractFactory getOpExtractFactory(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java index c4cc71a..4ca2836 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java @@ -1,103 +1,103 @@ -package com.gitee.starblues.extension; - -import com.gitee.starblues.factory.process.pipe.PluginPreProcessorExtend; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.integration.application.PluginApplication; -import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; -import org.springframework.context.ApplicationContext; - -import java.util.List; - -/** - * 抽象的扩展工厂 - * - * @author starBlues - * @version 2.4.0 - */ -public abstract class AbstractExtension { - - protected PluginApplication pluginApplication; - - public void setPluginApplication(PluginApplication pluginApplication) { - this.pluginApplication = pluginApplication; - } - - /** - * 扩展唯一的key - * @return String - */ - public abstract String key(); - - /** - * 该扩展初始化的操作 - * 主要是在插件初始化阶段被调用 - * @param mainApplicationContext 主程序ApplicationContext - * @throws Exception 初始化异常 - */ - public void initialize(ApplicationContext mainApplicationContext) throws Exception{ - } - - /** - * 返回插件的资源加载者。 - * 主要是加载插件中的某些资源,比如文件、图片等。 - * @return List PluginResourceLoader - */ - public List getPluginResourceLoader(){ - return null; - } - - /** - * 返回扩展的插件中的类分组器。 - * 该扩展主要是对插件中的Class文件分组,然后供 PluginPipeProcessor、PluginPostProcessor 阶段使用。 - * @param mainApplicationContext 主程序ApplicationContext - * @return List PluginPipeProcessorExtend - */ - public List getPluginClassGroup(ApplicationContext mainApplicationContext){ - return null; - } - - /** - * 返回扩展的插件前置处理者。 - * 该扩展主要是对每一个插件进行处理 - * @param mainApplicationContext 主程序ApplicationContext - * @return List PluginPipeProcessorExtend - */ - public List getPluginPreProcessor(ApplicationContext mainApplicationContext){ - return null; - } - - /** - * 返回扩展的bean定义注册者扩展 - * 该扩展主要是对每一个插件进行处理 - * @param mainApplicationContext 主程序ApplicationContext - * @return List PluginPipeProcessorExtend - */ - public List getPluginBeanRegistrar(ApplicationContext mainApplicationContext){ - return null; - } - - /** - * 返回扩展的流插件处理者。 - * 该扩展主要是对每一个插件进行处理 - * @param mainApplicationContext 主程序ApplicationContext - * @return List PluginPipeProcessorExtend - */ - public List getPluginPipeProcessor(ApplicationContext mainApplicationContext){ - return null; - } - - /** - * 返回扩展的插件后置处理者。 - * 该扩展主要是对全部插件进行处理。 - * @param mainApplicationContext 主程序ApplicationContext - * @return List PluginPostProcessorExtend - */ - public List getPluginPostProcessor(ApplicationContext mainApplicationContext){ - return null; - } - - -} +//package com.gitee.starblues.extension; +// +//import com.gitee.starblues.factory.process.pipe.PluginPreProcessorExtend; +//import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; +//import com.gitee.starblues.integration.application.PluginApplication; +//import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; +//import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; +//import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; +//import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; +//import org.springframework.context.ApplicationContext; +// +//import java.util.List; +// +///** +// * 抽象的扩展工厂 +// * +// * @author starBlues +// * @version 2.4.0 +// */ +//public abstract class AbstractExtension { +// +// protected PluginApplication pluginApplication; +// +// public void setPluginApplication(PluginApplication pluginApplication) { +// this.pluginApplication = pluginApplication; +// } +// +// /** +// * 扩展唯一的key +// * @return String +// */ +// public abstract String key(); +// +// /** +// * 该扩展初始化的操作 +// * 主要是在插件初始化阶段被调用 +// * @param mainApplicationContext 主程序ApplicationContext +// * @throws Exception 初始化异常 +// */ +// public void initialize(ApplicationContext mainApplicationContext) throws Exception{ +// } +// +// /** +// * 返回插件的资源加载者。 +// * 主要是加载插件中的某些资源,比如文件、图片等。 +// * @return List PluginResourceLoader +// */ +// public List getPluginResourceLoader(){ +// return null; +// } +// +// /** +// * 返回扩展的插件中的类分组器。 +// * 该扩展主要是对插件中的Class文件分组,然后供 PluginPipeProcessor、PluginPostProcessor 阶段使用。 +// * @param mainApplicationContext 主程序ApplicationContext +// * @return List PluginPipeProcessorExtend +// */ +// public List getPluginClassGroup(ApplicationContext mainApplicationContext){ +// return null; +// } +// +// /** +// * 返回扩展的插件前置处理者。 +// * 该扩展主要是对每一个插件进行处理 +// * @param mainApplicationContext 主程序ApplicationContext +// * @return List PluginPipeProcessorExtend +// */ +// public List getPluginPreProcessor(ApplicationContext mainApplicationContext){ +// return null; +// } +// +// /** +// * 返回扩展的bean定义注册者扩展 +// * 该扩展主要是对每一个插件进行处理 +// * @param mainApplicationContext 主程序ApplicationContext +// * @return List PluginPipeProcessorExtend +// */ +// public List getPluginBeanRegistrar(ApplicationContext mainApplicationContext){ +// return null; +// } +// +// /** +// * 返回扩展的流插件处理者。 +// * 该扩展主要是对每一个插件进行处理 +// * @param mainApplicationContext 主程序ApplicationContext +// * @return List PluginPipeProcessorExtend +// */ +// public List getPluginPipeProcessor(ApplicationContext mainApplicationContext){ +// return null; +// } +// +// /** +// * 返回扩展的插件后置处理者。 +// * 该扩展主要是对全部插件进行处理。 +// * @param mainApplicationContext 主程序ApplicationContext +// * @return List PluginPostProcessorExtend +// */ +// public List getPluginPostProcessor(ApplicationContext mainApplicationContext){ +// return null; +// } +// +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java index a3b6fd3..538aba0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java @@ -1,61 +1,61 @@ -package com.gitee.starblues.extension; - -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.util.StringUtils; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 静态的扩展工厂 - * - * @author starBlues - * @version 2.4.0 - */ -public class ExtensionFactory { - - private static final Logger LOG = LoggerFactory.getLogger(ExtensionFactory.class); - - /** - * 扩展工厂。key 扩展的key. 值为扩展的实现 - */ - private final static Map PLUGIN_EXTENSION_MAP = new ConcurrentHashMap<>(); - - private ExtensionFactory(){} - - - - public static void addExtension(AbstractExtension abstractExtension){ - if(abstractExtension == null){ - LOG.warn("add failure, abstractExtension is null"); - return; - } - String key = abstractExtension.key(); - if(StringUtils.isEmpty(key)){ - LOG.error("add failure, key is empty"); - } - PLUGIN_EXTENSION_MAP.put(key, abstractExtension); - } - - /** - * 得到PluginControllerProcessorExtend的实现 - * @param mainApplicationContext 主程序的 ApplicationContext - * @return PluginControllerProcessorExtend 的实现对象集合 - */ - public static List getPluginControllerProcessorExtend(ApplicationContext mainApplicationContext){ - return SpringBeanUtils.getBeans(mainApplicationContext, - PluginControllerProcessorExtend.class); - } - - - static Map getPluginExtension() { - return Collections.unmodifiableMap(PLUGIN_EXTENSION_MAP); - } - - - - -} +//package com.gitee.starblues.extension; +// +//import com.gitee.starblues.utils.SpringBeanUtils; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.context.ApplicationContext; +//import org.springframework.util.StringUtils; +// +//import java.util.*; +//import java.util.concurrent.ConcurrentHashMap; +// +///** +// * 静态的扩展工厂 +// * +// * @author starBlues +// * @version 2.4.0 +// */ +//public class ExtensionFactory { +// +// private static final Logger LOG = LoggerFactory.getLogger(ExtensionFactory.class); +// +// /** +// * 扩展工厂。key 扩展的key. 值为扩展的实现 +// */ +// private final static Map PLUGIN_EXTENSION_MAP = new ConcurrentHashMap<>(); +// +// private ExtensionFactory(){} +// +// +// +// public static void addExtension(AbstractExtension abstractExtension){ +// if(abstractExtension == null){ +// LOG.warn("add failure, abstractExtension is null"); +// return; +// } +// String key = abstractExtension.key(); +// if(StringUtils.isEmpty(key)){ +// LOG.error("add failure, key is empty"); +// } +// PLUGIN_EXTENSION_MAP.put(key, abstractExtension); +// } +// +// /** +// * 得到PluginControllerProcessorExtend的实现 +// * @param mainApplicationContext 主程序的 ApplicationContext +// * @return PluginControllerProcessorExtend 的实现对象集合 +// */ +// public static List getPluginControllerProcessorExtend(ApplicationContext mainApplicationContext){ +// return SpringBeanUtils.getBeans(mainApplicationContext, +// PluginControllerProcessorExtend.class); +// } +// +// +// static Map getPluginExtension() { +// return Collections.unmodifiableMap(PLUGIN_EXTENSION_MAP); +// } +// +// +// +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java index 9c5cc96..5c9c3a5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java @@ -1,161 +1,161 @@ -package com.gitee.starblues.extension; - -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import com.gitee.starblues.factory.process.pipe.PluginPreProcessorExtend; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; -import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.OrderPriority; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.function.Function; - -/** - * 静态的扩展初始化器 - * - * @author starBlues - * @version 2.4.0 - */ -public class ExtensionInitializer { - - - private static final Logger LOG = LoggerFactory.getLogger(ExtensionInitializer.class); - - private static final AtomicBoolean IS_INIT = new AtomicBoolean(false); - - private static final List RESOURCE_LOADERS_EXTENDS = new ArrayList<>(); - private static final List PIPE_PROCESSOR_EXTENDS = new ArrayList<>(); - private static final List BEAN_REGISTRAR_EXTEND = new ArrayList<>(); - private static final List CLASS_GROUP_EXTENDS = new ArrayList<>(); - private static final List PRE_PROCESSOR_EXTENDS = new ArrayList<>(); - private static final List POST_PROCESSOR_EXTENDS = new ArrayList<>(); - - private ExtensionInitializer(){ - - } - - - public static synchronized void initialize(ApplicationContext applicationContext){ - if(applicationContext == null){ - LOG.error("ApplicationContext is null, cannot initialize"); - return; - } - if(IS_INIT.get()){ - throw new RuntimeException("The extension has been initialized"); - } - Map pluginExtension = ExtensionFactory.getPluginExtension(); - for (Map.Entry entry : pluginExtension.entrySet()){ - AbstractExtension abstractExtension = entry.getValue(); - if(abstractExtension == null){ - continue; - } - try { - abstractExtension.initialize(applicationContext); - initialize(abstractExtension, applicationContext); - } catch (Exception e) { - LOG.error("Plugin extension '{}' initialize exception. {}", abstractExtension.key(), e.getMessage(), e); - } - } - IS_INIT.set(true); - } - - private static void initialize(AbstractExtension abstractExtension, ApplicationContext applicationContext){ - StringBuilder debug = new StringBuilder(); - debug.append("Plugin extension '").append(abstractExtension.key()).append("'") - .append(" are ["); - iteration(abstractExtension.getPluginResourceLoader(), extend->{ - RESOURCE_LOADERS_EXTENDS.add(extend); - debug.append(extend.key()).append("、"); - }, bean -> bean.order()); - - iteration(abstractExtension.getPluginPreProcessor(applicationContext), extend->{ - PRE_PROCESSOR_EXTENDS.add(extend); - debug.append(extend.key()).append("、"); - }, bean -> bean.order()); - - iteration(abstractExtension.getPluginBeanRegistrar(applicationContext), extend->{ - BEAN_REGISTRAR_EXTEND.add(extend); - debug.append(extend.key()).append("、"); - }, null); - - iteration(abstractExtension.getPluginPipeProcessor(applicationContext), extend->{ - PIPE_PROCESSOR_EXTENDS.add(extend); - debug.append(extend.key()).append("、"); - }, bean -> bean.order()); - - iteration(abstractExtension.getPluginClassGroup(applicationContext), extend->{ - CLASS_GROUP_EXTENDS.add(extend); - debug.append(extend.key()).append("、"); - }, null); - - iteration(abstractExtension.getPluginPostProcessor(applicationContext), extend->{ - POST_PROCESSOR_EXTENDS.add(extend); - debug.append(extend.key()); - }, bean -> bean.order()); - - debug.append("] is registered"); - LOG.info("Plugin extension '{}' is registered", abstractExtension.key()); - LOG.debug(debug.toString()); - } - - - public static List getResourceLoadersExtends() { - return RESOURCE_LOADERS_EXTENDS; - } - - public static List getPreProcessorExtends() { - return PRE_PROCESSOR_EXTENDS; - } - - public static List getPipeProcessorExtends() { - return PIPE_PROCESSOR_EXTENDS; - } - - public static List getPluginBeanRegistrarExtends() { - return BEAN_REGISTRAR_EXTEND; - } - - public static List getClassGroupExtends() { - return CLASS_GROUP_EXTENDS; - } - - public static List getPostProcessorExtends() { - return POST_PROCESSOR_EXTENDS; - } - - /** - * 迭代器 - * @param list 当前处理的集合 - * @param consumer 消费集合中的数据项 - * @param order 排序集合。传入 null 表示不需要排序 - */ - private static void iteration(List list, Consumer consumer, final Function order){ - if(list == null || list.isEmpty()){ - return; - } - if(order != null){ - list.stream() - .filter(t -> t != null) - .sorted(CommonUtils.orderPriority(order)) - .forEach(consumer); - ; - } else { - for (T t : list) { - if(t != null){ - consumer.accept(t); - } - } - } - } - - -} +//package com.gitee.starblues.extension; +// +//import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; +//import com.gitee.starblues.factory.process.pipe.PluginPreProcessorExtend; +//import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; +//import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; +//import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; +//import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; +//import com.gitee.starblues.utils.CommonUtils; +//import com.gitee.starblues.utils.OrderPriority; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.context.ApplicationContext; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Map; +//import java.util.concurrent.atomic.AtomicBoolean; +//import java.util.function.Consumer; +//import java.util.function.Function; +// +///** +// * 静态的扩展初始化器 +// * +// * @author starBlues +// * @version 2.4.0 +// */ +//public class ExtensionInitializer { +// +// +// private static final Logger LOG = LoggerFactory.getLogger(ExtensionInitializer.class); +// +// private static final AtomicBoolean IS_INIT = new AtomicBoolean(false); +// +// private static final List RESOURCE_LOADERS_EXTENDS = new ArrayList<>(); +// private static final List PIPE_PROCESSOR_EXTENDS = new ArrayList<>(); +// private static final List BEAN_REGISTRAR_EXTEND = new ArrayList<>(); +// private static final List CLASS_GROUP_EXTENDS = new ArrayList<>(); +// private static final List PRE_PROCESSOR_EXTENDS = new ArrayList<>(); +// private static final List POST_PROCESSOR_EXTENDS = new ArrayList<>(); +// +// private ExtensionInitializer(){ +// +// } +// +// +// public static synchronized void initialize(ApplicationContext applicationContext){ +// if(applicationContext == null){ +// LOG.error("ApplicationContext is null, cannot initialize"); +// return; +// } +// if(IS_INIT.get()){ +// throw new RuntimeException("The extension has been initialized"); +// } +// Map pluginExtension = ExtensionFactory.getPluginExtension(); +// for (Map.Entry entry : pluginExtension.entrySet()){ +// AbstractExtension abstractExtension = entry.getValue(); +// if(abstractExtension == null){ +// continue; +// } +// try { +// abstractExtension.initialize(applicationContext); +// initialize(abstractExtension, applicationContext); +// } catch (Exception e) { +// LOG.error("Plugin extension '{}' initialize exception. {}", abstractExtension.key(), e.getMessage(), e); +// } +// } +// IS_INIT.set(true); +// } +// +// private static void initialize(AbstractExtension abstractExtension, ApplicationContext applicationContext){ +// StringBuilder debug = new StringBuilder(); +// debug.append("Plugin extension '").append(abstractExtension.key()).append("'") +// .append(" are ["); +// iteration(abstractExtension.getPluginResourceLoader(), extend->{ +// RESOURCE_LOADERS_EXTENDS.add(extend); +// debug.append(extend.key()).append("、"); +// }, bean -> bean.order()); +// +// iteration(abstractExtension.getPluginPreProcessor(applicationContext), extend->{ +// PRE_PROCESSOR_EXTENDS.add(extend); +// debug.append(extend.key()).append("、"); +// }, bean -> bean.order()); +// +// iteration(abstractExtension.getPluginBeanRegistrar(applicationContext), extend->{ +// BEAN_REGISTRAR_EXTEND.add(extend); +// debug.append(extend.key()).append("、"); +// }, null); +// +// iteration(abstractExtension.getPluginPipeProcessor(applicationContext), extend->{ +// PIPE_PROCESSOR_EXTENDS.add(extend); +// debug.append(extend.key()).append("、"); +// }, bean -> bean.order()); +// +// iteration(abstractExtension.getPluginClassGroup(applicationContext), extend->{ +// CLASS_GROUP_EXTENDS.add(extend); +// debug.append(extend.key()).append("、"); +// }, null); +// +// iteration(abstractExtension.getPluginPostProcessor(applicationContext), extend->{ +// POST_PROCESSOR_EXTENDS.add(extend); +// debug.append(extend.key()); +// }, bean -> bean.order()); +// +// debug.append("] is registered"); +// LOG.info("Plugin extension '{}' is registered", abstractExtension.key()); +// LOG.debug(debug.toString()); +// } +// +// +// public static List getResourceLoadersExtends() { +// return RESOURCE_LOADERS_EXTENDS; +// } +// +// public static List getPreProcessorExtends() { +// return PRE_PROCESSOR_EXTENDS; +// } +// +// public static List getPipeProcessorExtends() { +// return PIPE_PROCESSOR_EXTENDS; +// } +// +// public static List getPluginBeanRegistrarExtends() { +// return BEAN_REGISTRAR_EXTEND; +// } +// +// public static List getClassGroupExtends() { +// return CLASS_GROUP_EXTENDS; +// } +// +// public static List getPostProcessorExtends() { +// return POST_PROCESSOR_EXTENDS; +// } +// +// /** +// * 迭代器 +// * @param list 当前处理的集合 +// * @param consumer 消费集合中的数据项 +// * @param order 排序集合。传入 null 表示不需要排序 +// */ +// private static void iteration(List list, Consumer consumer, final Function order){ +// if(list == null || list.isEmpty()){ +// return; +// } +// if(order != null){ +// list.stream() +// .filter(t -> t != null) +// .sorted(CommonUtils.orderPriority(order)) +// .forEach(consumer); +// ; +// } else { +// for (T t : list) { +// if(t != null){ +// consumer.accept(t); +// } +// } +// } +// } +// +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java index a5738b2..71e6b69 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java @@ -1,36 +1,36 @@ -package com.gitee.starblues.extension; - - -import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; - -import java.util.List; - -/** - * 可扩展的 controller 处理者 - * - * @author starBlues - * @version 2.4.0 - */ -public interface PluginControllerProcessorExtend { - - /** - * 初始化 - */ - void initialize(); - - /** - * 注册 - * @param pluginId 插件id - * @param controllerWrappers controller 类集合 - * @throws Exception 异常 - */ - void registry(String pluginId, List controllerWrappers) throws Exception; - - /** - * 注册 - * @param pluginId 插件id - * @param controllerWrappers controller 类集合 - * @throws Exception 异常 - */ - void unRegistry(String pluginId, List controllerWrappers) throws Exception; -} +//package com.gitee.starblues.extension; +// +// +//import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; +// +//import java.util.List; +// +///** +// * 可扩展的 controller 处理者 +// * +// * @author starBlues +// * @version 2.4.0 +// */ +//public interface PluginControllerProcessorExtend { +// +// /** +// * 初始化 +// */ +// void initialize(); +// +// /** +// * 注册 +// * @param pluginId 插件id +// * @param controllerWrappers controller 类集合 +// * @throws Exception 异常 +// */ +// void registry(String pluginId, List controllerWrappers) throws Exception; +// +// /** +// * 注册 +// * @param pluginId 插件id +// * @param controllerWrappers controller 类集合 +// * @throws Exception 异常 +// */ +// void unRegistry(String pluginId, List controllerWrappers) throws Exception; +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java index b8c962c..e15f7bb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java @@ -1,71 +1,71 @@ -package com.gitee.starblues.extension.support; - -import com.gitee.starblues.extension.PluginControllerProcessorExtend; -import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.springdoc.api.AbstractOpenApiResource; -import org.springdoc.core.OpenAPIService; -import org.springframework.context.ApplicationContext; - -import java.util.List; - -/** - * @author starBlues - * @version 2.4.0 - */ -public class SpringDocControllerProcessor implements PluginControllerProcessorExtend { - - private final ApplicationContext applicationContext; - - private List> restControllers; - private OpenAPIService openAPIService; - - public SpringDocControllerProcessor(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - - @Override - public void initialize() { - AbstractOpenApiResource openApiResource = SpringBeanUtils.getExistBean(applicationContext, AbstractOpenApiResource.class); - if(openApiResource == null){ - return; - } - try { - restControllers = ClassUtils.getReflectionField(openApiResource, - "ADDITIONAL_REST_CONTROLLERS"); - } catch (IllegalAccessException e) { - restControllers = null; - } - openAPIService = SpringBeanUtils.getExistBean(applicationContext, OpenAPIService.class); - } - - @Override - public void registry(String pluginId, List controllerWrappers) throws Exception { - if(restControllers != null){ - for (ControllerWrapper controllerWrapper : controllerWrappers) { - restControllers.add(controllerWrapper.getBeanClass()); - } - refresh(); - } - } - - @Override - public void unRegistry(String pluginId, List controllerWrappers) throws Exception { - if(restControllers != null && !restControllers.isEmpty()){ - for (ControllerWrapper controllerWrapper : controllerWrappers) { - restControllers.remove(controllerWrapper.getBeanClass()); - } - refresh(); - } - } - - private void refresh(){ - if(openAPIService != null){ - openAPIService.setCachedOpenAPI(null); - openAPIService.resetCalculatedOpenAPI(); - } - } - -} +//package com.gitee.starblues.extension.support; +// +//import com.gitee.starblues.extension.PluginControllerProcessorExtend; +//import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; +//import com.gitee.starblues.utils.ClassUtils; +//import com.gitee.starblues.utils.SpringBeanUtils; +//import org.springdoc.api.AbstractOpenApiResource; +//import org.springdoc.core.OpenAPIService; +//import org.springframework.context.ApplicationContext; +// +//import java.util.List; +// +///** +// * @author starBlues +// * @version 2.4.0 +// */ +//public class SpringDocControllerProcessor implements PluginControllerProcessorExtend { +// +// private final ApplicationContext applicationContext; +// +// private List> restControllers; +// private OpenAPIService openAPIService; +// +// public SpringDocControllerProcessor(ApplicationContext applicationContext) { +// this.applicationContext = applicationContext; +// } +// +// +// @Override +// public void initialize() { +// AbstractOpenApiResource openApiResource = SpringBeanUtils.getExistBean(applicationContext, AbstractOpenApiResource.class); +// if(openApiResource == null){ +// return; +// } +// try { +// restControllers = ClassUtils.getReflectionField(openApiResource, +// "ADDITIONAL_REST_CONTROLLERS"); +// } catch (IllegalAccessException e) { +// restControllers = null; +// } +// openAPIService = SpringBeanUtils.getExistBean(applicationContext, OpenAPIService.class); +// } +// +// @Override +// public void registry(String pluginId, List controllerWrappers) throws Exception { +// if(restControllers != null){ +// for (ControllerWrapper controllerWrapper : controllerWrappers) { +// restControllers.add(controllerWrapper.getBeanClass()); +// } +// refresh(); +// } +// } +// +// @Override +// public void unRegistry(String pluginId, List controllerWrappers) throws Exception { +// if(restControllers != null && !restControllers.isEmpty()){ +// for (ControllerWrapper controllerWrapper : controllerWrappers) { +// restControllers.remove(controllerWrapper.getBeanClass()); +// } +// refresh(); +// } +// } +// +// private void refresh(){ +// if(openAPIService != null){ +// openAPIService.setCachedOpenAPI(null); +// openAPIService.resetCalculatedOpenAPI(); +// } +// } +// +//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/DefaultPluginFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/DefaultPluginFactory.java deleted file mode 100644 index 5651f39..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/DefaultPluginFactory.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.gitee.starblues.factory; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessor; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorFactory; -import com.gitee.starblues.factory.process.post.PluginPostProcessor; -import com.gitee.starblues.factory.process.post.PluginPostProcessorFactory; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.integration.listener.PluginListener; -import com.gitee.starblues.integration.listener.PluginListenerFactory; -import com.gitee.starblues.integration.listener.SwaggerListeningListener; -import org.pf4j.PluginWrapper; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * 默认的插件处理者 - * - * @author starBlues - * @version 2.4.4 - */ -public class DefaultPluginFactory implements PluginFactory { - - - /** - * 注册的插件集合 - */ - private final Map registerPluginInfoMap = new HashMap<>(); - private final GenericApplicationContext applicationContext; - private final PluginPipeProcessor pluginPipeProcessor; - private final PluginPostProcessor pluginPostProcessor; - private final PluginListenerFactory pluginListenerFactory; - private final IntegrationConfiguration configuration; - - /** - * 0表示build、1 表示注册、2表示卸载 - */ - private Integer buildType = 0; - private final List buildContainer = new ArrayList<>(); - - public DefaultPluginFactory(ApplicationContext applicationContext) { - this(applicationContext, null); - } - - - public DefaultPluginFactory(ApplicationContext applicationContext, - PluginListenerFactory pluginListenerFactory) { - this.applicationContext = (GenericApplicationContext) applicationContext; - this.pluginPipeProcessor = new PluginPipeProcessorFactory(applicationContext); - this.pluginPostProcessor = new PluginPostProcessorFactory(applicationContext); - - if(pluginListenerFactory == null){ - this.pluginListenerFactory = new PluginListenerFactory(); - } else { - this.pluginListenerFactory = pluginListenerFactory; - } - configuration = applicationContext.getBean(IntegrationConfiguration.class); - } - - - @Override - public void initialize() throws Exception{ - // 新增默认监听者 - addDefaultPluginListener(); - pluginPipeProcessor.initialize(); - pluginPostProcessor.initialize(); - } - - @Override - public synchronized PluginFactory registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - if(pluginRegistryInfo == null){ - throw new IllegalArgumentException("Parameter:pluginRegistryInfo cannot be null"); - } - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - if(registerPluginInfoMap.containsKey(pluginWrapper.getPluginId())){ - throw new IllegalAccessException("The plugin '" - + pluginWrapper.getPluginId() +"' already exists, Can't register"); - } - if(!buildContainer.isEmpty() && buildType == 2){ - throw new IllegalAccessException("Unable to Registry operate. Because there's no build"); - } - try { - pluginPipeProcessor.registry(pluginRegistryInfo); - registerPluginInfoMap.put(pluginWrapper.getPluginId(), pluginRegistryInfo); - buildContainer.add(pluginRegistryInfo); - return this; - } catch (Exception e) { - pluginListenerFactory.registryFailure(pluginWrapper.getPluginId(), e); - throw e; - } finally { - buildType = 1; - } - } - - @Override - public synchronized PluginFactory unRegistry(String pluginId) throws Exception { - PluginRegistryInfo registerPluginInfo = registerPluginInfoMap.get(pluginId); - if(registerPluginInfo == null){ - throw new Exception("Not found plugin '" + pluginId + "' registered"); - } - if(!buildContainer.isEmpty() && buildType == 1){ - throw new Exception("Unable to UnRegistry operate. Because there's no build"); - } - try { - pluginPipeProcessor.unRegistry(registerPluginInfo); - buildContainer.add(registerPluginInfo); - return this; - } catch (Exception e) { - registerPluginInfo.destroy(); - pluginListenerFactory.unRegistryFailure(pluginId, e); - throw e; - } finally { - registerPluginInfoMap.remove(pluginId); - buildType = 2; - } - } - - - - @Override - public synchronized void build() throws Exception { - if(buildContainer.isEmpty()){ - return; - } - // 构建注册的Class插件监听者 - pluginListenerFactory.buildListenerClass(applicationContext); - try { - if(buildType == 1){ - registryBuild(); - } else { - unRegistryBuild(); - } - } finally { - if(buildType != 1){ - for (PluginRegistryInfo pluginRegistryInfo : buildContainer) { - pluginRegistryInfo.destroy(); - } - } - buildContainer.clear(); - buildType = 0; - } - } - - - - @Override - public void addListener(PluginListener pluginListener) { - pluginListenerFactory.addPluginListener(pluginListener); - } - - @Override - public void addListener(Class pluginListenerClass) { - pluginListenerFactory.addPluginListener(pluginListenerClass); - } - - @Override - public void addListener(List pluginListeners) { - if(pluginListeners != null){ - for (PluginListener pluginListener : pluginListeners) { - pluginListenerFactory.addPluginListener(pluginListener); - } - } - } - - /** - * 注册build - */ - private void registryBuild() throws Exception { - pluginPostProcessor.registry(buildContainer); - for (PluginRegistryInfo pluginRegistryInfo : buildContainer) { - pluginListenerFactory.registry( - pluginRegistryInfo.getPluginWrapper().getPluginId(), - pluginRegistryInfo.isFollowingInitial()); - } - } - - /** - * 卸载build - */ - private void unRegistryBuild() throws Exception { - pluginPostProcessor.unRegistry(buildContainer); - for (PluginRegistryInfo pluginRegistryInfo : buildContainer) { - pluginListenerFactory.unRegistry(pluginRegistryInfo.getPluginWrapper().getPluginId()); - } - } - - - - /** - * 添加默认插件监听者 - */ - private void addDefaultPluginListener(){ - if(configuration.enableSwaggerRefresh()){ - pluginListenerFactory.addPluginListener(new SwaggerListeningListener(applicationContext)); - } - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginFactory.java deleted file mode 100644 index 90b4212..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.gitee.starblues.factory; - -import com.gitee.starblues.integration.PluginListenerContext; -import org.pf4j.PluginWrapper; - - -/** - * 插件注册者接口 - * - * @author starBlues - * @version 2.4.0 - */ -public interface PluginFactory extends PluginListenerContext { - - /** - * 工厂初始化 - * @throws Exception 初始化异常 - */ - void initialize() throws Exception; - - - /** - * 注册插件。 - * @param pluginRegistryInfo 插件注册信息 - * @return 插件工厂 - * @throws Exception 插件工厂异常 - */ - PluginFactory registry(PluginRegistryInfo pluginRegistryInfo) throws Exception; - - - /** - * 注销插件。 - * @param pluginId 插件id - * @return 插件工厂 - * @throws Exception 插件工厂异常 - */ - PluginFactory unRegistry(String pluginId) throws Exception; - - - /** - * 注册或者注销后的构建调用 - * @throws Exception 插件工厂异常 - */ - void build() throws Exception; -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginRegistryInfo.java deleted file mode 100644 index 95cbb0d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PluginRegistryInfo.java +++ /dev/null @@ -1,346 +0,0 @@ -package com.gitee.starblues.factory; - -import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; -import com.gitee.starblues.factory.process.pipe.loader.ResourceWrapper; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.realize.BasePlugin; -import org.pf4j.PluginManager; -import org.pf4j.PluginWrapper; -import org.pf4j.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 注册的插件信息 - * - * @author starBlues - * @version 2.4.1 - */ -public class PluginRegistryInfo { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final PluginWrapper pluginWrapper; - private final PluginManager pluginManager; - private final IntegrationConfiguration configuration; - private final GenericApplicationContext mainApplicationContext; - private final AnnotationConfigApplicationContext pluginApplicationContext; - private final Binder pluginBinder; - private final SpringBeanRegister springBeanRegister; - - /** - * 是否跟随主程序启动而初始化 - */ - private final boolean followingInitial; - private final BasePlugin basePlugin; - - - /** - * 扩展存储项 - */ - private final Map extensionMap = new ConcurrentHashMap<>(); - - /** - * 插件中的配置单例bean - */ - private final Set configSingletonObjects = new HashSet<>(4); - - /** - * 插件中的Class - */ - private final List> classes = new ArrayList<>(8); - - /** - * 插件加载的资源 - */ - private final Map pluginLoadResources = new ConcurrentHashMap<>(8); - - /** - * 插件中分类的Class - */ - private final Map>> groupClasses = new ConcurrentHashMap<>(8); - - /** - * 处理者信息 - */ - private final Map processorInfo = new ConcurrentHashMap<>(8); - - - private PluginRegistryInfo(PluginWrapper pluginWrapper, - PluginManager pluginManager, - GenericApplicationContext mainApplicationContext, - boolean followingInitial) { - this.pluginWrapper = pluginWrapper; - this.pluginManager = pluginManager; - this.basePlugin = (BasePlugin) pluginWrapper.getPlugin(); - this.mainApplicationContext = mainApplicationContext; - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - this.followingInitial = followingInitial; - - ClassLoader pluginClassLoader = basePlugin.getWrapper().getPluginClassLoader(); - // 生成插件ApplicationContext-DefaultListableBeanFactory - DefaultListableBeanFactory defaultListableBeanFactory = new DefaultListableBeanFactory(); - this.pluginApplicationContext = new AnnotationConfigApplicationContext(defaultListableBeanFactory); - // 设置插件ApplicationContext的classLoader - this.pluginApplicationContext.setClassLoader(pluginClassLoader); - - this.pluginBinder = Binder.get(this.pluginApplicationContext.getEnvironment()); - this.springBeanRegister = new SpringBeanRegister(pluginApplicationContext); - } - - public static PluginRegistryInfo build(PluginWrapper pluginWrapper, - PluginManager pluginManager, - GenericApplicationContext parentApplicationContext, - boolean followingInitial){ - Objects.requireNonNull(pluginWrapper, "PluginWrapper can't is null"); - Objects.requireNonNull(pluginWrapper, "PluginManager can't is null"); - Objects.requireNonNull(pluginWrapper, "parentApplicationContext can't is null"); - return new PluginRegistryInfo(pluginWrapper, pluginManager, - parentApplicationContext, followingInitial); - } - - - public PluginWrapper getPluginWrapper() { - return pluginWrapper; - } - - public BasePlugin getBasePlugin() { - return basePlugin; - } - - /** - * 添加类到类集合容器 - * @param aClass 类 - */ - public void addClasses(Class aClass){ - if(aClass != null){ - classes.add(aClass); - } - } - - /** - * 清除类集合容器 - */ - public void cleanClasses(){ - classes.clear(); - } - - /** - * 得到类集合容器 - * @return 类集合容器 - */ - public List> getClasses(){ - return Collections.unmodifiableList(classes); - } - - /** - * 添加插件中加载的资源 - * @param key key - * @param resourceWrapper 资源包装者 - */ - public void addPluginLoadResource(String key, ResourceWrapper resourceWrapper){ - if(StringUtils.isNullOrEmpty(key)){ - return; - } - if(resourceWrapper == null){ - return; - } - pluginLoadResources.put(key, resourceWrapper); - } - - /** - * 得到插件中加载的资源 - * @param key 资源key - * @return ResourceWrapper - */ - public ResourceWrapper getPluginLoadResource(String key) { - return pluginLoadResources.get(key); - } - - /** - * 添加分组的类型 - * @param key 分组key - * @param aClass 类 - */ - public void addGroupClasses(String key, Class aClass){ - if(StringUtils.isNullOrEmpty(key)){ - return; - } - if(aClass == null){ - return; - } - List> classes = groupClasses.computeIfAbsent(key, k -> new ArrayList<>()); - classes.add(aClass); - } - - /** - * 通过分组key得到分组中的类类型 - * @param key 处理者key - * @return 类类型集合 - */ - public List> getGroupClasses(String key){ - List> classes = groupClasses.get(key); - List> result = new ArrayList<>(); - if(classes != null){ - result.addAll(classes); - } - return result; - } - - /** - * 得到插件bean注册者信息 - * @param key 扩展的key - * @param 处理者类型 - * @return 注册者信息 - */ - public T getProcessorInfo(String key){ - Object o = processorInfo.get(key); - if(o != null){ - return (T) o; - } - return null; - } - - /** - * 添加插件中的配置对象 - * @param singletonObject 单例对象 - */ - public void addConfigSingleton(Object singletonObject){ - configSingletonObjects.add(singletonObject); - } - - /** - * 添加插件中的配置对象 - * @return 配置的实现对象 - */ - public Set getConfigSingletons(){ - return Collections.unmodifiableSet(configSingletonObjects); - } - - /** - * 添加处理者信息 - * @param key key - * @param value value - */ - public void addProcessorInfo(String key, Object value){ - processorInfo.put(key, value); - } - - /** - * 添加扩展数据 - * @param key 扩展的key - * @param value 扩展值 - */ - public void addExtension(String key, Object value){ - if(extensionMap.containsKey(key)){ - throw new RuntimeException("The extension key ' " + key + " 'already exists"); - } - extensionMap.put(key, value); - } - - /** - * 得到主程序的ApplicationContext - * @return GenericApplicationContext - */ - public GenericApplicationContext getMainApplicationContext() { - return mainApplicationContext; - } - - /** - * 得到当前插件的ApplicationContext - * @return AnnotationConfigApplicationContext - */ - public GenericApplicationContext getPluginApplicationContext() { - return pluginApplicationContext; - } - - /** - * 得到当前插件的Binder - * @return Binder - */ - public Binder getPluginBinder() { - return pluginBinder; - } - - /** - * 得到当前插件Bean注册者 - * @return SpringBeanRegister - */ - public SpringBeanRegister getSpringBeanRegister() { - return springBeanRegister; - } - - /** - * 移除扩展数据 - * @param key 扩展的key - */ - public void removeExtension(String key){ - extensionMap.remove(key); - } - - /** - * 获取扩展值 - * @param key 扩展的key - * @param 返回值泛型 - * @return 扩展值 - */ - public T getExtension(String key){ - Object o = extensionMap.get(key); - if(o == null){ - return null; - } else { - return (T) o; - } - } - - public ClassLoader getPluginClassLoader(){ - return pluginWrapper.getPluginClassLoader(); - } - - public boolean isFollowingInitial() { - return followingInitial; - } - - public IntegrationConfiguration getConfiguration() { - return configuration; - } - - void destroy(){ - // 关闭ApplicationContext - try { - PluginInfoContainers.removePluginApplicationContext(getPluginWrapper().getPluginId()); - closePluginApplicationContext(); - } catch (Exception e){ - logger.error("Close plugin '{}'-ApplicationContext failure", getPluginWrapper().getPluginId(), e); - } - - // 清除数据集合 - try { - extensionMap.clear(); - classes.clear(); - groupClasses.clear(); - processorInfo.clear(); - pluginLoadResources.clear(); - configSingletonObjects.clear(); - } catch (Exception e){ - logger.error("Clear plugin '{}' failure", getPluginWrapper().getPluginId(), e); - } - } - - private void closePluginApplicationContext() { - try { - getSpringBeanRegister().destroySingletons(); - pluginApplicationContext.close(); - } catch (Exception e){ - logger.error("Close plugin '{}' ApplicationContext failure", getPluginWrapper().getPluginId(), e); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PropertyKey.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PropertyKey.java deleted file mode 100644 index c969208..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/PropertyKey.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.gitee.starblues.factory; - -/** - * 配置文件key - * @author starBlues - * @version 2.4.3 - */ -public class PropertyKey { - - public final static String INSTALL_AUTO_CONFIG_CLASS = "plugin.auto-config-class"; - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/SpringBeanRegister.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/SpringBeanRegister.java deleted file mode 100644 index 2557254..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/SpringBeanRegister.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.gitee.starblues.factory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.annotation.AnnotationBeanNameGenerator; -import org.springframework.context.support.GenericApplicationContext; - -import java.text.MessageFormat; -import java.util.function.Consumer; - -/** - * Spring bean注册者, 向Spring注册Bean时, 必须使用该对象进行注册 - * - * @author starBlues - * @version 2.4.1 - */ -public class SpringBeanRegister { - - private static final Logger logger = LoggerFactory.getLogger(SpringBeanRegister.class); - - private final GenericApplicationContext applicationContext; - - public SpringBeanRegister(GenericApplicationContext applicationContext){ - this.applicationContext = applicationContext; - } - - - public boolean exist(String name){ - return applicationContext.containsBean(name); - } - - - /** - * 基于class注册一个bean - * - * @param aClass 类名 - * @return 注册的bean名称 - */ - public String register(Class aClass) { - return register(aClass, null); - } - - - /** - * 基于class注册一个bean - * - * @param pluginId 插件id - * @param aClass 类名 - * @return 注册的bean名称 - */ - @Deprecated - public String register(String pluginId, Class aClass) { - return register(pluginId, aClass, null); - } - - - /** - * 基于class注册一个bean, 可自定义 BeanDefinition - * - * @param aClass 注册的类 - * @param consumer 自定义处理AnnotatedGenericBeanDefinition - * @return 注册的bean名称 - */ - public String register(Class aClass, - Consumer consumer) { - AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(aClass); - beanDefinition.setBeanClass(aClass); - BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator(); - String beanName = beanNameGenerator.generateBeanName(beanDefinition, applicationContext); - - if(applicationContext.containsBean(beanName)){ - String error = MessageFormat.format("Bean name {0} already exist of {1}", - beanName, aClass.getName()); - logger.debug(error); - return beanName; - } - if(consumer != null){ - consumer.accept(beanDefinition); - } - applicationContext.registerBeanDefinition(beanName, beanDefinition); - return beanName; - } - - - /** - * 基于class注册一个bean, 可自定义 BeanDefinition - * - * @param pluginId 插件id - * @param aClass 注册的类 - * @param consumer 自定义处理AnnotatedGenericBeanDefinition - * @return 注册的bean名称 - */ - @Deprecated - public String register(String pluginId, Class aClass, - Consumer consumer) { - return register(aClass, consumer); - } - - /** - * 指定bean名称注册 - * @param beanName 指定的bean名称 - * @param aClass 注册的类 - */ - public void registerOfSpecifyName(String beanName, Class aClass){ - registerOfSpecifyName(beanName, aClass, null); - } - - /** - * 指定bean名称注册 - * @param pluginId 插件id - * @param beanName 指定的bean名称 - * @param aClass 注册的类 - */ - @Deprecated - public void registerOfSpecifyName(String pluginId, String beanName, Class aClass){ - registerOfSpecifyName(pluginId, beanName, aClass, null); - } - - - /** - * 指定bean名称注册, 可自定义 BeanDefinition - * @param beanName 指定的bean名称 - * @param aClass 注册的类 - * @param consumer 自定义处理AnnotatedGenericBeanDefinition - */ - public void registerOfSpecifyName(String beanName, - Class aClass, - Consumer consumer) { - AnnotatedGenericBeanDefinition beanDefinition = new - AnnotatedGenericBeanDefinition(aClass); - if(applicationContext.containsBean(beanName)){ - String error = MessageFormat.format("Bean name {0} already exist of {1}", - beanName, aClass.getName()); - throw new RuntimeException(error); - } - if(consumer != null){ - consumer.accept(beanDefinition); - } - applicationContext.registerBeanDefinition(beanName, beanDefinition); - } - - - /** - * 指定bean名称注册, 可自定义 BeanDefinition - * @param pluginId 插件id - * @param beanName 指定的bean名称 - * @param aClass 注册的类 - * @param consumer 自定义处理AnnotatedGenericBeanDefinition - */ - @Deprecated - public void registerOfSpecifyName(String pluginId, - String beanName, - Class aClass, - Consumer consumer) { - registerOfSpecifyName(beanName, aClass, consumer); - } - - /** - * 注册单例 - * @param name 单例名称 - * @param object 对象 - */ - public void registerSingleton(String name, Object object){ - DefaultListableBeanFactory listableBeanFactory = applicationContext.getDefaultListableBeanFactory(); - if(!listableBeanFactory.containsSingleton(name)){ - listableBeanFactory.registerSingleton(name, object); - } - } - - /** - * 注册BeanDefinitionHolder - * @param definitionHolder BeanDefinitionHolder - */ - public void registerBeanDefinition(BeanDefinitionHolder definitionHolder) { - - String beanName = definitionHolder.getBeanName(); - applicationContext.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); - - String[] aliases = definitionHolder.getAliases(); - if (aliases != null) { - for (String alias : aliases) { - applicationContext.registerAlias(beanName, alias); - } - } - } - - /** - * 销毁单例 - * @param name 单例名称 - */ - public void destroySingleton(String name){ - DefaultListableBeanFactory listableBeanFactory = applicationContext.getDefaultListableBeanFactory(); - if(listableBeanFactory.containsSingleton(name)){ - listableBeanFactory.destroySingleton(name); - } - } - - /** - * 销毁所有单例 - */ - public void destroySingletons(){ - DefaultListableBeanFactory listableBeanFactory = applicationContext.getDefaultListableBeanFactory(); - listableBeanFactory.destroySingletons(); - } - - /** - * 卸载bean - * @param pluginId 插件id - * @param beanName bean名称 - */ - public void unregister(String pluginId, String beanName){ - try { - applicationContext.removeBeanDefinition(beanName); - } catch (Exception e){ - logger.error("Remove plugin '{}' bean {} error. {}", pluginId, beanName, e.getMessage()); - } - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginConfigBeanPipeProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginConfigBeanPipeProcessor.java deleted file mode 100644 index 39a4646..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginConfigBeanPipeProcessor.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.realize.ConfigBean; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author starBlues - * @version 2.4.0 - */ -public class PluginConfigBeanPipeProcessor implements PluginPipeProcessor{ - - private final static String KEY = "ConfigBeans"; - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List pluginBeans = SpringBeanUtils.getBeans(pluginRegistryInfo.getPluginApplicationContext(), - ConfigBean.class); - if(pluginBeans.isEmpty()){ - return; - } - List successConfigBeans = new ArrayList<>(pluginBeans.size()); - for (ConfigBean pluginBean : pluginBeans) { - try { - pluginBean.initialize(); - successConfigBeans.add(pluginBean); - } catch (Exception e){ - logger.error("Plugin '{}' configBean '{}' initialize exception.", - pluginRegistryInfo.getPluginWrapper().getPluginId(), - pluginBean.getClass().getName(), e); - } - } - pluginRegistryInfo.addExtension(KEY, successConfigBeans); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List pluginBeans = pluginRegistryInfo.getExtension(KEY); - if(pluginBeans == null || pluginBeans.isEmpty()){ - return; - } - for (ConfigBean pluginBean : pluginBeans) { - try { - pluginBean.destroy(); - } catch (Exception e){ - logger.error("Plugin '{}' configBean '{}' destroy exception.", - pluginRegistryInfo.getPluginWrapper().getPluginId(), - pluginBean.getClass().getName(), e); - } - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java deleted file mode 100644 index 7c482e1..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInfoContainers.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 插件信息容器 - * @author starBlues - * @version 2.4.0 - */ -@Deprecated -public class PluginInfoContainers { - - private final static Map PLUGIN_APPLICATION_CONTEXTS = - new ConcurrentHashMap<>(); - - public static void addPluginApplicationContext(String pluginId, ConfigurableApplicationContext applicationContext){ - PLUGIN_APPLICATION_CONTEXTS.put(pluginId, applicationContext); - } - - public static void removePluginApplicationContext(String pluginId){ - PLUGIN_APPLICATION_CONTEXTS.remove(pluginId); - } - - static public ConfigurableApplicationContext getPluginApplicationContext(String pluginId) { - ConfigurableApplicationContext applicationContext = PLUGIN_APPLICATION_CONTEXTS.get(pluginId); - if(applicationContext == null){ - return null; - } - return applicationContext; - } - - static public List getPluginApplicationContexts() { - Collection values = PLUGIN_APPLICATION_CONTEXTS.values(); - if(values.isEmpty()){ - return new ArrayList<>(); - } - return new ArrayList<>(values); - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java deleted file mode 100644 index fa628e9..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginInterceptorsPipeProcessor.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegister; -import com.gitee.starblues.spring.processor.interceptor.PluginInterceptorRegistry; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.web.context.request.WebRequestInterceptor; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.handler.AbstractHandlerMapping; -import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter; - -import java.util.ArrayList; -import java.util.List; - -/** - * 插件 SpringMVC 拦截器的处理 - * @author starBlues - * @version 2.4.1 - */ -public class PluginInterceptorsPipeProcessor implements PluginPipeProcessor{ - - private final ApplicationContext mainApplicationContext; - private final IntegrationConfiguration configuration; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final static String INTERCEPTORS = "interceptors"; - - private AbstractHandlerMapping handlerMapping; - - - public PluginInterceptorsPipeProcessor(ApplicationContext mainApplicationContext){ - this.mainApplicationContext = mainApplicationContext; - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - } - - @Override - public void initialize() throws Exception { - handlerMapping = SpringBeanUtils.getExistBean(mainApplicationContext, - AbstractHandlerMapping.class); - if(handlerMapping == null){ - logger.warn("Not found AbstractHandlerMapping, Plugin interceptor can't use"); - } - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - if(handlerMapping == null){ - return; - } - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - List interceptorRegisters = SpringBeanUtils.getBeans(pluginApplicationContext, - PluginInterceptorRegister.class); - List interceptorsObjects = new ArrayList<>(); - List adaptedInterceptors = getAdaptedInterceptors(); - if(adaptedInterceptors == null){ - return; - } - String pluginRestPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginRegistryInfo.getPluginWrapper().getPluginId()); - - for (PluginInterceptorRegister interceptorRegister : interceptorRegisters) { - PluginInterceptorRegistry interceptorRegistry = new PluginInterceptorRegistry(pluginRestPrefix); - interceptorRegister.registry(interceptorRegistry); - List interceptors = interceptorRegistry.getInterceptors(); - if(interceptors == null || interceptors.isEmpty()){ - continue; - } - for (Object interceptor : interceptors) { - HandlerInterceptor handlerInterceptor = adaptInterceptor(interceptor); - adaptedInterceptors.add(handlerInterceptor); - interceptorsObjects.add(handlerInterceptor); - } - } - pluginRegistryInfo.addExtension(INTERCEPTORS, interceptorsObjects); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - if(handlerMapping == null){ - return; - } - List interceptorsObjects = pluginRegistryInfo.getExtension(INTERCEPTORS); - if(interceptorsObjects == null || interceptorsObjects.isEmpty()){ - return; - } - List adaptedInterceptors = getAdaptedInterceptors(); - if(adaptedInterceptors == null){ - return; - } - for (HandlerInterceptor interceptor : interceptorsObjects) { - adaptedInterceptors.remove(interceptor); - } - } - - /** - * 得到拦截器存储者 - * @return List - */ - private List getAdaptedInterceptors(){ - try { - return ClassUtils.getReflectionField(handlerMapping, "adaptedInterceptors", List.class); - } catch (IllegalAccessException e) { - logger.error("Can't get 'adaptedInterceptors' from AbstractHandlerMapping, so " + - "You can't use HandlerInterceptor. {} ", e.getMessage()); - return null; - } - } - - /** - * 转换拦截器 - * @param interceptor interceptor - * @return HandlerInterceptor - */ - private HandlerInterceptor adaptInterceptor(Object interceptor) { - if (interceptor instanceof HandlerInterceptor) { - return (HandlerInterceptor) interceptor; - } else if (interceptor instanceof WebRequestInterceptor) { - return new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor); - } else { - throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName()); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginOneselfStopEventProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginOneselfStopEventProcessor.java deleted file mode 100644 index e7e717d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginOneselfStopEventProcessor.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.post.bean.PluginOneselfStartEventProcessor; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.realize.OneselfListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -/** - * 插件中 OneselfListener 监听者处理者。主要执行监听器的停止事件。 - * @author starBlues - * @version 1.0 - * @since 2021-05-30 - */ -public class PluginOneselfStopEventProcessor implements PluginPipeProcessor{ - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - // 当前不执行启动事件 - // 由类 com.gitee.starblues.factory.process.post.bean.PluginOneselfStartEventProcessor 实现启动 - // 主要是资源全部加载注册完成后再触发启动事件 - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List oneselfListeners = pluginRegistryInfo - .getExtension(PluginOneselfStartEventProcessor.KEY); - if(oneselfListeners == null || oneselfListeners.isEmpty()){ - return; - } - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - for (OneselfListener oneselfListener : oneselfListeners) { - try { - oneselfListener.stopEvent(basePlugin); - } catch (Exception e){ - log.error("OneselfListener {} execute stopEvent exception. {}", - oneselfListener.getClass().getName(), e.getMessage(), e); - } - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java deleted file mode 100644 index dcbcaa8..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeApplicationContextProcessor.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.extension.ExtensionInitializer; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.PropertyKey; -import com.gitee.starblues.factory.process.pipe.bean.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.autoconfigure.AutoConfigurationPackages; -import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.util.ObjectUtils; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * 插件的ApplicationContext 处理 - * 主要进行插件bean的扫描 - * @author starBlues - * @version 2.4.3 - */ -public class PluginPipeApplicationContextProcessor implements PluginPipeProcessor{ - - private final static Logger logger = LoggerFactory.getLogger(PluginPipeApplicationContextProcessor.class); - - private final List pluginBeanDefinitionRegistrars = new ArrayList<>(); - private final ApplicationContext mainApplicationContext; - - - public PluginPipeApplicationContextProcessor(ApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - } - - @Override - public void initialize() throws Exception { - pluginBeanDefinitionRegistrars.add(new SpringBootConfigFileRegistrar(mainApplicationContext)); - pluginBeanDefinitionRegistrars.add(new PluginInsetBeanRegistrar()); - pluginBeanDefinitionRegistrars.add(new ConfigBeanRegistrar()); - //pluginBeanDefinitionRegistrars.add(new ConfigFileBeanRegistrar(mainApplicationContext)); - pluginBeanDefinitionRegistrars.add(new BasicBeanRegistrar()); - pluginBeanDefinitionRegistrars.add(new InvokeBeanRegistrar()); - pluginBeanDefinitionRegistrars.addAll(ExtensionInitializer.getPluginBeanRegistrarExtends()); - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - // 进行bean注册 - for (PluginBeanRegistrar pluginBeanDefinitionRegistrar : pluginBeanDefinitionRegistrars) { - pluginBeanDefinitionRegistrar.registry(pluginRegistryInfo); - } - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - try { - registerMustDependencies(pluginApplicationContext, pluginRegistryInfo); - installPluginAutoConfiguration(pluginApplicationContext, pluginRegistryInfo); - pluginApplicationContext.refresh(); - } finally { - Thread.currentThread().setContextClassLoader(contextClassLoader); - } - - // 向插件静态容器中新增插件的ApplicationContext - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - PluginInfoContainers.addPluginApplicationContext(pluginId, pluginApplicationContext); - } - - /** - * 安装插件定义的自动装载配置类 - * @param pluginApplicationContext 插件ApplicationContext - * @param pluginRegistryInfo 插件注册信息 - */ - private void installPluginAutoConfiguration(GenericApplicationContext pluginApplicationContext, - PluginRegistryInfo pluginRegistryInfo) throws ClassNotFoundException { - Set installAutoConfigClassString = pluginRegistryInfo.getPluginBinder() - .bind(PropertyKey.INSTALL_AUTO_CONFIG_CLASS, Bindable.setOf(String.class)) - .orElseGet(()->null); - - if(ObjectUtils.isEmpty(installAutoConfigClassString)){ - return; - } - - // 注册AutoConfigurationPackages, 用于插件可自动配置 - AutoConfigurationPackages.register(pluginApplicationContext.getDefaultListableBeanFactory(), - pluginRegistryInfo.getBasePlugin().scanPackage()); - - Set> autoConfigurationClassSet = new HashSet<>(installAutoConfigClassString.size()); - ClassLoader pluginClassLoader = pluginRegistryInfo.getPluginClassLoader(); - for (String autoConfigClassPackage : installAutoConfigClassString) { - Class aClass = Class.forName(autoConfigClassPackage, false, pluginClassLoader); - autoConfigurationClassSet.add(aClass); - } - for (Class autoConfigurationClass : autoConfigurationClassSet) { - pluginApplicationContext.registerBean(autoConfigurationClass); - } - } - - /** - * 定义一些spring-boot中一些必要注册的依赖 - * @param pluginApplicationContext pluginApplicationContext - * @param pluginRegistryInfo pluginRegistryInfo - */ - private void registerMustDependencies(GenericApplicationContext pluginApplicationContext, - PluginRegistryInfo pluginRegistryInfo){ - // 注册AutoConfigurationPackages, 用于插件可自动配置 - AutoConfigurationPackages.register(pluginApplicationContext.getDefaultListableBeanFactory(), - pluginRegistryInfo.getBasePlugin().scanPackage()); - // 注册 ConfigurationPropertiesBindingPostProcessor - ConfigurationPropertiesBindingPostProcessor.register(pluginApplicationContext); - } - - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - for (PluginBeanRegistrar registrar : pluginBeanDefinitionRegistrars) { - try { - registrar.unRegistry(pluginRegistryInfo); - } catch (Exception e){ - logger.error("Plugin '{}'-'{}' unRegistry failure.", - pluginRegistryInfo.getPluginWrapper().getPluginId(), - registrar.getClass().getName()); - } - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessor.java deleted file mode 100644 index 7206178..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessor.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.factory.PluginRegistryInfo; - -/** - * 插件管道处理者接口 - * - * @author starBlues - * @version 2.1.0 - */ -public interface PluginPipeProcessor { - - - /** - * 初始化 - * @throws Exception 初始化异常 - */ - void initialize() throws Exception; - - - /** - * 处理该插件的注册 - * @param pluginRegistryInfo 插件注册的信息 - * @throws Exception 处理异常 - */ - void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception; - - - /** - * 处理该插件的卸载 - * @param pluginRegistryInfo 插件注册的信息 - * @throws Exception 处理异常 - */ - void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception; - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorExtend.java deleted file mode 100644 index cbb68c5..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorExtend.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.utils.OrderPriority; - -/** - * 单插件处理者扩展接口 - * - * @author starBlues - * @version 2.1.0 - */ -public interface PluginPipeProcessorExtend extends PluginPipeProcessor{ - - /** - * 扩展key - * @return String - */ - String key(); - - - /** - * 执行顺序 - * @return OrderPriority - */ - OrderPriority order(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java deleted file mode 100644 index 9127fcb..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPipeProcessorFactory.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.extension.ExtensionInitializer; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassProcess; -import com.gitee.starblues.spring.processor.extract.PluginExtractPipeProcessor; -import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoadFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * 插件的pipe处理者工厂 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginPipeProcessorFactory implements PluginPipeProcessor { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final ApplicationContext mainApplicationContext; - private final List pluginPipeProcessors = new ArrayList<>(); - - public PluginPipeProcessorFactory(ApplicationContext mainApplicationContext){ - this.mainApplicationContext = mainApplicationContext; - } - - - - @Override - public void initialize() throws Exception{ - // 以下顺序不能更改 - // 停止事件放在第一位 - pluginPipeProcessors.add(new PluginOneselfStopEventProcessor()); - // 插件资源加载者, 必须放在第二位 - pluginPipeProcessors.add(new PluginResourceLoadFactory()); - // 插件类处理者 - pluginPipeProcessors.add(new PluginClassProcess()); - // 添加前置扩展 - pluginPipeProcessors.addAll(ExtensionInitializer.getPreProcessorExtends()); - // 插件的ApplicationContext处理者 - pluginPipeProcessors.add(new PluginPipeApplicationContextProcessor(mainApplicationContext)); - // 拦截器处理者 - pluginPipeProcessors.add(new PluginInterceptorsPipeProcessor(mainApplicationContext)); - // 插件ConfigBean处理者 - pluginPipeProcessors.add(new PluginConfigBeanPipeProcessor()); - // 插件扩展的流处理者 - pluginPipeProcessors.add(new PluginExtractPipeProcessor(mainApplicationContext)); - // 添加扩展 - pluginPipeProcessors.addAll(ExtensionInitializer.getPipeProcessorExtends()); - - // 进行初始化 - for (PluginPipeProcessor pluginPipeProcessor : pluginPipeProcessors) { - pluginPipeProcessor.initialize(); - } - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - for (PluginPipeProcessor pluginPipeProcessor : pluginPipeProcessors) { - pluginPipeProcessor.registry(pluginRegistryInfo); - } - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - boolean findException = false; - for (PluginPipeProcessor pluginPipeProcessor : pluginPipeProcessors) { - try { - pluginPipeProcessor.unRegistry(pluginRegistryInfo); - } catch (Exception e){ - findException = true; - logger.error("unRegistry plugin '{}' failure by {}", pluginRegistryInfo.getPluginWrapper().getPluginId(), - pluginPipeProcessor.getClass().getName(), e); - } - } - if(findException){ - throw new Exception("UnRegistry plugin '" + pluginRegistryInfo.getPluginWrapper().getPluginId() + "'failure"); - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPreProcessorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPreProcessorExtend.java deleted file mode 100644 index 2c80305..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/PluginPreProcessorExtend.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.gitee.starblues.factory.process.pipe; - -import com.gitee.starblues.utils.OrderPriority; - -/** - * 单插件处理者扩展接口 - * - * @author starBlues - * @version 2.2.5 - */ -public interface PluginPreProcessorExtend extends PluginPipeProcessor { - - /** - * 扩展key - * @return String - */ - String key(); - - /** - * 执行顺序 - * @return OrderPriority - */ - OrderPriority order(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/BasicBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/BasicBeanRegistrar.java deleted file mode 100644 index 9291a78..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/BasicBeanRegistrar.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.classs.group.ComponentGroup; -import com.gitee.starblues.factory.process.pipe.classs.group.OneselfListenerGroup; -import com.gitee.starblues.factory.process.pipe.classs.group.RepositoryGroup; - -import java.util.*; - -/** - * 基础bean注册 - * - * @author starBlues - * @version 2.4.0 - */ -public class BasicBeanRegistrar implements PluginBeanRegistrar { - - - public BasicBeanRegistrar(){ - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List> springComponents = pluginRegistryInfo - .getGroupClasses(ComponentGroup.GROUP_ID); - List> springRepository = pluginRegistryInfo - .getGroupClasses(RepositoryGroup.GROUP_ID); - List> oneselfListener = pluginRegistryInfo - .getGroupClasses(OneselfListenerGroup.GROUP_ID); - - register(pluginRegistryInfo, springComponents); - register(pluginRegistryInfo, springRepository); - register(pluginRegistryInfo, oneselfListener); - } - - /** - * 往Spring注册bean - * @param pluginRegistryInfo 插件注册的信息 - * @param classes 要注册的类集合 - */ - private void register(PluginRegistryInfo pluginRegistryInfo, - List> classes){ - if(classes == null || classes.isEmpty()){ - return; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - for (Class aClass : classes) { - if(aClass == null){ - continue; - } - springBeanRegister.register(aClass); - } - } - - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigBeanRegistrar.java deleted file mode 100644 index b874aae..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigBeanRegistrar.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.classs.group.ConfigBeanGroup; -import com.gitee.starblues.realize.ConfigBean; - -import java.util.*; - -/** - * 插件中实现 ConfigBean 接口的的处理者 - * @see ConfigBean - * - * @author starBlues - * @version 2.4.0 - */ -public class ConfigBeanRegistrar implements PluginBeanRegistrar { - - public final static String KEY = "ConfigBeanNames"; - - public ConfigBeanRegistrar() { - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List> configBeans = - pluginRegistryInfo.getGroupClasses(ConfigBeanGroup.GROUP_ID); - if(configBeans == null || configBeans.isEmpty()){ - return; - } - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - for (Class aClass : configBeans) { - if(aClass == null){ - continue; - } - springBeanRegister.register(aClass); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java deleted file mode 100644 index dd0cc73..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/ConfigFileBeanRegistrar.java +++ /dev/null @@ -1,100 +0,0 @@ -//package com.gitee.starblues.factory.process.pipe.bean; -// -//import com.gitee.starblues.annotation.ConfigDefinition; -//import com.gitee.starblues.factory.PluginRegistryInfo; -//import com.gitee.starblues.factory.SpringBeanRegister; -//import com.gitee.starblues.factory.process.pipe.bean.configuration.ConfigurationParser; -//import com.gitee.starblues.factory.process.pipe.bean.configuration.PluginConfigDefinition; -//import com.gitee.starblues.factory.process.pipe.bean.configuration.YamlConfigurationParser; -//import com.gitee.starblues.factory.process.pipe.classs.group.ConfigDefinitionGroup; -//import com.gitee.starblues.integration.IntegrationConfiguration; -//import com.gitee.starblues.realize.ConfigDefinitionTip; -//import com.gitee.starblues.utils.ClassUtils; -//import com.gitee.starblues.utils.PluginConfigUtils; -//import org.pf4j.util.StringUtils; -//import org.springframework.context.ApplicationContext; -//import org.springframework.util.ReflectionUtils; -// -//import java.lang.reflect.Field; -//import java.util.List; -// -///** -// * 插件中配置文件 bean 的处理者。包括配置文件 -// * @author starBlues -// * @version 2.4.0 -// */ -//public class ConfigFileBeanRegistrar implements PluginBeanRegistrar { -// -// private final ConfigurationParser configurationParser; -// private final IntegrationConfiguration integrationConfiguration; -// -// public ConfigFileBeanRegistrar(ApplicationContext mainApplicationContext) { -// integrationConfiguration = -// mainApplicationContext.getBean(IntegrationConfiguration.class); -// this.configurationParser = new YamlConfigurationParser(integrationConfiguration); -// } -// -// -// @Override -// public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { -// List> configDefinitions = -// pluginRegistryInfo.getGroupClasses(ConfigDefinitionGroup.GROUP_ID); -// if(configDefinitions == null || configDefinitions.isEmpty()){ -// return; -// } -// for (Class aClass : configDefinitions) { -// registry(pluginRegistryInfo, aClass); -// } -// } -// -// /** -// * 注册配置文件 -// * @param pluginRegistryInfo 插件注册的信息 -// * @param aClass 配置文件类 -// * @throws Exception Exception -// */ -// private void registry(PluginRegistryInfo pluginRegistryInfo, Class aClass) throws Exception{ -// ConfigDefinition configDefinition = aClass.getAnnotation(ConfigDefinition.class); -// if(configDefinition == null){ -// return; -// } -// PluginConfigUtils.FileNamePack fileNamePack = PluginConfigUtils.getConfigFileName( -// configDefinition.fileName(), -// configDefinition.prodSuffix(), -// configDefinition.devSuffix(), -// integrationConfiguration.environment()); -// String fileName = PluginConfigUtils.joinConfigFileName(fileNamePack); -// Object parseObject = null; -// if(!StringUtils.isNullOrEmpty(fileName)){ -// PluginConfigDefinition pluginConfigDefinition = -// new PluginConfigDefinition(fileName, aClass); -// parseObject = configurationParser.parse(pluginRegistryInfo, -// pluginConfigDefinition); -// } else { -// parseObject = aClass.newInstance(); -// } -// -// String name = aClass.getName(); -// SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); -// setConfigDefinitionTip(pluginRegistryInfo, parseObject); -// springBeanRegister.registerSingleton(name, parseObject); -// pluginRegistryInfo.addConfigSingleton(parseObject); -// } -// -// /** -// * 设置小工具类 -// * @param parseObject 当前的配置对象 -// */ -// private void setConfigDefinitionTip(PluginRegistryInfo pluginRegistryInfo, Object parseObject) { -// Class aClass = parseObject.getClass(); -// List fields = ClassUtils.getAllFields(aClass); -// ConfigDefinitionTip configDefinitionTip = new ConfigDefinitionTip(pluginRegistryInfo); -// for (Field field : fields) { -// if(field.getType() == ConfigDefinitionTip.class){ -// field.setAccessible(true); -// ReflectionUtils.setField(field, parseObject, configDefinitionTip); -// } -// } -// } -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/InvokeBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/InvokeBeanRegistrar.java deleted file mode 100644 index ceca253..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/InvokeBeanRegistrar.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.gitee.starblues.annotation.Caller; -import com.gitee.starblues.annotation.Supplier; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; -import com.gitee.starblues.factory.process.pipe.classs.group.CallerGroup; -import com.gitee.starblues.factory.process.pipe.classs.group.SupplierGroup; -import com.gitee.starblues.factory.process.post.bean.PluginInvokePostProcessor; -import org.pf4j.util.StringUtils; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.util.ClassUtils; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.text.MessageFormat; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 插件互相调用的bean注册者 - * @author starBlues - * @version 2.4.0 - */ -public class InvokeBeanRegistrar implements PluginBeanRegistrar{ - - private final static Map> PLUGIN_SUPPER_MAP = new ConcurrentHashMap<>(4); - - public static final String SUPPLIER_KEY = "Invoke_Supplier"; - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - registrySupper(pluginRegistryInfo); - registryCall(pluginRegistryInfo); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - PLUGIN_SUPPER_MAP.remove(pluginRegistryInfo.getPluginWrapper().getPluginId()); - } - - /** - * 处理被调用者 - * @param pluginRegistryInfo 插件注册的信息 - * @throws Exception 处理异常 - */ - private void registrySupper(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List> supperClasses = pluginRegistryInfo.getGroupClasses(SupplierGroup.GROUP_ID); - if(supperClasses.isEmpty()){ - return; - } - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - Set beanNames = new HashSet<>(supperClasses.size()); - for (Class supperClass : supperClasses) { - if(supperClass == null){ - continue; - } - Supplier supplier = supperClass.getAnnotation(Supplier.class); - if(supplier == null){ - continue; - } - String beanName = supplier.value(); - if(springBeanRegister.exist(beanName)){ - String error = MessageFormat.format( - "Plugin {0} : Bean @Supplier name {1} already exist of {2}", - pluginRegistryInfo.getPluginWrapper().getPluginId(), beanName, supperClass.getName()); - throw new Exception(error); - } - springBeanRegister.registerOfSpecifyName(beanName, supperClass); - beanNames.add(beanName); - } - pluginRegistryInfo.addExtension(SUPPLIER_KEY, beanNames); - } - - - private void registryCall(PluginRegistryInfo pluginRegistryInfo) { - List> callerClasses = pluginRegistryInfo.getGroupClasses(CallerGroup.GROUP_ID); - if(callerClasses == null || callerClasses.isEmpty()){ - return; - } - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - for (Class callerClass : callerClasses) { - Caller caller = callerClass.getAnnotation(Caller.class); - if(caller == null){ - continue; - } - springBeanRegister.register(callerClass, (beanDefinition) ->{ - beanDefinition.getPropertyValues().add("callerInterface", callerClass); - beanDefinition.getPropertyValues().add("callerAnnotation", caller); - beanDefinition.setBeanClass(CallerInterfaceFactory.class); - beanDefinition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE); - }); - } - - } - - public static void addSupper(String pluginId, String name, Object o){ - Map superMap = PLUGIN_SUPPER_MAP.computeIfAbsent(pluginId, k -> new HashMap<>(4)); - superMap.put(name, o); - } - - public static Object getSupper(String name){ - for (Map superMap : PLUGIN_SUPPER_MAP.values()) { - Object o = superMap.get(name); - if(o != null){ - return o; - } - } - return null; - } - - public static Object getSupper(String pluginId, String name){ - Map superMap = PLUGIN_SUPPER_MAP.get(pluginId); - if(superMap == null || superMap.isEmpty()){ - return null; - } - return superMap.get(name); - } - - - /** - * 调用者的接口工厂 - * @param 接口泛型 - */ - private static class CallerInterfaceFactory implements FactoryBean { - - private Class callerInterface; - private Caller callerAnnotation; - - @Override - public T getObject() throws Exception { - ClassLoader classLoader = callerInterface.getClassLoader(); - Class[] interfaces = new Class[]{callerInterface}; - ProxyHandler proxy = new ProxyHandler(callerAnnotation); - return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy); - } - - @Override - public Class getObjectType() { - return callerInterface; - } - - @Override - public boolean isSingleton() { - return true; - } - - public Class getCallerInterface() { - return callerInterface; - } - - public void setCallerInterface(Class callerInterface) { - this.callerInterface = callerInterface; - } - - public Caller getCallerAnnotation() { - return callerAnnotation; - } - - public void setCallerAnnotation(Caller callerAnnotation) { - this.callerAnnotation = callerAnnotation; - } - } - - - - /** - * 代理类 - */ - private static class ProxyHandler implements InvocationHandler { - - private final Caller callerAnnotation; - - private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private ProxyHandler(Caller callerAnnotation) { - this.callerAnnotation = callerAnnotation; - } - - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Object supplierObject = null; - String pluginId = callerAnnotation.pluginId(); - if(StringUtils.isNullOrEmpty(pluginId)){ - supplierObject = getSupper(callerAnnotation.value()); - } else { - supplierObject = getSupper(pluginId, callerAnnotation.value()); - } - if(supplierObject == null){ - if(StringUtils.isNullOrEmpty(pluginId)){ - throw new Exception("Not found '" + callerAnnotation.value() + "' supplier object"); - } else { - throw new Exception("Not found '" + callerAnnotation.value() + "' supplier object in plugin '" + - pluginId + "'"); - } - } - - Caller.Method callerMethod = method.getAnnotation(Caller.Method.class); - if(args == null){ - args = new Object[]{}; - } - if(callerMethod == null){ - return notAnnotationInvoke(method, supplierObject, args); - } else { - return annotationInvoke(method, callerMethod, supplierObject, args); - } - } - - /** - * 有注解的调用 - * @param method 调用接口的方法 - * @param callerMethod 调用者方法注解 - * @param supplierObject 调用者对象 - * @param args 传入参数 - * @return 返回值 - * @throws Throwable 异常 - */ - private Object annotationInvoke(Method method, Caller.Method callerMethod, - Object supplierObject, Object[] args) throws Throwable{ - - String callerMethodName = callerMethod.value(); - Class supplierClass = supplierObject.getClass(); - Method[] methods = supplierClass.getMethods(); - Method supplierMethod = null; - for (Method m : methods) { - Supplier.Method supplierMethodAnnotation = m.getAnnotation(Supplier.Method.class); - if(supplierMethodAnnotation == null){ - continue; - } - if(Objects.equals(supplierMethodAnnotation.value(), callerMethodName)){ - supplierMethod = m; - break; - } - } - if(supplierMethod == null){ - // 如果为空, 说明没有找到被调用者的注解, 则走没有注解的代理调用。 - return notAnnotationInvoke(method, supplierObject, args); - } - Class[] parameterTypes = supplierMethod.getParameterTypes(); - if(parameterTypes.length != args.length){ - // 参数不匹配 - return notAnnotationInvoke(method, supplierObject, args); - } - Object[] supplierArgs = new Object[args.length]; - for (int i = 0; i < parameterTypes.length; i++) { - Class parameterType = parameterTypes[i]; - Object arg = args[i]; - if(parameterType == arg.getClass()){ - supplierArgs[i] = arg; - } else { - // 类型不匹配, 尝试使用json序列化 - String json = OBJECT_MAPPER.writeValueAsString(arg); - Object serializeObject = OBJECT_MAPPER.readValue(json, parameterType); - supplierArgs[i] = serializeObject; - } - } - Object invokeReturn = supplierMethod.invoke(supplierObject, supplierArgs); - return getReturnObject(invokeReturn, method); - } - - /** - * 没有注解调用 - * @param method 调用接口的方法 - * @param supplierObject 提供者对象 - * @param args 传入参数 - * @return 返回值 - * @throws Throwable 异常 - */ - private Object notAnnotationInvoke(Method method, Object supplierObject, Object[] args) throws Throwable{ - String name = method.getName(); - Class[] argClasses = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - argClasses[i] = args[i].getClass(); - } - Class supplierClass = supplierObject.getClass(); - Method supplierMethod = supplierClass.getMethod(name, argClasses); - Object invokeReturn = supplierMethod.invoke(supplierObject, args); - return getReturnObject(invokeReturn, method); - } - - - /** - * 得到返回值对象 - * @param invokeReturn 反射调用后返回的对象 - * @param method 调用接口的方法 - * @return 返回值对象 - * @throws Throwable Throwable - */ - private Object getReturnObject(Object invokeReturn, Method method) throws Throwable{ - if(invokeReturn == null){ - return null; - } - Class returnType = method.getReturnType(); - if(ClassUtils.isAssignable(invokeReturn.getClass(),returnType)){ - return invokeReturn; - } else { - String json = OBJECT_MAPPER.writeValueAsString(invokeReturn); - return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructType(method.getGenericReturnType()) ); - } - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrar.java deleted file mode 100644 index 97a8071..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrar.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PluginBeanRegistrar { - - - /** - * 处理该插件的注册 - * @param pluginRegistryInfo 插件注册的信息 - * @throws Exception 处理异常 - */ - void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception; - - /** - * 处理该插件的卸载 - * @param pluginRegistryInfo 插件注册的信息 - * @throws Exception 处理异常 - */ - default void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception{} - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrarExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrarExtend.java deleted file mode 100644 index d9446b1..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginBeanRegistrarExtend.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PluginBeanRegistrarExtend extends PluginBeanRegistrar { - - /** - * 扩展key - * @return String - */ - String key(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginInsetBeanRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginInsetBeanRegistrar.java deleted file mode 100644 index 8b5e07b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/PluginInsetBeanRegistrar.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.bean.inset.ExtractFactoryInset; -import com.gitee.starblues.factory.process.pipe.bean.inset.PluginInsetBean; -import com.gitee.starblues.factory.process.pipe.bean.inset.PluginUtilsInset; -import org.pf4j.util.StringUtils; - -import java.util.ArrayList; -import java.util.List; - -/** - * 系统内嵌的Bean注册者 - * @author starBlues - * @version 1.0 - */ -public class PluginInsetBeanRegistrar implements PluginBeanRegistrar{ - - private final List pluginInsetBeans = new ArrayList<>(2); - - public PluginInsetBeanRegistrar() { - this.pluginInsetBeans.add(new PluginUtilsInset()); - this.pluginInsetBeans.add(new ExtractFactoryInset()); - } - - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - for (PluginInsetBean pluginInsetBean : this.pluginInsetBeans) { - String beanName = pluginInsetBean.getBeanName(); - Object bean = pluginInsetBean.getBean(pluginRegistryInfo); - if(bean == null){ - continue; - } - if(StringUtils.isNullOrEmpty(beanName)){ - beanName = bean.getClass().getName(); - } - springBeanRegister.registerSingleton(beanName, bean); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/SpringBootConfigFileRegistrar.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/SpringBootConfigFileRegistrar.java deleted file mode 100644 index cb8d65a..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/SpringBootConfigFileRegistrar.java +++ /dev/null @@ -1,310 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean; - -import com.gitee.starblues.annotation.ConfigDefinition; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.loader.ResourceWrapper; -import com.gitee.starblues.factory.process.pipe.loader.load.PluginConfigFileLoader; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.integration.pf4j.descriptor.DefaultPluginDescriptorExtend; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.PluginConfigUtils; -import org.pf4j.PluginDescriptor; -import org.pf4j.RuntimeMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.env.PropertiesPropertySourceLoader; -import org.springframework.boot.env.PropertySourceLoader; -import org.springframework.boot.env.YamlPropertySourceLoader; -import org.springframework.context.ApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.Environment; -import org.springframework.core.env.PropertySource; -import org.springframework.core.io.Resource; -import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import java.io.IOException; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 解析springboot中的插件中的配置文件。目前支持: prop、yaml - * @author starBlues - * @version 2.4.5 - */ -public class SpringBootConfigFileRegistrar implements PluginBeanRegistrar{ - - /** - * The "active profiles" property name. - */ - private static final String ACTIVE_PROFILES_PROPERTY = "spring.profiles.active"; - - /** - * The "includes profiles" property name. - */ - private static final String INCLUDE_PROFILES_PROPERTY = "spring.profiles.include"; - - private final Logger logger = LoggerFactory.getLogger(SpringBootConfigFileRegistrar.class); - - private final IntegrationConfiguration integrationConfiguration; - private final List propertySourceLoaders; - - public SpringBootConfigFileRegistrar(ApplicationContext mainApplicationContext){ - integrationConfiguration = - mainApplicationContext.getBean(IntegrationConfiguration.class); - this.propertySourceLoaders = new ArrayList<>(); - addPropertySourceLoader(); - } - - protected void addPropertySourceLoader(){ - this.propertySourceLoaders.add(new YamlPropertySourceLoader()); - this.propertySourceLoaders.add(new PropertiesPropertySourceLoader()); - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - ConfigurableEnvironment environment = pluginRegistryInfo.getPluginApplicationContext().getEnvironment(); - - PluginConfigUtils.FileNamePack fileNamePack = getConfigFileName(pluginRegistryInfo); - if(fileNamePack == null){ - return; - } - String configFileName = PluginConfigUtils.joinConfigFileName(fileNamePack); - - PluginConfigFileLoader pluginConfigFileLoader = new PluginConfigFileLoader( - integrationConfiguration.pluginConfigFilePath(), configFileName - ); - - ResourceWrapper resourceWrapper = pluginConfigFileLoader.load(pluginRegistryInfo); - List resources = resourceWrapper.getResources(); - if(ObjectUtils.isEmpty(resources)){ - return; - } - // 获取注解中原始文件配置 - List> propProfiles = getPropProfiles(resources); - if(ObjectUtils.isEmpty(propProfiles)){ - return; - } - for (PropertySource propertySource : propProfiles) { - environment.getPropertySources().addLast(propertySource); - } - // 发现原始文件中配置的 profiles - List profiles = getProfiles(environment); - if(!ObjectUtils.isEmpty(profiles)){ - loadProfilesConfig(pluginRegistryInfo, fileNamePack, environment, profiles); - } - } - - /** - * 获取插件中定义的配置文件名称信息 - * @param pluginRegistryInfo PluginRegistryInfo - * @return 配置文件信息 - */ - private PluginConfigUtils.FileNamePack getConfigFileName(PluginRegistryInfo pluginRegistryInfo){ - // 先从插件引导配置获取配置文件 - PluginDescriptor descriptor = pluginRegistryInfo.getPluginWrapper().getDescriptor(); - if(descriptor instanceof DefaultPluginDescriptorExtend){ - DefaultPluginDescriptorExtend descriptorExtend = (DefaultPluginDescriptorExtend) descriptor; - String configFileName = descriptorExtend.getConfigFileName(); - if(!ObjectUtils.isEmpty(configFileName)){ - return new PluginConfigUtils.FileNamePack(configFileName, descriptorExtend.getConfigFileProfile()); - } - } - - // 如果插件引导文件未设置, 则从引导类的注解添加 ConfigDefinition - //加载成PropertySource对象,并添加到Environment环境中 - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - ConfigDefinition configDefinition = basePlugin.getClass().getAnnotation(ConfigDefinition.class); - if(configDefinition == null){ - return null; - } - RuntimeMode runtimeMode = pluginRegistryInfo.getPluginWrapper().getRuntimeMode(); - return PluginConfigUtils.getConfigFileName( - configDefinition.fileName(), - configDefinition.prodSuffix(), - configDefinition.devSuffix(), - runtimeMode); - } - - /** - * 从 Resource 中解析出 PropertySource - * @param resources resources - * @return List - * @throws IOException 加载文件 IOException 异常 - */ - private List> getPropProfiles(List resources) throws IOException { - List> propProfiles = new ArrayList<>(); - if(resources == null || resources.isEmpty()){ - return propProfiles; - } - for (Resource resource : resources) { - if(resource == null || !resource.exists()){ - continue; - } - String filename = resource.getFilename(); - if(ObjectUtils.isEmpty(filename)){ - logger.error("File name is empty!"); - return null; - } - for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { - if(!canLoadFileExtension(propertySourceLoader, filename)){ - continue; - } - List> propertySources = propertySourceLoader.load(filename, resource); - if(ObjectUtils.isEmpty(propertySources)){ - continue; - } - propProfiles.addAll(propertySources); - } - } - return propProfiles; - } - - /** - * 加载 spring.profiles.active/spring.profiles.include 定义的配置 - * @param pluginRegistryInfo 插件注册信息 - * @param fileNamePack 配置文件包装 - * @param environment ConfigurableEnvironment - * @param profiles 主配置文件中定义的值 - * @throws Exception Exception - */ - private void loadProfilesConfig(PluginRegistryInfo pluginRegistryInfo, - PluginConfigUtils.FileNamePack fileNamePack, - ConfigurableEnvironment environment, List profiles) throws Exception { - // 解析当前文件名称 - for (Profile profile : profiles) { - String name = profile.getName(); - String fileName = PluginConfigUtils.joinConfigFileName(fileNamePack.getSourceFileName(), name); - PluginConfigFileLoader pluginConfigFileLoader = new PluginConfigFileLoader( - integrationConfiguration.pluginConfigFilePath(), fileName - ); - - ResourceWrapper resourceWrapper = pluginConfigFileLoader.load(pluginRegistryInfo); - List resources = resourceWrapper.getResources(); - if(ObjectUtils.isEmpty(resources)){ - continue; - } - List> propProfiles = getPropProfiles(resources); - if(ObjectUtils.isEmpty(propProfiles)){ - return; - } - for (PropertySource propertySource : propProfiles) { - environment.getPropertySources().addLast(propertySource); - } - } - // 重新设置 ActiveProfiles - String[] names = profiles.stream() - .filter((profile) -> profile != null && !profile.isDefaultProfile()) - .map(Profile::getName).toArray(String[]::new); - environment.setActiveProfiles(names); - } - - /** - * 根据文件后缀判断是否可解析 - * @param loader PropertySourceLoader - * @param name 文件名称 - * @return boolean - */ - private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { - return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, - fileExtension)); - } - - - /** - * 得到主配置文件中的 Profile - * @param environment Environment - * @return List - */ - private List getProfiles(Environment environment) { - List profiles = new ArrayList<>(); - Set activatedViaProperty = getProfilesActivatedViaProperty(environment); - profiles.addAll(getOtherActiveProfiles(environment, activatedViaProperty)); - profiles.addAll(activatedViaProperty); - profiles.removeIf( - (profile) -> (profile != null && profile.isDefaultProfile())); - return profiles; - } - - private Set getProfilesActivatedViaProperty(Environment environment) { - if (!environment.containsProperty(ACTIVE_PROFILES_PROPERTY) - && !environment.containsProperty(INCLUDE_PROFILES_PROPERTY)) { - return Collections.emptySet(); - } - Binder binder = Binder.get(environment); - Set activeProfiles = new LinkedHashSet<>(); - activeProfiles.addAll(getProfiles(binder, INCLUDE_PROFILES_PROPERTY)); - activeProfiles.addAll(getProfiles(binder, ACTIVE_PROFILES_PROPERTY)); - return activeProfiles; - } - - private List getOtherActiveProfiles(Environment environment, Set activatedViaProperty) { - return Arrays.stream(environment.getActiveProfiles()).map(Profile::new) - .filter((profile) -> !activatedViaProperty.contains(profile)) - .collect(Collectors.toList()); - } - - private Set getProfiles(Binder binder, String name) { - return binder.bind(name, String[].class).map(this::asProfileSet) - .orElse(Collections.emptySet()); - } - - private Set asProfileSet(String[] profileNames) { - List profiles = new ArrayList<>(); - for (String profileName : profileNames) { - profiles.add(new Profile(profileName)); - } - return new LinkedHashSet<>(profiles); - } - - private static class Profile { - - private final String name; - - private final boolean defaultProfile; - - Profile(String name) { - this(name, false); - } - - Profile(String name, boolean defaultProfile) { - Assert.notNull(name, "Name must not be null"); - this.name = name; - this.defaultProfile = defaultProfile; - } - - public String getName() { - return this.name; - } - - public boolean isDefaultProfile() { - return this.defaultProfile; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || obj.getClass() != getClass()) { - return false; - } - return ((Profile) obj).name.equals(this.name); - } - - @Override - public int hashCode() { - return this.name.hashCode(); - } - - @Override - public String toString() { - return this.name; - } - - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/AbstractConfigurationParser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/AbstractConfigurationParser.java deleted file mode 100644 index 89065fa..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/AbstractConfigurationParser.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.configuration; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -import com.gitee.starblues.factory.process.pipe.loader.ResourceWrapper; -import com.gitee.starblues.factory.process.pipe.loader.load.PluginConfigFileLoader; -import org.springframework.core.io.Resource; - -import java.util.List; -import java.util.Objects; - -/** - * 抽象的插件配置文件解析者 - * @author starBlues - * @version 1.0 - */ -public abstract class AbstractConfigurationParser implements ConfigurationParser { - - private final IntegrationConfiguration configuration; - - public AbstractConfigurationParser(IntegrationConfiguration configuration) { - Objects.requireNonNull(configuration); - this.configuration = configuration; - } - - @Override - public Object parse(PluginRegistryInfo pluginRegistryInfo, PluginConfigDefinition pluginConfigDefinition) throws Exception { - Class configClass = pluginConfigDefinition.getConfigClass(); - if(pluginConfigDefinition.getConfigClass() == null){ - throw new IllegalArgumentException("pluginConfigDefinition : " + pluginConfigDefinition + " " + - "configClass can not be null"); - } - String fileName = pluginConfigDefinition.getFileName(); - if(pluginConfigDefinition.getFileName() == null || "".equals(pluginConfigDefinition.getFileName())){ - throw new IllegalArgumentException("pluginConfigDefinition : " + pluginConfigDefinition + " " + - "fileName can not be empty"); - } - - PluginResourceLoader resourceLoader = new PluginConfigFileLoader( - configuration.pluginConfigFilePath(), - fileName - ); - ResourceWrapper resourceWrapper = resourceLoader.load(pluginRegistryInfo); - if(resourceWrapper == null){ - return null; - } - List resources = resourceWrapper.getResources(); - if(resources.size() != 1){ - return null; - } - Object o = parse(resources.get(0), configClass); - if(o == null){ - return configClass.newInstance(); - } - return o; - } - - - /** - * 子类实现解析 - * @param resource 配置文件的资源信息 - * @param pluginConfigClass 配置文件class - * @return 返回映射后的存在值得对象 - * @throws Exception 配置文件解析异常 - */ - protected abstract Object parse(Resource resource, - Class pluginConfigClass) throws Exception; - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/ConfigurationParser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/ConfigurationParser.java deleted file mode 100644 index cf53ae3..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/ConfigurationParser.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.configuration; - -import com.gitee.starblues.factory.PluginRegistryInfo; - -/** - * 配置解析者 - * @author starBlues - * @version 1.0 - */ -public interface ConfigurationParser { - - /** - * 配置解析 - * @param pluginRegistryInfo 插件信息 - * @param pluginConfigDefinition 插件配置定义 - * @return 解析后映射值的对象 - * @throws Exception 抛出配置解析异常 - */ - Object parse(PluginRegistryInfo pluginRegistryInfo, PluginConfigDefinition pluginConfigDefinition) throws Exception; - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/PluginConfigDefinition.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/PluginConfigDefinition.java deleted file mode 100644 index c150453..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/PluginConfigDefinition.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.configuration; - -import java.util.Objects; - -/** - * 插件配置的参数定义 - * @author starBlues - * @version 1.0 - */ -public class PluginConfigDefinition { - - /** - * 插件中的配置文件名称 - */ - private final String fileName; - - /** - * 配置文件实现类的Class定义 - */ - private final Class configClass; - - - - public PluginConfigDefinition(String fileName, Class configClass) { - this.fileName = fileName; - this.configClass = configClass; - } - - public String getFileName() { - return fileName; - } - - public Class getConfigClass() { - return configClass; - } - - - @Override - public boolean equals(Object o) { - if (this == o){ - return true; - } - if (!(o instanceof PluginConfigDefinition)){ - return false; - } - PluginConfigDefinition that = (PluginConfigDefinition) o; - return getFileName().equals(that.getFileName()) && - getConfigClass().equals(that.getConfigClass()); - } - - @Override - public int hashCode() { - return Objects.hash(getFileName(), getConfigClass()); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/YamlConfigurationParser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/YamlConfigurationParser.java deleted file mode 100644 index b2e00cd..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/configuration/YamlConfigurationParser.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.configuration; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.TreeTraversingParser; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.fasterxml.jackson.dataformat.yaml.YAMLParser; -import com.gitee.starblues.integration.IntegrationConfiguration; -import org.springframework.core.io.Resource; - -import java.io.InputStream; - -/** - * yaml 配置解析者 - * @author starBlues - * @version 1.0 - */ -public class YamlConfigurationParser extends AbstractConfigurationParser { - - private final YAMLFactory yamlFactory; - private final ObjectMapper objectMapper; - - public YamlConfigurationParser(IntegrationConfiguration configuration) { - super(configuration); - this.yamlFactory = new YAMLFactory(); - this.objectMapper = new ObjectMapper(); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - } - - - @Override - protected Object parse(Resource resource, Class pluginConfigClass) - throws Exception{ - InputStream inputStream = null; - YAMLParser yamlParser = null; - TreeTraversingParser treeTraversingParser = null; - try { - inputStream = resource.getInputStream(); - yamlParser = yamlFactory.createParser(inputStream); - final JsonNode node = objectMapper.readTree(yamlParser); - if(node == null){ - return pluginConfigClass.newInstance(); - } - treeTraversingParser = new TreeTraversingParser(node); - return objectMapper.readValue(treeTraversingParser, pluginConfigClass); - } finally { - if(treeTraversingParser != null){ - treeTraversingParser.close(); - } - if(yamlParser != null){ - yamlParser.close(); - } - if(inputStream != null){ - inputStream.close(); - } - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java deleted file mode 100644 index 9f6bdfe..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/ExtractFactoryInset.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.inset; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.spring.processor.extract.ExtractFactory; - -/** - * ExtractFactory 扩展工厂注册者 - * @author starBlues - * @version 2.4.1 - */ -public class ExtractFactoryInset implements PluginInsetBean{ - - @Override - public String getBeanName() { - return ExtractFactoryInset.class.getName(); - } - - @Override - public Object getBean(PluginRegistryInfo pluginRegistryInfo) { - return ExtractFactory.getInstant(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginInsetBean.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginInsetBean.java deleted file mode 100644 index a745d3f..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginInsetBean.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.inset; - -import com.gitee.starblues.factory.PluginRegistryInfo; - -/** - * @author starBlues - * @version 2.4.1 - */ -public interface PluginInsetBean { - - /** - * 得到bean名称 - * @return bean 名称 - */ - String getBeanName(); - - /** - * 得到bean对象 - * @param pluginRegistryInfo pluginRegistryInfo - * @return 对象 - */ - Object getBean(PluginRegistryInfo pluginRegistryInfo); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java deleted file mode 100644 index cec7e98..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/inset/PluginUtilsInset.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.inset; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.realize.PluginUtils; -import org.springframework.context.support.GenericApplicationContext; - -/** - * PluginUtils 对象注册者 - * @author starBlues - * @version 2.4.1 - */ -public class PluginUtilsInset implements PluginInsetBean{ - @Override - public String getBeanName() { - return "PluginUtilsName"; - } - - @Override - public Object getBean(PluginRegistryInfo pluginRegistryInfo) { - GenericApplicationContext parentApplicationContext = pluginRegistryInfo.getMainApplicationContext(); - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - return new PluginUtils(parentApplicationContext, - pluginApplicationContext, - null); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/name/PluginAnnotationBeanNameGenerator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/name/PluginAnnotationBeanNameGenerator.java deleted file mode 100644 index 70a13bc..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/bean/name/PluginAnnotationBeanNameGenerator.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.bean.name; - -import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.AnnotationBeanNameGenerator; -import org.springframework.util.StringUtils; - -/** - * 插件注解名称生成者 - * - * @author starBlues - * @version 1.0 - */ -@Deprecated -public class PluginAnnotationBeanNameGenerator extends AnnotationBeanNameGenerator { - - /** - * 插件id - */ - private final String pluginId; - - public PluginAnnotationBeanNameGenerator(String pluginId) { - this.pluginId = pluginId; - } - - @Override - public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { - if (definition instanceof AnnotatedBeanDefinition) { - String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition); - if (StringUtils.hasText(beanName)) { - return beanName.concat("@").concat(pluginId); - } - } - return buildDefaultBeanName(definition, registry).concat("@").concat(pluginId); - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java deleted file mode 100644 index 77a7cf4..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroup.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs; - -import com.gitee.starblues.realize.BasePlugin; - -/** - * 插件类分组器 - * - * @author starBlues - * @version 2.1.0 - */ -public interface PluginClassGroup { - - String KEY = "PluginClassGroup_"; - - String OTHER_CLASS_GROUP_ID = KEY + "otherClass"; - - /** - * 得到全分组id - * @param groupId 分组id - * @return String - */ - static String getFullId(String groupId){ - return KEY + groupId; - } - - /** - * 组id - * @return 组id - */ - String groupId(); - - /** - * 初始化。每处理一个插件, 该方法调用一次。 - * @param basePlugin 当前插件信息 - */ - void initialize(BasePlugin basePlugin); - - - /** - * 过滤类。 - * @param aClass 类 - * @return 返回true.说明符合该分组器。false不符合该分组器 - */ - boolean filter(Class aClass); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroupExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroupExtend.java deleted file mode 100644 index c9326d7..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassGroupExtend.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs; - -/** - * 插件类分组器扩展 - * - * @author starBlues - * @version 2.1.0 - */ -public interface PluginClassGroupExtend extends PluginClassGroup{ - - /** - * 扩展key - * @return String - */ - String key(); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassProcess.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassProcess.java deleted file mode 100644 index 6e6c03b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/PluginClassProcess.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs; - -import com.gitee.starblues.extension.ExtensionInitializer; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessor; -import com.gitee.starblues.factory.process.pipe.classs.group.*; -import com.gitee.starblues.factory.process.pipe.loader.ResourceWrapper; -import com.gitee.starblues.factory.process.pipe.loader.load.PluginClassLoader; -import com.gitee.starblues.realize.BasePlugin; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; -import org.springframework.util.StringUtils; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * 插件类加载处理者 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginClassProcess implements PluginPipeProcessor { - - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - /** - * 其他类 - */ - public static final String OTHER = "other"; - - - private final List pluginClassGroups = new ArrayList<>(); - - - public PluginClassProcess(){} - - - @Override - public void initialize() { - pluginClassGroups.add(new ComponentGroup()); - pluginClassGroups.add(new ControllerGroup()); - pluginClassGroups.add(new RepositoryGroup()); - pluginClassGroups.add(new ConfigDefinitionGroup()); - pluginClassGroups.add(new ConfigBeanGroup()); - pluginClassGroups.add(new SupplierGroup()); - pluginClassGroups.add(new CallerGroup()); - pluginClassGroups.add(new OneselfListenerGroup()); - pluginClassGroups.add(new WebSocketGroup()); - // 添加扩展 - pluginClassGroups.addAll(ExtensionInitializer.getClassGroupExtends()); - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - ResourceWrapper resourceWrapper = pluginRegistryInfo.getPluginLoadResource(PluginClassLoader.KEY); - if(resourceWrapper == null){ - return; - } - List pluginResources = resourceWrapper.getResources(); - if(pluginResources == null){ - return; - } - for (PluginClassGroup pluginClassGroup : pluginClassGroups) { - try { - pluginClassGroup.initialize(basePlugin); - } catch (Exception e){ - log.error("PluginClassGroup {} initialize exception. {}", pluginClassGroup.getClass(), - e.getMessage(), e); - } - } - Set classPackageNames = resourceWrapper.getClassPackageNames(); - ClassLoader classLoader = basePlugin.getWrapper().getPluginClassLoader(); - for (String classPackageName : classPackageNames) { - Class aClass = Class.forName(classPackageName, false, classLoader); - if(aClass == null){ - continue; - } - boolean findGroup = false; - for (PluginClassGroup pluginClassGroup : pluginClassGroups) { - if(pluginClassGroup == null || StringUtils.isEmpty(pluginClassGroup.groupId())){ - continue; - } - if(pluginClassGroup.filter(aClass)){ - pluginRegistryInfo.addGroupClasses(pluginClassGroup.groupId(), aClass); - findGroup = true; - } - } - if(!findGroup){ - pluginRegistryInfo.addGroupClasses(OTHER, aClass); - } - pluginRegistryInfo.addClasses(aClass); - } - } - - @Override - public void unRegistry(PluginRegistryInfo registerPluginInfo) throws Exception { - registerPluginInfo.cleanClasses(); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/CallerGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/CallerGroup.java deleted file mode 100644 index 11cee41..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/CallerGroup.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.annotation.Caller; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; - - -/** - * 分组存在注解: @Caller - * - * @author starBlues - * @version 2.1.0 - */ -public class CallerGroup implements PluginClassGroup { - - - /** - * 自定义 @Caller - */ - public static final String GROUP_ID = "caller"; - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - return AnnotationsUtils.haveAnnotations(aClass, false, Caller.class); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ComponentGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ComponentGroup.java deleted file mode 100644 index 99eaed9..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ComponentGroup.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.annotation.Extract; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Controller; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RestController; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.List; - -/** - * 分组存在注解: Component、Service - * - * @author starBlues - * @version 2.4.0 - */ -public class ComponentGroup implements PluginClassGroup { - - /** - * spring 组件bean. - * 包括Component、Service - */ - public static final String GROUP_ID = "spring_component"; - - - private final List filters = new ArrayList<>(); - - public ComponentGroup(){ - filters.add(new ConfigDefinitionGroup()); - filters.add(new ConfigBeanGroup()); - filters.add(new OneselfListenerGroup()); - filters.add(new CallerGroup()); - filters.add(new SupplierGroup()); - } - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - boolean have = AnnotationsUtils.haveAnnotations(aClass, false, - Component.class, Service.class, - Controller.class, RestController.class, Configuration.class, - Extract.class); - if(!have){ - return false; - } - // 进行基本组件Bean的过滤 - for (PluginClassGroup filter : filters) { - if(filter.filter(aClass)){ - return false; - } - } - return true; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigBeanGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigBeanGroup.java deleted file mode 100644 index d837d89..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigBeanGroup.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.realize.ConfigBean; -import org.springframework.util.ClassUtils; - -import java.util.Set; - -/** - * 对接口ConfigBean实现的类分组 - * @see ConfigBean - * - * @author starBlues - * @version 2.2.2 - */ -public class ConfigBeanGroup implements PluginClassGroup { - - - public static final String GROUP_ID = "config_bean"; - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - if(aClass == null){ - return false; - } - Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(aClass); - return allInterfacesForClassAsSet.contains(ConfigBean.class); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigDefinitionGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigDefinitionGroup.java deleted file mode 100644 index 953a8ad..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ConfigDefinitionGroup.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.annotation.ConfigDefinition; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.springframework.util.ObjectUtils; - -/** - * 分组存在注解: @ConfigDefinition - * - * @author starBlues - * @version 2.1.0 - */ -public class ConfigDefinitionGroup implements PluginClassGroup { - - /** - * 自定义插件配置文件bean @ConfigDefinition - */ - public static final String GROUP_ID= "config_definition"; - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - if(BasePlugin.class.isAssignableFrom(aClass)){ - return false; - } - return AnnotationsUtils.haveAnnotations(aClass, false, ConfigDefinition.class); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ControllerGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ControllerGroup.java deleted file mode 100644 index 4a9bb31..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/ControllerGroup.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RestController; - -/** - * 分组存在注解: @Controller、@RestController - * - * @author starBlues - * @version 2.1.0 - */ -public class ControllerGroup implements PluginClassGroup { - - - /** - * spring @Controller @RestController 注解bean - */ - public static final String GROUP_ID = "spring_controller"; - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - return AnnotationsUtils.haveAnnotations(aClass, false, RestController.class, Controller.class); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/OneselfListenerGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/OneselfListenerGroup.java deleted file mode 100644 index 282ee84..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/OneselfListenerGroup.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.realize.OneselfListener; -import org.springframework.util.ClassUtils; - -import java.util.Set; - -/** - * 插件自己的监听器分组 - * - * @author starBlues - * @version 2.2.1 - */ -public class OneselfListenerGroup implements PluginClassGroup { - - public static final String GROUP_ID = "oneself_listener"; - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - if(aClass == null){ - return false; - } - Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(aClass); - return allInterfacesForClassAsSet.contains(OneselfListener.class); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/RepositoryGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/RepositoryGroup.java deleted file mode 100644 index 5efb442..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/RepositoryGroup.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.springframework.stereotype.Repository; - -/** - * 分组存在注解: @Repository - * - * @author starBlues - * @version 2.1.0 - */ -public class RepositoryGroup implements PluginClassGroup { - - /** - * spring @Repository 注解bean - */ - public static final String GROUP_ID = "spring_repository"; - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - return AnnotationsUtils.haveAnnotations(aClass, false, Repository.class); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/SupplierGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/SupplierGroup.java deleted file mode 100644 index b673e7d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/SupplierGroup.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.annotation.Supplier; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; - - -/** - * 分组存在注解: @Supplier - * - * @author starBlues - * @version 2.1.0 - */ -public class SupplierGroup implements PluginClassGroup { - - /** - * 自定义 @Supplier - */ - public static final String GROUP_ID = "supplier"; - - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - return AnnotationsUtils.haveAnnotations(aClass, false, Supplier.class); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/WebSocketGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/WebSocketGroup.java deleted file mode 100644 index cdf3d7b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/classs/group/WebSocketGroup.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.classs.group; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroup; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import javax.websocket.server.ServerEndpoint; - -/** - * 分组存在注解: @ServerEndpoint - * - * @author sousouki - */ -public class WebSocketGroup implements PluginClassGroup { - - public static final String GROUP_ID = "websocket"; - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - return AnnotationsUtils.haveAnnotations(aClass, false, ServerEndpoint.class); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResource.java deleted file mode 100644 index 59543fb..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResource.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.loader; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import org.pf4j.PluginWrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.NestedIOException; -import org.springframework.core.io.Resource; -import org.springframework.util.ResourceUtils; -import org.springframework.util.StringUtils; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; - -/** - * 插件资源实现类.主要是对Spring中的抽象的Resource实现. - * 功能: 主要是获取插件包中的文件资源。 - * @author starBlues - * @version 2.4.0 - */ -public class PluginResource implements Resource { - - private final static Logger log = LoggerFactory.getLogger(PluginResource.class); - - private ClassLoader classLoader; - private final PluginWrapper pluginWrapper; - - private final long lastModified; - private final String path; - - - /** - * 相对Classpath 路径 - * @param path 路径 - * @param pluginRegistryInfo pluginRegistryInfo bean - */ - public PluginResource(String path, PluginRegistryInfo pluginRegistryInfo) { - String pathToUse = StringUtils.cleanPath(path); - if (pathToUse.startsWith("/")) { - pathToUse = pathToUse.substring(1); - } - this.path = pathToUse; - - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - this.classLoader = pluginRegistryInfo.getPluginClassLoader(); - this.pluginWrapper = pluginWrapper; - - this.lastModified = pluginRegistryInfo.getBasePlugin().getBasePluginExtend().getStartTimestamp(); - } - - public void setClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - @Override - public InputStream getInputStream() throws IOException { - return classLoader.getResourceAsStream(path); - } - - - @Override - public long contentLength() throws IOException { - URL url = getURL(); - if (ResourceUtils.isFileURL(url)) { - return getFile().length(); - } - if(ResourceUtils.isJarURL(url)){ - URLConnection con = getURL().openConnection(); - return con.getContentLength(); - } - return 0L; - } - - @Override - public long lastModified() throws IOException { - return lastModified; - } - - - @Override - public Resource createRelative(String relativePath) { - throw new RuntimeException("This method is not supported"); - } - - @Override - public String getFilename() { - return StringUtils.getFilename(this.path); - } - - @Override - public String getDescription() { - return pluginWrapper.getDescriptor().getPluginDescription(); - } - - @Override - public boolean exists() { - try { - URL url = getURL(); - if(url == null){ - return false; - } - if (ResourceUtils.isFileURL(url)) { - return getFile().exists(); - } - if (contentLength() >= 0) { - return true; - } - InputStream is = getInputStream(); - is.close(); - return true; - } catch (Exception e){ - log.debug(e.getMessage(), e); - return false; - } - } - - @Override - public boolean isReadable() { - try { - URL url = getURL(); - if (ResourceUtils.isFileURL(url)) { - File file = getFile(); - return (file.canRead() && !file.isDirectory()); - } else { - return true; - } - } catch (Exception e) { - log.debug(e.getMessage(), e); - return false; - } - } - - @Override - public boolean isOpen() { - return false; - } - - - - @Override - public File getFile() throws IOException { - URL url = getURL(); - if (ResourceUtils.isJarURL(url)) { - URL actualUrl = ResourceUtils.extractArchiveURL(url); - return ResourceUtils.getFile(actualUrl, "Jar URL"); - } else { - return ResourceUtils.getFile(url, getDescription()); - } - } - - @Override - public URL getURL() throws IOException { - return classLoader.getResource(path); - } - - @Override - public URI getURI() throws IOException { - URL url = getURL(); - try { - return ResourceUtils.toURI(url); - } catch (URISyntaxException ex) { - throw new NestedIOException("Invalid URI [" + url + "]", ex); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoadFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoadFactory.java deleted file mode 100644 index 2646be0..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoadFactory.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.loader; - -import com.gitee.starblues.extension.ExtensionInitializer; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessor; -import com.gitee.starblues.factory.process.pipe.loader.load.PluginClassLoader; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.OrderPriority; -import org.pf4j.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 插件资源加载者 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginResourceLoadFactory implements PluginPipeProcessor { - - private static final Logger LOG = LoggerFactory.getLogger(PluginResourceLoadFactory.class); - - - private final List pluginResourceLoaders = new ArrayList<>(5); - - - public PluginResourceLoadFactory() { - this.pluginResourceLoaders.add(new PluginClassLoader()); - // 添加扩展 - this.pluginResourceLoaders.addAll(ExtensionInitializer.getResourceLoadersExtends()); - CommonUtils.order(pluginResourceLoaders, (pluginResourceLoader -> { - OrderPriority order = pluginResourceLoader.order(); - if (order == null) { - order = OrderPriority.getMiddlePriority(); - } - return order.getPriority(); - })); - } - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - for (PluginResourceLoader pluginResourceLoader : pluginResourceLoaders) { - if(pluginResourceLoader == null){ - continue; - } - String key = pluginResourceLoader.key(); - if(StringUtils.isNullOrEmpty(key)){ - LOG.error("pluginResourceLoader {} key is empty, skip!", - pluginResourceLoader.getClass().getName()); - continue; - } - try { - ResourceWrapper resourceWrapper = pluginResourceLoader.load(pluginRegistryInfo); - if(resourceWrapper != null){ - pluginRegistryInfo.addPluginLoadResource(key, resourceWrapper); - } - } catch (Exception e){ - LOG.error("Plugin resource loader '{}' load error. {}", key, e.getMessage(), e); - } - } - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - for (PluginResourceLoader pluginResourceLoader : pluginResourceLoaders) { - if(pluginResourceLoader == null){ - continue; - } - String key = pluginResourceLoader.key(); - try { - ResourceWrapper resourceWrapper = pluginRegistryInfo.getPluginLoadResource(key); - if(resourceWrapper == null){ - continue; - } - pluginResourceLoader.unload(pluginRegistryInfo, resourceWrapper); - } catch (Exception e){ - LOG.error("Plugin resource loader '{}' unload error. {}", key, e.getMessage(), e); - } - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoader.java deleted file mode 100644 index ed45d45..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/PluginResourceLoader.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.loader; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.OrderPriority; - -/** - * 插件资源加载者统一定义的接口 - * - * @author starBlues - * @version 2.4.0 - */ -public interface PluginResourceLoader { - - /** - * 加载者的key - * @return String - */ - String key(); - - - /** - * 加载资源 - * @param pluginRegistryInfo 插件注册者信息 - * @return 资源包装对象 - * @throws Exception Exception - */ - ResourceWrapper load(PluginRegistryInfo pluginRegistryInfo) throws Exception; - - /** - * 卸载时的操作 - * @param pluginRegistryInfo 插件对象 - * @param resourceWrapper 资源包装者 - * @throws Exception 卸载异常 - */ - void unload(PluginRegistryInfo pluginRegistryInfo, ResourceWrapper resourceWrapper) throws Exception; - - - /** - * 执行顺序 - * @return OrderPriority - */ - OrderPriority order(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/ResourceWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/ResourceWrapper.java deleted file mode 100644 index d2d7b89..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/ResourceWrapper.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.loader; - -import org.springframework.core.io.Resource; -import org.springframework.util.StringUtils; - -import java.util.*; - -/** - * 资源包装类 - * - * @author starBlues - * @version 2.4.0 - */ -public class ResourceWrapper { - - private final List resources = new ArrayList<>(); - private final Set classPackageNames = new HashSet<>(); - private final Map extensions = new HashMap<>(); - - public void addResource(Resource resource){ - if(resource == null){ - return; - } - resources.add(resource); - } - - public void addResources(List resources){ - if(resources == null || resources.isEmpty()){ - return; - } - this.resources.addAll(resources); - } - - public List getResources(){ - return Collections.unmodifiableList(resources); - } - - public void addClassPackageName(String classFullName){ - if(StringUtils.isEmpty(classFullName)){ - return; - } - classPackageNames.add(classFullName); - } - - public void addClassPackageNames(Set classPackageNames){ - if(classPackageNames == null || classPackageNames.isEmpty()){ - return; - } - this.classPackageNames.addAll(classPackageNames); - } - - public Set getClassPackageNames(){ - return Collections.unmodifiableSet(classPackageNames); - } - - - public void addExtension(String key, Object value) { - extensions.put(key, value); - } - - public Object getExtension(String key){ - return extensions.get(key); - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginClassLoader.java deleted file mode 100644 index 7e26a58..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginClassLoader.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.loader.load; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -import com.gitee.starblues.factory.process.pipe.loader.ResourceWrapper; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.ScanUtils; -import org.pf4j.RuntimeMode; - -import java.util.Set; - -/** - * 插件类文件加载者 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginClassLoader implements PluginResourceLoader { - - public static final String KEY = "PluginClassProcess"; - - @Override - public String key() { - return KEY; - } - - @Override - public ResourceWrapper load(PluginRegistryInfo pluginRegistryInfo) throws Exception{ - RuntimeMode runtimeMode = pluginRegistryInfo.getPluginWrapper().getRuntimeMode(); - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - Set classPackageName = null; - if(runtimeMode == RuntimeMode.DEPLOYMENT){ - // 生产环境 - classPackageName = ScanUtils.scanClassPackageName( - basePlugin.scanPackage(), basePlugin.getWrapper()); - - } else if(runtimeMode == RuntimeMode.DEVELOPMENT){ - // 开发环境 - classPackageName = ScanUtils.scanClassPackageName( - basePlugin.scanPackage(), basePlugin.getClass()); - } - ResourceWrapper resourceWrapper = new ResourceWrapper(); - resourceWrapper.addClassPackageNames(classPackageName); - return resourceWrapper; - } - - @Override - public void unload(PluginRegistryInfo pluginRegistryInfo, ResourceWrapper resourceWrapper) throws Exception { - // Do nothing - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginConfigFileLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginConfigFileLoader.java deleted file mode 100644 index 1628b80..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/pipe/loader/load/PluginConfigFileLoader.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.gitee.starblues.factory.process.pipe.loader.load; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -import com.gitee.starblues.factory.process.pipe.loader.ResourceWrapper; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.OrderPriority; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; - -import java.io.File; -import java.io.FileNotFoundException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** - * 插件配置文件加载者 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginConfigFileLoader implements PluginResourceLoader { - - private final static Logger log = LoggerFactory.getLogger(PluginConfigFileLoader.class); - - private final String configFilePath; - private final String fileName; - - public PluginConfigFileLoader(String configFilePath, - String fileName) { - this.configFilePath = configFilePath; - this.fileName = fileName; - } - - - @Override - public String key() { - return null; - } - - @Override - public ResourceWrapper load(PluginRegistryInfo pluginRegistryInfo) throws Exception { - List> suppliers = new ArrayList<>(); - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - suppliers.add(findConfigRoot()); - suppliers.add(findPluginRoot(basePlugin)); - suppliers.add(findClassPath(pluginRegistryInfo.getPluginClassLoader())); - - for (Supplier supplier : suppliers) { - SupplierBean supplierBean = supplier.get(); - Resource resource = supplierBean.getResource(); - if(resource.exists()){ - List resources = new ArrayList<>(); - resources.add(resource); - ResourceWrapper resourceWrapper = new ResourceWrapper(); - resourceWrapper.addResources(resources); - log.info("Load the plugin '{}' config file '{}' from '{}'", - basePlugin.getWrapper().getPluginId(), fileName, supplierBean.getPath()); - return resourceWrapper; - } - } - throw new FileNotFoundException("Not found plugin '" + basePlugin.getWrapper().getPluginId() + "' " + - "config file : " + fileName); - } - - @Override - public void unload(PluginRegistryInfo pluginRegistryInfo, ResourceWrapper resourceWrapper) throws Exception { - // Do nothing - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority().down(20); - } - - /** - * 从插件文件的根目录查找配置文件 - * @param basePlugin basePlugin - * @return 返回resource - */ - private Supplier findPluginRoot(BasePlugin basePlugin){ - return ()->{ - Path pluginPath = basePlugin.getWrapper().getPluginPath(); - String rootPath = pluginPath.getParent().toString(); - String configPath = rootPath + File.separatorChar + fileName; - Resource resource = new FileSystemResource(configPath); - return new SupplierBean(rootPath, resource); - }; - } - - - /** - * 从插件配置文件 pluginConfigFilePath 的路径下查找配置文件 - * @return 返回resource - */ - private Supplier findConfigRoot(){ - return ()->{ - String filePath = configFilePath + File.separatorChar + fileName; - Resource resource = new FileSystemResource(filePath); - return new SupplierBean(configFilePath, resource); - }; - } - - /** - * 从ClassPath 中查找配置文件 - * @param classLoader classLoader - * @return 返回resource - */ - private Supplier findClassPath(ClassLoader classLoader){ - return ()->{ - Resource resource = new ClassPathResource("/" + fileName, classLoader); - return new SupplierBean("classPath", resource); - }; - } - - private class SupplierBean{ - private String path; - private Resource resource; - - public SupplierBean(String path, Resource resource) { - this.path = path; - this.resource = resource; - } - - public String getPath() { - return path; - } - - public Resource getResource() { - return resource; - } - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessor.java deleted file mode 100644 index 9436192..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessor.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.gitee.starblues.factory.process.post; - -import com.gitee.starblues.factory.PluginRegistryInfo; - -import java.util.List; - -/** - * 插件后置处理者接口 - * - * @author starBlues - * @version 2.1.0 - */ -public interface PluginPostProcessor { - - /** - * 初始化 - * @throws Exception 初始化异常 - */ - void initialize() throws Exception; - - - /** - * 处理该插件的注册 - * @param pluginRegistryInfos 插件注册的信息 - * @throws Exception 处理异常 - */ - void registry(List pluginRegistryInfos) throws Exception; - - - /** - * 处理该插件的卸载 - * @param pluginRegistryInfos 插件注册的信息 - * @throws Exception 处理异常 - */ - void unRegistry(List pluginRegistryInfos) throws Exception; - - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorExtend.java deleted file mode 100644 index 3c7a58f..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorExtend.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.gitee.starblues.factory.process.post; - -import com.gitee.starblues.utils.OrderPriority; - -/** - * 后置插件处理者 - * - * @author starBlues - * @version 2.1.0 - */ -public interface PluginPostProcessorExtend extends PluginPostProcessor{ - - /** - * 扩展key - * @return String - */ - String key(); - - /** - * 执行顺序 - * @return OrderPriority - */ - OrderPriority order(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorFactory.java deleted file mode 100644 index 778b29e..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/PluginPostProcessorFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.gitee.starblues.factory.process.post; - -import com.gitee.starblues.extension.ExtensionInitializer; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.post.bean.*; -import com.gitee.starblues.integration.IntegrationConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * 插件后置处理工厂 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginPostProcessorFactory implements PluginPostProcessor { - - private final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); - - private final List pluginPostProcessors = new ArrayList<>(); - private final ApplicationContext mainApplicationContext; - private final IntegrationConfiguration integrationConfiguration; - - public PluginPostProcessorFactory(ApplicationContext mainApplicationContext){ - this.mainApplicationContext = mainApplicationContext; - this.integrationConfiguration = mainApplicationContext.getBean(IntegrationConfiguration.class); - } - - @Override - public void initialize() throws Exception{ - // 以下顺序不能更改 - pluginPostProcessors.add(new PluginInvokePostProcessor(mainApplicationContext)); - pluginPostProcessors.add(new PluginControllerPostProcessor(mainApplicationContext)); - if(integrationConfiguration.enableWebSocket()){ - // 如果配置启用webSocket的功能, 则进行引入 - pluginPostProcessors.add(new PluginWebSocketProcessor(mainApplicationContext)); - } - // 添加扩展 - pluginPostProcessors.addAll(ExtensionInitializer.getPostProcessorExtends()); - - // 主要触发启动监听事件,因此在最后一个执行。配合 OneselfListenerStopEventProcessor 该类触发启动、停止事件。 - pluginPostProcessors.add(new PluginOneselfStartEventProcessor()); - // 进行初始化 - for (PluginPostProcessor pluginPostProcessor : pluginPostProcessors) { - pluginPostProcessor.initialize(); - } - } - - - @Override - public void registry(List pluginRegistryInfos) throws Exception{ - for (PluginPostProcessor pluginPostProcessor : pluginPostProcessors) { - pluginPostProcessor.registry(pluginRegistryInfos); - } - } - - @Override - public void unRegistry(List pluginRegistryInfos) throws Exception{ - boolean findException = false; - for (PluginPostProcessor pluginPostProcessor : pluginPostProcessors) { - try { - pluginPostProcessor.unRegistry(pluginRegistryInfos); - } catch (Exception e){ - findException = true; - LOGGER.error("PluginPostProcessor '{}' unRegistry process exception", - pluginPostProcessor.getClass().getName(), e); - } - } - if(findException){ - throw new Exception("UnRegistry plugin failure"); - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginControllerPostProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginControllerPostProcessor.java deleted file mode 100644 index 3afb71a..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginControllerPostProcessor.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.gitee.starblues.factory.process.post.bean; - -import com.gitee.starblues.extension.ExtensionFactory; -import com.gitee.starblues.extension.PluginControllerProcessorExtend; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.classs.group.ControllerGroup; -import com.gitee.starblues.factory.process.post.PluginPostProcessor; -import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.CommonUtils; -import org.pf4j.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import java.lang.reflect.Method; -import java.util.*; -import java.util.function.Consumer; - -/** - * 插件中controller处理者 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginControllerPostProcessor implements PluginPostProcessor { - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - private static final String KEY = "PluginControllerPostProcessor"; - - private final RequestMappingHandlerMapping requestMappingHandlerMapping; - private final IntegrationConfiguration configuration; - - private final List pluginControllerProcessors; - - public PluginControllerPostProcessor(ApplicationContext mainApplicationContext){ - Objects.requireNonNull(mainApplicationContext); - this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - this.pluginControllerProcessors = ExtensionFactory - .getPluginControllerProcessorExtend(mainApplicationContext); - } - - - @Override - public void initialize() throws Exception { - resolveProcessExtend(extend->{ - try { - extend.initialize(); - }catch (Exception e){ - log.error("'{}' initialize error", - extend.getClass().getName(), - e); - } - }); - } - - @Override - public void registry(List pluginRegistryInfos) throws Exception { - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - List> groupClasses = pluginRegistryInfo.getGroupClasses(ControllerGroup.GROUP_ID); - if(groupClasses == null || groupClasses.isEmpty()){ - continue; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - List controllerBeanWrappers = new ArrayList<>(); - for (Class groupClass : groupClasses) { - if(groupClass == null){ - continue; - } - try { - ControllerWrapper controllerBeanWrapper = registry(pluginRegistryInfo, groupClass); - controllerBeanWrappers.add(controllerBeanWrapper); - } catch (Exception e){ - pluginRegistryInfo.addProcessorInfo(getKey(pluginRegistryInfo), controllerBeanWrappers); - throw e; - } - } - resolveProcessExtend(extend->{ - try { - extend.registry(pluginId, controllerBeanWrappers); - }catch (Exception e){ - log.error("'{}' process plugin[{}] error in registry", - extend.getClass().getName(), - pluginId, e); - } - }); - pluginRegistryInfo.addProcessorInfo(getKey(pluginRegistryInfo), controllerBeanWrappers); - } - } - - @Override - public void unRegistry(List pluginRegistryInfos) { - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - List controllerBeanWrappers = - pluginRegistryInfo.getProcessorInfo(getKey(pluginRegistryInfo)); - if(controllerBeanWrappers == null || controllerBeanWrappers.isEmpty()){ - continue; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - for (ControllerWrapper controllerBeanWrapper : controllerBeanWrappers) { - if(controllerBeanWrapper == null){ - continue; - } - unregister(controllerBeanWrapper); - } - resolveProcessExtend(extend->{ - try { - extend.unRegistry(pluginId, controllerBeanWrappers); - }catch (Exception e){ - log.error("'{}' process plugin[{}] error in unRegistry", - extend.getClass().getName(), - pluginId, e); - } - }); - } - } - - /** - * 注册单一插件 - * @param pluginRegistryInfo 注册的插件信息 - * @param aClass controller 类 - * @return ControllerBeanWrapper - * @throws Exception Exception - */ - private ControllerWrapper registry(PluginRegistryInfo pluginRegistryInfo, Class aClass) - throws Exception { - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - try { - Object object = pluginApplicationContext.getBean(aClass); - ControllerWrapper controllerBeanWrapper = new ControllerWrapper(); - setPathPrefix(pluginId, aClass); - Method getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, - "getMappingForMethod", Method.class, Class.class); - getMappingForMethod.setAccessible(true); - Method[] methods = aClass.getMethods(); - Set requestMappingInfos = new HashSet<>(); - for (Method method : methods) { - if (isHaveRequestMapping(method)) { - RequestMappingInfo requestMappingInfo = (RequestMappingInfo) - getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass); - requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method); - requestMappingInfos.add(requestMappingInfo); - } - } - controllerBeanWrapper.setRequestMappingInfos(requestMappingInfos); - controllerBeanWrapper.setBeanClass(aClass); - return controllerBeanWrapper; - } catch (Exception e){ - // 出现异常, 卸载该 controller bean - throw e; - } - } - - /** - * 卸载具体的Controller操作 - * @param controllerBeanWrapper controllerBean包装 - */ - private void unregister(ControllerWrapper controllerBeanWrapper) { - Set requestMappingInfos = controllerBeanWrapper.getRequestMappingInfos(); - if(requestMappingInfos != null && !requestMappingInfos.isEmpty()){ - for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { - requestMappingHandlerMapping.unregisterMapping(requestMappingInfo); - } - } - } - - /** - * 调用扩展出的接口控制器 - * @param extendConsumer 扩展消费者 - */ - private void resolveProcessExtend(Consumer extendConsumer){ - if(pluginControllerProcessors == null || pluginControllerProcessors.isEmpty()){ - return; - } - for (PluginControllerProcessorExtend pluginControllerProcessor : pluginControllerProcessors) { - extendConsumer.accept(pluginControllerProcessor); - } - } - - /** - * 得到往RegisterPluginInfo->processorInfo 保存的key - * @param registerPluginInfo 注册的插件信息 - * @return String - */ - private String getKey(PluginRegistryInfo registerPluginInfo){ - return KEY + "_" + registerPluginInfo.getPluginWrapper().getPluginId(); - } - - /** - * 设置请求路径前缀 - * @param aClass controller 类 - */ - private void setPathPrefix(String pluginId, - Class aClass) { - RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class); - if(requestMapping == null){ - return; - } - String pathPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginId); - if(StringUtils.isNullOrEmpty(pathPrefix)){ - return; - } - Set definePaths = new HashSet<>(); - definePaths.addAll(Arrays.asList(requestMapping.path())); - definePaths.addAll(Arrays.asList(requestMapping.value())); - try { - Map memberValues = ClassUtils.getAnnotationsUpdater(requestMapping); - String[] newPath = new String[definePaths.size()]; - int i = 0; - for (String definePath : definePaths) { - // 解决插件启用、禁用后, 路径前缀重复的问题。 - if(definePath.contains(pathPrefix)){ - newPath[i++] = definePath; - } else { - newPath[i++] = CommonUtils.restJoiningPath(pathPrefix, definePath); - } - } - if(newPath.length == 0){ - newPath = new String[]{ pathPrefix }; - } - memberValues.put("path", newPath); - memberValues.put("value", new String[]{}); - } catch (Exception e) { - log.error("Define Plugin RestController pathPrefix error : {}", e.getMessage(), e); - } - } - - /** - * 方法上是否存在 @RequestMapping 注解 - * @param method method - * @return boolean - */ - private boolean isHaveRequestMapping(Method method){ - if (AnnotationUtils.findAnnotation(method, RequestMapping.class) != null) { - return true; - } else { - return false; - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginInvokePostProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginInvokePostProcessor.java deleted file mode 100644 index ccfaa18..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginInvokePostProcessor.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.gitee.starblues.factory.process.post.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.bean.InvokeBeanRegistrar; -import com.gitee.starblues.factory.process.post.PluginPostProcessor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.aop.framework.AdvisedSupport; -import org.springframework.aop.framework.AopProxy; -import org.springframework.aop.support.AopUtils; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -import java.lang.reflect.Field; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * 处理插件中类之间相互调用的的功能. 主要获取被调用者的对象, 然后存储到被调用者容器中 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginInvokePostProcessor implements PluginPostProcessor { - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - public PluginInvokePostProcessor(ApplicationContext applicationContext){ - Objects.requireNonNull(applicationContext); - } - - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(List pluginRegistryInfos) throws Exception { - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - try { - Set supperBeanNames = pluginRegistryInfo.getExtension(InvokeBeanRegistrar.SUPPLIER_KEY); - if(supperBeanNames == null || supperBeanNames.isEmpty()){ - continue; - } - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - for (String supperBeanName : supperBeanNames) { - if(pluginApplicationContext.containsBean(supperBeanName)){ - Object bean = pluginApplicationContext.getBean(supperBeanName); - InvokeBeanRegistrar.addSupper(pluginId, supperBeanName, getTarget(bean)); - } - } - } catch (Exception e){ - log.error("Process plugin '{}' supper bean exception.", pluginId, e); - } - } - } - - - @Override - public void unRegistry(List pluginRegistryInfos) throws Exception{ - // 什么也不做 - } - - /** - * 获取 目标对象. 解决@Supplier中开启事务,@Caller中调用异常 - * fix: https://gitee.com/starblues/springboot-plugin-framework-parent/issues/I4BOSK - * @param proxy 代理对象 - * @return 目标对象 - * @throws Exception Exception - */ - public Object getTarget(Object proxy) throws Exception { - //不是代理对象 - if(!AopUtils.isAopProxy(proxy)) { - return proxy; - } - if(AopUtils.isJdkDynamicProxy(proxy)) { - return getJdkDynamicProxyTargetObject(proxy); - } else { - //cglib - return getCglibProxyTargetObject(proxy); - } - } - - private Object getCglibProxyTargetObject(Object proxy) throws Exception { - Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0"); - h.setAccessible(true); - Object dynamicAdvisedInterceptor = h.get(proxy); - Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised"); - advised.setAccessible(true); - return ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget(); - } - - private Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception { - Field h = proxy.getClass().getSuperclass().getDeclaredField("h"); - h.setAccessible(true); - AopProxy aopProxy = (AopProxy) h.get(proxy); - Field advised = aopProxy.getClass().getDeclaredField("advised"); - advised.setAccessible(true); - return ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget(); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginOneselfStartEventProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginOneselfStartEventProcessor.java deleted file mode 100644 index 94854ed..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginOneselfStartEventProcessor.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.gitee.starblues.factory.process.post.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.post.PluginPostProcessor; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.realize.OneselfListener; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * 插件中 OneselfListener 监听者处理者。主要执行监听器的启动事件。 - * @author starBlues - * @version 2.4.0 - */ -public class PluginOneselfStartEventProcessor implements PluginPostProcessor { - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - public final static String KEY = "OneselfListeners"; - - public PluginOneselfStartEventProcessor(){ - } - - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(List pluginRegistryInfos) throws Exception { - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - try { - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - List oneselfListeners = SpringBeanUtils.getBeans(pluginApplicationContext, OneselfListener.class); - List saveOneselfListeners = new ArrayList<>(oneselfListeners.size()); - oneselfListeners.stream() - .filter(oneselfListener -> oneselfListener != null) - .sorted(CommonUtils.orderPriority(oneselfListener -> oneselfListener.order())) - .forEach(oneselfListener -> { - try { - oneselfListener.startEvent(basePlugin); - } catch (Exception e){ - log.error("OneselfListener {} execute stopEvent exception. {}", - oneselfListener.getClass().getName(), e.getMessage(), e); - } finally { - saveOneselfListeners.add(oneselfListener); - } - }); - if(!saveOneselfListeners.isEmpty()){ - pluginRegistryInfo.addExtension(KEY, saveOneselfListeners); - } - } catch (Exception e){ - log.error("Plugin '{}' OneselfListener process exception.", basePlugin.getWrapper().getPluginId(), e); - } - } - } - - - @Override - public void unRegistry(List pluginRegistryInfos) { - // 当前不执行停止事件 - // 由类 com.gitee.starblues.factory.process.pipe.PluginOneselfStopEventProcessor 实现停止 - // 主要考虑到停止时, 需要先执行, 自主来关闭当前插件某些资源 - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginWebSocketProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginWebSocketProcessor.java deleted file mode 100644 index f8db4c9..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/PluginWebSocketProcessor.java +++ /dev/null @@ -1,254 +0,0 @@ -package com.gitee.starblues.factory.process.post.bean; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.classs.group.WebSocketGroup; -import com.gitee.starblues.factory.process.post.PluginPostProcessor; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import javax.servlet.ServletContext; -import javax.websocket.DeploymentException; -import javax.websocket.EndpointConfig; -import javax.websocket.Session; -import javax.websocket.server.ServerContainer; -import javax.websocket.server.ServerEndpoint; -import javax.websocket.server.ServerEndpointConfig; - -import com.gitee.starblues.utils.ClassUtils; -import org.pf4j.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.socket.server.standard.ServerEndpointExporter; - -/** - * 插件中websocket处理者 - * - * @author sousouki - * @version 2.4.2 - */ -public class PluginWebSocketProcessor implements PluginPostProcessor { - - private static final Logger log = LoggerFactory.getLogger(PluginWebSocketProcessor.class); - - public static final String KEY = "PluginWsConfigProcessor"; - private static final String WEB_SOCKET_PATH = "WEB_SOCKET_PATH"; - - private final ApplicationContext applicationContext; - - public PluginWebSocketProcessor(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(List pluginRegistryInfos) throws Exception { - ServerContainer serverContainer = getServerContainer(); - if (serverContainer == null) return; - - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - Map webSocketPathMap = new HashMap<>(); - List> websocketClasses = pluginRegistryInfo.getGroupClasses(WebSocketGroup.GROUP_ID); - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - websocketClasses.forEach(websocketClass -> { - ServerEndpoint serverEndpoint = websocketClass.getDeclaredAnnotation(ServerEndpoint.class); - if (serverEndpoint == null) { - log.warn("WebSocket class {} doesn't has annotation {}", websocketClass.getName(), ServerEndpoint.class.getName()); - return; - } - String sourcePath = serverEndpoint.value(); - if (StringUtils.isNullOrEmpty(sourcePath)) { - return; - } - String processPath = sourcePath; - if(!processPath.startsWith("/")){ - processPath = "/".concat(processPath); - } - UriTemplate uriTemplate; - - try { - uriTemplate = new UriTemplate(processPath); - } catch (DeploymentException e) { - log.error("Websocket path validate failed.", e); - return; - } - String newWebsocketPath = "/".concat(pluginId).concat(processPath); - String newWebsocketTemplatePath = "/".concat(pluginId).concat(uriTemplate.getPath()); - Map annotationsUpdater = null; - try { - annotationsUpdater = ClassUtils.getAnnotationsUpdater(serverEndpoint); - } catch (Exception e) { - log.error("Process and update websocket path '{}' annotation exception.", sourcePath, e); - return; - } - try { - annotationsUpdater.put("value", newWebsocketPath); - serverContainer.addEndpoint(websocketClass); - webSocketPathMap.put(newWebsocketPath, newWebsocketTemplatePath); - log.info("Succeed to create websocket service for path {}", newWebsocketPath); - } catch (Exception e) { - log.error("Create websocket service for websocket class " + websocketClass.getName() + " failed.", e); - } finally { - annotationsUpdater.put("value", sourcePath); - } - }); - pluginRegistryInfo.addExtension(WEB_SOCKET_PATH, webSocketPathMap); - } - } - - @Override - public void unRegistry(List pluginRegistryInfos) throws Exception { - ServerContainer serverContainer = getServerContainer(); - if (serverContainer == null) { - log.warn("Not found ServerContainer, So websocket can't used!"); - return; - } - Map configExactMatchMap = ClassUtils.getReflectionField(serverContainer, "configExactMatchMap"); - Map> configTemplateMatchMap = - ClassUtils.getReflectionField(serverContainer, "configTemplateMatchMap"); - Map endpointSessionMap = ClassUtils.getReflectionField(serverContainer, "endpointSessionMap"); - Map sessions = ClassUtils.getReflectionField(serverContainer, "sessions"); - pluginRegistryInfos.forEach(pluginRegistryInfo -> { - Map webSocketPathMap = pluginRegistryInfo.getExtension(WEB_SOCKET_PATH); - webSocketPathMap.forEach((webSocketPath,newWebsocketTemplatePath)->{ - configExactMatchMap.remove(webSocketPath); - log.debug("Removed websocket config for path {}", webSocketPath); - configTemplateMatchMap.forEach((key, value) -> { - value.remove(newWebsocketTemplatePath); - }); - endpointSessionMap.remove(webSocketPath); - log.debug("Removed websocket session for path {}", webSocketPath); - - for (Map.Entry entry : sessions.entrySet()) { - Session session = entry.getKey(); - try { - if(closeSession(session, webSocketPath)){ - sessions.remove(session); - log.debug("Removed websocket session {} for path {}", session.getId(), webSocketPath); - } - } catch (Exception e) { - log.debug("Close websocket session {} for path {} failure", session.getId(), webSocketPath, e); - } - } - log.info("Remove websocket for path {} success.", webSocketPath); - }); - }); - } - - /** - * 得到 Tomcat ServerContainer - * @return ServerContainer - */ - private ServerContainer getServerContainer() { - try { - applicationContext.getBean(ServerEndpointExporter.class); - } catch (BeansException e) { - log.debug("The required bean of {} not found, if you want to use plugin websocket, please create it.", ServerEndpointExporter.class.getName()); - return null; - } - if (!(applicationContext instanceof WebApplicationContext)) { - return null; - } - WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext; - ServletContext servletContext = webApplicationContext.getServletContext(); - if (servletContext == null) { - log.warn("Servlet context is null."); - return null; - } - Object obj = servletContext.getAttribute("javax.websocket.server.ServerContainer"); - if (!(obj instanceof ServerContainer)) { - return null; - } - return (ServerContainer) obj; - } - - /** - * 关闭session - * @param session session - * @param websocketPath websocketPath 路径 - * @return 如果需要关闭并且关闭成功, 则返回true。 否则返回false - * @throws Exception 关闭异常 - */ - private boolean closeSession(Session session, String websocketPath) throws Exception{ - EndpointConfig endpointConfig = ClassUtils.getReflectionField(session, "endpointConfig"); - ServerEndpointConfig perEndpointConfig = ClassUtils.getReflectionField(endpointConfig, "perEndpointConfig"); - String path = ClassUtils.getReflectionField(perEndpointConfig, "path"); - if (path.equals(websocketPath)) { - session.close(); - log.info("Closed websocket session {} for path {}", session.getId(), websocketPath); - return true; - } - return false; - } - - /** - * websocket路径解析类,主要用于处理参数 - */ - private static class UriTemplate { - - private final Map paramMap = new ConcurrentHashMap<>(); - private final String path; - - private UriTemplate(String path) throws DeploymentException { - if (path == null || path.length() == 0 || !path.startsWith("/") || path.contains("/../") || path.contains("/./") || path.contains("//")) { - throw new DeploymentException(String.format("The path [%s] is not valid.", path)); - } - StringBuilder normalized = new StringBuilder(path.length()); - Set paramNames = new HashSet<>(); - - // Include empty segments. - String[] segments = path.split("/", -1); - int paramCount = 0; - - for (int i = 0; i < segments.length; i++) { - String segment = segments[i]; - if (segment.length() == 0) { - if (i == 0 || (i == segments.length - 1 && paramCount == 0)) { - // Ignore the first empty segment as the path must always - // start with '/' - // Ending with a '/' is also OK for instances used for - // matches but not for parameterised templates. - continue; - } else { - // As per EG discussion, all other empty segments are - // invalid - throw new DeploymentException(String.format("The path [%s] contains one or more empty segments which is not permitted", path)); - } - } - normalized.append('/'); - if (segment.startsWith("{") && segment.endsWith("}")) { - segment = segment.substring(1, segment.length() - 1); - normalized.append('{'); - normalized.append(paramCount++); - normalized.append('}'); - if (!paramNames.add(segment)) { - throw new DeploymentException(String.format("The parameter [%s] appears more than once in the path which is not permitted", segment)); - } - paramMap.put(segment, paramCount - 1); - } else { - if (segment.contains("{") || segment.contains("}")) { - throw new DeploymentException(String.format("The segment [%s] is not valid in the provided path [%s]", segment, path)); - } - normalized.append(segment); - } - } - this.path = normalized.toString(); - } - - public String getPath() { - return path; - } - - public Map getParamMap() { - return paramMap; - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java deleted file mode 100644 index bf4839b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/factory/process/post/bean/model/ControllerWrapper.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.gitee.starblues.factory.process.post.bean.model; - -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; - -import java.util.Set; - -/** - * controller 包装 - * @author starBlues - * @version 3.0.0 - */ -public class ControllerWrapper { - - /** - * controller bean 名称 - */ - private String beanName; - - /** - * controller 路径前缀 - */ - private String[] pathPrefix; - - /** - * controller bean 类型 - */ - private Class beanClass; - - /** - * controller 的 RequestMappingInfo 集合 - */ - private Set requestMappingInfos; - - public Class getBeanClass() { - return beanClass; - } - - public void setBeanClass(Class beanClass) { - this.beanClass = beanClass; - } - - public String getBeanName() { - return beanName; - } - - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String[] getPathPrefix() { - return pathPrefix; - } - - public void setPathPrefix(String[] pathPrefix) { - this.pathPrefix = pathPrefix; - } - - public Set getRequestMappingInfos() { - return requestMappingInfos; - } - - public void setRequestMappingInfos(Set requestMappingInfos) { - this.requestMappingInfos = requestMappingInfos; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java index d1db186..c513d7f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java @@ -9,9 +9,7 @@ import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; -import com.gitee.starblues.spring.DefaultSpringPlugin; -import com.gitee.starblues.spring.SpringPlugin; -import com.gitee.starblues.spring.processor.extract.ExtractFactory; +import com.gitee.starblues.spring.extract.ExtractFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.support.GenericApplicationContext; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java index ab044c2..542711c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java @@ -1,7 +1,5 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.extension.AbstractExtension; -import com.gitee.starblues.extension.ExtensionFactory; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginListener; import com.gitee.starblues.integration.listener.PluginListenerFactory; @@ -23,15 +21,6 @@ public abstract class AbstractPluginApplication implements PluginApplication { protected final PluginListenerFactory listenerFactory = new PluginListenerFactory(); protected final PluginStateListenerFactory pluginStateListenerFactory = new PluginStateListenerFactory(); - @Override - public PluginApplication addExtension(AbstractExtension extension) { - if(extension == null){ - return this; - } - extension.setPluginApplication(this); - ExtensionFactory.addExtension(extension); - return this; - } @Override public void addListener(PluginListener pluginListener) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index 7ef3dc8..ec7b847 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -1,16 +1,25 @@ package com.gitee.starblues.integration.application; +import com.gitee.starblues.annotation.Extract; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.user.PluginUser; +import com.gitee.starblues.spring.extract.DefaultExtractFactory; +import com.gitee.starblues.spring.extract.DefaultOpExtractFactory; +import com.gitee.starblues.spring.extract.ExtractFactory; +import com.gitee.starblues.spring.extract.OpExtractFactory; +import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; +import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; @@ -47,7 +56,9 @@ public class DefaultPluginApplication extends AbstractPluginApplication { if(!(pluginOperator instanceof PluginOperatorWrapper)){ pluginOperator = new PluginOperatorWrapper(pluginOperator, configuration); } - setBeanFactory(applicationContext); + GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext; + setBeanFactory(genericApplicationContext); + initExtractFactory(genericApplicationContext); pluginOperator.initPlugins(listener); beInitialized.set(true); } catch (Exception e) { @@ -89,30 +100,39 @@ public class DefaultPluginApplication extends AbstractPluginApplication { return pluginUser; } -// /** -// * 将pf4j中的监听器加入 -// * @param pluginManager pluginManager -// * @param applicationContext ApplicationContext -// */ -// private void addPf4jStateListener(PluginManager pluginManager, ApplicationContext applicationContext){ -// List pluginStateListeners = pluginStateListenerFactory -// .buildListenerClass((GenericApplicationContext) applicationContext); -// if(ObjectUtils.isEmpty(pluginStateListeners)){ -// return; -// } -// for (PluginStateListener pluginStateListener : pluginStateListeners) { -// pluginManager.addPluginStateListener(pluginStateListener); -// } -// } + /** + * 初始化扩展工厂 + * @param applicationContext applicationContext + */ + private void initExtractFactory(GenericApplicationContext applicationContext){ + ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); + DefaultExtractFactory defaultExtractFactory = (DefaultExtractFactory)ExtractFactory.getInstant(); + initMainExtract((OpExtractFactory)defaultExtractFactory.getTarget(), beanFactory); + } + /** + * 初始化主程序中的扩展 + * @param opExtractFactory opExtractFactory + * @param beanFactory beanFactory + */ + private void initMainExtract(OpExtractFactory opExtractFactory, ListableBeanFactory beanFactory){ + // 获取主程序的扩展 + Map extractMap = beanFactory.getBeansWithAnnotation(Extract.class); + if(ObjectUtils.isEmpty(extractMap)){ + return; + } + for (Object extract : extractMap.values()) { + opExtractFactory.addOfMain(extract); + } + } /** * 直接将 PluginOperator 和 PluginUser 注入到ApplicationContext容器中 * @param applicationContext ApplicationContext */ - private void setBeanFactory(ApplicationContext applicationContext){ - GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext; - DefaultListableBeanFactory defaultListableBeanFactory = genericApplicationContext.getDefaultListableBeanFactory(); + @Deprecated + private void setBeanFactory(GenericApplicationContext applicationContext){ + DefaultListableBeanFactory defaultListableBeanFactory = applicationContext.getDefaultListableBeanFactory(); defaultListableBeanFactory.registerSingleton(pluginOperator.getClass().getName(), pluginOperator); defaultListableBeanFactory.registerSingleton(pluginUser.getClass().getName(), pluginUser); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java index 1df096d..c5b27cf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java @@ -1,6 +1,5 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.extension.AbstractExtension; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.listener.PluginListener; import com.gitee.starblues.integration.operator.EmptyPluginOperator; @@ -34,11 +33,6 @@ public class EmptyPluginApplication implements PluginApplication{ return new EmptyPluginUser(); } - @Override - public PluginApplication addExtension(AbstractExtension extension) { - return null; - } - @Override public void addListener(PluginListener pluginListener) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java index c85f0e5..1c229dc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java @@ -1,6 +1,5 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.extension.AbstractExtension; import com.gitee.starblues.integration.PluginListenerContext; import com.gitee.starblues.integration.PluginStateListenerContext; import com.gitee.starblues.integration.listener.PluginInitializerListener; @@ -34,12 +33,4 @@ public interface PluginApplication extends PluginListenerContext, PluginStateLis * @return 插件操作者 */ PluginUser getPluginUser(); - - /** - * 添加扩展 - * @param extension 扩展类 - * @return PluginApplication - */ - PluginApplication addExtension(AbstractExtension extension); - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java index f5d1563..71a936a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java @@ -1,6 +1,5 @@ package com.gitee.starblues.integration.listener; -import com.gitee.starblues.extension.ExtensionInitializer; import org.springframework.context.ApplicationContext; /** @@ -20,8 +19,7 @@ public class DefaultInitializerListener implements PluginInitializerListener{ @Override public void before() { - // 初始化扩展注册信息 - ExtensionInitializer.initialize(applicationContext); + } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 690a4ef..6a1fef3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -1,7 +1,6 @@ package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; @@ -11,7 +10,6 @@ import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; @@ -210,24 +208,24 @@ public class PluginOperatorWrapper implements PluginOperator{ * @throws Exception 检查异常 */ private void checkIsUnRegistry(String pluginId) throws Exception{ - ConfigurableApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); - if(pluginApplicationContext == null){ - log.error("Plugin '{}' Not found ApplicationContext. So cannot found and execute unRegistryValidator", - pluginId); - return; - } - List unRegistryValidators = SpringBeanUtils.getBeans(pluginApplicationContext, UnRegistryValidator.class); - for (UnRegistryValidator unRegistryValidator : unRegistryValidators) { - UnRegistryValidator.Result result = unRegistryValidator.verify(); - if(result.isVerify()){ - return; - } - String message = result.getMessage(); - if(StringUtils.isNullOrEmpty(message)){ - message = "Plugin [" + pluginId + "] Stop or Uninstall be banned"; - } - throw new Exception(message); - } +// ConfigurableApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); +// if(pluginApplicationContext == null){ +// log.error("Plugin '{}' Not found ApplicationContext. So cannot found and execute unRegistryValidator", +// pluginId); +// return; +// } +// List unRegistryValidators = SpringBeanUtils.getBeans(pluginApplicationContext, UnRegistryValidator.class); +// for (UnRegistryValidator unRegistryValidator : unRegistryValidators) { +// UnRegistryValidator.Result result = unRegistryValidator.verify(); +// if(result.isVerify()){ +// return; +// } +// String message = result.getMessage(); +// if(StringUtils.isNullOrEmpty(message)){ +// message = "Plugin [" + pluginId + "] Stop or Uninstall be banned"; +// } +// throw new Exception(message); +// } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java index f4d9e4c..70deb81 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java @@ -1,7 +1,5 @@ package com.gitee.starblues.integration.user; -import com.gitee.starblues.core.PluginManager; -import com.gitee.starblues.factory.process.pipe.PluginInfoContainers; import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,92 +77,95 @@ public class DefaultPluginUser implements PluginUser{ @Override public List getPluginBeans(String pluginId, Class aClass) { - ConfigurableApplicationContext pluginApplicationContext = - PluginInfoContainers.getPluginApplicationContext(pluginId); - if(pluginApplicationContext == null){ - return Collections.emptyList(); - } - return SpringBeanUtils.getBeans(pluginApplicationContext, aClass); +// ConfigurableApplicationContext pluginApplicationContext = +// PluginInfoContainers.getPluginApplicationContext(pluginId); +// if(pluginApplicationContext == null){ +// return Collections.emptyList(); +// } +// return SpringBeanUtils.getBeans(pluginApplicationContext, aClass); + return null; } @Override public List getPluginBeansWithAnnotation(Class annotationType) { - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); - List beans = new ArrayList<>(); - for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { - Map beanMap = pluginApplicationContext.getBeansWithAnnotation(annotationType); - if(!ObjectUtils.isEmpty(beanMap)){ - beans.addAll(beanMap.values()); - } - } - return beans; +// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); +// List beans = new ArrayList<>(); +// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { +// Map beanMap = pluginApplicationContext.getBeansWithAnnotation(annotationType); +// if(!ObjectUtils.isEmpty(beanMap)){ +// beans.addAll(beanMap.values()); +// } +// } +// return beans; + return null; } @Override public List getPluginBeansWithAnnotation(String pluginId, Class annotationType) { - ConfigurableApplicationContext genericApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); - if(genericApplicationContext == null){ - return Collections.emptyList(); - } - Map beanMap = genericApplicationContext.getBeansWithAnnotation(annotationType); - if(!ObjectUtils.isEmpty(beanMap)){ - return new ArrayList<>(beanMap.values()); - } else { - return Collections.emptyList(); - } +// ConfigurableApplicationContext genericApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); +// if(genericApplicationContext == null){ +// return Collections.emptyList(); +// } +// Map beanMap = genericApplicationContext.getBeansWithAnnotation(annotationType); +// if(!ObjectUtils.isEmpty(beanMap)){ +// return new ArrayList<>(beanMap.values()); +// } else { +// return Collections.emptyList(); +// } + return null; } @Override public T generateNewInstance(T object) { - if(object == null){ - return null; - } - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); - pluginApplicationContexts.add(parentApplicationContext); - Class aClass = object.getClass(); - for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { - try { - // 判断是否存在 - pluginApplicationContext.getBean(aClass); - Object newBean = pluginApplicationContext.getBeanFactory() - .createBean(aClass); - return (T) newBean; - } catch (Exception e){ - // 忽略 - } - } +// if(object == null){ +// return null; +// } +// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); +// pluginApplicationContexts.add(parentApplicationContext); +// Class aClass = object.getClass(); +// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { +// try { +// // 判断是否存在 +// pluginApplicationContext.getBean(aClass); +// Object newBean = pluginApplicationContext.getBeanFactory() +// .createBean(aClass); +// return (T) newBean; +// } catch (Exception e){ +// // 忽略 +// } +// } return null; } private T getBean(String name, boolean haveParent){ - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); - if(haveParent){ - pluginApplicationContexts.add(parentApplicationContext); - } - for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { - if(pluginApplicationContext.containsBean(name)){ - return (T) pluginApplicationContext.getBean(name); - } - } +// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); +// if(haveParent){ +// pluginApplicationContexts.add(parentApplicationContext); +// } +// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { +// if(pluginApplicationContext.containsBean(name)){ +// return (T) pluginApplicationContext.getBean(name); +// } +// } return null; } private T getBean(Class aClass, boolean haveParent) { - List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); - if(haveParent){ - pluginApplicationContexts.add(parentApplicationContext); - } - for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { - try { - T bean = pluginApplicationContext.getBean(aClass); - if(bean != null){ - return bean; - } - } catch (Exception e){ - // 忽略 - } - } +// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); +// if(haveParent){ +// pluginApplicationContexts.add(parentApplicationContext); +// } +// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { +// try { +// T bean = pluginApplicationContext.getBean(aClass); +// if(bean != null){ +// return bean; +// } +// } catch (Exception e){ +// // 忽略 +// } +// } return null; } @@ -176,27 +177,28 @@ public class DefaultPluginUser implements PluginUser{ * @return List */ private List getBeans(Class aClass, int type) { - List pluginApplicationContexts = new ArrayList<>(1); - - if(type == 1){ - pluginApplicationContexts.add(parentApplicationContext); - } else if(type == 2){ - pluginApplicationContexts.addAll(PluginInfoContainers.getPluginApplicationContexts()); - } else if(type == 3){ - pluginApplicationContexts.add(parentApplicationContext); - pluginApplicationContexts.addAll(PluginInfoContainers.getPluginApplicationContexts()); - } else { - return Collections.emptyList(); - } - - List result = new ArrayList<>(); - for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { - List pluginBeans = SpringBeanUtils.getBeans(pluginApplicationContext, aClass); - if(!pluginBeans.isEmpty()){ - result.addAll(pluginBeans); - } - } - return result; +// List pluginApplicationContexts = new ArrayList<>(1); +// +// if(type == 1){ +// pluginApplicationContexts.add(parentApplicationContext); +// } else if(type == 2){ +// pluginApplicationContexts.addAll(PluginInfoContainers.getPluginApplicationContexts()); +// } else if(type == 3){ +// pluginApplicationContexts.add(parentApplicationContext); +// pluginApplicationContexts.addAll(PluginInfoContainers.getPluginApplicationContexts()); +// } else { +// return Collections.emptyList(); +// } +// +// List result = new ArrayList<>(); +// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { +// List pluginBeans = SpringBeanUtils.getBeans(pluginApplicationContext, aClass); +// if(!pluginBeans.isEmpty()){ +// result.addAll(pluginBeans); +// } +// } +// return result; + return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java index 5c03962..09570e1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java @@ -1,6 +1,5 @@ package com.gitee.starblues.realize; -import com.gitee.starblues.factory.PluginRegistryInfo; import com.gitee.starblues.integration.operator.module.PluginInfo; import com.gitee.starblues.utils.SpringBeanUtils; import org.pf4j.PluginManager; @@ -22,119 +21,119 @@ import java.util.Set; */ public class ConfigDefinitionTip { - private final PluginRegistryInfo pluginRegistryInfo; - - public ConfigDefinitionTip(PluginRegistryInfo pluginRegistryInfo) { - this.pluginRegistryInfo = pluginRegistryInfo; - } - - /** - * 得到当前插件信息 - * @return 插件信息 - */ - public PluginInfo getCurrentPluginInfo(){ - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - PluginManager pluginManager = pluginWrapper.getPluginManager(); -// return new PluginInfo(pluginWrapper.getDescriptor(), pluginWrapper.getPluginState(), -// pluginWrapper.getPluginPath().toAbsolutePath().toString(), -// pluginManager.getRuntimeMode().toString()); - return null; - } - - /** - * 得到主程序的 ApplicationContext - * @return ApplicationContext - */ - public ApplicationContext getMainApplication() { - return pluginRegistryInfo.getMainApplicationContext(); - } - - /** - * 获取当前插件的其他的ConfigDefinition - * @param configDefinitionClass ConfigDefinition的类类型 - * @param 类类型 - * @return T - */ - public T getOtherConfigDefinition(Class configDefinitionClass){ - return SpringBeanUtils.getObjectClass( - pluginRegistryInfo.getConfigSingletons(), - configDefinitionClass); - } - - /** - * 将Springboot类型的配置文件中的值映射为bean - * 注意: 只针对插件扩展的 springboot 配置文件生效 - * @param prefix 配置文件中的前置, 比如: plugin.config - * @param type 配置文件中结构对应的类类型, 比如: plugin.config 下定义的键值对和type类类型一致 - * @param 类类型 - * @return T - */ - public T getConfigOfBean(String prefix, Class type){ - return pluginRegistryInfo.getPluginBinder() - .bind(prefix, Bindable.of(type)) - .orElseGet(() -> null); - } - - /** - * 将Springboot类型的配置文件中的值映射为 List - * 注意: 只针对插件扩展的 springboot 配置文件生效 - * @param prefix 配置文件中的前置, 比如: plugin.config - * @param type List元素的类类型 - * @param List中定义的类类型 - * @return List - */ - public List getConfigOfList(String prefix, Class type){ - return pluginRegistryInfo.getPluginBinder() - .bind(prefix, Bindable.listOf(type)) - .orElseGet(Collections::emptyList); - } - - /** - * 将Springboot类型的配置文件中的值映射为 Set - * 注意: 只针对插件扩展的 springboot 配置文件生效 - * @param prefix 配置文件中的前置, 比如: plugin.config - * @param type Set元素的类类型 - * @param 类类型 - * @return Set - */ - public Set getConfigOfSet(String prefix, Class type){ - return pluginRegistryInfo.getPluginBinder() - .bind(prefix, Bindable.setOf(type)) - .orElseGet(Collections::emptySet); - } - - - /** - * 将Springboot类型的配置文件中的值映射为 Map - * 注意: 只针对插件扩展的 springboot 配置文件生效 - * @param prefix 配置文件中的前置, 比如: plugin.config - * @param keyType map的key元素类型 - * @param valueType map的值元素类型 - * @param map key 元素的类类型 - * @param map value 元素的类类型 - * @return Map - */ - public Map getConfigOfSet(String prefix, Class keyType, Class valueType){ - return pluginRegistryInfo.getPluginBinder() - .bind(prefix, Bindable.mapOf(keyType, valueType)) - .orElseGet(Collections::emptyMap); - } - - - /** - * 返回当前插件的ConfigurableEnvironment - * @return ConfigurableEnvironment - */ - public ConfigurableEnvironment getPluginEnvironment(){ - return pluginRegistryInfo.getPluginApplicationContext().getEnvironment(); - } - - /** - * 返回当前插件的Binder - * @return Binder - */ - public Binder getPluginBinder(){ - return pluginRegistryInfo.getPluginBinder(); - } +// private final PluginRegistryInfo pluginRegistryInfo; +// +// public ConfigDefinitionTip(PluginRegistryInfo pluginRegistryInfo) { +// this.pluginRegistryInfo = pluginRegistryInfo; +// } +// +// /** +// * 得到当前插件信息 +// * @return 插件信息 +// */ +// public PluginInfo getCurrentPluginInfo(){ +// PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); +// PluginManager pluginManager = pluginWrapper.getPluginManager(); +//// return new PluginInfo(pluginWrapper.getDescriptor(), pluginWrapper.getPluginState(), +//// pluginWrapper.getPluginPath().toAbsolutePath().toString(), +//// pluginManager.getRuntimeMode().toString()); +// return null; +// } +// +// /** +// * 得到主程序的 ApplicationContext +// * @return ApplicationContext +// */ +// public ApplicationContext getMainApplication() { +// return pluginRegistryInfo.getMainApplicationContext(); +// } +// +// /** +// * 获取当前插件的其他的ConfigDefinition +// * @param configDefinitionClass ConfigDefinition的类类型 +// * @param 类类型 +// * @return T +// */ +// public T getOtherConfigDefinition(Class configDefinitionClass){ +// return SpringBeanUtils.getObjectClass( +// pluginRegistryInfo.getConfigSingletons(), +// configDefinitionClass); +// } +// +// /** +// * 将Springboot类型的配置文件中的值映射为bean +// * 注意: 只针对插件扩展的 springboot 配置文件生效 +// * @param prefix 配置文件中的前置, 比如: plugin.config +// * @param type 配置文件中结构对应的类类型, 比如: plugin.config 下定义的键值对和type类类型一致 +// * @param 类类型 +// * @return T +// */ +// public T getConfigOfBean(String prefix, Class type){ +// return pluginRegistryInfo.getPluginBinder() +// .bind(prefix, Bindable.of(type)) +// .orElseGet(() -> null); +// } +// +// /** +// * 将Springboot类型的配置文件中的值映射为 List +// * 注意: 只针对插件扩展的 springboot 配置文件生效 +// * @param prefix 配置文件中的前置, 比如: plugin.config +// * @param type List元素的类类型 +// * @param List中定义的类类型 +// * @return List +// */ +// public List getConfigOfList(String prefix, Class type){ +// return pluginRegistryInfo.getPluginBinder() +// .bind(prefix, Bindable.listOf(type)) +// .orElseGet(Collections::emptyList); +// } +// +// /** +// * 将Springboot类型的配置文件中的值映射为 Set +// * 注意: 只针对插件扩展的 springboot 配置文件生效 +// * @param prefix 配置文件中的前置, 比如: plugin.config +// * @param type Set元素的类类型 +// * @param 类类型 +// * @return Set +// */ +// public Set getConfigOfSet(String prefix, Class type){ +// return pluginRegistryInfo.getPluginBinder() +// .bind(prefix, Bindable.setOf(type)) +// .orElseGet(Collections::emptySet); +// } +// +// +// /** +// * 将Springboot类型的配置文件中的值映射为 Map +// * 注意: 只针对插件扩展的 springboot 配置文件生效 +// * @param prefix 配置文件中的前置, 比如: plugin.config +// * @param keyType map的key元素类型 +// * @param valueType map的值元素类型 +// * @param map key 元素的类类型 +// * @param map value 元素的类类型 +// * @return Map +// */ +// public Map getConfigOfSet(String prefix, Class keyType, Class valueType){ +// return pluginRegistryInfo.getPluginBinder() +// .bind(prefix, Bindable.mapOf(keyType, valueType)) +// .orElseGet(Collections::emptyMap); +// } +// +// +// /** +// * 返回当前插件的ConfigurableEnvironment +// * @return ConfigurableEnvironment +// */ +// public ConfigurableEnvironment getPluginEnvironment(){ +// return pluginRegistryInfo.getPluginApplicationContext().getEnvironment(); +// } +// +// /** +// * 返回当前插件的Binder +// * @return Binder +// */ +// public Binder getPluginBinder(){ +// return pluginRegistryInfo.getPluginBinder(); +// } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java index 66548ff..741e6a8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java @@ -1,14 +1,15 @@ package com.gitee.starblues.spring; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.ListableBeanFactory; - -import java.util.Set; - /** * @author starBlues * @version 1.0 */ -public interface ApplicationContext extends ListableBeanFactory { +public interface ApplicationContext extends AutoCloseable { + + /** + * 得到 SpringBeanFactory + * @return SpringBeanFactory + */ + SpringBeanFactory getSpringBeanFactory(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java index 15f8635..5381a46 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java @@ -1,22 +1,24 @@ package com.gitee.starblues.spring; -import org.springframework.context.support.GenericApplicationContext; - - /** * @author starBlues * @version 1.0 */ -public class ApplicationContextProxy { - - - - -// public static MainApplicationContext getMainApplicationContext(GenericApplicationContext applicationContext){ -// ProxyInvokeFactory proxyInvokeFactory = new DiffProxyInvokeFactory(applicationContext); -// return proxyInvokeFactory.getObject(MainApplicationContext.class); -// } - - - +public class ApplicationContextProxy extends GenericApplicationContext{ + + public ApplicationContextProxy(Object targetBeanFactory, + AutoCloseable autoCloseable) { + super(autoCloseable); + setSpringBeanFactory(createSpringBeanFactory(targetBeanFactory)); + } + + public ApplicationContextProxy(Object targetBeanFactory) { + super(); + setSpringBeanFactory(createSpringBeanFactory(targetBeanFactory)); + } + + protected SpringBeanFactory createSpringBeanFactory(Object targetBeanFactory){ + ProxyFactory proxyFactory = new CacheJdkSameTypeParamProxyFactory(targetBeanFactory); + return proxyFactory.getObject(SpringBeanFactory.class); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java new file mode 100644 index 0000000..2d5c3f8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java @@ -0,0 +1,44 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.utils.ReflectionUtils; + +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class CacheJdkSameTypeParamProxyFactory extends JdkSameTypeParamProxyFactory{ + + private final Map methodCache = new ConcurrentHashMap<>(); + + public CacheJdkSameTypeParamProxyFactory(Object target) { + super(target); + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Method targetMethod = methodCache.get(method); + if(targetMethod == null){ + Class[] paramTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + paramTypes[i] = args[i].getClass(); + } + targetMethod = ReflectionUtils.findMethod(target.getClass(), method.getName(), paramTypes); + if(targetMethod != null){ + methodCache.put(method, targetMethod); + } else { + throw ReflectionUtils.getNoSuchMethodException(target.getClass(), method.getName(), paramTypes); + } + } + return targetMethod.invoke(target, args); + } + + + + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java deleted file mode 100644 index c0471af..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CglibProxyInvokeFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.utils.ReflectionUtils; -import org.springframework.cglib.proxy.Enhancer; -import org.springframework.cglib.proxy.MethodInterceptor; -import org.springframework.cglib.proxy.MethodProxy; - -import java.lang.reflect.Method; - -/** - * @author starBlues - * @version 1.0 - */ -public class CglibProxyInvokeFactory implements ProxyInvokeFactory { - - private final Object source; - - public CglibProxyInvokeFactory(Object source) { - this.source = source; - } - - @Override - public T getObject(Class interfacesClass) { - Enhancer enhancer = new Enhancer(); - enhancer.setSuperclass(interfacesClass); - enhancer.setCallback(new MethodInvoke(source)); - enhancer.setClassLoader(interfacesClass.getClassLoader()); - try { - return (T)enhancer.create(); - } catch (Exception e){ - System.out.println(interfacesClass); - e.printStackTrace(); - return null; - } - } - - private static class MethodInvoke implements MethodInterceptor { - - private final Object source; - - private MethodInvoke(Object source) { - this.source = source; - } - - @Override - public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { - Method delegateMethod = ReflectionUtils.findMethod(source.getClass(), method.getName(), - method.getParameterTypes()); - if(delegateMethod == null){ - throw ReflectionUtils.getNoSuchMethodException(source.getClass(), method.getName(), - method.getParameterTypes()); - } - return delegateMethod.invoke(source, objects); - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java deleted file mode 100644 index d54f24f..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultPluginSpringApplication.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.integration.AutoIntegrationConfiguration; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.environment.PluginEnvironmentProcessor; -import com.gitee.starblues.spring.environment.PluginLocalConfigFileProcessor; -import com.gitee.starblues.spring.processor.SpringPluginProcessor; -import com.gitee.starblues.spring.processor.SpringPluginProcessorFactory; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.io.ResourceLoader; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * PluginSpringApplication - * @author starBlues - * @version 3.0.0 - */ -public class DefaultPluginSpringApplication implements PluginSpringApplication{ - - private final AtomicBoolean isStarted = new AtomicBoolean(false); - - private final GenericApplicationContext mainApplicationContext; - - private final DefaultListableBeanFactory beanFactory; - private final PluginApplicationContext applicationContext; - private final IntegrationConfiguration configuration; - private final List environmentProcessors; - - private final SpringPluginRegistryInfo registryInfo; - - private SpringPluginProcessor springPluginProcessor; - - public DefaultPluginSpringApplication(GenericApplicationContext mainApplicationContext, - SpringPluginRegistryInfo registryInfo){ - Assert.isNotNull(mainApplicationContext, "参数 mainApplicationContext 不能为空"); - Assert.isNotNull(registryInfo, "参数 registryInfo 不能为空"); - this.mainApplicationContext = mainApplicationContext; - this.registryInfo = registryInfo; - - PluginWrapper pluginWrapper = registryInfo.getPluginWrapper(); - ClassLoader classLoader = pluginWrapper.getPluginClassLoader(); - this.beanFactory = new PluginListableBeanFactory(mainApplicationContext); - this.beanFactory.setBeanClassLoader(classLoader); - this.configuration = mainApplicationContext.getBean(AutoIntegrationConfiguration.class); - this.applicationContext = new PluginApplicationContext(beanFactory, classLoader); - this.environmentProcessors = new ArrayList<>(); - addDefaultEnvironmentProcessor(pluginWrapper); - - springPluginProcessor = new SpringPluginProcessorFactory(SpringPluginProcessor.RunMode.PLUGIN); - } - - protected void addDefaultEnvironmentProcessor(PluginWrapper pluginWrapper){ - String configFileName = pluginWrapper.getPluginDescriptor().getConfigFileName(); - PluginLocalConfigFileProcessor configFileProcessor = new PluginLocalConfigFileProcessor(configuration); - if(!ObjectUtils.isEmpty(configFileName)){ - configFileProcessor.setSearchNames(PluginFileUtils.getFileName(configFileName)); - } - addEnvironmentProcessor(configFileProcessor); - } - - public void addEnvironmentProcessor(PluginEnvironmentProcessor environmentProcessor){ - if(environmentProcessor == null){ - return; - } - environmentProcessors.add(environmentProcessor); - } - - - @Override - public GenericApplicationContext run() throws Exception{ - synchronized (isStarted){ - if(isStarted.get()){ - throw new RuntimeException("已经运行了PluginSpringApplication, 无法再运行"); - } - try { - springPluginProcessor.initialize(mainApplicationContext); - processEnvironment(); - addPluginEnvironment(); - addDefaultProcessor(); - springPluginProcessor.refreshBefore(registryInfo); - refresh(); - springPluginProcessor.refreshAfter(registryInfo); - isStarted.set(true); - return applicationContext; - } catch (Exception e){ - springPluginProcessor.failure(registryInfo); - throw e; - } - } - } - - protected void processEnvironment() { - List orderPluginEnvironmentProcessor = - CommonUtils.order(environmentProcessors, Ordered::getOrder); - for (PluginEnvironmentProcessor environmentProcessor : orderPluginEnvironmentProcessor) { - environmentProcessor.postProcessEnvironment(applicationContext.getEnvironment(), - applicationContext.getResourceLoader()); - } - } - - private void addPluginEnvironment() { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - Map pluginEnvironment = new HashMap<>(); - pluginEnvironment.put(AutoIntegrationConfiguration.ENABLE_KEY, false); - pluginEnvironment.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); - environment.getPropertySources().addFirst(new MapPropertySource("pluginEnvironment", pluginEnvironment)); - } - - private void addDefaultProcessor() { - // 注册 ConfigurationPropertiesBindingPostProcessor, 用于将配置信息绑定到Bean上 - ConfigurationPropertiesBindingPostProcessor.register(applicationContext); - applicationContext.register(PropertySourcesPlaceholderConfigurer.class); - } - - - protected void loadBean() { - //beanDefinitionLoader.load(); - } - - protected void refresh() { - applicationContext.refresh(); - String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); - for (String beanDefinitionName : beanDefinitionNames) { - System.out.println(beanDefinitionName); - } - } - - @Override - public void close() { - synchronized (isStarted){ - if(!isStarted.get()){ - throw new RuntimeException("PluginSpringApplication没有运行, 不能close"); - } - try { - springPluginProcessor.close(registryInfo); - } catch (Exception e) { - e.printStackTrace(); - } finally { - applicationContext.close(); - isStarted.set(false); - } - } - } - - @Override - public GenericApplicationContext getApplicationContext() { - return applicationContext; - } - - @Override - public ResourceLoader getResourceLoader() { - return applicationContext.getResourceLoader(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java deleted file mode 100644 index 4c98165..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultRegistryInfo.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.gitee.starblues.spring; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class DefaultRegistryInfo implements RegistryInfo{ - - private final Map registryInfo = new ConcurrentHashMap<>(); - - @Override - public void addRegistryInfo(String key, Object value) { - registryInfo.put(key, value); - } - - @SuppressWarnings("unchecked") - @Override - public T getRegistryInfo(String key) { - Object o = registryInfo.get(key); - if(o == null){ - return null; - } - return (T) o; - } - - @Override - public T getRegistryInfo(String key, Supplier notExistCreate) { - T t = getRegistryInfo(key); - if(t != null){ - return t; - } - t = notExistCreate.get(); - registryInfo.put(key, t); - return t; - } - - @Override - public void removeRegistryInfo(String key) { - registryInfo.remove(key); - } - - @Override - public void clearRegistryInfo() { - registryInfo.clear(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java deleted file mode 100644 index f089862..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPlugin.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.core.loader.PluginWrapper; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class DefaultSpringPlugin implements SpringPlugin { - - private final Map registryInfoMap = new ConcurrentHashMap<>(); - - private final GenericApplicationContext mainApplicationContext; - - public DefaultSpringPlugin(GenericApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - } - - @Override - public synchronized void registry(PluginWrapper pluginWrapper) throws Exception { - SpringPluginRegistryInfo registryInfo = createRegistryInfo(pluginWrapper); - registryInfo.getPluginSpringApplication().run(); - registryInfoMap.put(pluginWrapper.getPluginId(), registryInfo); - } - - @Override - public synchronized void unRegistry(String pluginId) throws Exception { - SpringPluginRegistryInfo springPluginRegistryInfo = registryInfoMap.get(pluginId); - if(springPluginRegistryInfo == null){ - return; - } - springPluginRegistryInfo.getPluginSpringApplication().close(); - registryInfoMap.remove(pluginId); - } - - @Override - public Map getPluginRegistryInfos() { - return new HashMap<>(registryInfoMap); - } - - protected SpringPluginRegistryInfo createRegistryInfo(PluginWrapper pluginWrapper){ - return new DefaultSpringPluginRegistryInfo( - pluginWrapper, mainApplicationContext - ); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java deleted file mode 100644 index f9a2f7c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DefaultSpringPluginRegistryInfo.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.integration.IntegrationConfiguration; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class DefaultSpringPluginRegistryInfo extends DefaultRegistryInfo implements SpringPluginRegistryInfo{ - - private final PluginWrapper pluginWrapper; - private final PluginSpringApplication pluginSpringApplication; - private final GenericApplicationContext mainApplicationContext; - private final IntegrationConfiguration configuration; - - public DefaultSpringPluginRegistryInfo(PluginWrapper pluginWrapper, - GenericApplicationContext mainApplicationContext) { - this.pluginWrapper = pluginWrapper; - this.pluginSpringApplication = new DefaultPluginSpringApplication(mainApplicationContext, this); - this.mainApplicationContext = mainApplicationContext; - this.configuration = mainApplicationContext.getBean(IntegrationConfiguration.class); - } - - @Override - public PluginWrapper getPluginWrapper() { - return pluginWrapper; - } - - @Override - public PluginSpringApplication getPluginSpringApplication() { - return pluginSpringApplication; - } - - @Override - public ConfigurableApplicationContext getMainApplicationContext() { - return mainApplicationContext; - } - - @Override - public IntegrationConfiguration getConfiguration() { - return configuration; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java deleted file mode 100644 index a99f6f4..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/DiffProxyInvokeFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -//package com.gitee.starblues.spring; -// -//import java.lang.reflect.Proxy; -// -///** -// * @author starBlues -// * @version 1.0 -// */ -//public class DiffProxyInvokeFactory implements ProxyInvokeFactory{ -// -// private final Object invokeSource; -// private final ClassLoader invokeClassLoader; -// -// public DiffProxyInvokeFactory(Object invokeSource) { -// this(invokeSource, null); -// } -// -// public DiffProxyInvokeFactory(Object invokeSource, ClassLoader invokeClassLoader) { -// this.invokeSource = invokeSource; -// if(invokeClassLoader == null){ -// this.invokeClassLoader = invokeSource.getClass().getClassLoader(); -// } else { -// this.invokeClassLoader = invokeClassLoader; -// } -// } -// -// @SuppressWarnings("unchecked") -// @Override -// public T getObject(Class interfacesClass) { -// Class[] interfaces = new Class[]{ interfacesClass }; -// ProxyInvoke proxy = new ProxyInvoke(invokeSource); -// return (T) Proxy.newProxyInstance(invokeClassLoader, interfaces, proxy); -// } -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java new file mode 100644 index 0000000..0b9c8ef --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java @@ -0,0 +1,38 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.utils.Assert; + +/** + * @author starBlues + * @version 1.0 + */ +public class GenericApplicationContext implements ApplicationContext{ + + public final AutoCloseable autoCloseable; + + protected SpringBeanFactory springBeanFactory; + + public GenericApplicationContext() { + this(null); + } + + public GenericApplicationContext(AutoCloseable autoCloseable) { + this.autoCloseable = autoCloseable; + } + + public void setSpringBeanFactory(SpringBeanFactory springBeanFactory){ + this.springBeanFactory = Assert.isNotNull(springBeanFactory, "参数 springBeanFactory 不能为空"); + } + + @Override + public SpringBeanFactory getSpringBeanFactory() { + return springBeanFactory; + } + + @Override + public void close() throws Exception { + if(autoCloseable != null){ + autoCloseable.close(); + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java new file mode 100644 index 0000000..59e226e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java @@ -0,0 +1,34 @@ +package com.gitee.starblues.spring; + +import com.gitee.starblues.utils.ReflectionUtils; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * @author starBlues + * @version 1.0 + */ +public class JdkSameTypeParamProxyFactory implements ProxyFactory, InvocationHandler { + + protected final Object target; + + public JdkSameTypeParamProxyFactory(Object target) { + this.target = target; + } + + @SuppressWarnings("unchecked") + @Override + public T getObject(Class interfacesClass) { + ClassLoader classLoader = interfacesClass.getClassLoader(); + Class[] interfaces = new Class[]{ interfacesClass }; + return (T) Proxy.newProxyInstance(classLoader, interfaces, this); + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return ReflectionUtils.invoke(target, method.getName(), args); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java index 51f8352..2d765e8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java @@ -1,6 +1,5 @@ package com.gitee.starblues.spring; -import java.util.Set; /** * @author starBlues @@ -8,11 +7,4 @@ import java.util.Set; */ public interface MainApplicationContext extends ApplicationContext { - - Object resolveDependency(Object descriptor, String requestingBeanName); - - - Object resolveDependency(Object descriptor, String requestingBeanName, - Set autowiredBeanNames, Object typeConverter); - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java new file mode 100644 index 0000000..285b7c7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java @@ -0,0 +1,16 @@ +package com.gitee.starblues.spring; + +/** + * @author starBlues + * @version 1.0 + */ +public class MainApplicationContextProxy extends ApplicationContextProxy implements MainApplicationContext{ + + public MainApplicationContextProxy(Object targetBeanFactory) { + super(targetBeanFactory); + } + + public MainApplicationContextProxy(Object targetBeanFactory, AutoCloseable autoCloseable) { + super(targetBeanFactory, autoCloseable); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java deleted file mode 100644 index 3e761fb..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextReflection.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.utils.ReflectionUtils; - -import java.lang.reflect.Field; -import java.util.Set; - -/** - * @author starBlues - * @version 1.0 - */ -public class MainApplicationContextReflection extends GenericApplicationContextReflection implements MainApplicationContext { - - private ClassLoader mainClassLoader; - - public MainApplicationContextReflection(Object mainGenericApplicationContext) { - super(mainGenericApplicationContext); - this.mainClassLoader = mainGenericApplicationContext.getClass().getClassLoader(); - } - - public void setMainClassLoader(ClassLoader mainClassLoader) { - this.mainClassLoader = mainClassLoader; - } - - @Override - public Object resolveDependency(Object descriptor, String requestingBeanName) { - - return null; - } - - @Override - public Object resolveDependency(Object descriptor, String requestingBeanName, - Set autowiredBeanNames, Object typeConverter) { - try { - Class descriptorClass = mainClassLoader.loadClass(descriptor.getClass().getName()); - Class typeConverterClass = mainClassLoader.loadClass(typeConverter.getClass().getName()); - - Object descriptorObject = descriptorClass.getConstructor(Field.class, boolean.class).newInstance( - ReflectionUtils.getField(descriptor, "field", Field.class), - ReflectionUtils.getField(descriptor, "required", boolean.class) - ); - - Object o = invokeReturn("getBeanFactory"); - return ReflectionUtils.invoke(o, "resolveDependency", descriptorObject, requestingBeanName, - autowiredBeanNames, typeConverterClass.getConstructor().newInstance()); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java deleted file mode 100644 index 42955e1..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginApplicationContext.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.utils.Assert; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.core.env.StandardEnvironment; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.ResourceLoader; - -/** - * 插件 ApplicationContext - * @author starBlues - * @version 3.0.0 - */ -public class PluginApplicationContext extends AnnotationConfigApplicationContext { - - private final ResourceLoader resourceLoader; - - public PluginApplicationContext(DefaultListableBeanFactory beanFactory, ClassLoader classLoader) { - super(beanFactory); - Assert.isNotNull(classLoader, "classLoader 不能为空"); - this.resourceLoader = new DefaultResourceLoader(classLoader); - setClassLoader(classLoader); - setResourceLoader(resourceLoader); - setEnvironment(new StandardEnvironment()); - } - - public ResourceLoader getResourceLoader() { - return resourceLoader; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java deleted file mode 100644 index 2ee5614..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginBeanDefinitionLoader.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.utils.Assert; -import org.springframework.beans.factory.BeanDefinitionStoreException; -import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; -import org.springframework.beans.factory.support.AbstractBeanDefinitionReader; -import org.springframework.beans.factory.support.BeanDefinitionReader; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; -import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; -import org.springframework.core.SpringProperties; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter; -import org.springframework.core.type.filter.TypeFilter; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -/** - * 加载插件中的bean - * @author starBlues - * @version 3.0.0 - */ -public class PluginBeanDefinitionLoader { - private static final boolean XML_ENABLED = !SpringProperties.getFlag("spring.xml.ignore"); - - private final Object[] sources; - - private final AnnotatedBeanDefinitionReader annotatedReader; - - private final AbstractBeanDefinitionReader xmlReader; - - private final BeanDefinitionReader groovyReader; - - private final ClassPathBeanDefinitionScanner scanner; - - private ResourceLoader resourceLoader; - - PluginBeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) { - Assert.isNotNull(registry, "参数 registry 不能为空"); - Assert.isNotEmpty(sources, "参数 sources 不能为空"); - this.sources = sources; - this.annotatedReader = new AnnotatedBeanDefinitionReader(registry); - this.xmlReader = (XML_ENABLED ? new XmlBeanDefinitionReader(registry) : null); - this.groovyReader = (isGroovyPresent() ? new GroovyBeanDefinitionReader(registry) : null); - this.scanner = new ClassPathBeanDefinitionScanner(registry); - this.scanner.addExcludeFilter(new PluginBeanDefinitionLoader.ClassExcludeFilter(sources)); - } - - void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { - this.annotatedReader.setBeanNameGenerator(beanNameGenerator); - this.scanner.setBeanNameGenerator(beanNameGenerator); - if (this.xmlReader != null) { - this.xmlReader.setBeanNameGenerator(beanNameGenerator); - } - } - - - void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - this.scanner.setResourceLoader(resourceLoader); - if (this.xmlReader != null) { - this.xmlReader.setResourceLoader(resourceLoader); - } - } - - - void setEnvironment(ConfigurableEnvironment environment) { - this.annotatedReader.setEnvironment(environment); - this.scanner.setEnvironment(environment); - if (this.xmlReader != null) { - this.xmlReader.setEnvironment(environment); - } - } - - void load() { - for (Object source : this.sources) { - load(source); - } - } - - private void load(Object source) { - Assert.isNotEmpty(source, "Source must not be null"); - if (source instanceof Class) { - load((Class) source); - return; - } - if (source instanceof Resource) { - load((Resource) source); - return; - } - if (source instanceof Package) { - load((Package) source); - return; - } - if (source instanceof CharSequence) { - load((CharSequence) source); - return; - } - throw new IllegalArgumentException("Invalid source type " + source.getClass()); - } - - private void load(Class source) { - if (isEligible(source)) { - this.annotatedReader.register(source); - } - } - - private void load(Resource source) { - if (Objects.requireNonNull(source.getFilename()).endsWith(".groovy")) { - if (this.groovyReader == null) { - throw new BeanDefinitionStoreException("Cannot load Groovy beans without Groovy on classpath"); - } - this.groovyReader.loadBeanDefinitions(source); - } - else { - if (this.xmlReader == null) { - throw new BeanDefinitionStoreException("Cannot load XML bean definitions when XML support is disabled"); - } - this.xmlReader.loadBeanDefinitions(source); - } - } - - private void load(Package source) { - this.scanner.scan(source.getName()); - } - - private void load(CharSequence source) { - String resolvedSource = this.scanner.getEnvironment().resolvePlaceholders(source.toString()); - // Attempt as a Class - try { - load(ClassUtils.forName(resolvedSource, null)); - return; - } - catch (IllegalArgumentException | ClassNotFoundException ex) { - // swallow exception and continue - } - // Attempt as Resources - if (loadAsResources(resolvedSource)) { - return; - } - // Attempt as package - Package packageResource = findPackage(resolvedSource); - if (packageResource != null) { - load(packageResource); - return; - } - throw new IllegalArgumentException("Invalid source '" + resolvedSource + "'"); - } - - private boolean loadAsResources(String resolvedSource) { - boolean foundCandidate = false; - Resource[] resources = findResources(resolvedSource); - for (Resource resource : resources) { - if (isLoadCandidate(resource)) { - foundCandidate = true; - load(resource); - } - } - return foundCandidate; - } - - private boolean isGroovyPresent() { - return ClassUtils.isPresent("groovy.lang.MetaClass", null); - } - - private Resource[] findResources(String source) { - ResourceLoader loader = (this.resourceLoader != null) ? this.resourceLoader - : new PathMatchingResourcePatternResolver(); - try { - if (loader instanceof ResourcePatternResolver) { - return ((ResourcePatternResolver) loader).getResources(source); - } - return new Resource[] { loader.getResource(source) }; - } - catch (IOException ex) { - throw new IllegalStateException("Error reading source '" + source + "'"); - } - } - - private boolean isLoadCandidate(Resource resource) { - if (resource == null || !resource.exists()) { - return false; - } - if (resource instanceof ClassPathResource) { - // A simple package without a '.' may accidentally get loaded as an XML - // document if we're not careful. The result of getInputStream() will be - // a file list of the package content. We double check here that it's not - // actually a package. - String path = ((ClassPathResource) resource).getPath(); - if (path.indexOf('.') == -1) { - try { - return Package.getPackage(path) == null; - } - catch (Exception ex) { - // Ignore - } - } - } - return true; - } - - private Package findPackage(CharSequence source) { - Package pkg = Package.getPackage(source.toString()); - if (pkg != null) { - return pkg; - } - try { - // Attempt to find a class in this package - ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); - Resource[] resources = resolver - .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); - for (Resource resource : resources) { - String className = StringUtils.stripFilenameExtension(resource.getFilename()); - load(Class.forName(source.toString() + "." + className)); - break; - } - } - catch (Exception ex) { - // swallow exception and continue - } - return Package.getPackage(source.toString()); - } - - /** - * Check whether the bean is eligible for registration. - * @param type candidate bean type - * @return true if the given bean type is eligible for registration, i.e. not a groovy - * closure nor an anonymous class - */ - private boolean isEligible(Class type) { - return !(type.isAnonymousClass() || isGroovyClosure(type) || hasNoConstructors(type)); - } - - private boolean isGroovyClosure(Class type) { - return type.getName().matches(".*\\$_.*closure.*"); - } - - private boolean hasNoConstructors(Class type) { - Constructor[] constructors = type.getDeclaredConstructors(); - return ObjectUtils.isEmpty(constructors); - } - - /** - * Simple {@link TypeFilter} used to ensure that specified {@link Class} sources are - * not accidentally re-added during scanning. - */ - private static class ClassExcludeFilter extends AbstractTypeHierarchyTraversingFilter { - - private final Set classNames = new HashSet<>(); - - ClassExcludeFilter(Object... sources) { - super(false, false); - for (Object source : sources) { - if (source instanceof Class) { - this.classNames.add(((Class) source).getName()); - } - } - } - - @Override - protected boolean matchClassName(String className) { - return this.classNames.contains(className); - } - - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java deleted file mode 100644 index a4255c5..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginListableBeanFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.gitee.starblues.spring; - -import org.springframework.beans.BeansException; -import org.springframework.beans.TypeConverter; -import org.springframework.beans.factory.config.DependencyDescriptor; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.lang.Nullable; - -import java.util.Set; - -/** - * 扩展 DefaultListableBeanFactory - * @author starBlues - * @version 3.0.0 - */ -public class PluginListableBeanFactory extends DefaultListableBeanFactory { - - private final DefaultListableBeanFactory mainDefaultListableBeanFactory; - - - public PluginListableBeanFactory(GenericApplicationContext applicationContext) { - this.mainDefaultListableBeanFactory = applicationContext.getDefaultListableBeanFactory(); - } - - - @Override - public Object resolveDependency(DependencyDescriptor descriptor, - @Nullable String requestingBeanName, - @Nullable Set autowiredBeanNames, - @Nullable TypeConverter typeConverter) throws BeansException{ - - try { - return super.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); - } catch (Exception e){ - return mainDefaultListableBeanFactory.resolveDependency(descriptor, - requestingBeanName, autowiredBeanNames, typeConverter); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java similarity index 63% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java index fef842d..896a2cd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvokeFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java @@ -1,10 +1,11 @@ package com.gitee.starblues.spring; /** + * 代理工厂 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ -public interface ProxyInvokeFactory { +public interface ProxyFactory { T getObject(Class interfacesClass); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java deleted file mode 100644 index f7f09a7..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyInvoke.java +++ /dev/null @@ -1,73 +0,0 @@ -//package com.gitee.starblues.spring; -// -//import com.gitee.starblues.utils.ObjectUtils; -//import com.gitee.starblues.utils.ReflectionUtils; -// -//import java.lang.reflect.InvocationHandler; -//import java.lang.reflect.Method; -//import java.util.List; -//import java.util.Objects; -// -///** -// * @author starBlues -// * @version 1.0 -// */ -//public class ProxyInvoke implements InvocationHandler { -// -// private final Object source; -// -// public ProxyInvoke(Object source) { -// this.source = source; -// } -// -// @Override -// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { -// String name = method.getName(); -// Method invokeMethod = findMethod(name, args); -// Class[] parameterTypes = invokeMethod.getParameterTypes(); -// Object[] invokeArgs = new Object[args.length]; -// for (int i = 0; i < parameterTypes.length; i++) { -// Class parameterType = parameterTypes[i]; -// Object arg = args[i]; -// Class aClass = arg.getClass(); -// if(parameterType == aClass){ -// // 类型一致 -// invokeArgs[i] = arg; -// } else { -// // 类型不一致 -// ProxyInvokeFactory factory = new DiffProxyInvokeFactory( -// arg, parameterType.getClassLoader() -// ); -// invokeArgs[i] = factory.getObject(); -// } -// } -// return invokeMethod.invoke(source, invokeArgs); -// } -// -// private Method findMethod(String sourceMethodName, Object[] args) throws Exception{ -// List methods = ReflectionUtils.findMethods(source.getClass(), sourceMethodName); -// if(ObjectUtils.isEmpty(methods)){ -// throw new NoSuchMethodException("Not found method:" + sourceMethodName); -// } -// for (Method m : methods) { -// if (m.getParameterCount() != args.length) { -// continue; -// } -// Class[] parameterTypes = m.getParameterTypes(); -// int matchCount = 0; -// for (int j = 0; j < parameterTypes.length; j++) { -// Class parameterType = parameterTypes[j]; -// Class aClass = args[j].getClass(); -// if (Objects.equals(parameterType.getName(), aClass.getName())) { -// matchCount++; -// } -// } -// if(matchCount == parameterTypes.length){ -// return m; -// } -// } -// throw new NoSuchMethodException("Not found method:" + sourceMethodName); -// } -// -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java deleted file mode 100644 index 8ea143d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/RegistryInfo.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gitee.starblues.spring; - -import java.util.function.Supplier; - -/** - * 注册信息 - * @author starBlues - * @version 3.0.0 - */ -public interface RegistryInfo { - - /** - * 添加注册的信息 - * @param key 注册信息key - * @param value 注册信息值 - */ - void addRegistryInfo(String key, Object value); - - /** - * 得到注册信息 - * @param key 注册信息key - * @return 注册信息的值 - */ - T getRegistryInfo(String key); - - /** - * 得到注册信息 - * @param key 注册信息key - * @param notExistCreate 不存在的话, 进行创建操作 - * @return 注册信息的值 - */ - T getRegistryInfo(String key, Supplier notExistCreate); - - - /** - * 移除注册信息 - * @param key 注册信息key - */ - void removeRegistryInfo(String key); - - /** - * 清除全部的注册信息 - */ - void clearRegistryInfo(); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java new file mode 100644 index 0000000..ea74c3d --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java @@ -0,0 +1,10 @@ +package com.gitee.starblues.spring; + +import org.springframework.beans.factory.ListableBeanFactory; + +/** + * @author starBlues + * @version 1.0 + */ +public interface SpringBeanFactory extends ListableBeanFactory { +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java deleted file mode 100644 index e66c831..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.factory.PluginFactory; - -import java.util.Map; - -/** - * @author starBlues - * @version 3.0.0 - */ -public interface SpringPlugin { - - /** - * 注册插件 - * @param pluginWrapper pluginWrapper - * @throws Exception Exception - */ - void registry(PluginWrapper pluginWrapper) throws Exception; - - /** - * 卸载插件 - * @param pluginId 插件id - * @throws Exception Exception - */ - void unRegistry(String pluginId) throws Exception; - - /** - * 获取当前注册的插件信息 - * @return Map - */ - Map getPluginRegistryInfos(); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java index 8b4d070..b080647 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java @@ -6,6 +6,6 @@ package com.gitee.starblues.spring; */ public interface SpringPluginHook extends AutoCloseable{ - Object getGenericApplicationContext(); + ApplicationContext getApplicationContext(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java deleted file mode 100644 index e5b424c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginRegistryInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.spring; - -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.integration.IntegrationConfiguration; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -/** - * @author starBlues - * @version 3.0.0 - */ -public interface SpringPluginRegistryInfo extends RegistryInfo{ - - /** - * 得到插件 PluginWrapper - * @return PluginWrapper - */ - PluginWrapper getPluginWrapper(); - - /** - * 得到当前插件的 PluginSpringApplication 实现 - * @return PluginSpringApplication - */ - PluginSpringApplication getPluginSpringApplication(); - - /** - * 得到主程序的 ApplicationContext - * @return ConfigurableApplicationContext - */ - ConfigurableApplicationContext getMainApplicationContext(); - - /** - * 得到集成的配置 - * @return IntegrationConfiguration - */ - IntegrationConfiguration getConfiguration(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java deleted file mode 100644 index dee2d3e..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/FilteredPropertySource.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.gitee.starblues.spring.environment; - -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertySource; - -import java.util.Set; -import java.util.function.Consumer; - -/** - * PropertySource 过滤 - * @author starBlues - * @version 3.0.0 - */ -public class FilteredPropertySource extends PropertySource> { - - private final Set filteredProperties; - - FilteredPropertySource(PropertySource original, Set filteredProperties) { - super(original.getName(), original); - this.filteredProperties = filteredProperties; - } - - @Override - public Object getProperty(String name) { - if (this.filteredProperties.contains(name)) { - return null; - } - return getSource().getProperty(name); - } - - static void apply(ConfigurableEnvironment environment, String propertySourceName, Set filteredProperties, - Consumer> operation) { - MutablePropertySources propertySources = environment.getPropertySources(); - PropertySource original = propertySources.get(propertySourceName); - if (original == null) { - operation.accept(null); - return; - } - propertySources.replace(propertySourceName, new FilteredPropertySource(original, filteredProperties)); - try { - operation.accept(original); - } - finally { - propertySources.replace(propertySourceName, original); - } - } - -} - diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java deleted file mode 100644 index 251ffbb..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginEnvironmentProcessor.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gitee.starblues.spring.environment; - -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.io.ResourceLoader; - -/** - * 插件 Environment 处理者 - * @author starBlues - * @version 3.0.0 - */ -public interface PluginEnvironmentProcessor extends Ordered { - - /** - * 处理 Environment - * @param environment ConfigurableEnvironment - * @param pnClassLoader ResourceLoader - */ - void postProcessEnvironment(ConfigurableEnvironment environment, ResourceLoader pnClassLoader); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java deleted file mode 100644 index 8a7fb64..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/environment/PluginLocalConfigFileProcessor.java +++ /dev/null @@ -1,901 +0,0 @@ -package com.gitee.starblues.spring.environment; - -import com.gitee.starblues.core.RuntimeMode; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ResourceUtils; -import org.apache.commons.logging.Log; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.DefaultPropertiesPropertySource; -import org.springframework.boot.context.config.ConfigDataLocation; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; -import org.springframework.boot.context.properties.source.ConfigurationPropertySources; -import org.springframework.boot.env.PropertiesPropertySourceLoader; -import org.springframework.boot.env.PropertySourceLoader; -import org.springframework.boot.env.RandomValuePropertySource; -import org.springframework.boot.env.YamlPropertySourceLoader; -import org.springframework.boot.logging.DeferredLog; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.ConfigurationClassPostProcessor; -import org.springframework.core.Ordered; -import org.springframework.core.env.*; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.io.support.SpringFactoriesLoader; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * copy from springboot - * @author starBlues - * @version 3.0.0 - */ -public class PluginLocalConfigFileProcessor implements PluginEnvironmentProcessor { - - private static final String ENVIRONMENT_NAME = "defaultPluginProperties"; - - private static final String DEFAULT_SEARCH_LOCATIONS = - "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"; - - private static final String DEFAULT_NAMES = "application"; - - /** - * The "active profiles" property name. - */ - public static final String ACTIVE_PROFILES_PROPERTY = "spring.profiles.active"; - - /** - * The "includes profiles" property name. - */ - public static final String INCLUDE_PROFILES_PROPERTY = "spring.profiles.include"; - - /** - * The "config name" property name. - */ - public static final String CONFIG_NAME_PROPERTY = "spring.config.name"; - - /** - * The "config location" property name. - */ - public static final String CONFIG_LOCATION_PROPERTY = "spring.config.location"; - - private final Set NO_SEARCH_NAMES = Collections.singleton(null); - - private final Bindable STRING_ARRAY = Bindable.of(String[].class); - - private final Bindable> STRING_LIST = Bindable.listOf(String.class); - - private final Set LOAD_FILTERED_PROPERTY; - - /** - * The "config additional location" property name. - */ - public final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location"; - - /** - * The default order for the processor. - */ - public final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; - - private final Log logger = new DeferredLog(); - - private final Resource[] EMPTY_RESOURCES = {}; - - private final Comparator FILE_COMPARATOR = Comparator.comparing(File::getAbsolutePath); - - private String searchLocations; - - private String names; - - private int order = DEFAULT_ORDER; - - public PluginLocalConfigFileProcessor(IntegrationConfiguration configuration) { - Set filteredProperties = new HashSet<>(); - filteredProperties.add("spring.profiles.active"); - filteredProperties.add("spring.profiles.include"); - LOAD_FILTERED_PROPERTY = Collections.unmodifiableSet(filteredProperties); - - resolveSearchLocations(configuration); - } - - /** - * 根据环境设置查询配置文件路径 - * @param configuration IntegrationConfiguration - */ - private void resolveSearchLocations(IntegrationConfiguration configuration) { - RuntimeMode runtimeMode = configuration.environment(); - if(runtimeMode== RuntimeMode.DEV){ - setSearchLocations("classpath:/"); - } else { - String pluginConfigFilePath = configuration.pluginConfigFilePath(); - if(ObjectUtils.isEmpty(pluginConfigFilePath)){ - pluginConfigFilePath = ""; - } else { - Path path = Paths.get(pluginConfigFilePath); - if(Files.exists(path)){ - pluginConfigFilePath = path.toUri().toString() + ","; - } else { - pluginConfigFilePath = ""; - } - } - // 生产环境读取文件顺序: - // pluginConfigFilePath配置的目录 > 当前插件jar包目录 > 当前插件jar包/config/*/ 目录 > 当前插件包/config/ 下的目录 > classpath:/ - pluginConfigFilePath = pluginConfigFilePath + "file:./,file:./config/*/,file:./config/,classpath:/"; - setSearchLocations(pluginConfigFilePath); - } - } - - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, ResourceLoader pnClassLoader) { - addPropertySources(environment, pnClassLoader); - } - - /** - * Add config file property sources to the specified environment. - * @param environment the environment to add source to - * @param resourceLoader the resource loader - * @see #addPostProcessors(ConfigurableApplicationContext) - */ - protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { - RandomValuePropertySource.addToEnvironment(environment); - new Loader(environment, resourceLoader).load(); - } - - /** - * Add appropriate post-processors to post-configure the property-sources. - * @param context the context to configure - */ - protected void addPostProcessors(ConfigurableApplicationContext context) { - context.addBeanFactoryPostProcessor(new PropertySourceOrderingPostProcessor(context)); - } - - public void setOrder(int order) { - this.order = order; - } - - @Override - public int getOrder() { - return this.order; - } - - /** - * Set the search locations that will be considered as a comma-separated list. Each - * search location should be a directory path (ending in "/") and it will be prefixed - * by the file names constructed from {@link #setSearchNames(String) search names} and - * profiles (if any) plus file extensions supported by the properties loaders. - * Locations are considered in the order specified, with later items taking precedence - * (like a map merge). - * @param locations the search locations - */ - public void setSearchLocations(String locations) { - this.searchLocations = Assert.isNotEmpty(locations, "locations 不能为空"); - } - - /** - * Sets the names of the files that should be loaded (excluding file extension) as a - * comma-separated list. - * @param names the names to load - */ - public void setSearchNames(String names) { - this.names = Assert.isNotEmpty(names, "names 不能为空"); - } - - /** - * {@link BeanFactoryPostProcessor} to re-order our property sources below any - * {@code @PropertySource} items added by the {@link ConfigurationClassPostProcessor}. - */ - private static class PropertySourceOrderingPostProcessor implements BeanFactoryPostProcessor, Ordered { - - private final ConfigurableApplicationContext context; - - PropertySourceOrderingPostProcessor(ConfigurableApplicationContext context) { - this.context = context; - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - reorderSources(this.context.getEnvironment()); - } - - private void reorderSources(ConfigurableEnvironment environment) { - DefaultPropertiesPropertySource.moveToEnd(environment); - } - - } - - - private class Loader { - - private final Log logger = PluginLocalConfigFileProcessor.this.logger; - - private final ConfigurableEnvironment environment; - - private final PropertySourcesPlaceholdersResolver placeholdersResolver; - - private final ResourceLoader resourceLoader; - - private final List propertySourceLoaders; - - private Deque profiles; - - private List processedProfiles; - - private boolean activatedProfiles; - - private Map loaded; - - private Map> loadDocumentsCache = new HashMap<>(); - - Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { - this.environment = environment; - this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment); - this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(null); - this.propertySourceLoaders = new ArrayList<>(); - initPropertySourceLoader(); - } - - private void initPropertySourceLoader(){ - this.propertySourceLoaders.add(new YamlPropertySourceLoader()); - this.propertySourceLoaders.add(new PropertiesPropertySourceLoader()); - } - - void load() { - FilteredPropertySource.apply(this.environment, ENVIRONMENT_NAME, LOAD_FILTERED_PROPERTY, - this::loadWithFilteredProperties); - } - - private void loadWithFilteredProperties(PropertySource defaultProperties) { - this.profiles = new LinkedList<>(); - this.processedProfiles = new LinkedList<>(); - this.activatedProfiles = false; - this.loaded = new LinkedHashMap<>(); - initializeProfiles(); - while (!this.profiles.isEmpty()) { - Profile profile = this.profiles.poll(); - if (isDefaultProfile(profile)) { - addProfileToEnvironment(profile.getName()); - } - load(profile, this::getPositiveProfileFilter, addToLoaded(MutablePropertySources::addLast, false)); - this.processedProfiles.add(profile); - } - load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true)); - addLoadedPropertySources(); - applyActiveProfiles(defaultProperties); - } - - /** - * Initialize profile information from both the {@link Environment} active - * profiles and any {@code spring.profiles.active}/{@code spring.profiles.include} - * properties that are already set. - */ - private void initializeProfiles() { - // The default profile for these purposes is represented as null. We add it - // first so that it is processed first and has lowest priority. - this.profiles.add(null); - Binder binder = Binder.get(this.environment); - Set activatedViaProperty = getProfiles(binder, ACTIVE_PROFILES_PROPERTY); - Set includedViaProperty = getProfiles(binder, INCLUDE_PROFILES_PROPERTY); - List otherActiveProfiles = getOtherActiveProfiles(activatedViaProperty, includedViaProperty); - this.profiles.addAll(otherActiveProfiles); - // Any pre-existing active profiles set via property sources (e.g. - // System properties) take precedence over those added in config files. - this.profiles.addAll(includedViaProperty); - addActiveProfiles(activatedViaProperty); - if (this.profiles.size() == 1) { // only has null profile - for (String defaultProfileName : getDefaultProfiles(binder)) { - Profile defaultProfile = new Profile(defaultProfileName, true); - this.profiles.add(defaultProfile); - } - } - } - - private String[] getDefaultProfiles(Binder binder) { - return binder.bind(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, STRING_ARRAY) - .orElseGet(this.environment::getDefaultProfiles); - } - - private List getOtherActiveProfiles(Set activatedViaProperty, - Set includedViaProperty) { - return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new).filter( - (profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile)) - .collect(Collectors.toList()); - } - - void addActiveProfiles(Set profiles) { - if (profiles.isEmpty()) { - return; - } - if (this.activatedProfiles) { - if (this.logger.isDebugEnabled()) { - this.logger.debug("Profiles already activated, '" + profiles + "' will not be applied"); - } - return; - } - this.profiles.addAll(profiles); - if (this.logger.isDebugEnabled()) { - this.logger.debug("Activated activeProfiles " + ObjectUtils.collectionToCommaDelimitedString(profiles)); - } - this.activatedProfiles = true; - removeUnprocessedDefaultProfiles(); - } - - private void removeUnprocessedDefaultProfiles() { - this.profiles.removeIf((profile) -> (profile != null && profile.isDefaultProfile())); - } - - private DocumentFilter getPositiveProfileFilter(Profile profile) { - return (Document document) -> { - if (profile == null) { - return ObjectUtils.isEmpty(document.getProfiles()); - } - return ObjectUtils.containsElement(document.getProfiles(), profile.getName()) - && this.environment.acceptsProfiles(Profiles.of(document.getProfiles())); - }; - } - - private DocumentFilter getNegativeProfileFilter(Profile profile) { - return (Document document) -> (profile == null && !ObjectUtils.isEmpty(document.getProfiles()) - && this.environment.acceptsProfiles(Profiles.of(document.getProfiles()))); - } - - private DocumentConsumer addToLoaded(BiConsumer> addMethod, - boolean checkForExisting) { - return (profile, document) -> { - if (checkForExisting) { - for (MutablePropertySources merged : this.loaded.values()) { - if (merged.contains(document.getPropertySource().getName())) { - return; - } - } - } - MutablePropertySources merged = this.loaded.computeIfAbsent(profile, - (k) -> new MutablePropertySources()); - addMethod.accept(merged, document.getPropertySource()); - }; - } - - private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) { - getSearchLocations().forEach((location) -> { - String nonOptionalLocation = ConfigDataLocation.of(location).getValue(); - boolean isDirectory = location.endsWith("/"); - Set names = isDirectory ? getSearchNames() : NO_SEARCH_NAMES; - names.forEach((name) -> load(nonOptionalLocation, name, profile, filterFactory, consumer)); - }); - } - - private void load(String location, String name, Profile profile, DocumentFilterFactory filterFactory, - DocumentConsumer consumer) { - if (!ObjectUtils.hasText(name)) { - for (PropertySourceLoader loader : this.propertySourceLoaders) { - if (canLoadFileExtension(loader, location)) { - load(loader, location, profile, filterFactory.getDocumentFilter(profile), consumer); - return; - } - } - throw new IllegalStateException("File extension of config file location '" + location - + "' is not known to any PropertySourceLoader. If the location is meant to reference " - + "a directory, it must end in '/'"); - } - Set processed = new HashSet<>(); - for (PropertySourceLoader loader : this.propertySourceLoaders) { - for (String fileExtension : loader.getFileExtensions()) { - if (processed.add(fileExtension)) { - loadForFileExtension(loader, location + name, "." + fileExtension, profile, filterFactory, - consumer); - } - } - } - } - - private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { - return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> ObjectUtils.endsWithIgnoreCase(name, fileExtension)); - } - - private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension, - Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) { - DocumentFilter defaultFilter = filterFactory.getDocumentFilter(null); - DocumentFilter profileFilter = filterFactory.getDocumentFilter(profile); - if (profile != null) { - // Try profile-specific file & profile section in profile file (gh-340) - String profileSpecificFile = prefix + "-" + profile + fileExtension; - load(loader, profileSpecificFile, profile, defaultFilter, consumer); - load(loader, profileSpecificFile, profile, profileFilter, consumer); - // Try profile specific sections in files we've already processed - for (Profile processedProfile : this.processedProfiles) { - if (processedProfile != null) { - String previouslyLoaded = prefix + "-" + processedProfile + fileExtension; - load(loader, previouslyLoaded, profile, profileFilter, consumer); - } - } - } - // Also try the profile-specific section (if any) of the normal file - load(loader, prefix + fileExtension, profile, profileFilter, consumer); - } - - private void load(PropertySourceLoader loader, String location, Profile profile, DocumentFilter filter, - DocumentConsumer consumer) { - Resource[] resources = getResources(location); - for (Resource resource : resources) { - try { - if (resource == null || !resource.exists()) { - if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription("Skipped missing config ", location, resource, - profile); - this.logger.trace(description); - } - continue; - } - if (!ObjectUtils.hasText(ObjectUtils.getFilenameExtension(resource.getFilename()))) { - if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription("Skipped empty config extension ", location, - resource, profile); - this.logger.trace(description); - } - continue; - } - if (resource.isFile() && isPatternLocation(location) && hasHiddenPathElement(resource)) { - if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription("Skipped location with hidden path element ", - location, resource, profile); - this.logger.trace(description); - } - continue; - } - String name = "applicationConfig: [" + getLocationName(location, resource) + "]"; - List documents = loadDocuments(loader, name, resource); - if (ObjectUtils.isEmpty(documents)) { - if (this.logger.isTraceEnabled()) { - StringBuilder description = getDescription("Skipped unloaded config ", location, resource, - profile); - this.logger.trace(description); - } - continue; - } - List loaded = new ArrayList<>(); - for (Document document : documents) { - if (filter.match(document)) { - addActiveProfiles(document.getActiveProfiles()); - addIncludedProfiles(document.getIncludeProfiles()); - loaded.add(document); - } - } - Collections.reverse(loaded); - if (!loaded.isEmpty()) { - loaded.forEach((document) -> consumer.accept(profile, document)); - if (this.logger.isDebugEnabled()) { - StringBuilder description = getDescription("Loaded config file ", location, resource, - profile); - this.logger.debug(description); - } - } - } catch (Exception ex) { - StringBuilder description = getDescription("Failed to load property source from ", location, - resource, profile); - throw new IllegalStateException(description.toString(), ex); - } finally { - try { - if(resource != null && resource.exists() && resource.isOpen()){ - resource.getInputStream().close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private boolean hasHiddenPathElement(Resource resource) throws IOException { - String cleanPath = ObjectUtils.cleanPath(resource.getFile().getAbsolutePath()); - for (Path value : Paths.get(cleanPath)) { - if (value.toString().startsWith("..")) { - return true; - } - } - return false; - } - - private String getLocationName(String locationReference, Resource resource) { - if (!locationReference.contains("*")) { - return locationReference; - } - if (resource instanceof FileSystemResource) { - return ((FileSystemResource) resource).getPath(); - } - return resource.getDescription(); - } - - private Resource[] getResources(String locationReference) { - try { - if (isPatternLocation(locationReference)) { - return getResourcesFromPatternLocationReference(locationReference); - } - return new Resource[] { this.resourceLoader.getResource(locationReference) }; - } - catch (Exception ex) { - return EMPTY_RESOURCES; - } - } - - private boolean isPatternLocation(String location) { - return location.contains("*"); - } - - private Resource[] getResourcesFromPatternLocationReference(String locationReference) throws IOException { - String directoryPath = locationReference.substring(0, locationReference.indexOf("*/")); - Resource resource = this.resourceLoader.getResource(directoryPath); - File[] files = resource.getFile().listFiles(File::isDirectory); - if (files != null) { - String fileName = locationReference.substring(locationReference.lastIndexOf("/") + 1); - Arrays.sort(files, FILE_COMPARATOR); - return Arrays.stream(files).map((file) -> file.listFiles((dir, name) -> name.equals(fileName))) - .filter(Objects::nonNull).flatMap((Function>) Arrays::stream) - .map(FileSystemResource::new).toArray(Resource[]::new); - } - return EMPTY_RESOURCES; - } - - private void addIncludedProfiles(Set includeProfiles) { - LinkedList existingProfiles = new LinkedList<>(this.profiles); - this.profiles.clear(); - this.profiles.addAll(includeProfiles); - this.profiles.removeAll(this.processedProfiles); - this.profiles.addAll(existingProfiles); - } - - private List loadDocuments(PropertySourceLoader loader, String name, Resource resource) - throws IOException { - DocumentsCacheKey cacheKey = new DocumentsCacheKey(loader, resource); - List documents = this.loadDocumentsCache.get(cacheKey); - if (documents == null) { - List> loaded = loader.load(name, resource); - documents = asDocuments(loaded); - this.loadDocumentsCache.put(cacheKey, documents); - } - return documents; - } - - private List asDocuments(List> loaded) { - if (loaded == null) { - return Collections.emptyList(); - } - return loaded.stream().map((propertySource) -> { - Binder binder = new Binder(ConfigurationPropertySources.from(propertySource), - this.placeholdersResolver); - String[] profiles = binder.bind("spring.profiles", STRING_ARRAY).orElse(null); - Set activeProfiles = getProfiles(binder, ACTIVE_PROFILES_PROPERTY); - Set includeProfiles = getProfiles(binder, INCLUDE_PROFILES_PROPERTY); - return new Document(propertySource, profiles, activeProfiles, includeProfiles); - }).collect(Collectors.toList()); - } - - private StringBuilder getDescription(String prefix, String locationReference, Resource resource, - Profile profile) { - StringBuilder result = new StringBuilder(prefix); - try { - if (resource != null) { - String uri = resource.getURI().toASCIIString(); - result.append("'"); - result.append(uri); - result.append("' ("); - result.append(locationReference); - result.append(")"); - } - } - catch (IOException ex) { - result.append(locationReference); - } - if (profile != null) { - result.append(" for profile "); - result.append(profile); - } - return result; - } - - private Set getProfiles(Binder binder, String name) { - return binder.bind(name, STRING_ARRAY).map(this::asProfileSet).orElse(Collections.emptySet()); - } - - private Set asProfileSet(String[] profileNames) { - List profiles = new ArrayList<>(); - for (String profileName : profileNames) { - profiles.add(new Profile(profileName)); - } - return new LinkedHashSet<>(profiles); - } - - private void addProfileToEnvironment(String profile) { - for (String activeProfile : this.environment.getActiveProfiles()) { - if (activeProfile.equals(profile)) { - return; - } - } - this.environment.addActiveProfile(profile); - } - - private List getSearchLocations() { - return asResolvedList(PluginLocalConfigFileProcessor.this.searchLocations, DEFAULT_SEARCH_LOCATIONS); - } - - private Set getSearchLocations(String propertyName) { - Set locations = new LinkedHashSet<>(); - if (this.environment.containsProperty(propertyName)) { - for (String path : asResolvedSet(this.environment.getProperty(propertyName), null)) { - if (!path.contains("$")) { - path = ObjectUtils.cleanPath(path); - Assert.state(!path.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX), - "Classpath wildcard patterns cannot be used as a search location"); - validateWildcardLocation(path); - if (!ResourceUtils.isUrl(path)) { - path = ResourceUtils.FILE_URL_PREFIX + path; - } - } - locations.add(path); - } - } - return locations; - } - - private void validateWildcardLocation(String path) { - if (path.contains("*")) { - Assert.state(ObjectUtils.countOccurrencesOf(path, "*") == 1, - () -> "Search location '" + path + "' cannot contain multiple wildcards"); - String directoryPath = path.substring(0, path.lastIndexOf("/") + 1); - Assert.state(directoryPath.endsWith("*/"), () -> "Search location '" + path + "' must end with '*/'"); - } - } - - private Set getSearchNames() { - if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) { - String property = this.environment.getProperty(CONFIG_NAME_PROPERTY); - Set names = asResolvedSet(property, null); - names.forEach(this::assertValidConfigName); - return names; - } - return asResolvedSet(PluginLocalConfigFileProcessor.this.names, DEFAULT_NAMES); - } - - private Set asResolvedSet(String value, String fallback) { - List list = Arrays.asList(ObjectUtils.trimArrayElements(ObjectUtils.commaDelimitedListToStringArray( - (value != null) ? this.environment.resolvePlaceholders(value) : fallback))); - Collections.reverse(list); - return new LinkedHashSet<>(list); - } - - private List asResolvedList(String value, String fallback) { - return Arrays.asList(ObjectUtils.trimArrayElements(ObjectUtils.commaDelimitedListToStringArray( - (value != null) ? this.environment.resolvePlaceholders(value) : fallback))); - } - - private void assertValidConfigName(String name) { - Assert.state(!name.contains("*"), () -> "Config name '" + name + "' cannot contain wildcards"); - } - - private void addLoadedPropertySources() { - MutablePropertySources destination = this.environment.getPropertySources(); - List loaded = new ArrayList<>(this.loaded.values()); - Collections.reverse(loaded); - String lastAdded = null; - Set added = new HashSet<>(); - for (MutablePropertySources sources : loaded) { - for (PropertySource source : sources) { - if (added.add(source.getName())) { - addLoadedPropertySource(destination, lastAdded, source); - lastAdded = source.getName(); - } - } - } - } - - private void addLoadedPropertySource(MutablePropertySources destination, String lastAdded, - PropertySource source) { - if (lastAdded == null) { - if (destination.contains(ENVIRONMENT_NAME)) { - destination.addBefore(ENVIRONMENT_NAME, source); - } - else { - destination.addLast(source); - } - } - else { - destination.addAfter(lastAdded, source); - } - } - - private void applyActiveProfiles(PropertySource defaultProperties) { - List activeProfiles = new ArrayList<>(); - if (defaultProperties != null) { - Binder binder = new Binder(ConfigurationPropertySources.from(defaultProperties), - new PropertySourcesPlaceholdersResolver(this.environment)); - activeProfiles.addAll(bindStringList(binder, "spring.profiles.include")); - if (!this.activatedProfiles) { - activeProfiles.addAll(bindStringList(binder, "spring.profiles.active")); - } - } - this.processedProfiles.stream().filter(this::isDefaultProfile).map(Profile::getName) - .forEach(activeProfiles::add); - this.environment.setActiveProfiles(activeProfiles.toArray(new String[0])); - } - - private boolean isDefaultProfile(Profile profile) { - return profile != null && !profile.isDefaultProfile(); - } - - private List bindStringList(Binder binder, String property) { - return binder.bind(property, STRING_LIST).orElse(Collections.emptyList()); - } - - } - - private static class Profile { - - private final String name; - - private final boolean defaultProfile; - - Profile(String name) { - this(name, false); - } - - Profile(String name, boolean defaultProfile) { - Assert.isNotEmpty(name, "name 不能为空"); - this.name = name; - this.defaultProfile = defaultProfile; - } - - String getName() { - return this.name; - } - - boolean isDefaultProfile() { - return this.defaultProfile; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || obj.getClass() != getClass()) { - return false; - } - return ((Profile) obj).name.equals(this.name); - } - - @Override - public int hashCode() { - return this.name.hashCode(); - } - - @Override - public String toString() { - return this.name; - } - - } - - /** - * Cache key used to save loading the same document multiple times. - */ - private static class DocumentsCacheKey { - - private final PropertySourceLoader loader; - - private final Resource resource; - - DocumentsCacheKey(PropertySourceLoader loader, Resource resource) { - this.loader = loader; - this.resource = resource; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - DocumentsCacheKey other = (DocumentsCacheKey) obj; - return this.loader.equals(other.loader) && this.resource.equals(other.resource); - } - - @Override - public int hashCode() { - return this.loader.hashCode() * 31 + this.resource.hashCode(); - } - - } - - /** - * A single document loaded by a {@link PropertySourceLoader}. - */ - private static class Document { - - private final PropertySource propertySource; - - private String[] profiles; - - private final Set activeProfiles; - - private final Set includeProfiles; - - Document(PropertySource propertySource, String[] profiles, Set activeProfiles, - Set includeProfiles) { - this.propertySource = propertySource; - this.profiles = profiles; - this.activeProfiles = activeProfiles; - this.includeProfiles = includeProfiles; - } - - PropertySource getPropertySource() { - return this.propertySource; - } - - String[] getProfiles() { - return this.profiles; - } - - Set getActiveProfiles() { - return this.activeProfiles; - } - - Set getIncludeProfiles() { - return this.includeProfiles; - } - - @Override - public String toString() { - return this.propertySource.toString(); - } - - } - - @FunctionalInterface - private interface DocumentFilterFactory { - - /** - * Create a filter for the given profile. - * @param profile the profile or {@code null} - * @return the filter - */ - DocumentFilter getDocumentFilter(Profile profile); - - } - - @FunctionalInterface - private interface DocumentFilter { - - boolean match(Document document); - - } - - @FunctionalInterface - private interface DocumentConsumer { - - void accept(Profile profile, Document document); - - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java new file mode 100644 index 0000000..0b83b22 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java @@ -0,0 +1,56 @@ +package com.gitee.starblues.spring.extract; + +import java.util.*; + +/** + * 默认的扩展工厂 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultExtractFactory implements ExtractFactory{ + + private final ExtractFactory target; + + public DefaultExtractFactory() { + this.target = new DefaultOpExtractFactory(); + } + + public ExtractFactory getTarget() { + return target; + } + + @Override + public T getExtractByCoordinate(ExtractCoordinate coordinate) { + return target.getExtractByCoordinate(coordinate); + } + + @Override + public T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate) { + return target.getExtractByCoordinate(pluginId, coordinate); + } + + @Override + public T getExtractByCoordinateOfMain(ExtractCoordinate coordinate) { + return target.getExtractByCoordinate(coordinate); + } + + @Override + public List getExtractByInterClass(Class interfaceClass) { + return target.getExtractByInterClass(interfaceClass); + } + + @Override + public List getExtractByInterClass(String pluginId, Class interfaceClass) { + return target.getExtractByInterClass(pluginId, interfaceClass); + } + + @Override + public List getExtractByInterClassOfMain(Class interfaceClass) { + return target.getExtractByInterClassOfMain(interfaceClass); + } + + @Override + public Map> getExtractCoordinates() { + return target.getExtractCoordinates(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java new file mode 100644 index 0000000..7eef6e5 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java @@ -0,0 +1,194 @@ +package com.gitee.starblues.spring.extract; + +import com.gitee.starblues.annotation.Extract; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.util.ClassUtils; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +/** + * 默认的可扩展的工厂 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultOpExtractFactory implements OpExtractFactory { + + public static final String MAIN_EXTRACT_KEY = ExtractFactory.class.getName() + UUID.randomUUID().toString(); + + private final Map> extractMap = new ConcurrentHashMap<>(); + + + @Override + public void addOfMain(Object extractObject) { + add(MAIN_EXTRACT_KEY, extractObject); + } + + @Override + public void add(String pluginId, Object extractObject) { + if(extractObject == null){ + return; + } + Extract extract = getExtract(extractObject); + if(extract == null){ + return; + } + Map extractObjects = extractMap.computeIfAbsent(pluginId, k -> + new ConcurrentHashMap<>()); + ExtractWrapper extractWrapper = new ExtractWrapper(extractObject, extract.order()); + extractObjects.put(new ExtractCoordinate(extract, extractObject.getClass()), extractWrapper); + } + + @Override + public void remove(String pluginId) { + extractMap.remove(pluginId); + } + + @SuppressWarnings("unchecked") + @Override + public T getExtractByCoordinate(ExtractCoordinate coordinate) { + Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); + int currentOrder = Integer.MIN_VALUE; + Object currentObject = null; + for (Map value : extractMap.values()) { + ExtractWrapper extractWrapper = value.get(coordinate); + if(extractWrapper != null){ + int order = extractWrapper.getOrder(); + if(order > currentOrder){ + currentObject = extractWrapper.getObject(); + // fix: https://gitee.com/starblues/springboot-plugin-framework-parent/issues/I430R6 + currentOrder = order; + } + } + } + if(currentObject != null){ + return (T) currentObject; + } + throw new RuntimeException("Not found " + coordinate); + } + + @SuppressWarnings("unchecked") + @Override + public T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate) { + Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); + Map extractCoordinates = extractMap.get(pluginId); + if(extractCoordinates == null){ + throw new RuntimeException("Not found " + coordinate + " from plugin '" + pluginId + "'"); + } + Object extracts = extractCoordinates.get(coordinate); + if(extracts == null){ + throw new RuntimeException("Not found " + coordinate + " from plugin '" + pluginId + "'"); + } + return (T) extracts; + } + + @SuppressWarnings("unchecked") + @Override + public T getExtractByCoordinateOfMain(ExtractCoordinate coordinate) { + Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); + Map extractCoordinates = extractMap.get(MAIN_EXTRACT_KEY); + if(extractCoordinates == null){ + throw new RuntimeException("Not found " + coordinate + " from main"); + } + ExtractWrapper extractWrapper = extractCoordinates.get(coordinate); + if(extractWrapper == null){ + throw new RuntimeException("Not found " + coordinate + " from main"); + } + return (T) extractWrapper.getObject(); + } + + @Override + public List getExtractByInterClass(Class interfaceClass) { + if(interfaceClass == null){ + return Collections.emptyList(); + } + List extracts = new ArrayList<>(); + for (Map value : extractMap.values()) { + for (ExtractWrapper extractWrapper : value.values()) { + Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet( + extractWrapper.getObject().getClass()); + if(allInterfacesForClassAsSet.contains(interfaceClass)){ + extracts.add(extractWrapper); + } + } + } + return sort(extracts); + } + + @Override + public List getExtractByInterClass(String pluginId, Class interfaceClass) { + if(interfaceClass == null){ + return Collections.emptyList(); + } + List extracts = new ArrayList<>(); + Map extractCoordinateObjectMap = extractMap.get(pluginId); + if(extractCoordinateObjectMap == null || extractCoordinateObjectMap.isEmpty()){ + return Collections.emptyList(); + } + for (ExtractWrapper wrapper : extractCoordinateObjectMap.values()) { + Object object = wrapper.getObject(); + Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(object.getClass()); + if(allInterfacesForClassAsSet.contains(interfaceClass)){ + extracts.add(wrapper); + } + } + return sort(extracts); + } + + @Override + public List getExtractByInterClassOfMain(Class interfaceClass) { + return getExtractByInterClass(MAIN_EXTRACT_KEY, interfaceClass); + } + + @Override + public Map> getExtractCoordinates() { + Map> extractCoordinateMap = new HashMap<>(extractMap.size()); + extractMap.forEach((k, v)->{ + Set extractCoordinates = new HashSet<>(v.size()); + extractCoordinates.addAll(v.keySet()); + extractCoordinateMap.put(k, extractCoordinates); + }); + return extractCoordinateMap; + } + + @SuppressWarnings("unchecked") + private List sort(List extractWrappers){ + if(ObjectUtils.isEmpty(extractWrappers)){ + return new ArrayList<>(0); + } + return extractWrappers.stream() + .sorted(Comparator.comparing(ExtractWrapper::getOrder, + Comparator.nullsLast(Comparator.reverseOrder()))) + .map(extractWrapper -> (T) extractWrapper.getObject()) + .collect(Collectors.toList()); + } + + private Extract getExtract(Object extractObject){ + return extractObject.getClass().getAnnotation(Extract.class); + } + + + /** + * 扩展对象包装类型 + **/ + private static class ExtractWrapper{ + private final Object object; + private final int order; + + public ExtractWrapper(Object object, int order) { + this.object = object; + this.order = order; + } + + public Object getObject() { + return object; + } + + public int getOrder() { + return order; + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java new file mode 100644 index 0000000..3644852 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java @@ -0,0 +1,47 @@ +package com.gitee.starblues.spring.extract; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class EmptyExtractFactory implements ExtractFactory{ + @Override + public T getExtractByCoordinate(ExtractCoordinate coordinate) { + return null; + } + + @Override + public T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate) { + return null; + } + + @Override + public T getExtractByCoordinateOfMain(ExtractCoordinate coordinate) { + return null; + } + + @Override + public List getExtractByInterClass(Class interfaceClass) { + return Collections.emptyList(); + } + + @Override + public List getExtractByInterClass(String pluginId, Class interfaceClass) { + return Collections.emptyList(); + } + + @Override + public List getExtractByInterClassOfMain(Class interfaceClass) { + return Collections.emptyList(); + } + + @Override + public Map> getExtractCoordinates() { + return Collections.emptyMap(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractCoordinate.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractCoordinate.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java index fb0e424..409ce4a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/ExtractCoordinate.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.processor.extract; +package com.gitee.starblues.spring.extract; import com.gitee.starblues.annotation.Extract; import org.pf4j.util.StringUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java new file mode 100644 index 0000000..33cbaed --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java @@ -0,0 +1,81 @@ +package com.gitee.starblues.spring.extract; + +import java.util.*; + +/** + * 扩展工厂 + * @author starBlues + * @version 3.0.0 + */ +public interface ExtractFactory { + + ExtractFactory INSTANT = new DefaultExtractFactory(); + + /** + * 获取实例 + * @return ExtractFactory + */ + static ExtractFactory getInstant(){ + return INSTANT; + } + + /** + * 通过坐标得到扩展 + * @param coordinate 扩展的坐标 + * @param 扩展的泛型 + * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 + */ + T getExtractByCoordinate(ExtractCoordinate coordinate); + + /** + * 根据插件id和坐标得到扩展 + * @param pluginId 插件id + * @param coordinate 扩展的坐标 + * @param 扩展的泛型 + * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 + */ + T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate); + + + /** + * 根据坐标得到主程序的扩展 + * 主程序扩展必须使用 @Extract+@Component 进行定义 + * @param coordinate 扩展的坐标 + * @param 扩展的泛型 + * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 + */ + T getExtractByCoordinateOfMain(ExtractCoordinate coordinate); + + /** + * 根据接口类型获取扩展 + * @param interfaceClass 接口类类型 + * @param 接口类型泛型 + * @return 扩展实现集合 + */ + List getExtractByInterClass(Class interfaceClass); + + /** + * 根据插件id和接口类型获取扩展 + * @param pluginId 插件id + * @param interfaceClass 接口类类型 + * @param 接口类型泛型 + * @return 扩展实现集合 + */ + List getExtractByInterClass(String pluginId, Class interfaceClass); + + /** + * 根据接口类型获取主程序的扩展 + * 主程序扩展必须使用 @Extract+@Component 进行定义 + * @param interfaceClass 接口类类型 + * @param 接口类型泛型 + * @return 扩展实现集合 + */ + List getExtractByInterClassOfMain(Class interfaceClass); + + /** + * 得到所有的扩展坐标 + * @return 扩展坐标集合, key 为插件id, 值为所有扩展坐标集合 + */ + Map> getExtractCoordinates(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java new file mode 100644 index 0000000..8bfe73a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java @@ -0,0 +1,29 @@ +package com.gitee.starblues.spring.extract; + +/** + * 可操作的扩展工厂 + * @author starBlues + * @version 3.0.0 + */ +public interface OpExtractFactory extends ExtractFactory{ + + /** + * 添加main中的扩展 + * @param extractObject extractObject + */ + void addOfMain(Object extractObject); + + /** + * 添加插件中的扩展 + * @param pluginId 插件 + * @param extractObject 扩展对象 + */ + void add(String pluginId, Object extractObject); + + /** + * 移除插件中的扩展 + * @param pluginId 插件id + */ + void remove(String pluginId); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java similarity index 84% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java index f74017a..896c3d3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/DefaultInvokeSupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java @@ -1,6 +1,7 @@ -package com.gitee.starblues.spring.processor.invoke; +package com.gitee.starblues.spring.invoke; import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; import com.gitee.starblues.utils.ObjectUtils; import java.util.HashMap; @@ -54,8 +55,9 @@ public class DefaultInvokeSupperCache implements InvokeSupperCache{ return null; } ApplicationContext applicationContext = cache.getApplicationContext(); - if(applicationContext.containsBean(cache.getBeanName())){ - return applicationContext.getBean(cache.getBeanName()); + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + if(springBeanFactory.containsBean(cache.getBeanName())){ + return springBeanFactory.getBean(cache.getBeanName()); } return null; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java similarity index 84% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java index 6a60ae9..c33c188 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/InvokeSupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.processor.invoke; +package com.gitee.starblues.spring.invoke; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java similarity index 93% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java index 78dcb05..71e813f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/invoke/SupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.spring.processor.invoke; +package com.gitee.starblues.spring.invoke; import com.gitee.starblues.spring.ApplicationContext; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java deleted file mode 100644 index 1707e3d..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfPluginSpringApplication.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.gitee.starblues.spring.oneself; - - -import org.springframework.context.support.GenericApplicationContext; - -/** - * 插件可主运行的 PluginSpringApplication 实现, 插件如果需要自动运行, 则使用该类进行引导启动 - * @author starBlues - * @version 3.0.0 - */ -public class OneselfPluginSpringApplication { - - public static GenericApplicationContext run(Class ...primarySources){ - try { - return new OneselfSpringApplication(primarySources).run(); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java deleted file mode 100644 index 9019ec2..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringApplication.java +++ /dev/null @@ -1,230 +0,0 @@ -package com.gitee.starblues.spring.oneself; - -import com.gitee.starblues.core.PluginState; -import com.gitee.starblues.core.descriptor.*; -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.integration.AutoIntegrationConfiguration; -import com.gitee.starblues.integration.DefaultIntegrationConfiguration; -import com.gitee.starblues.spring.PluginSpringApplication; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.SpringPluginProcessor; -import com.gitee.starblues.spring.processor.SpringPluginProcessorFactory; -import com.gitee.starblues.utils.ObjectUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.io.ResourceLoader; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -/** - * 插件自主运行时的SpringApplication环境, 对 SpringApplication 进行再次封装 - * @author starBlues - * @version 3.0.0 - * @see SpringApplication - */ -public class OneselfSpringApplication extends SpringApplication implements PluginSpringApplication{ - - private final static Logger LOG = LoggerFactory.getLogger(OneselfSpringApplication.class); - - private final Class primarySource; - - private final PluginWrapper pluginWrapper; - - private final SpringPluginProcessor springPluginProcessor; - - private SpringPluginRegistryInfo registryInfo; - - private GenericApplicationContext applicationContext; - - public OneselfSpringApplication(Class... primarySources) { - this(null, primarySources); - } - - public OneselfSpringApplication(ResourceLoader resourceLoader, Class... primarySources) { - super(resourceLoader, primarySources); - if(primarySources.length > 0){ - primarySource = primarySources[0]; - } else { - primarySource = null; - } - // 运行之前, 从当前插件的 classpath 下获取插件引导信息 - pluginWrapper = tryGetPluginWrapper(); - this.springPluginProcessor = new SpringPluginProcessorFactory(SpringPluginProcessor.RunMode.ONESELF); - } - - - @Override - public GenericApplicationContext run() throws Exception { - return (GenericApplicationContext) super.run(); - } - - @Override - public void close(){ - if(applicationContext != null){ - try { - springPluginProcessor.close(registryInfo); - } catch (Exception e) { - e.printStackTrace(); - } finally { - applicationContext.close(); - } - } - } - - @Override - public GenericApplicationContext getApplicationContext() { - return applicationContext; - } - - - @Override - protected void bindToSpringApplication(ConfigurableEnvironment environment) { - super.bindToSpringApplication(environment); - Map env = new HashMap<>(); - // 禁用插件的自动装配 - env.put(AutoIntegrationConfiguration.ENABLE_KEY, false); - env.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); - String contextPath = getContextPath(environment); - env.put("server.servlet.context-path", contextPath); - LOG.info("当前应用接口前缀为: {}", contextPath); - environment.getPropertySources().addFirst(new MapPropertySource("springPluginRegistryInfo", env)); - } - - @Override - protected ConfigurableApplicationContext createApplicationContext() { - ConfigurableApplicationContext applicationContext = super.createApplicationContext(); - try { - this.applicationContext = (GenericApplicationContext) applicationContext; - springPluginProcessor.initialize(this.applicationContext); - } catch (Exception e) { - e.printStackTrace(); - } - return applicationContext; - } - - @Override - protected void refresh(ConfigurableApplicationContext applicationContext) { - try { - AutoIntegrationConfiguration configuration = bindIntegrationConfiguration(applicationContext); - registryInfo = new OneselfSpringPluginRegistryInfo(pluginWrapper, this, - applicationContext, configuration); - springPluginProcessor.refreshBefore(registryInfo); - } catch (Exception e) { - throw new RuntimeException(e); - } - try { - super.refresh(applicationContext); - springPluginProcessor.refreshAfter(registryInfo); - } catch (Exception e){ - try { - springPluginProcessor.failure(registryInfo); - } catch (Exception exception) { - throw new RuntimeException(e); - } - } - - } - - private AutoIntegrationConfiguration bindIntegrationConfiguration( - ConfigurableApplicationContext applicationContext){ - Binder binder = Binder.get(applicationContext.getEnvironment()); - AutoIntegrationConfiguration configuration = - binder.bind("plugin", Bindable.of(AutoIntegrationConfiguration.class)) - .orElseGet(() -> null); - if(configuration == null){ - configuration = new AutoIntegrationConfiguration(); - } - applicationContext.getBeanFactory().registerSingleton("integrationConfiguration", - configuration); - return configuration; - } - - - /** - * 尝试从 classpath 获取插件引导信息, 如果不存在, 则生成空的 PluginWrapper - * @return PluginWrapper - */ - private PluginWrapper tryGetPluginWrapper(){ - try { - PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); - PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load( - Paths.get(this.getClass().getResource("/").toURI())); - if(pluginDescriptor == null){ - return getPluginWrapper(new EmptyPluginDescriptor()); - } else { - return getPluginWrapper(pluginDescriptor); - } - } catch (Exception e){ - return getPluginWrapper(new EmptyPluginDescriptor()); - } - } - - private PluginWrapper getPluginWrapper(PluginDescriptor pluginDescriptor){ - return new PluginWrapper() { - @Override - public String getPluginId() { - return pluginDescriptor.getPluginId(); - } - - @Override - public PluginDescriptor getPluginDescriptor() { - return pluginDescriptor; - } - - @Override - public ClassLoader getPluginClassLoader() { - return this.getClass().getClassLoader(); - } - - @Override - public Class getPluginClass() { - return primarySource; - } - - @Override - public Path getPluginPath() { - return pluginDescriptor.getPluginPath(); - } - - @Override - public PluginState getPluginState() { - return PluginState.STARTED; - } - }; - } - - /** - * 获取独立运行插件的接口 url 前缀 - * @param environment environment - * @return String - */ - private String getContextPath(ConfigurableEnvironment environment){ - String pluginRestPathPrefix = environment.getProperty("plugin.pluginRestPathPrefix", String.class); - Boolean enablePluginIdRestPathPrefix = environment.getProperty("plugin.enablePluginIdRestPathPrefix", - Boolean.class); - String contextPath = ""; - if(ObjectUtils.isEmpty(pluginRestPathPrefix)){ - pluginRestPathPrefix = DefaultIntegrationConfiguration.DEFAULT_PLUGIN_REST_PATH_PREFIX; - } - if(enablePluginIdRestPathPrefix == null){ - enablePluginIdRestPathPrefix = DefaultIntegrationConfiguration.DEFAULT_ENABLE_PLUGIN_ID_REST_PATH_PREFIX; - } - String pluginId = pluginWrapper.getPluginId(); - contextPath = "/" + pluginRestPathPrefix; - if(enablePluginIdRestPathPrefix && !ObjectUtils.isEmpty(pluginId)){ - contextPath = contextPath + "/" + pluginId; - } - return contextPath; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java deleted file mode 100644 index 3eb227c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/oneself/OneselfSpringPluginRegistryInfo.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.gitee.starblues.spring.oneself; - -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.DefaultRegistryInfo; -import com.gitee.starblues.spring.PluginSpringApplication; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author starBlues - * @version 1.0 - */ -public class OneselfSpringPluginRegistryInfo extends DefaultRegistryInfo implements SpringPluginRegistryInfo { - - - private final PluginSpringApplication pluginSpringApplication; - private final PluginWrapper pluginWrapper; - private final ConfigurableApplicationContext applicationContext; - private final IntegrationConfiguration configuration; - - public OneselfSpringPluginRegistryInfo(PluginWrapper pluginWrapper, - PluginSpringApplication pluginSpringApplication, - ConfigurableApplicationContext applicationContext, - IntegrationConfiguration configuration) { - this.pluginWrapper = pluginWrapper; - this.pluginSpringApplication = pluginSpringApplication; - this.applicationContext = applicationContext; - this.configuration = configuration; - } - - @Override - public PluginWrapper getPluginWrapper() { - return pluginWrapper; - } - - @Override - public PluginSpringApplication getPluginSpringApplication() { - return pluginSpringApplication; - } - - @Override - public ConfigurableApplicationContext getMainApplicationContext() { - return applicationContext; - } - - @Override - public IntegrationConfiguration getConfiguration() { - return configuration; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java deleted file mode 100644 index a2cf2d9..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/BeanRegistryProcessor.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.scanner.PluginClassPathBeanDefinitionScanner; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.ScanUtils; - - -/** - * @author starBlues - * @version 1.0 - */ -public class BeanRegistryProcessor implements SpringPluginProcessor{ - - @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - PluginClassPathBeanDefinitionScanner scanner = new PluginClassPathBeanDefinitionScanner(registryInfo); - scanner.scan(ScanUtils.getScanBasePackages((registryInfo.getPluginWrapper().getPluginClass()))); - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority().down(10); - } - - @Override - public RunMode runMode() { - return RunMode.PLUGIN; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java deleted file mode 100644 index c8de5a6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/FrameDefineBeanRegistryProcessor.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.realize.PluginUtils; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * 框架 bean 注册 - * @author starBlues - * @version 1.0 - */ -public class FrameDefineBeanRegistryProcessor implements SpringPluginProcessor{ - - @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); - PluginDescriptor pluginDescriptor = registryInfo.getPluginWrapper().getPluginDescriptor(); - ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - beanFactory.registerSingleton("pluginDescriptor", pluginDescriptor); - beanFactory.registerSingleton("pluginUtils", new PluginUtils(applicationContext)); - } - - @Override - public RunMode runMode() { - return RunMode.ALL; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java deleted file mode 100644 index 0208151..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/OneselfBeanRegistryProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.integration.IntegrationExtendPoint; -import com.gitee.starblues.integration.application.EmptyPluginApplication; -import com.gitee.starblues.integration.application.PluginApplication; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.extract.ExtractFactory; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author starBlues - * @version 1.0 - * @see IntegrationExtendPoint - */ -public class OneselfBeanRegistryProcessor implements SpringPluginProcessor{ - - @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication() - .getApplicationContext(); - ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - PluginApplication pluginApplication = new EmptyPluginApplication(); - beanFactory.registerSingleton("pluginApplication", pluginApplication); - beanFactory.registerSingleton("pluginOperator", pluginApplication.getPluginOperator()); - beanFactory.registerSingleton("pluginUser", pluginApplication.getPluginUser()); - beanFactory.registerSingleton("extractFactory", ExtractFactory.getInstant()); - } - - @Override - public RunMode runMode() { - return RunMode.ONESELF; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java deleted file mode 100644 index 9d3a385..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/PluginControllerRegistryProcessor.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.PluginSpringApplication; -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ReflectionUtils; -import org.pf4j.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @author starBlues - * @version 1.0 - */ -public class PluginControllerRegistryProcessor implements SpringPluginProcessor{ - - private final static Logger LOG = LoggerFactory.getLogger(PluginControllerRegistryProcessor.class); - - private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; - - private GenericApplicationContext mainApplicationContext; - - private RequestMappingHandlerMapping requestMappingHandlerMapping; - private Method getMappingForMethod; - - private final AtomicBoolean canRegistered = new AtomicBoolean(false); - - - @Override - public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { - this.requestMappingHandlerMapping = mainApplicationContext.getBean(RequestMappingHandlerMapping.class); - this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, - "getMappingForMethod", Method.class, Class.class); - if(getMappingForMethod == null){ - LOG.warn("RequestMappingHandlerMapping 类中没有发现 方法, 无法注册插件接口. " + - "请检查当前环境是否为 web 环境"); - } - this.getMappingForMethod.setAccessible(true); - canRegistered.set(true); - } - - - @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - if(!canRegistered.get()){ - return; - } - PluginSpringApplication pluginSpringApplication = registryInfo.getPluginSpringApplication(); - AnnotationConfigApplicationContext applicationContext = - (AnnotationConfigApplicationContext)pluginSpringApplication.getApplicationContext(); - applicationContext.registerBean("changeRestPathPostProcessor", - ChangeRestPathPostProcessor.class, ()-> new ChangeRestPathPostProcessor(registryInfo)); - } - - @Override - public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { - if(!canRegistered.get()){ - return; - } - IntegrationConfiguration configuration = registryInfo.getConfiguration(); - if(ObjectUtils.isEmpty(configuration.pluginRestPathPrefix()) - && !configuration.enablePluginIdRestPathPrefix()){ - // 如果 pluginRestPathPrefix 为空, 并且没有启用插件id作为插件前缀, 则不进行修改插件controller地址前缀 - return; - } - String pluginId = registryInfo.getPluginWrapper().getPluginId(); - List controllerWrappers = registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); - if(ObjectUtils.isEmpty(controllerWrappers)){ - LOG.warn("插件 [{}] 没有发现可注册的 Controller", pluginId); - return; - } - ConfigurableApplicationContext applicationContext = registryInfo.getPluginSpringApplication().getApplicationContext(); - - Iterator iterator = controllerWrappers.iterator(); - while (iterator.hasNext()){ - ControllerWrapper controllerWrapper = iterator.next(); - if(!applicationContext.containsBean(controllerWrapper.getBeanName())){ - iterator.remove(); - } - Object controllerBean = applicationContext.getBean(controllerWrapper.getBeanName()); - Set requestMappingInfos = registry(registryInfo, controllerBean.getClass()); - if(requestMappingInfos.isEmpty()){ - iterator.remove(); - } else { - for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { - LOG.info("插件[{}]注册接口: {}", pluginId, requestMappingInfo.toString()); - } - } - } - } - - @Override - public RunMode runMode() { - return RunMode.PLUGIN; - } - - - private Set registry(SpringPluginRegistryInfo pluginRegistryInfo, Class aClass) - throws Exception { - ConfigurableApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginSpringApplication() - .getApplicationContext(); - Object object = pluginApplicationContext.getBean(aClass); - - Method[] methods = aClass.getMethods(); - Set requestMappingInfos = new HashSet<>(); - for (Method method : methods) { - if (isHaveRequestMapping(method)) { - RequestMappingInfo requestMappingInfo = (RequestMappingInfo) - getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass); - requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method); - requestMappingInfos.add(requestMappingInfo); - } - } - return requestMappingInfos; - } - - /** - * 方法上是否存在 @RequestMapping 注解 - * @param method method - * @return boolean - */ - private boolean isHaveRequestMapping(Method method){ - return AnnotationUtils.findAnnotation(method, RequestMapping.class) != null; - } - - private static class ChangeRestPathPostProcessor implements BeanPostProcessor { - - private final static Logger LOG = LoggerFactory.getLogger(ChangeRestPathPostProcessor.class); - private final static String COMMON_ERROR = "无法统一处理该 Controller 统一请求路径前缀"; - - private final SpringPluginRegistryInfo registryInfo; - - - - private ChangeRestPathPostProcessor(SpringPluginRegistryInfo registryInfo) { - this.registryInfo = registryInfo; - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - Class aClass = bean.getClass(); - Controller controller = AnnotationUtils.findAnnotation(aClass, Controller.class); - if(controller == null){ - return bean; - } - RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class); - if(requestMapping != null){ - changePathForClass(beanName, aClass, requestMapping); - } - return bean; - } - - private void changePathForClass(String beanName, Class aClass, RequestMapping requestMapping){ - String pluginId = registryInfo.getPluginWrapper().getPluginId(); - String pathPrefix = CommonUtils.getPluginRestPrefix(registryInfo.getConfiguration(), pluginId); - - if(StringUtils.isNullOrEmpty(pathPrefix)){ - LOG.error("插件 [{}] Controller类 [{}] 未发现 path 配置, {}", - pluginId, aClass.getSimpleName(), COMMON_ERROR); - return; - } - Set definePaths = new HashSet<>(); - definePaths.addAll(Arrays.asList(requestMapping.path())); - definePaths.addAll(Arrays.asList(requestMapping.value())); - try { - Map memberValues = ClassUtils.getAnnotationsUpdater(requestMapping); - if(memberValues == null){ - LOG.error("插件 [{}] Controller 类 [{}] 无法反射获取注解属性, {}", - pluginId, aClass.getSimpleName(), COMMON_ERROR); - return; - } - String[] newPath = new String[definePaths.size()]; - int i = 0; - for (String definePath : definePaths) { - // 解决插件启用、禁用后, 路径前缀重复的问题。 - if(definePath.contains(pathPrefix)){ - newPath[i++] = definePath; - } else { - newPath[i++] = CommonUtils.restJoiningPath(pathPrefix, definePath); - } - } - if(newPath.length == 0){ - newPath = new String[]{ pathPrefix }; - } - memberValues.put("path", newPath); - memberValues.put("value", newPath); - - List controllerWrappers = this.registryInfo.getRegistryInfo(PROCESS_CONTROLLERS); - if(controllerWrappers == null){ - controllerWrappers = new ArrayList<>(); - this.registryInfo.addRegistryInfo(PROCESS_CONTROLLERS, controllerWrappers); - } - ControllerWrapper controllerWrapper = new ControllerWrapper(); - controllerWrapper.setPathPrefix(newPath); - controllerWrapper.setBeanName(beanName); - controllerWrappers.add(controllerWrapper); - } catch (Exception e) { - LOG.error("插件 [{}] Controller 类[{}] 注册异常. {}", pluginId, aClass.getName(), e.getMessage(), e); - } - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java deleted file mode 100644 index ba580ab..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessor.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.utils.Order; -import com.gitee.starblues.utils.OrderPriority; -import org.springframework.context.support.GenericApplicationContext; - -/** - * @author starBlues - * @version 1.0 - */ -public interface SpringPluginProcessor extends Order { - - default void initialize(GenericApplicationContext mainApplicationContext) throws Exception{}; - - default void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception{} - default void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception{} - - default void failure(SpringPluginRegistryInfo registryInfo) throws Exception{} - - default void close(SpringPluginRegistryInfo registryInfo) throws Exception{} - - @Override - default OrderPriority order(){ - return OrderPriority.getLowPriority(); - } - - - RunMode runMode(); - - - enum RunMode{ - /** - * 全部运行 - */ - ALL, - - /** - * 插件环境运行 - */ - PLUGIN, - - /** - * 插件独立运行 - */ - ONESELF - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java deleted file mode 100644 index 9774308..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/SpringPluginProcessorFactory.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.gitee.starblues.spring.processor; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import com.gitee.starblues.spring.processor.extract.ExtractBeanProcessor; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * @author starBlues - * @version 1.0 - */ -public class SpringPluginProcessorFactory implements SpringPluginProcessor{ - - private final SpringPluginProcessor.RunMode runMode; - - private List processors; - - public SpringPluginProcessorFactory(SpringPluginProcessor.RunMode runMode) { - this.runMode = runMode; - } - - @Override - public void initialize(GenericApplicationContext mainApplicationContext) throws Exception { - List processors = getDefaultProcessors(); - if(runMode == RunMode.PLUGIN){ - List extendProcessors = SpringBeanUtils.getBeans(mainApplicationContext, - SpringPluginProcessor.class); - processors.addAll(extendProcessors); - } - this.processors = processors.stream() - .filter(p->{ - RunMode runMode = p.runMode(); - return runMode == RunMode.ALL || runMode == this.runMode; - }) - .sorted(CommonUtils.orderPriority(SpringPluginProcessor::order)) - .collect(Collectors.toList()); - for (SpringPluginProcessor processor : this.processors) { - processor.initialize(mainApplicationContext); - } - } - - private List getDefaultProcessors(){ - List processors = new ArrayList<>(); - processors.add(new BeanRegistryProcessor()); - processors.add(new FrameDefineBeanRegistryProcessor()); - processors.add(new ExtractBeanProcessor()); - processors.add(new PluginInterceptorsProcessor()); - processors.add(new PluginControllerRegistryProcessor()); - - processors.add(new OneselfBeanRegistryProcessor()); - return processors; - } - - - @Override - public void refreshBefore(SpringPluginRegistryInfo registryInfo) throws Exception { - for (SpringPluginProcessor processor : processors) { - processor.refreshBefore(registryInfo); - } - } - - @Override - public void refreshAfter(SpringPluginRegistryInfo registryInfo) throws Exception { - for (SpringPluginProcessor processor : processors) { - processor.refreshAfter(registryInfo); - } - } - - @Override - public void failure(SpringPluginRegistryInfo registryInfo) throws Exception { - for (SpringPluginProcessor processor : processors) { - try { - processor.failure(registryInfo); - } catch (Exception e){ - e.printStackTrace(); - } - } - } - - @Override - public void close(SpringPluginRegistryInfo registryInfo) throws Exception { - for (SpringPluginProcessor processor : processors) { - try { - processor.close(registryInfo); - } catch (Exception e){ - e.printStackTrace(); - } - } - } - - @Override - public OrderPriority order() { - return OrderPriority.getHighPriority(); - } - - @Override - public RunMode runMode() { - return RunMode.ALL; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java deleted file mode 100644 index 10b058b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/CallerClassGroup.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.starblues.spring.processor.classgroup; - -import com.gitee.starblues.annotation.Caller; -import org.springframework.core.annotation.AnnotationUtils; - -/** - * @author starBlues - * @version 1.0 - */ -public class CallerClassGroup extends PluginClassGroup{ - - public final static String ID = getFullId("CallerClassGroup"); - - @Override - public String groupId() { - return ID; - } - - @Override - public boolean filter(Class aClass) { - return AnnotationUtils.findAnnotation(aClass, Caller.class) != null; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java deleted file mode 100644 index ad69846..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/ComposeClassGroup.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.starblues.spring.processor.classgroup; - -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.stereotype.Component; - -/** - * @author starBlues - * @version 1.0 - */ -public class ComposeClassGroup extends PluginClassGroup{ - - public final static String ID = getFullId("ComposeClassGroup"); - - @Override - public String groupId() { - return ID; - } - - @Override - public boolean filter(Class aClass) { - return AnnotationUtils.findAnnotation(aClass, Component.class) != null; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java deleted file mode 100644 index 336a003..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/classgroup/PluginClassGroup.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.gitee.starblues.spring.processor.classgroup; - -/** - * @author starBlues - * @version 1.0 - */ -public abstract class PluginClassGroup { - - protected static String ID_PREFIX = "PluginClassGroup_"; - - public static String OTHER_CLASS_GROUP_ID = ID_PREFIX + "otherClass"; - - /** - * 得到全id - * @param groupId groupId - * @return String - */ - static String getFullId(String groupId){ - return ID_PREFIX + groupId; - } - - /** - * 组id - * @return 组id - */ - public abstract String groupId(); - - /** - * 过滤类。 - * @param aClass 类 - * @return 返回true.说明符合该分组器。false不符合该分组器 - */ - public abstract boolean filter(Class aClass); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java deleted file mode 100644 index 4293f03..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/extract/PluginExtractPipeProcessor.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.gitee.starblues.spring.processor.extract; - -import com.gitee.starblues.annotation.Extract; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessor; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.Map; - -/** - * 插件扩展处理者 - * @author starBlues - * @version 2.4.1 - */ -public class PluginExtractPipeProcessor implements PluginPipeProcessor { - - private final ApplicationContext mainApplicationContext; - private final SpringBeanRegister springBeanRegister; - private final ExtractFactory extractFactory; - - public PluginExtractPipeProcessor(ApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - this.springBeanRegister = new SpringBeanRegister((GenericApplicationContext) mainApplicationContext); - this.extractFactory = ExtractFactory.getInstant(); - } - - @Override - public void initialize() throws Exception { - springBeanRegister.registerSingleton(ExtractFactory.class.getName(), extractFactory); - // 获取主程序的扩展 - Map extractMap = mainApplicationContext.getBeansWithAnnotation(Extract.class); - if(!extractMap.isEmpty()){ - for (Object extract : extractMap.values()) { - extractFactory.addOfMain(extract); - } - } - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - Map extractMap = pluginApplicationContext.getBeansWithAnnotation(Extract.class); - if(extractMap.isEmpty()){ - return; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - for (Object extract : extractMap.values()) { - extractFactory.add(pluginId, extract); - } - pluginRegistryInfo.getSpringBeanRegister().registerSingleton( - ExtractFactory.class.getName(), extractFactory - ); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - extractFactory.remove(pluginId); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java deleted file mode 100644 index bea92fe..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/processor/scanner/PluginClassPathBeanDefinitionScanner.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.starblues.spring.processor.scanner; - -import com.gitee.starblues.spring.SpringPluginRegistryInfo; -import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; - - -/** - * @author starBlues - * @version 1.0 - */ -public class PluginClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { - - public PluginClassPathBeanDefinitionScanner(SpringPluginRegistryInfo registryInfo) { - this(registryInfo, true); - } - - public PluginClassPathBeanDefinitionScanner(SpringPluginRegistryInfo registryInfo, boolean useDefaultFilters) { - super(registryInfo.getPluginSpringApplication().getApplicationContext(), useDefaultFilters, - registryInfo.getPluginSpringApplication().getApplicationContext().getEnvironment(), - registryInfo.getPluginSpringApplication().getResourceLoader()); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java new file mode 100644 index 0000000..acd5e26 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java @@ -0,0 +1,83 @@ +package com.gitee.starblues.utils; + +/** + * 比较两个类类型 + * @author starBlues + * @version 3.0.0 + */ +public abstract class CompareClassTypeUtils { + + private CompareClassTypeUtils(){} + + public static boolean compare(Class class1, Class class2){ + if(class1.isAssignableFrom(class2)){ + return true; + } + if(isBoolean(class1) && isBoolean(class2)){ + return true; + } + if(isChar(class1) && isChar(class2)){ + return true; + } + if(isByte(class1) && isByte(class2)){ + return true; + } + if(isShort(class1) && isShort(class2)){ + return true; + } + if(isInt(class1) && isInt(class2)){ + return true; + } + if(isLong(class1) && isLong(class2)){ + return true; + } + if(isFloat(class1) && isFloat(class2)){ + return true; + } + if(isDouble(class1) && isDouble(class2)){ + return true; + } + if(isVoid(class1) && isVoid(class2)){ + return true; + } + return false; + } + + + public static boolean isBoolean(Class class1){ + return class1.isAssignableFrom(Boolean.class) || class1.isAssignableFrom(boolean.class); + } + + public static boolean isChar(Class class1){ + return class1.isAssignableFrom(Character.class) || class1.isAssignableFrom(char.class); + } + + public static boolean isByte(Class class1){ + return class1.isAssignableFrom(Byte.class) || class1.isAssignableFrom(byte.class); + } + + public static boolean isShort(Class class1){ + return class1.isAssignableFrom(Short.class) || class1.isAssignableFrom(short.class); + } + + public static boolean isInt(Class class1){ + return class1.isAssignableFrom(Integer.class) || class1.isAssignableFrom(int.class); + } + + public static boolean isLong(Class class1){ + return class1.isAssignableFrom(Long.class) || class1.isAssignableFrom(long.class); + } + + public static boolean isFloat(Class class1){ + return class1.isAssignableFrom(Float.class) || class1.isAssignableFrom(float.class); + } + + public static boolean isDouble(Class class1){ + return class1.isAssignableFrom(Double.class) || class1.isAssignableFrom(double.class); + } + + public static boolean isVoid(Class class1){ + return class1.isAssignableFrom(Void.class) || class1.isAssignableFrom(void.class); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 9feeb34..9c9aab6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -210,13 +210,14 @@ public abstract class ReflectionUtils { for (int i = 0; i < paramTypes.length; i++) { Class paramType = paramTypes[i]; Class methodParamType = parameterTypes[i]; - if(!methodParamType.isAssignableFrom(paramType)){ + if(!CompareClassTypeUtils.compare(methodParamType, paramType)){ return false; } } return true; } + public static NoSuchMethodException getNoSuchMethodException(Class aClass, String name, Class[] argTypes) { return new NoSuchMethodException("Not found method:" + methodToString(aClass, name, argTypes)); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 98ae68f..5e187a7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -1,6 +1,5 @@ package com.gitee.starblues.utils; -import com.gitee.starblues.factory.PluginRegistryInfo; import com.gitee.starblues.integration.IntegrationConfiguration; import org.pf4j.PluginWrapper; import org.pf4j.RuntimeMode; @@ -73,34 +72,34 @@ public class ResourceUtils { return locationMatch.startsWith(TYPE_PACKAGE + TYPE_SPLIT); } - /** - * 根据 ~ 标记获取, 得到绝对路径 - * @param pluginRegistryInfo pluginRegistryInfo - * @param rootDir 根目录 - * @return java.lang.String - **/ - public static String getAbsolutePath(PluginRegistryInfo pluginRegistryInfo, String rootDir){ - if(StringUtils.isNullOrEmpty(rootDir)){ - return rootDir; - } - String home = null; - if(rootDir.startsWith(ResourceUtils.ROOT_PLUGIN_SIGN)){ - String pluginRootDir; - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - RuntimeMode runtimeMode = pluginWrapper.getRuntimeMode(); - if(runtimeMode == RuntimeMode.DEVELOPMENT){ - pluginRootDir = pluginWrapper.getPluginPath().toString(); - } else { - pluginRootDir = System.getProperty("user.dir"); - } - // 如果root路径中开始存在ROOT_PLUGIN_SIGN,则说明进行插件根路替换 - home = rootDir.replaceFirst("\\" + ResourceUtils.ROOT_PLUGIN_SIGN, ""); - home = CommonUtils.joiningFilePath(pluginRootDir, home); - } else { - home = rootDir; - } - return home; - } +// /** +// * 根据 ~ 标记获取, 得到绝对路径 +// * @param pluginRegistryInfo pluginRegistryInfo +// * @param rootDir 根目录 +// * @return java.lang.String +// **/ +// public static String getAbsolutePath(PluginRegistryInfo pluginRegistryInfo, String rootDir){ +// if(StringUtils.isNullOrEmpty(rootDir)){ +// return rootDir; +// } +// String home = null; +// if(rootDir.startsWith(ResourceUtils.ROOT_PLUGIN_SIGN)){ +// String pluginRootDir; +// PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); +// RuntimeMode runtimeMode = pluginWrapper.getRuntimeMode(); +// if(runtimeMode == RuntimeMode.DEVELOPMENT){ +// pluginRootDir = pluginWrapper.getPluginPath().toString(); +// } else { +// pluginRootDir = System.getProperty("user.dir"); +// } +// // 如果root路径中开始存在ROOT_PLUGIN_SIGN,则说明进行插件根路替换 +// home = rootDir.replaceFirst("\\" + ResourceUtils.ROOT_PLUGIN_SIGN, ""); +// home = CommonUtils.joiningFilePath(pluginRootDir, home); +// } else { +// home = rootDir; +// } +// return home; +// } public static boolean isUrl(String resourceLocation) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java new file mode 100644 index 0000000..70e9be0 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java @@ -0,0 +1,105 @@ +package com.gitee.starblues.utils; + +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.SpringBeanFactory; +import org.springframework.util.ClassUtils; + +import java.util.*; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class SpringBeanUtilsV3 { + + /** + * 得到ApplicationContext中的bean的实现 + * @param applicationContext applicationContext + * @param aClass 接口或者抽象类型bean类型 + * @param 接口或者抽象类型bean类型 + * @return 所有的实现对象 + */ + public static List getBeans(ApplicationContext applicationContext, Class aClass) { + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + Map beansOfTypeMap = springBeanFactory.getBeansOfType(aClass); + if(beansOfTypeMap.isEmpty()){ + return new ArrayList<>(); + } + return new ArrayList<>(beansOfTypeMap.values()); + } + + /** + * 得到某个接口的实现对象 + * @param sourceObject 遍历的对象 + * @param interfaceClass 接口类类型 + * @param 接口类型 + * @return 实现对象 + */ + public static T getObjectByInterfaceClass(Set sourceObject, Class interfaceClass){ + if(sourceObject == null || sourceObject.isEmpty()){ + return null; + } + for (Object configSingletonObject : sourceObject) { + Set> allInterfacesForClassAsSet = ClassUtils + .getAllInterfacesAsSet(configSingletonObject); + if(allInterfacesForClassAsSet.contains(interfaceClass)){ + return (T) configSingletonObject; + } + } + return null; + } + + /** + * 获取具体类的对象 + * @param sourceObject 源对象集合 + * @param aClass 对象对应的类类型 + * @param 类实现 + * @return T + */ + public static T getObjectClass(Set sourceObject, Class aClass){ + if(sourceObject == null || sourceObject.isEmpty()){ + return null; + } + for (Object configSingletonObject : sourceObject) { + if(Objects.equals(configSingletonObject.getClass(), aClass)){ + return (T) configSingletonObject; + } + } + return null; + } + + /** + * 得到存在的bean, 不存在则返回null + * @param applicationContext applicationContext + * @param aClass bean 类型 + * @param bean 类型 + * @return 存在bean对象, 不存在返回null + */ + public static T getExistBean(ApplicationContext applicationContext, Class aClass){ + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + String[] beanNamesForType = springBeanFactory.getBeanNamesForType(aClass, false, false); + if(beanNamesForType.length > 0){ + return springBeanFactory.getBean(aClass); + } else { + return null; + } + } + + /** + * 得到存在的bean, 不存在则返回null + * @param applicationContext applicationContext + * @param beanName bean 名称 + * @param 返回的bean类型 + * @return 存在bean对象, 不存在返回null + */ + public static T getExistBean(ApplicationContext applicationContext, String beanName){ + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + if(springBeanFactory.containsBean(beanName)){ + Object bean = springBeanFactory.getBean(beanName); + return (T) bean; + } else { + return null; + } + } + +} -- Gitee From 101ef2b2a3de10ede5206fb80552406fb36ffbc2 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Tue, 11 Jan 2022 15:12:05 +0800 Subject: [PATCH 20/37] add package --- pom.xml | 2 + spring-plugin-framework-common/pom.xml | 33 ++ .../starblues/common/PackageStructure.java | 64 ++++ .../starblues/common/PluginDescriptorKey.java | 30 ++ .../starblues/common/utils/ManifestUtils.java | 35 +++ springboot-plugin-bootstrap/pom.xml | 21 +- .../bootstrap/ConfigurePluginEnvironment.java | 9 + .../bootstrap/PluginApplicationContext.java | 5 + .../bootstrap/PluginListableBeanFactory.java | 26 +- .../bootstrap/PluginOneselfInteractive.java | 3 +- .../bootstrap/PluginSpringApplication.java | 2 + .../bootstrap/SpringPluginBootstrap.java | 41 +-- .../annotation/DisablePluginWeb.java | 14 + .../ComposeSpringPluginProcessor.java | 47 ++- .../processor/DefaultProcessorContext.java | 10 +- .../{extract => }/ExtractBeanProcessor.java | 4 +- .../PluginControllerRegistryProcessor.java | 28 +- .../bootstrap/processor/ProcessorContext.java | 6 + .../processor/extract/ExtractCoordinate.java | 106 ------- .../processor/extract/ExtractFactory.java | 259 ---------------- .../bootstrap/utils/DestroyUtils.java | 46 +++ springboot-plugin-framework/pom.xml | 36 +-- .../starblues/core/DefaultPluginChecker.java | 4 +- .../starblues/core/DefaultPluginManager.java | 115 ++++--- .../core/DefaultRealizeProvider.java | 29 +- .../gitee/starblues/core/PluginException.java | 29 +- ...anager.java => PluginLauncherManager.java} | 67 ++-- .../gitee/starblues/core/PluginManager.java | 2 - .../core/{loader => }/PluginWrapper.java | 15 +- .../core/{loader => }/PluginWrapperFace.java | 16 +- .../{loader => }/PluginWrapperInside.java | 26 +- .../gitee/starblues/core/RealizeProvider.java | 15 +- .../gitee/starblues/core/ResourceClear.java | 14 - .../classloader/AbstractResourceLoader.java | 20 +- .../classloader/CacheMainResourceMatcher.java | 17 +- .../core/classloader/ClassPathLoader.java | 2 +- .../DefaultMainResourceMatcher.java | 13 +- .../DefaultMainResourcePatternDefiner.java | 16 +- .../EmptyMainResourcePatternDefiner.java | 9 +- .../core/classloader/GenericClassLoader.java | 284 +++++++++++++++++ .../core/classloader/JarResourceLoader.java | 49 +-- .../core/classloader/MainResourceMatcher.java | 10 +- .../MainResourcePatternDefiner.java | 14 +- .../classloader/NestedJarResourceLoader.java | 72 +++++ .../core/classloader/PluginClassLoader.java | 224 +++----------- .../PluginResourceLoaderFactory.java | 52 ++++ .../ProhibitMainResourceMatcher.java | 14 + .../RepeatResourceLoaderFactory.java | 11 + .../starblues/core/classloader/Resource.java | 9 +- .../classloader/ResourceLoaderFactory.java | 44 +-- .../AbstractPluginDescriptorLoader.java | 96 ++++-- .../descriptor/DefaultPluginDescriptor.java | 54 +++- .../descriptor/DevPluginDescriptorLoader.java | 25 +- .../descriptor/EmptyPluginDescriptor.java | 21 +- .../core/descriptor/PluginDescriptor.java | 52 +++- .../descriptor/PluginDescriptorLoader.java | 14 +- .../ProdDirPluginDescriptorLoader.java | 110 +++++++ .../ProdPackagePluginDescriptorLoader.java | 76 +++++ .../ProdPluginDescriptorLoader.java | 42 +-- .../core/launcher/AbstractLauncher.java | 27 +- .../core/launcher/ClasspathLauncher.java | 26 -- .../JavaMainResourcePatternDefiner.java | 10 +- .../core/launcher/MainProgramLauncher.java | 30 +- .../starblues/core/launcher/MethodRunner.java | 8 +- .../core/launcher/archive/Archive.java | 2 - .../starblues/core/launcher/jar/JarFile.java | 2 +- .../starblues/core/launcher/jar/JarTest2.java | 26 ++ .../launcher/plugin/CacheRegistryInfo.java | 3 +- .../plugin/DefaultPluginInteractive.java | 3 +- .../plugin/DefaultPluginRegistryInfo.java | 37 --- .../launcher/plugin/PluginInteractive.java | 23 +- .../core/launcher/plugin/PluginLauncher.java | 66 ++-- .../plugin/PluginLauncherManager.java | 18 -- .../plugin/PluginLauncherStorage.java | 48 --- .../launcher/plugin/PluginMethodRunner.java | 32 +- .../launcher/plugin/PluginRegistryInfo.java | 15 - .../core/launcher/plugin/RegistryInfo.java | 3 +- .../plugin/SpringPluginHookWrapper.java | 34 +++ .../core/loader/DefaultPluginLoader.java | 145 --------- .../starblues/core/loader/PluginLoader.java | 22 -- .../core/scanner/DevPathResolve.java | 6 +- .../core/scanner/ProdPathResolve.java | 33 +- .../integration/IntegrationExtendPoint.java | 5 +- .../integration/PluginListenerContext.java | 1 - .../PluginStateListenerContext.java | 36 --- .../AbstractPluginApplication.java | 24 -- .../application/EmptyPluginApplication.java | 16 - .../application/PluginApplication.java | 3 +- .../listener/PluginStateListenerFactory.java | 76 ----- .../operator/DefaultPluginOperator.java | 77 +++-- .../operator/EmptyPluginOperator.java | 34 ++- .../integration/operator/PluginOperator.java | 65 ++-- .../operator/PluginOperatorWrapper.java | 39 ++- .../pf4j/ConfigPluginStatusProvider.java | 62 ---- .../integration/pf4j/DefaultPf4jFactory.java | 143 --------- .../integration/pf4j/JarPluginLoader.java | 38 --- .../integration/pf4j/Pf4jFactory.java | 21 -- .../pf4j/SortDependencyResolver.java | 83 ----- .../DefaultPluginDescriptorExtend.java | 43 --- .../ManifestPluginDescriptorFinderExtend.java | 43 --- .../descriptor/PluginDescriptorExtend.java | 26 -- ...solvePropertiesPluginDescriptorFinder.java | 65 ---- .../ResourcesPluginDescriptorFinder.java | 87 ------ .../gitee/starblues/realize/BasePlugin.java | 96 ------ .../starblues/realize/BasePluginExtend.java | 40 --- .../realize/ConfigDefinitionTip.java | 2 - .../starblues/realize/OneselfListener.java | 33 -- .../gitee/starblues/realize/PluginUtils.java | 1 - .../spring/JdkSameTypeParamProxyFactory.java | 3 +- .../spring/MainApplicationContext.java | 3 +- .../spring/MainApplicationContextProxy.java | 3 +- .../spring/PluginSpringApplication.java | 40 --- .../gitee/starblues/spring/ProxyFactory.java | 6 + .../starblues/spring/SpringBeanFactory.java | 3 +- .../starblues/spring/SpringPluginHook.java | 7 +- .../spring/extract/ExtractCoordinate.java | 10 +- .../com/gitee/starblues/utils/AopUtils.java | 168 ---------- .../gitee/starblues/utils/CommonUtils.java | 8 +- .../gitee/starblues/utils/FieldFilter.java | 20 ++ .../com/gitee/starblues/utils/MsgUtils.java | 25 ++ .../gitee/starblues/utils/ObjectUtils.java | 29 +- .../starblues/utils/PluginConfigUtils.java | 16 +- .../starblues/utils/PluginFileUtils.java | 36 +-- .../starblues/utils/ReflectionUtils.java | 29 +- .../gitee/starblues/utils/ResourceUtils.java | 52 +++- .../com/gitee/starblues/utils/ScanUtils.java | 28 -- .../utils/PluginConfigUtilsTest.java | 68 ----- springboot-plugin-maven-pack/pom.xml | 103 +++++++ .../pack/AbstractDependencyFilterMojo.java | 61 ++++ .../plugin/pack/AbstractPackagerMojo.java | 72 +++++ .../plugin/pack/BasicRepackager.java | 200 ++++++++++++ .../gitee/starblues/plugin/pack/Constant.java | 25 ++ .../starblues/plugin/pack/PluginInfo.java | 43 +++ .../starblues/plugin/pack/RepackageMojo.java | 47 +++ .../starblues/plugin/pack/Repackager.java | 16 + .../starblues/plugin/pack/dev/Dependency.java | 22 ++ .../starblues/plugin/pack/dev/DevConfig.java | 31 ++ .../plugin/pack/dev/DevRepackager.java | 69 +++++ .../starblues/plugin/pack/dev/LibCopy.java | 101 ++++++ .../plugin/pack/filter/DependencyFilter.java | 56 ++++ .../starblues/plugin/pack/filter/Exclude.java | 8 + .../plugin/pack/filter/ExcludeFilter.java | 32 ++ .../pack/filter/FilterableDependency.java | 19 ++ .../starblues/plugin/pack/filter/Include.java | 8 + .../plugin/pack/filter/IncludeFilter.java | 27 ++ .../plugin/pack/prod/DirPackageGenerator.java | 122 ++++++++ .../plugin/pack/prod/JarPackageGenerator.java | 43 +++ .../starblues/plugin/pack/prod/JarWriter.java | 14 + .../plugin/pack/prod/PackageGenerator.java | 13 + .../plugin/pack/prod/ProdConfig.java | 42 +++ .../plugin/pack/prod/ProdRepackager.java | 79 +++++ .../plugin/pack/prod/ZipProdRepackager.java | 288 ++++++++++++++++++ .../plugin/pack/utils/CommonUtils.java | 98 ++++++ .../main/resources/META-INF/maven/plugin.xml | 133 ++++++++ 154 files changed, 3770 insertions(+), 2843 deletions(-) create mode 100644 spring-plugin-framework-common/pom.xml create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java rename springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/{extract => }/ExtractBeanProcessor.java (95%) delete mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java delete mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{launcher/plugin/DefaultPluginLauncherManager.java => PluginLauncherManager.java} (36%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{loader => }/PluginWrapper.java (66%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{loader => }/PluginWrapperFace.java (64%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{loader => }/PluginWrapperInside.java (51%) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarTest2.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginStateListenerContext.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginStateListenerFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePlugin.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePluginExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/OneselfListener.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AopUtils.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java delete mode 100644 springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/PluginConfigUtilsTest.java create mode 100644 springboot-plugin-maven-pack/pom.xml create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java create mode 100644 springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml diff --git a/pom.xml b/pom.xml index ad021fd..2141dd2 100644 --- a/pom.xml +++ b/pom.xml @@ -12,10 +12,12 @@ spring boot 插件开发集成包 + spring-plugin-framework-common springboot-plugin-framework springboot-plugin-bootstrap springboot-plugin-framework-example + springboot-plugin-maven-pack diff --git a/spring-plugin-framework-common/pom.xml b/spring-plugin-framework-common/pom.xml new file mode 100644 index 0000000..59c6a68 --- /dev/null +++ b/spring-plugin-framework-common/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + com.gitee.starblues + spring-plugin-framework-common + 3.0.0-RELEASE + jar + + + 1.8 + UTF-8 + 3.8.1 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + + \ No newline at end of file diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java new file mode 100644 index 0000000..344abcd --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java @@ -0,0 +1,64 @@ +package com.gitee.starblues.common; + + +import java.io.File; +import java.util.regex.Matcher; + +/** + * 插件打包结构 + * @author starBlues + * @version 3.0.0 + */ +public abstract class PackageStructure { + + private PackageStructure(){} + + public static final String CHARSET_NAME = "utf-8"; + + public static final String SEPARATOR = "/"; + + public static final String CLASSES_NAME = "classes"; + + public static final String LIB_NAME = "lib"; + + public static final String META_INF_NAME = "META-INF"; + + public static final String MANIFEST = "MANIFEST.MF"; + + public static final String LIB_INDEX_NAME = "lib.index"; + + public static final String PROD_MANIFEST_PATH = META_INF_NAME + SEPARATOR + MANIFEST; + + public static final String PROD_LIB_INDEX_PATH = META_INF_NAME + SEPARATOR + LIB_INDEX_NAME; + + public static final String PROD_CLASSES_PATH = CLASSES_NAME + SEPARATOR; + + public static final String PROD_LIB_PATH = LIB_NAME + SEPARATOR; + + public static String resolvePath(String path){ + if(path == null || "".equals(path)){ + return path; + } + if(path.contains(SEPARATOR)){ + return path.replaceAll(SEPARATOR, Matcher.quoteReplacement(File.separator)); + } + return path; + } + + +// public final static String PROD_LIB_DIR = LIB_NAME + SEPARATOR; +// +// public final static String PROD_CLASSES_DIR = CLASSES_NAME + SEPARATOR; + + +// public static final String PROD_META_INF_PATH = META_INF_NAME + SEPARATOR; +// +// public static final String DEV_MANIFEST_PATH = META_INF_NAME + SEPARATOR + MANIFEST; +// +// public static final String PROD_MANIFEST_PATH = PROD_META_INF_PATH + MANIFEST; + + + +// public static final String PROD_LIB_INDEX_PATH = PROD_META_INF_PATH + LIB_INDEX_NAME; + +} diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java new file mode 100644 index 0000000..cad8f4b --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.common; + +/** + * 插件描述文件配置key + * @author starBlues + * @version 3.0.0 + */ +public class PluginDescriptorKey { + + public static final String MAIN_CLASS = "Main-Class"; + + /** Must configure prop **/ + public static final String PLUGIN_ID = "Plugin-Id"; + public static final String PLUGIN_BOOTSTRAP_CLASS = "Plugin-Bootstrap-Class"; + public static final String PLUGIN_VERSION = "Plugin-Version"; + + /** Optional configure prop **/ + public static final String PLUGIN_DESCRIPTION = "Plugin-Description"; + public static final String PLUGIN_PROVIDER = "Plugin-Provider"; + public static final String PLUGIN_DEPENDENCIES = "Plugin-Dependencies"; + public static final String PLUGIN_REQUIRES = "Plugin-Requires"; + public static final String PLUGIN_LICENSE = "Plugin-License"; + public static final String PLUGIN_CONFIG_FILE_NAME = "Plugin-Config-Filename"; + + /** System create prop **/ + public static final String PLUGIN_PATH = "Plugin-Path"; + public static final String PLUGIN_LIB_INDEX = "Plugin-Lib-Index"; + + +} diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java new file mode 100644 index 0000000..a7ae2db --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java @@ -0,0 +1,35 @@ +package com.gitee.starblues.common.utils; + +import java.util.jar.Attributes; + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class ManifestUtils { + + private ManifestUtils(){} + + public static String getValue(Attributes attributes, String key){ + return getValue(attributes, key, true); + } + + public static String getValue(Attributes attributes, String key, boolean notExitsThrowException){ + boolean throwException = false; + String value = null; + try { + value = attributes.getValue(key); + if(value == null && notExitsThrowException){ + throwException = true; + } + } catch (Throwable e){ + // 忽略 + throwException = true; + } + if(throwException){ + throw new IllegalStateException("Not found '" + key + "' from " + attributes.getClass().getName()); + } + return value; + } + +} diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index 7fc8a38..ba2cf73 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -17,40 +17,51 @@ UTF-8 3.8.1 + 1.7.7 2.5.0 5.3.2 2.11.3 + + org.slf4j + slf4j-api + ${slf4j.version} + + + + com.gitee.starblues + spring-plugin-framework-common + ${project.version} + + org.springframework.boot spring-boot ${spring-boot.version} provided + org.springframework spring-webmvc ${spring.version} provided + com.fasterxml.jackson.core jackson-databind ${jackson.version} + com.gitee.starblues springboot-plugin-framework 3.0.0-RELEASE provided - - org.slf4j - slf4j-api - 1.7.32 - diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index ede8c0a..99b36dc 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -19,9 +19,15 @@ class ConfigurePluginEnvironment { private final static String PLUGIN_PROPERTY_NAME = "pluginPropertySources"; private final static String SPRING_CONFIG_NAME = "spring.config.name"; + + private final static String SPRING_JMX_UNIQUE_NAMES = "spring.jmx.unique-names"; private final static String SPRING_ADMIN_JMX_NAME = "spring.application.admin.jmx-name"; private final static String SPRING_ADMIN_JMX_VALUE = "org.springframework.boot:type=Admin,name="; + public static final String REGISTER_SHUTDOWN_HOOK_PROPERTY = "logging.register-shutdown-hook"; + public static final String MBEAN_DOMAIN_PROPERTY_NAME = "spring.liveBeansView.mbeanDomain"; + + private final PluginDescriptor pluginDescriptor; ConfigurePluginEnvironment(PluginDescriptor pluginDescriptor) { @@ -35,7 +41,10 @@ class ConfigurePluginEnvironment { if(!ObjectUtils.isEmpty(configFileName)){ env.put(SPRING_CONFIG_NAME, PluginFileUtils.getFileName(configFileName)); } + env.put(SPRING_JMX_UNIQUE_NAMES, true); env.put(SPRING_ADMIN_JMX_NAME, SPRING_ADMIN_JMX_VALUE + pluginId); + env.put(REGISTER_SHUTDOWN_HOOK_PROPERTY, false); + env.put(MBEAN_DOMAIN_PROPERTY_NAME, null); environment.getPropertySources().addLast(new MapPropertySource(PLUGIN_PROPERTY_NAME, env)); } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java index d9787c2..08c76c6 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java @@ -22,6 +22,11 @@ public class PluginApplicationContext extends AnnotationConfigApplicationContext this.pluginDescriptor = processorContext.getPluginDescriptor(); } + @Override + public void registerShutdownHook() { + // 忽略 + } + @Override public String getApplicationName() { return pluginDescriptor.getPluginId(); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java index f5deb3d..6f1da23 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -1,9 +1,10 @@ package com.gitee.starblues.bootstrap; -import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.bootstrap.utils.DestroyUtils; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringBeanFactory; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; @@ -56,4 +57,27 @@ public class PluginListableBeanFactory extends DefaultListableBeanFactory { } } + @Override + public void destroySingletons() { + String[] beanDefinitionNames = getBeanDefinitionNames(); + for (String beanDefinitionName : beanDefinitionNames) { + destroyBean(beanDefinitionName); + } + super.destroySingletons(); + destroyAll(); + } + + private void destroyAll(){ + ReflectionUtils.findField(this.getClass(), field -> { + field.setAccessible(true); + try { + Object o = field.get(this); + DestroyUtils.destroy(o); + } catch (IllegalAccessException e) { + // 忽略 + } + return false; + }); + } + } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index 39e0816..64648e8 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -65,8 +65,7 @@ public class PluginOneselfInteractive implements PluginInteractive { private PluginDescriptor createPluginDescriptor(){ PluginDescriptor pluginDescriptor; - try { - PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader(); + try (PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader()){ pluginDescriptor = pluginDescriptorLoader.load( Paths.get(this.getClass().getResource("/").toURI())); if(pluginDescriptor == null){ diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java index 74a906a..2f7c5a8 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -48,6 +48,8 @@ public class PluginSpringApplication extends SpringApplication { setBannerMode(Banner.Mode.OFF); setEnvironment(new StandardEnvironment()); setWebApplicationType(WebApplicationType.NONE); + setRegisterShutdownHook(false); + setLogStartupInfo(false); } @Override diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java index be76a89..9ad1211 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java @@ -1,19 +1,12 @@ package com.gitee.starblues.bootstrap; -import com.gitee.starblues.bootstrap.processor.*; -import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; -import com.gitee.starblues.core.descriptor.EmptyPluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; -import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; +import com.gitee.starblues.bootstrap.processor.ComposeSpringPluginProcessor; +import com.gitee.starblues.bootstrap.processor.DefaultProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; -import com.gitee.starblues.integration.AutoIntegrationConfiguration; -import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; -import com.gitee.starblues.spring.extract.DefaultOpExtractFactory; -import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @@ -30,24 +23,24 @@ public abstract class SpringPluginBootstrap { private final List customPluginProcessors = new ArrayList<>(); - public SpringPluginHook run(String[] args){ + public final SpringPluginHook run(String[] args){ return run(this.getClass(), args); } - public SpringPluginHook run(Class primarySources, String[] args){ + public final SpringPluginHook run(Class primarySources, String[] args){ return run(new Class[]{ primarySources }, args); } - public SpringPluginHook run(Class[] primarySources, String[] args){ + public final SpringPluginHook run(Class[] primarySources, String[] args){ return start(primarySources, args); } private SpringPluginHook start(Class[] primarySources, String[] args){ + addCustomSpringPluginProcessor(); createPluginInteractive(); SpringPluginProcessor pluginProcessor = new ComposeSpringPluginProcessor(runMode, customPluginProcessors); ProcessorContext processorContext = new DefaultProcessorContext( - pluginInteractive, - this.getClass() + this, pluginInteractive, this.getClass() ); PluginSpringApplication springApplication = new PluginSpringApplication( pluginProcessor, @@ -57,26 +50,34 @@ public abstract class SpringPluginBootstrap { return new DefaultSpringPluginHook(pluginProcessor, processorContext); } - public final void setPluginInteractive(PluginInteractive pluginInteractive) { + public final SpringPluginBootstrap setPluginInteractive(PluginInteractive pluginInteractive) { this.pluginInteractive = pluginInteractive; this.runMode = SpringPluginProcessor.RunMode.PLUGIN; + return this; } - public final void addSpringPluginProcessor(SpringPluginProcessor springPluginProcessor){ + public final SpringPluginBootstrap addSpringPluginProcessor(SpringPluginProcessor springPluginProcessor){ if(springPluginProcessor != null){ customPluginProcessors.add(springPluginProcessor); } + return this; } - protected void createPluginInteractive(){ + protected final void createPluginInteractive(){ if(pluginInteractive != null){ return; } createPluginInteractiveOfOneself(); } - protected void createPluginInteractiveOfOneself(){ + protected final void createPluginInteractiveOfOneself(){ this.pluginInteractive = new PluginOneselfInteractive(); } + + /** + * 子类自定义插件 SpringPluginProcessor + */ + protected void addCustomSpringPluginProcessor(){} + } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java new file mode 100644 index 0000000..b923eeb --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java @@ -0,0 +1,14 @@ +package com.gitee.starblues.bootstrap.annotation; + +import java.lang.annotation.*; + +/** + * 禁用web环境. 如果该注解加入到入口类上, 表示 + * @author starBlues + * @version 1.0 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface DisablePluginWeb { +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index 6aa1545..a62b3dc 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -1,5 +1,8 @@ package com.gitee.starblues.bootstrap.processor; +import com.gitee.starblues.bootstrap.SpringPluginBootstrap; +import com.gitee.starblues.bootstrap.annotation.DisablePluginWeb; +import com.gitee.starblues.bootstrap.utils.AnnotationUtils; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.OrderPriority; @@ -41,18 +44,11 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { } } - private List getDefaultProcessors(){ - List processors = new ArrayList<>(); - processors.add(new FrameDefineBeanProcessor()); - processors.add(new PluginControllerRegistryProcessor()); - processors.add(new InvokeOtherPluginProcessor()); - processors.add(new PluginInterceptorsProcessor()); - return processors; - } - @Override - public void initialize(ProcessorContext processorContext) throws ProcessorException { - List processors = getDefaultProcessors(); + public void initialize(ProcessorContext context) throws ProcessorException { + List processors = new ArrayList<>(); + addDefaultProcessors(context, processors); + addDefaultWebEnvProcessors(context, processors); processors.addAll(this.processors); this.processors = processors.stream() .filter(p->{ @@ -63,7 +59,7 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { .collect(Collectors.toList()); for (SpringPluginProcessor processor : this.processors) { try { - processor.initialize(processorContext); + processor.initialize(context); } catch (Throwable e){ processException(processor, "initialize", e, true); } @@ -124,6 +120,33 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { return RunMode.ALL; } + /** + * 获取默认的处理者 + * @param context ProcessorContext + * @param processors 处理者容器集合 + */ + protected void addDefaultProcessors(ProcessorContext context, List processors){ + processors.add(new FrameDefineBeanProcessor()); + processors.add(new ExtractBeanProcessor()); + processors.add(new InvokeOtherPluginProcessor()); + } + + /** + * 添加默认web环境处理者 + * @param context ProcessorContext + * @param processors 处理者容器集合 + */ + protected void addDefaultWebEnvProcessors(ProcessorContext context, List processors){ + SpringPluginBootstrap springPluginBootstrap = context.getSpringPluginBootstrap(); + DisablePluginWeb disablePluginWeb = AnnotationUtils.findAnnotation(springPluginBootstrap.getClass(), + DisablePluginWeb.class); + if(disablePluginWeb != null){ + return; + } + processors.add(new PluginControllerRegistryProcessor()); + processors.add(new PluginInterceptorsProcessor()); + } + private void processException(SpringPluginProcessor processor, String executeType, Throwable e, boolean isThrow) throws ProcessorException{ String error = "Processor[" + processor.getClass().getName() + "] execute[" + executeType + "] failure : " diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 9d04ff6..4034cd4 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -18,6 +18,7 @@ import org.springframework.util.ClassUtils; */ public class DefaultProcessorContext extends CacheRegistryInfo implements ProcessorContext{ + private final SpringPluginBootstrap springPluginBootstrap; private final PluginInteractive pluginInteractive; private final Class runnerClass; private final MainApplicationContext mainApplicationContext; @@ -28,8 +29,10 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces private GenericApplicationContext applicationContext; - public DefaultProcessorContext(PluginInteractive pluginInteractive, + public DefaultProcessorContext(SpringPluginBootstrap springPluginBootstrap, + PluginInteractive pluginInteractive, Class runnerClass) { + this.springPluginBootstrap = springPluginBootstrap; this.pluginInteractive = pluginInteractive; this.runnerClass = runnerClass; this.classLoader = getPluginClassLoader(); @@ -38,6 +41,11 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces this.configuration = pluginInteractive.getConfiguration(); } + @Override + public SpringPluginBootstrap getSpringPluginBootstrap() { + return springPluginBootstrap; + } + @Override public PluginDescriptor getPluginDescriptor() { return pluginInteractive.getPluginDescriptor(); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java similarity index 95% rename from springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractBeanProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java index 5325c92..2f3fe2d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.bootstrap.processor.extract; +package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.annotation.Extract; import com.gitee.starblues.bootstrap.processor.ProcessorContext; @@ -13,7 +13,7 @@ import java.util.Map; /** * Extract 扩展Bean注册处理者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ExtractBeanProcessor implements SpringPluginProcessor { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java index 6cadf9c..c7c532a 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java @@ -78,7 +78,6 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor String pluginId = processorContext.getPluginDescriptor().getPluginId(); List controllerWrappers = processorContext.getRegistryInfo(PROCESS_CONTROLLERS); if(ObjectUtils.isEmpty(controllerWrappers)){ - LOG.warn("插件 [{}] 没有发现可注册的 Controller", pluginId); return; } GenericApplicationContext applicationContext = processorContext.getApplicationContext(); @@ -97,10 +96,22 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { LOG.info("插件[{}]注册接口: {}", pluginId, requestMappingInfo.toString()); } + controllerWrapper.setRequestMappingInfos(requestMappingInfos); } } } + @Override + public void close(ProcessorContext context) throws ProcessorException { + List controllerWrappers = context.getRegistryInfo(PROCESS_CONTROLLERS); + if(ObjectUtils.isEmpty(controllerWrappers)){ + return; + } + for (ControllerWrapper controllerWrapper : controllerWrappers) { + unregister(controllerWrapper); + } + } + @Override public RunMode runMode() { return RunMode.PLUGIN; @@ -128,6 +139,19 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor return requestMappingInfos; } + /** + * 卸载具体的Controller操作 + * @param controllerBeanWrapper controllerBean包装 + */ + private void unregister(ControllerWrapper controllerBeanWrapper) { + Set requestMappingInfos = controllerBeanWrapper.getRequestMappingInfos(); + if(requestMappingInfos != null && !requestMappingInfos.isEmpty()){ + for (RequestMappingInfo requestMappingInfo : requestMappingInfos) { + requestMappingHandlerMapping.unregisterMapping(requestMappingInfo); + } + } + } + /** * 方法上是否存在 @RequestMapping 注解 * @param method method @@ -144,8 +168,6 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor private final ProcessorContext processorContext; - - private ChangeRestPathPostProcessor(ProcessorContext processorContext) { this.processorContext = processorContext; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index ed09026..a187fbd 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -18,6 +18,12 @@ import org.springframework.core.io.ResourceLoader; */ public interface ProcessorContext extends RegistryInfo { + /** + * 得到入口类对象-SpringPluginBootstrap + * @return SpringPluginBootstrap + */ + SpringPluginBootstrap getSpringPluginBootstrap(); + /** * 得到插件信息 PluginDescriptor * @return PluginDescriptor diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java deleted file mode 100644 index 958801c..0000000 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractCoordinate.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.gitee.starblues.bootstrap.processor.extract; - -import com.gitee.starblues.annotation.Extract; -import org.pf4j.util.StringUtils; - -import java.util.Objects; - -/** - * 执行器坐标 - * @author starBlues - * @version 2.4.4 - */ -public class ExtractCoordinate { - - private final String bus; - private final String scene; - private final String useCase; - private final Class extractClass; - - ExtractCoordinate(String bus, String scene, String useCase, Class extractClass) { - this.bus = bus; - this.scene = scene; - this.useCase = useCase; - this.extractClass = extractClass; - } - - - ExtractCoordinate(Extract extract, Class extractClass) { - this.bus = extract.bus(); - this.scene = extract.scene(); - this.useCase = extract.useCase(); - this.extractClass = extractClass; - } - - public static ExtractCoordinate build(String bus) { - return new ExtractCoordinate(bus, null, null, null); - } - - public static ExtractCoordinate build(String bus, String scene) { - return new ExtractCoordinate(bus, scene, null, null); - } - - public static ExtractCoordinate build(String bus, String scene, String useCase) { - return new ExtractCoordinate(bus, scene, useCase, null); - } - - public String getBus() { - return bus; - } - - public String getScene() { - return scene; - } - - public String getUseCase() { - return useCase; - } - - public Class getExtractClass() { - return extractClass; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof ExtractCoordinate)) { - return false; - } - ExtractCoordinate that = (ExtractCoordinate) o; - if(StringUtils.isNotNullOrEmpty(bus) && - StringUtils.isNotNullOrEmpty(scene) && - StringUtils.isNotNullOrEmpty(useCase)){ - return Objects.equals(getBus(), that.getBus()) && - Objects.equals(getScene(), that.getScene()) && - Objects.equals(getUseCase(), that.getUseCase()); - } - - if(StringUtils.isNotNullOrEmpty(bus) && StringUtils.isNotNullOrEmpty(scene)){ - return Objects.equals(getBus(), that.getBus()) && - Objects.equals(getScene(), that.getScene()); - } - - if(StringUtils.isNotNullOrEmpty(bus)){ - return Objects.equals(getBus(), that.getBus()); - } - - return false; - } - - @Override - public int hashCode() { - return Objects.hash(getBus(), getScene(), getUseCase()); - } - - @Override - public String toString() { - return "ExtractCoordinate{" + - "bus='" + bus + '\'' + - ", scene='" + scene + '\'' + - ", useCase='" + useCase + '\'' + - '}'; - } - -} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java deleted file mode 100644 index c002591..0000000 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/extract/ExtractFactory.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.gitee.starblues.bootstrap.processor.extract; - -import com.gitee.starblues.annotation.Extract; -import com.gitee.starblues.utils.ObjectUtils; -import org.springframework.util.ClassUtils; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -/** - * 扩展工厂 - * @author starBlues - * @version 2.4.4 - */ -public class ExtractFactory { - - public static final String MAIN_EXTRACT_KEY = ExtractFactory.class.getName() + UUID.randomUUID().toString(); - - private final Map> extractMap = new ConcurrentHashMap<>(); - - private final static ExtractFactory EXTRACT_FACTORY = new ExtractFactory(); - - private ExtractFactory(){} - - /** - * 得到全局的扩展工厂 - * @return ExtractFactory - */ - public static ExtractFactory getInstant(){ - return EXTRACT_FACTORY; - } - - /** - * 添加扩展 - * @param extractObject 扩展的bean - */ - void addOfMain(Object extractObject){ - add(MAIN_EXTRACT_KEY, extractObject); - } - - - /** - * 添加扩展 - * @param pluginId 插件id - * @param extractObject 扩展的bean - */ - void add(String pluginId, Object extractObject){ - if(extractObject == null){ - return; - } - Extract extract = getExtract(extractObject); - if(extract == null){ - return; - } - Map extractObjects = extractMap.computeIfAbsent(pluginId, k -> - new ConcurrentHashMap<>()); - ExtractWrapper extractWrapper = new ExtractWrapper(extractObject, extract.order()); - extractObjects.put(new ExtractCoordinate(extract, extractObject.getClass()), extractWrapper); - } - - /** - * 根据插件id来移除扩展 - * @param pluginId 插件id - */ - void remove(String pluginId){ - extractMap.remove(pluginId); - } - - /** - * 通过坐标得到扩展 - * @param coordinate 扩展的坐标 - * @param 扩展的泛型 - * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 - */ - @SuppressWarnings("unchecked") - public T getExtractByCoordinate(ExtractCoordinate coordinate){ - Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); - int currentOrder = Integer.MIN_VALUE; - Object currentObject = null; - for (Map value : extractMap.values()) { - ExtractWrapper extractWrapper = value.get(coordinate); - if(extractWrapper != null){ - int order = extractWrapper.getOrder(); - if(order > currentOrder){ - currentObject = extractWrapper.getObject(); - // fix: https://gitee.com/starblues/springboot-plugin-framework-parent/issues/I430R6 - currentOrder = order; - } - } - } - if(currentObject != null){ - return (T) currentObject; - } - throw new RuntimeException("Not found " + coordinate); - } - - /** - * 根据插件id和坐标得到扩展 - * @param pluginId 插件id - * @param coordinate 扩展的坐标 - * @param 扩展的泛型 - * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 - */ - @SuppressWarnings("unchecked") - public T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate){ - Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); - Map extractCoordinates = extractMap.get(pluginId); - if(extractCoordinates == null){ - throw new RuntimeException("Not found " + coordinate + " from plugin '" + pluginId + "'"); - } - Object extracts = extractCoordinates.get(coordinate); - if(extracts == null){ - throw new RuntimeException("Not found " + coordinate + " from plugin '" + pluginId + "'"); - } - return (T) extracts; - } - - - /** - * 根据坐标得到主程序的扩展 - * 主程序扩展必须使用 @Extract+@Component 进行定义 - * @param coordinate 扩展的坐标 - * @param 扩展的泛型 - * @return 扩展实例, 如果不存在则抛出 RuntimeException 异常 - */ - @SuppressWarnings("unchecked") - public T getExtractByCoordinateOfMain(ExtractCoordinate coordinate){ - Objects.requireNonNull(coordinate, "ExtractCoordinate can't be null"); - Map extractCoordinates = extractMap.get(MAIN_EXTRACT_KEY); - if(extractCoordinates == null){ - throw new RuntimeException("Not found " + coordinate + " from main"); - } - ExtractWrapper extractWrapper = extractCoordinates.get(coordinate); - if(extractWrapper == null){ - throw new RuntimeException("Not found " + coordinate + " from main"); - } - return (T) extractWrapper.getObject(); - } - - /** - * 根据接口类型获取扩展 - * @param interfaceClass 接口类类型 - * @param 接口类型泛型 - * @return 扩展实现集合 - */ - @SuppressWarnings("unchecked") - public List getExtractByInterClass(Class interfaceClass){ - if(interfaceClass == null){ - return Collections.emptyList(); - } - List extracts = new ArrayList<>(); - for (Map value : extractMap.values()) { - for (ExtractWrapper extractWrapper : value.values()) { - Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet( - extractWrapper.getObject().getClass()); - if(allInterfacesForClassAsSet.contains(interfaceClass)){ - extracts.add(extractWrapper); - } - } - } - return sort(extracts); - } - - /** - * 根据插件id和接口类型获取扩展 - * @param pluginId 插件id - * @param interfaceClass 接口类类型 - * @param 接口类型泛型 - * @return 扩展实现集合 - */ - @SuppressWarnings("unchecked") - public List getExtractByInterClass(String pluginId, Class interfaceClass){ - if(interfaceClass == null){ - return Collections.emptyList(); - } - List extracts = new ArrayList<>(); - Map extractCoordinateObjectMap = extractMap.get(pluginId); - if(extractCoordinateObjectMap == null || extractCoordinateObjectMap.isEmpty()){ - return Collections.emptyList(); - } - for (ExtractWrapper wrapper : extractCoordinateObjectMap.values()) { - Object object = wrapper.getObject(); - Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(object.getClass()); - if(allInterfacesForClassAsSet.contains(interfaceClass)){ - extracts.add(wrapper); - } - } - return sort(extracts); - } - - /** - * 根据接口类型获取主程序的扩展 - * 主程序扩展必须使用 @Extract+@Component 进行定义 - * @param interfaceClass 接口类类型 - * @param 接口类型泛型 - * @return 扩展实现集合 - */ - public List getExtractByInterClassOfMain(Class interfaceClass){ - return getExtractByInterClass(MAIN_EXTRACT_KEY, interfaceClass); - } - - /** - * 得到所有的扩展坐标 - * @return 扩展坐标集合, key 为插件id, 值为所有扩展坐标集合 - */ - public Map> getExtractCoordinates(){ - Map> extractCoordinateMap = new HashMap<>(extractMap.size()); - extractMap.forEach((k, v)->{ - Set extractCoordinates = new HashSet<>(v.size()); - extractCoordinates.addAll(v.keySet()); - extractCoordinateMap.put(k, extractCoordinates); - }); - return extractCoordinateMap; - } - - /** - * 得到扩展的对象注解 - * @param extractObject 扩展对象 - * @return Extract 注解 - */ - private Extract getExtract(Object extractObject){ - return extractObject.getClass().getAnnotation(Extract.class); - } - - @SuppressWarnings("unchecked") - private List sort(List extractWrappers){ - if(ObjectUtils.isEmpty(extractWrappers)){ - return new ArrayList<>(0); - } - return extractWrappers.stream() - .sorted(Comparator.comparing(ExtractWrapper::getOrder, - Comparator.nullsLast(Comparator.reverseOrder()))) - .map(extractWrapper -> (T) extractWrapper.getObject()) - .collect(Collectors.toList()); - } - - /** - * 扩展对象包装类型 - **/ - private static class ExtractWrapper{ - private final Object object; - private final int order; - - public ExtractWrapper(Object object, int order) { - this.object = object; - this.order = order; - } - - public Object getObject() { - return object; - } - - public int getOrder() { - return order; - } - } - -} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java new file mode 100644 index 0000000..cedb10b --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java @@ -0,0 +1,46 @@ +package com.gitee.starblues.bootstrap.utils; + +import com.gitee.starblues.utils.ReflectionUtils; + +import java.util.Collection; +import java.util.Map; + +/** + * @author starBlues + * @version 1.0 + */ +public class DestroyUtils { + + private DestroyUtils(){} + + + public static void destroy(Object o, String fieldName, Class fieldType){ + try { + Object fieldObject = ReflectionUtils.getField(o, fieldName, fieldType); + if(fieldObject == null){ + return; + } + destroy(fieldObject); + } catch (Exception e){ + // 忽略 + } + } + + @SuppressWarnings("all") + public static void destroy(Object object){ + if(object == null){ + return; + } + if(object instanceof Map){ + ((Map)object).clear(); + } else if (object instanceof Collection){ + ((Collection)object).clear(); + } else if(object.getClass().isArray()){ + Object[] array = (Object[])object; + for (int i = 0; i < array.length; i++) { + array[i] = null; + } + } + } + +} diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index 29f32a6..d2d43d5 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -64,7 +64,6 @@ 3.1.0 1.6 - 3.6.0 2.10.1 1.7.7 @@ -73,21 +72,15 @@ 2.10.5 1.5.2 4.0.1 + 0.9.0 4.11 - - org.pf4j - pf4j - ${pf4j-version} - - - org.slf4j - slf4j-api - - + com.gitee.starblues + spring-plugin-framework-common + ${project.version} @@ -96,6 +89,12 @@ ${slf4j.version} + + commons-io + commons-io + 2.11.0 + + org.springframework.boot spring-boot @@ -125,11 +124,9 @@ - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - true + com.github.zafarkhaja + java-semver + ${java-semver.version} @@ -139,13 +136,6 @@ test - - org.springframework.boot - spring-boot-starter-websocket - ${spring-boot-version} - provided - - diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java index 18e0f9a..ad32cfe 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java @@ -33,8 +33,8 @@ public class DefaultPluginChecker implements PluginChecker{ Assert.isNotNull(descriptor.getPluginId(), "插件id[pluginDescriptor->getPluginId] 不能为空"); - Assert.isNotNull(descriptor.getPluginClass(), - "插件id[pluginDescriptor->getPluginClass] 不能为空"); + Assert.isNotNull(descriptor.getPluginBootstrapClass(), + "插件id[pluginDescriptor->getPluginBootstrapClass] 不能为空"); Assert.isNotNull(descriptor.getPluginVersion(), "插件id[pluginDescriptor->getPluginVersion] 不能为空"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 5c66a2f..728e490 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -1,11 +1,10 @@ package com.gitee.starblues.core; +import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.core.loader.PluginWrapperFace; -import com.gitee.starblues.core.loader.PluginWrapperInside; import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.MsgUtils; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -75,12 +74,9 @@ public class DefaultPluginManager implements PluginManager{ List scanPluginPaths = provider.getPluginScanner().scan(pluginRootDirs); if(ObjectUtils.isEmpty(scanPluginPaths)){ StringBuilder warn = new StringBuilder("\n\n路径 {} 中未发现插件.\n"); - warn.append("1. 请检查路径是否合适.\n"); - warn.append("2. 请检查插件包中是否存在[") - .append(PluginDescriptorLoader.BOOTSTRAP_FILE_NAME) - .append("]插件引导文件.\n"); + warn.append("请检查路径是否合适.\n"); if(provider.getRuntimeMode() == RuntimeMode.DEV){ - warn.append("3. 请检查插件包是否手动编译.\n"); + warn.append("请检查插件包是否编译.\n"); } log.warn(warn.toString(), pluginRootDirs); return Collections.emptyList(); @@ -104,9 +100,9 @@ public class DefaultPluginManager implements PluginManager{ @Override public boolean verify(Path jarPath) { - try { + try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ provider.getPluginChecker().check(jarPath); - PluginDescriptor pluginDescriptor = provider.getPluginDescriptor().load(jarPath); + PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(jarPath); if(pluginDescriptor == null){ return false; } @@ -119,37 +115,44 @@ public class DefaultPluginManager implements PluginManager{ } @Override - public PluginDescriptor load(Path pluginPath) throws PluginException { + public synchronized PluginDescriptor load(Path pluginPath) throws PluginException { try { provider.getPluginChecker().check(pluginPath); } catch (Exception e) { throw new PluginException("非法插件: " + pluginPath, e); } - PluginDescriptor pluginDescriptor = provider.getPluginDescriptor().load(pluginPath); - if(pluginDescriptor == null){ - return null; - } - String pluginId = pluginDescriptor.getPluginId(); - if(resolvedPlugins.containsKey(pluginId) || startedPlugins.containsKey(pluginId)){ - log.error("已经存在插件: {}", pluginId); - return null; + try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ + PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); + if(pluginDescriptor == null){ + return null; + } + String pluginId = pluginDescriptor.getPluginId(); + if(resolvedPlugins.containsKey(pluginId) || startedPlugins.containsKey(pluginId)){ + log.error("已经存在插件: {}", pluginId); + return null; + } + resolvedPlugins.put(pluginDescriptor.getPluginId(), pluginDescriptor); + log.info("加载插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); + return pluginDescriptor; + } catch (Exception e){ + throw new PluginException("加载插件失败"); } - resolvedPlugins.put(pluginDescriptor.getPluginId(), pluginDescriptor); - return pluginDescriptor; + } @Override - public void unLoad(String pluginId) { + public synchronized void unLoad(String pluginId) { resolvedPlugins.remove(pluginId); } @Override - public PluginDescriptor install(Path pluginPath) throws PluginException { + public synchronized PluginDescriptor install(Path pluginPath) throws PluginException { PluginDescriptor pluginDescriptor = load(pluginPath); if(pluginDescriptor == null){ throw new PluginException("安装[" + pluginPath + "]插件包失败."); } try { + log.info("安装插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); return start(pluginDescriptor); } catch (Exception e){ unLoad(pluginDescriptor.getPluginId()); @@ -166,16 +169,22 @@ public class DefaultPluginManager implements PluginManager{ } if(pluginWrapper != null){ if(pluginWrapper.getPluginState() == PluginState.STARTED){ - stop(pluginWrapper); + try { + stop(pluginWrapper); + } catch (Exception e) { + throw new PluginException("停止", pluginId, e); + } } startedPlugins.remove(pluginId); - } else { - resolvedPlugins.remove(pluginId); + pluginDescriptor = pluginWrapper.getPluginDescriptor(); } + resolvedPlugins.remove(pluginId); + System.gc(); + log.info("卸载插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); } @Override - public void upgrade(Path pluginPath) throws PluginException { + public synchronized void upgrade(Path pluginPath) throws PluginException { PluginDescriptor upgradePluginDescriptor = load(pluginPath); if(upgradePluginDescriptor == null){ throw new PluginException("解析[" + pluginPath + "]插件更新包失败."); @@ -204,26 +213,42 @@ public class DefaultPluginManager implements PluginManager{ } else { uninstall(pluginId); } - start(upgradePluginDescriptor); + try { + start(upgradePluginDescriptor); + log.info("更新插件[{}]成功", MsgUtils.getPluginUnique(upgradePluginDescriptor)); + } catch (Exception e){ + throw new PluginException("更新启动", pluginId, e); + } } @Override - public PluginDescriptor start(String pluginId) throws PluginException { + public synchronized PluginDescriptor start(String pluginId) throws PluginException { PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); if(pluginDescriptor == null){ throw new PluginException("没有发现插件: " + pluginId); } - return start(pluginDescriptor); + try { + start(pluginDescriptor); + log.info("启动插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); + return pluginDescriptor; + } catch (Exception e){ + throw new PluginException("启动", pluginId, e); + } } @Override - public PluginDescriptor stop(String pluginId) throws PluginException { + public synchronized PluginDescriptor stop(String pluginId) throws PluginException { PluginWrapperInside pluginWrapper = startedPlugins.get(pluginId); if(pluginWrapper == null){ throw new PluginException("没有发现插件: " + pluginId); } - stop(pluginWrapper); - return pluginWrapper.getPluginDescriptor(); + try { + stop(pluginWrapper); + log.info("停止插件[{}]成功", MsgUtils.getPluginUnique(pluginWrapper.getPluginDescriptor())); + return pluginWrapper.getPluginDescriptor(); + } catch (Exception e) { + throw new PluginException("停止插件 [" + pluginId + "] 失败. ", e); + } } @Override @@ -258,34 +283,32 @@ public class DefaultPluginManager implements PluginManager{ return startedPlugins.get(pluginId); } - private PluginDescriptor start(PluginDescriptor pluginDescriptor) throws PluginException { + protected PluginDescriptor start(PluginDescriptor pluginDescriptor) throws Exception { String pluginId = pluginDescriptor.getPluginId(); if(startedPlugins.containsKey(pluginId)){ - throw new PluginException("已经存在插件: " + pluginId); - } - try { - provider.getPluginChecker().check(pluginDescriptor); - PluginWrapperInside pluginWrapper = provider.getPluginLoader().load(pluginDescriptor); - pluginWrapper.setPluginState(PluginState.RESOLVED); - start(pluginWrapper); - return pluginDescriptor; - } catch (Exception e) { - throw new PluginException("启动插件 [" + pluginId + "] 失败. ", e); + throw new PluginException("已经存在插件: " + MsgUtils.getPluginUnique(pluginDescriptor)); } + provider.getPluginChecker().check(pluginDescriptor); + PluginWrapperInside pluginWrapper = new PluginWrapperInside(pluginDescriptor); + pluginWrapper.setPluginState(PluginState.RESOLVED); + start(pluginWrapper); + return pluginDescriptor; } - private void start(PluginWrapperInside pluginWrapper){ + protected void start(PluginWrapperInside pluginWrapper) throws Exception{ String pluginId = pluginWrapper.getPluginId(); pluginWrapper.setPluginState(PluginState.STARTED); startedPlugins.put(pluginId, pluginWrapper); resolvedPlugins.remove(pluginId); } - private void stop(PluginWrapperInside pluginWrapper){ + protected void stop(PluginWrapperInside pluginWrapper) throws Exception{ String pluginId = pluginWrapper.getPluginId(); pluginWrapper.setPluginState(PluginState.STOPPED); resolvedPlugins.put(pluginId, pluginWrapper.getPluginDescriptor()); startedPlugins.remove(pluginId); } + + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java index 6a1c3f4..f45e97a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -1,12 +1,9 @@ package com.gitee.starblues.core; -import com.gitee.starblues.core.classloader.DefaultMainResourcePatternDefiner; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.ProdPackagePluginDescriptorLoader; import com.gitee.starblues.core.descriptor.ProdPluginDescriptorLoader; -import com.gitee.starblues.core.loader.DefaultPluginLoader; -import com.gitee.starblues.core.loader.PluginLoader; import com.gitee.starblues.core.scanner.BasePluginScanner; import com.gitee.starblues.core.scanner.DevPathResolve; import com.gitee.starblues.core.scanner.PluginScanner; @@ -23,8 +20,6 @@ public class DefaultRealizeProvider implements RealizeProvider { private PluginScanner pluginScanner; private PluginDescriptorLoader pluginDescriptorLoader; - private MainResourcePatternDefiner mainResourcePatternDefiner; - private PluginLoader pluginLoader; private PluginChecker pluginChecker; private VersionInspector versionInspector; @@ -48,16 +43,10 @@ public class DefaultRealizeProvider implements RealizeProvider { setPluginScanner(basePluginScanner); setPluginDescriptorLoader(pluginDescriptorLoader); - setPluginLoader(new DefaultPluginLoader(this.mainResourcePatternDefiner)); setPluginChecker(new DefaultPluginChecker()); setVersionInspector(new SemverVersionInspector()); } - public void setMainResourcePatternDefiner(MainResourcePatternDefiner mainResourcePatternDefiner){ - this.mainResourcePatternDefiner = Assert.isNotNull(mainResourcePatternDefiner, - "mainResourcePatternDefiner 不能为空"); - } - public void setPluginScanner(PluginScanner pluginScanner) { this.pluginScanner = Assert.isNotNull(pluginScanner, "pluginScanner 不能为空"); } @@ -67,10 +56,6 @@ public class DefaultRealizeProvider implements RealizeProvider { "pluginDescriptorLoader 不能为空"); } - public void setPluginLoader(PluginLoader pluginLoader) { - this.pluginLoader = Assert.isNotNull(pluginLoader, "pluginLoader 不能为空"); - } - public void setPluginChecker(PluginChecker pluginChecker) { this.pluginChecker = Assert.isNotNull(pluginChecker, "pluginChecker 不能为空"); } @@ -90,20 +75,10 @@ public class DefaultRealizeProvider implements RealizeProvider { } @Override - public PluginDescriptorLoader getPluginDescriptor() { + public PluginDescriptorLoader getPluginDescriptorLoader() { return Assert.isNotNull(pluginDescriptorLoader, "PluginDescriptorLoader 实现不能为空"); } - @Override - public MainResourcePatternDefiner getMainResourcePatternDefiner() { - return Assert.isNotNull(mainResourcePatternDefiner, "MainResourcePatternDefiner 实现不能为空"); - } - - @Override - public PluginLoader getPluginLoader() { - return Assert.isNotNull(pluginLoader, "PluginLoader 实现不能为空"); - } - @Override public PluginChecker getPluginChecker() { return Assert.isNotNull(pluginChecker, "PluginChecker 实现不能为空"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java index 1029bfa..b17652a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java @@ -1,33 +1,42 @@ package com.gitee.starblues.core; -import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.MsgUtils; + /** * 插件异常 * @author starBlues - * @version 3.0.03 + * @version 3.0.0 */ -public class PluginException extends Exception{ +public class PluginException extends RuntimeException{ public PluginException() { super(); } public PluginException(String message) { - this(null, message); + super(message); } public PluginException(String message, Throwable cause) { - this(null, message, cause); + super(message, cause); + } + + public PluginException(String opType, PluginDescriptor pluginDescriptor, Throwable cause) { + this(opType, MsgUtils.getPluginUnique(pluginDescriptor), cause); + } + + public PluginException(String opType, PluginDescriptor pluginDescriptor, String message) { + this(opType, MsgUtils.getPluginUnique(pluginDescriptor), message); } - public PluginException(String pluginId, String message) { - this(null, message, null); + public PluginException(String opType, String pluginId, Throwable cause) { + super(opType + "插件[" + pluginId + "]失败. " + MsgUtils.getThrowableMsg(cause), cause); } - public PluginException(String pluginId, String message, Throwable cause) { - super(ObjectUtils.isEmpty(pluginId) ? message : "插件[" + pluginId + "]操作异常. " + message, - cause); + public PluginException(String opType, String pluginId, String message) { + super(opType + "插件[" + pluginId + "]失败. " + MsgUtils.getThrowableMsg(message)); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java similarity index 36% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index f209870..61e94e0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -1,9 +1,13 @@ -package com.gitee.starblues.core.launcher.plugin; +package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; +import com.gitee.starblues.core.launcher.plugin.PluginInteractive; +import com.gitee.starblues.core.launcher.plugin.PluginLauncher; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.MainApplicationContextProxy; +import com.gitee.starblues.spring.SpringPluginHook; import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; import com.gitee.starblues.spring.invoke.InvokeSupperCache; import org.springframework.context.support.GenericApplicationContext; @@ -15,39 +19,68 @@ import java.util.concurrent.ConcurrentHashMap; * @author starBlues * @version 1.0 */ -public class DefaultPluginLauncherManager implements PluginLauncherManager{ +public class PluginLauncherManager extends DefaultPluginManager{ - private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); + private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); private final MainApplicationContext mainApplicationContext; private final IntegrationConfiguration configuration; private final InvokeSupperCache invokeSupperCache; - public DefaultPluginLauncherManager(GenericApplicationContext mainGenericApplicationContext, - IntegrationConfiguration configuration) { - this.configuration = configuration; + + public PluginLauncherManager(RealizeProvider realizeProvider, + GenericApplicationContext applicationContext, + IntegrationConfiguration configuration) { + super(realizeProvider, configuration.pluginPath()); this.mainApplicationContext = new MainApplicationContextProxy( - mainGenericApplicationContext.getBeanFactory(), - mainGenericApplicationContext); + applicationContext.getBeanFactory(), + applicationContext); + this.configuration = configuration; this.invokeSupperCache = new DefaultInvokeSupperCache(); } + @Override - public synchronized void start(PluginDescriptor pluginDescriptor) throws Exception{ - if(pluginRegistryInfoMap.containsKey(pluginDescriptor.getPluginId())){ - throw new Exception("已经存在插件 : " + pluginDescriptor.getPluginId()); - } + protected void start(PluginWrapperInside pluginWrapper) throws Exception { + super.start(pluginWrapper); + PluginDescriptor pluginDescriptor = pluginWrapper.getPluginDescriptor(); PluginInteractive pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, mainApplicationContext, configuration, invokeSupperCache); PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive); - Object pluginApplicationContext = pluginLauncher.run(); -// PluginRegistryInfo pluginRegistryInfo = new DefaultPluginRegistryInfo(pluginApplicationContext, -// pluginLauncher); -// pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), pluginRegistryInfo); + SpringPluginHook springPluginHook = pluginLauncher.run(); + RegistryPluginInfo registryPluginInfo = new RegistryPluginInfo(pluginDescriptor, springPluginHook); + pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), registryPluginInfo); } + @Override - public synchronized void stop(String pluginId) throws Exception{ + protected void stop(PluginWrapperInside pluginWrapper) throws Exception { + String pluginId = pluginWrapper.getPluginId(); + RegistryPluginInfo registryPluginInfo = pluginRegistryInfoMap.get(pluginId); + if(registryPluginInfo == null){ + throw new PluginException("没有发现插件 '" + pluginId + "' 信息"); + } + registryPluginInfo.getSpringPluginHook().close(); invokeSupperCache.remove(pluginId); + pluginRegistryInfoMap.remove(pluginId); + super.stop(pluginWrapper); + } + + private static class RegistryPluginInfo{ + private final PluginDescriptor descriptor; + private final SpringPluginHook springPluginHook; + + private RegistryPluginInfo(PluginDescriptor descriptor, SpringPluginHook springPluginHook) { + this.descriptor = descriptor; + this.springPluginHook = springPluginHook; + } + + public PluginDescriptor getDescriptor() { + return descriptor; + } + + public SpringPluginHook getSpringPluginHook() { + return springPluginHook; + } } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java index 14f25a8..96792d0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -1,8 +1,6 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.loader.PluginWrapper; -import com.gitee.starblues.integration.operator.module.PluginInfo; import java.nio.file.Path; import java.util.List; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapper.java similarity index 66% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapper.java index c3dff99..ebf4150 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapper.java @@ -1,6 +1,5 @@ -package com.gitee.starblues.core.loader; +package com.gitee.starblues.core; -import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.PluginDescriptor; import java.nio.file.Path; @@ -24,18 +23,6 @@ public interface PluginWrapper { */ PluginDescriptor getPluginDescriptor(); - /** - * 得到插件classLoader - * @return ClassLoader - */ - ClassLoader getPluginClassLoader(); - - /** - * 得到插件引导类 - * @return Class - */ - Class getPluginClass(); - /** * 得到插件路径 * @return Path diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java similarity index 64% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java index c815f03..b945c35 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperFace.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java @@ -1,8 +1,6 @@ -package com.gitee.starblues.core.loader; +package com.gitee.starblues.core; -import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import org.apache.catalina.core.ApplicationContext; import java.nio.file.Path; @@ -11,7 +9,7 @@ import java.nio.file.Path; * @author starBlues * @version 3.0.0 */ -public class PluginWrapperFace implements PluginWrapper{ +public class PluginWrapperFace implements PluginWrapper { private final PluginWrapper pluginWrapper; @@ -29,16 +27,6 @@ public class PluginWrapperFace implements PluginWrapper{ return pluginWrapper.getPluginDescriptor(); } - @Override - public ClassLoader getPluginClassLoader() { - return pluginWrapper.getPluginClassLoader(); - } - - @Override - public Class getPluginClass() { - return pluginWrapper.getPluginClass(); - } - @Override public Path getPluginPath() { return pluginWrapper.getPluginPath(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperInside.java similarity index 51% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperInside.java index 558cfb3..46d7629 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginWrapperInside.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperInside.java @@ -1,6 +1,5 @@ -package com.gitee.starblues.core.loader; +package com.gitee.starblues.core; -import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.PluginDescriptor; import java.nio.file.Path; @@ -9,22 +8,17 @@ import java.nio.file.Path; * 内部的 * @author starBlues */ -public class PluginWrapperInside implements PluginWrapper{ +public class PluginWrapperInside implements PluginWrapper { private final String pluginId; private final PluginDescriptor pluginDescriptor; - private final ClassLoader pluginClassLoader; - private final Class pluginClass; private final Path pluginPath; private PluginState pluginState; - public PluginWrapperInside(String pluginId, PluginDescriptor pluginDescriptor, - ClassLoader pluginClassLoader, Class pluginClass, Path pluginPath) { - this.pluginId = pluginId; + public PluginWrapperInside(PluginDescriptor pluginDescriptor) { + this.pluginId = pluginDescriptor.getPluginId(); this.pluginDescriptor = pluginDescriptor; - this.pluginClassLoader = pluginClassLoader; - this.pluginClass = pluginClass; - this.pluginPath = pluginPath; + this.pluginPath = pluginDescriptor.getPluginPath(); } public void setPluginState(PluginState pluginState) { @@ -41,16 +35,6 @@ public class PluginWrapperInside implements PluginWrapper{ return pluginDescriptor; } - @Override - public ClassLoader getPluginClassLoader() { - return pluginClassLoader; - } - - @Override - public Class getPluginClass() { - return pluginClass; - } - @Override public Path getPluginPath() { return pluginPath; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java index d5f1d51..75fdf15 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -2,7 +2,6 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; -import com.gitee.starblues.core.loader.PluginLoader; import com.gitee.starblues.core.scanner.PluginScanner; import com.gitee.starblues.core.version.VersionInspector; /** @@ -33,19 +32,7 @@ public interface RealizeProvider { * 得到 PluginDescriptorLoader 实现 * @return PluginDescriptorLoader */ - PluginDescriptorLoader getPluginDescriptor(); - - /** - * 得到 MainResourcePatternDefiner 实现 - * @return MainResourcePatternDefiner - */ - MainResourcePatternDefiner getMainResourcePatternDefiner(); - - /** - * 得到 PluginLoader 实现 - * @return PluginLoader - */ - PluginLoader getPluginLoader(); + PluginDescriptorLoader getPluginDescriptorLoader(); /** * 得到 PluginChecker 实现 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java deleted file mode 100644 index 4ea6ac6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/ResourceClear.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.starblues.core; - -/** - * @author starBlues - * @version 3.0.0 - */ -public interface ResourceClear { - - /** - * 清除资源 - */ - void clear(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index 35f5516..80240e6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -1,11 +1,11 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ResourceUtils; +import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.InputStream; -import java.net.MalformedURLException; +import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; @@ -39,7 +39,7 @@ public abstract class AbstractResourceLoader { */ public void init() throws Exception{ // 添加root 路径 - Resource rootResource = new Resource("root", baseUrl, baseUrl, null); + Resource rootResource = new Resource("root", baseUrl, baseUrl); resourceCache.put("/", rootResource); } @@ -54,7 +54,14 @@ public abstract class AbstractResourceLoader { public InputStream getInputStream(final String name) { Resource resourceInfo = resourceCache.get(name); if (resourceInfo != null) { - return new ByteArrayInputStream(resourceInfo.getBytes()); + try (InputStream inputStream = resourceInfo.getUrl().openStream(); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){ + IOUtils.copy(inputStream, byteArrayOutputStream); + return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + } catch (Exception e){ + e.printStackTrace(); + return null; + } } else { return null; } @@ -65,9 +72,6 @@ public abstract class AbstractResourceLoader { } public void clear() { - for (Resource resource : resourceCache.values()) { - resource.tryCloseUrlSystemFile(); - } resourceCache.clear(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java index 587f229..2edc8f2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java @@ -1,6 +1,5 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.core.ResourceClear; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -9,10 +8,9 @@ import java.util.concurrent.ConcurrentHashMap; * @author starBlues * @version 1.0 */ -public class CacheMainResourceMatcher extends DefaultMainResourceMatcher implements ResourceClear { +public class CacheMainResourceMatcher extends DefaultMainResourceMatcher implements AutoCloseable { private final Map resourceUrlMatchCache = new ConcurrentHashMap<>(); - private final Map springFactoriesUrlMatchCache = new ConcurrentHashMap<>(); public CacheMainResourceMatcher(MainResourcePatternDefiner mainResourcePatternDefiner) { super(mainResourcePatternDefiner); @@ -28,20 +26,9 @@ public class CacheMainResourceMatcher extends DefaultMainResourceMatcher impleme return match; } - @Override - public boolean matchSpringFactories(String springFactoriesUrl) { - Boolean match = springFactoriesUrlMatchCache.get(springFactoriesUrl); - if(match == null){ - match = super.matchSpringFactories(springFactoriesUrl); - springFactoriesUrlMatchCache.put(springFactoriesUrl, match); - } - return match; - } @Override - public void clear(){ + public void close() throws Exception { resourceUrlMatchCache.clear(); - springFactoriesUrlMatchCache.clear(); } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java index 8c644eb..0038d5d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -71,7 +71,7 @@ public class ClassPathLoader extends AbstractResourceLoader{ private void addResource(File file, String packageName, byte[] bytes) throws MalformedURLException { Resource resource = new Resource( - file.getName(), url, new URL(url.toString() + packageName), bytes + file.getName(), url, new URL(url.toString() + packageName) ); addResource(packageName, resource); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java index 4db8f2d..5da26c9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java @@ -8,8 +8,9 @@ import java.util.Collection; import java.util.Set; /** + * 默认的主程序资源匹配者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DefaultMainResourceMatcher implements MainResourceMatcher{ @@ -23,16 +24,10 @@ public class DefaultMainResourceMatcher implements MainResourceMatcher{ @Override public boolean match(String resourceUrl) { - Set resourcePatterns = mainResourcePatternDefiner.getIncludeResourcePatterns(); + Set resourcePatterns = mainResourcePatternDefiner.getIncludePatterns(); return match(resourcePatterns, resourceUrl); } - @Override - public boolean matchSpringFactories(String springFactoriesUrl) { - Set springFactoriesPatterns = mainResourcePatternDefiner.getSpringFactoriesPatterns(); - return match(springFactoriesPatterns, springFactoriesUrl); - } - private boolean match(Collection patterns, String url){ if(ObjectUtils.isEmpty(patterns) || ObjectUtils.isEmpty(url)){ return false; @@ -41,7 +36,7 @@ public class DefaultMainResourceMatcher implements MainResourceMatcher{ for (String pattern : patterns) { boolean match = pathMatcher.match(pattern, url); if(match){ - return !excludeMatch(mainResourcePatternDefiner.getExcludeResourcePatterns(), url); + return !excludeMatch(mainResourcePatternDefiner.getExcludePatterns(), url); } } return false; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java index d8db0c4..cca5db5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java @@ -14,7 +14,6 @@ import java.util.*; public class DefaultMainResourcePatternDefiner implements MainResourcePatternDefiner { private final Set resourcePatterns = new HashSet<>(); - private final Set springFactoriesPatterns = new HashSet<>(); private final String mainPackageName; @@ -22,25 +21,19 @@ public class DefaultMainResourcePatternDefiner implements MainResourcePatternDef this.mainPackageName = Assert.isNotEmpty(mainPackageName, "参数 mainPackageName 不能为空"); initDefaultResources(); - initDefaultSpringFactories(); } @Override - public Set getIncludeResourcePatterns() { + public Set getIncludePatterns() { return resourcePatterns; } @Override - public Set getExcludeResourcePatterns() { + public Set getExcludePatterns() { return null; } - @Override - public Set getSpringFactoriesPatterns() { - return springFactoriesPatterns; - } - private void initDefaultResources() { // == java == @@ -87,8 +80,5 @@ public class DefaultMainResourcePatternDefiner implements MainResourcePatternDef resourcePatterns.add("org/yaml/snakeyaml/**"); } - private void initDefaultSpringFactories() { - // 当前框架名称 - springFactoriesPatterns.add("**/springboot-plugin-framework/**"); - } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java index 987f1d4..883e13d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java @@ -10,17 +10,12 @@ import java.util.Set; public class EmptyMainResourcePatternDefiner implements MainResourcePatternDefiner { @Override - public Set getIncludeResourcePatterns() { + public Set getIncludePatterns() { return null; } @Override - public Set getExcludeResourcePatterns() { - return null; - } - - @Override - public Set getSpringFactoriesPatterns() { + public Set getExcludePatterns() { return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java new file mode 100644 index 0000000..9841a44 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java @@ -0,0 +1,284 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ResourceUtils; +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Path; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class GenericClassLoader extends URLClassLoader { + + private final String name; + private final ClassLoader parent; + + protected final ResourceLoaderFactory resourceLoaderFactory; + + private final Map> pluginClassCache = new ConcurrentHashMap<>(); + + public GenericClassLoader(String name) { + this(name, null); + } + + public GenericClassLoader(String name, ClassLoader parent) { + this(name, parent, null); + } + + public GenericClassLoader(String name, ClassLoader parent, ResourceLoaderFactory loaderFactory) { + super(new URL[]{}, null); + this.name = Assert.isNotEmpty(name, "参数 name 不能为空"); + this.parent = parent; + if(loaderFactory == null){ + resourceLoaderFactory = new ResourceLoaderFactory(); + } else { + resourceLoaderFactory = loaderFactory; + } + } + + public String getName() { + return name; + } + + + public void addResource(String path) throws Exception { + resourceLoaderFactory.addResource(path); + } + + public void addResource(File file) throws Exception { + resourceLoaderFactory.addResource(file); + } + + public void addResource(Path path) throws Exception { + resourceLoaderFactory.addResource(path); + } + + @Override + public Class loadClass(String className) throws ClassNotFoundException { + synchronized (getClassLoadingLock(className)) { + return findClass(className); + } + } + + @Override + protected Class findClass(String className) throws ClassNotFoundException { + Class loadedClass = findClassFromParent(className); + if (loadedClass != null) { + return loadedClass; + } + loadedClass = findLoadedClass(className); + if (loadedClass != null) { + return loadedClass; + } + loadedClass = findClassFromLocal(className); + if (loadedClass != null) { + return loadedClass; + } + throw new ClassNotFoundException(className); + } + + protected Class findClassFromParent(String className) throws ClassNotFoundException{ + if(parent != null){ + return parent.loadClass(className); + } + return null; + } + + protected Class findClassFromLocal(String name) { + synchronized (pluginClassCache){ + Class aClass; + String formatClassName = formatClassName(name); + aClass = pluginClassCache.get(formatClassName); + if (aClass != null) { + return aClass; + } + + InputStream inputStream = resourceLoaderFactory.getInputStream(formatClassName); + if(inputStream == null){ + return null; + } + ByteArrayOutputStream byteArrayOutputStream = null; + byte[] bytes; + try { + if(inputStream instanceof ByteArrayInputStream){ + ByteArrayInputStream arrayInputStream = (ByteArrayInputStream) inputStream; + bytes = IOUtils.readFully(inputStream, arrayInputStream.available()); + } else { + byteArrayOutputStream = new ByteArrayOutputStream(); + IOUtils.copy(inputStream, byteArrayOutputStream); + bytes = byteArrayOutputStream.toByteArray(); + } + } catch (Exception e){ + e.printStackTrace(); + return null; + } finally { + IOUtils.closeQuietly(inputStream); + if(byteArrayOutputStream != null){ + IOUtils.closeQuietly(byteArrayOutputStream); + } + } + aClass = defineClass(name, bytes, 0, bytes.length ); + if(aClass == null) { + return null; + } + if (aClass.getPackage() == null) { + int lastDotIndex = name.lastIndexOf( '.' ); + String packageName = (lastDotIndex >= 0) ? name.substring( 0, lastDotIndex) : ""; + definePackage(packageName, null, null, null, + null, null, null, null ); + } + pluginClassCache.put(name, aClass); + return aClass; + } + } + + @Override + public URL[] getURLs() { + List resources = resourceLoaderFactory.getResources(); + URL[] urls = new URL[resources.size()]; + for (int i = 0; i < resources.size(); i++) { + urls[i] = resources.get(i).getUrl(); + } + return urls; + } + + @Override + public InputStream getResourceAsStream(String name) { + name = formatResourceName(name); + InputStream inputStream = findInputStreamFromParent(name); + if(inputStream != null){ + return inputStream; + } + return findInputStreamFromLocal(name); + } + + protected InputStream findInputStreamFromParent(String name){ + if(parent != null){ + return parent.getResourceAsStream(name); + } + return null; + } + + protected InputStream findInputStreamFromLocal(String name){ + return resourceLoaderFactory.getInputStream(name); + } + + @Override + public URL getResource(String name) { + name = formatResourceName(name); + URL url = findResourceFromParent(name); + if(url != null){ + return url; + } + return findResourceFromLocal(name); + } + + protected URL findResourceFromParent(String name){ + if(parent != null){ + return parent.getResource(name); + } + return null; + } + + protected URL findResourceFromLocal(String name) { + Resource resource = resourceLoaderFactory.findResource(name); + if (resource == null) { + return null; + } + return resource.getUrl(); + } + + @Override + public Enumeration getResources(String name) throws IOException { + name = formatResourceName(name); + Enumeration parentResources = findResourcesFromParent(name); + Vector vector = new Vector<>(); + if(parentResources != null){ + while (parentResources.hasMoreElements()){ + URL url = parentResources.nextElement(); + vector.add(url); + } + } + Enumeration localResources = findResourcesFromLocal(name); + if(localResources != null){ + while (localResources.hasMoreElements()){ + URL url = localResources.nextElement(); + vector.add(url); + } + } + return vector.elements(); + } + + protected Enumeration findResourcesFromParent(String name) throws IOException{ + if(parent != null){ + return parent.getResources(name); + } + return null; + } + + protected Enumeration findResourcesFromLocal(String name) throws IOException{ + List resourceList = resourceLoaderFactory.findResources(name); + if(!ObjectUtils.isEmpty(resourceList)){ + Vector vector = new Vector<>(); + for (Resource resource : resourceList) { + vector.add(resource.getUrl()); + } + return vector.elements(); + } + return null; + } + + private String formatClassName(String className) { + className = className.replace( '/', '~' ); + className = className.replace( '.', '/' ) + ".class"; + className = className.replace( '~', '/' ); + return className; + } + + private String formatResourceName(String resourceName){ + if(ObjectUtils.isEmpty(resourceName)) { + return ResourceUtils.PACKAGE_SPLIT; + } + String[] split = resourceName.split("/"); + StringBuilder newPath = new StringBuilder(); + for (int i = 0; i < split.length; i++) { + String s = split[i]; + if("".equals(s)){ + continue; + } + if(i == 0){ + newPath = new StringBuilder(s); + } else { + newPath.append(ResourceUtils.PACKAGE_SPLIT).append(s); + } + } + if(resourceName.endsWith(ResourceUtils.PACKAGE_SPLIT)){ + newPath.append(ResourceUtils.PACKAGE_SPLIT); + } + return newPath.toString(); + } + + + + @Override + public void close() throws IOException { + synchronized (pluginClassCache){ + pluginClassCache.clear(); + resourceLoaderFactory.clear(); + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index e026fd6..7cf8028 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -1,10 +1,7 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.utils.Assert; +import org.apache.commons.io.IOUtils; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.net.URL; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; @@ -16,48 +13,34 @@ import java.util.jar.JarInputStream; */ public class JarResourceLoader extends AbstractResourceLoader{ - private final URL sourceUrl; + private final JarInputStream jarInputStream; public JarResourceLoader(URL url) throws Exception{ super(new URL("jar:" + url.toString() + "!/")); - this.sourceUrl = Assert.isNotNull(url, "url 不能为空"); + this.jarInputStream = new JarInputStream(url.openStream()); + } + + public JarResourceLoader(URL url, JarInputStream jarInputStream) throws Exception{ + super(url); + this.jarInputStream = jarInputStream; } @Override public void init() throws Exception { super.init(); // 解析 - try (InputStream fileInputStream = sourceUrl.openStream(); - BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); - JarInputStream jarStream = new JarInputStream(bufferedInputStream); - ){ + try { JarEntry jarEntry = null; - while ((jarEntry = jarStream.getNextJarEntry()) != null) { + while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String name = jarEntry.getName(); URL url = new URL(baseUrl.toString() + name); - if (jarEntry.isDirectory()) { - Resource resource = new Resource( - name, baseUrl, url, null - ); - addResource(name, resource); - continue; - } - if (existResource(name)) { - continue; - } - byte[] bytes = new byte[2048]; - - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - int len = 0; - while ((len = jarStream.read(bytes)) > 0) { - out.write(bytes, 0, len); - } - Resource resource = new Resource( - name, baseUrl, url, out.toByteArray() - ); - addResource(name, resource); - } + Resource resource = new Resource(name, baseUrl, url); + addResource(name, resource); } + } finally { + IOUtils.closeQuietly(jarInputStream); } } + + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java index 182fd81..c99999e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java @@ -1,13 +1,17 @@ package com.gitee.starblues.core.classloader; /** + * 主程序资源匹配者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface MainResourceMatcher { - + /** + * 匹配主程序资源 + * @param resourceUrl 主程序资源url + * @return true 匹配成功, false 匹配失败 + */ boolean match(String resourceUrl); - boolean matchSpringFactories(String springFactoriesUrl); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java index 65af2ac..ce63c12 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java @@ -10,19 +10,17 @@ import java.util.Set; public interface MainResourcePatternDefiner { /** - * 资源名称. + * 包含资源名称. * @return 资源名称集合 */ - Set getIncludeResourcePatterns(); - - - Set getExcludeResourcePatterns(); + Set getIncludePatterns(); /** - * spring spi 定义 - * @return spring spi 集合 + * 排除资源 + * @return String */ - Set getSpringFactoriesPatterns(); + Set getExcludePatterns(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java new file mode 100644 index 0000000..bc46cde --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java @@ -0,0 +1,72 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; + +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; + +/** + * @author starBlues + * @version 1.0 + */ +public class NestedJarResourceLoader extends AbstractResourceLoader{ + + private final PluginDescriptor pluginDescriptor; + private final ResourceLoaderFactory resourceLoaderFactory; + + public NestedJarResourceLoader(PluginDescriptor pluginDescriptor, ResourceLoaderFactory resourceLoaderFactory) throws Exception { + super(new URL("jar:" + pluginDescriptor.getPluginPath().toUri().toURL() + "!/")); + this.pluginDescriptor = pluginDescriptor; + this.resourceLoaderFactory = resourceLoaderFactory; + } + + @Override + public void init() throws Exception { + super.init(); + try (JarFile jarFile = new JarFile(pluginDescriptor.getPluginPath().toFile())) { + addClassPath(jarFile); + addLib(jarFile); + } + } + + private void addClassPath(JarFile jarFile) throws Exception{ + String classesPath = pluginDescriptor.getPluginClassPath(); + Enumeration entries = jarFile.entries(); + JarEntry jarEntry; + while (entries.hasMoreElements()){ + jarEntry = entries.nextElement(); + if(!jarEntry.getName().startsWith(classesPath)){ + continue; + } + String realName = jarEntry.getName().replace(classesPath, ""); + URL url = new URL(baseUrl.toString() + jarEntry.getName()); + Resource resource = new Resource(realName, baseUrl, url); + addResource(realName, resource); + } + } + + private void addLib(JarFile jarFile) throws Exception { + JarEntry jarEntry = null; + Set pluginLibPaths = pluginDescriptor.getPluginLibPaths(); + for (String pluginLibPath : pluginLibPaths) { + jarEntry = jarFile.getJarEntry(pluginLibPath); + InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); + URL url = new URL(baseUrl.toString() + pluginLibPath + "!/"); + JarResourceLoader jarResourceLoader = new JarResourceLoader(url, new JarInputStream(jarFileInputStream)); + jarResourceLoader.init(); + resourceLoaderFactory.addResourceLoader(jarResourceLoader); + } + } + + @Override + public void clear() { + super.clear(); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index ebe0375..742047f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -1,238 +1,98 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.core.ResourceClear; +import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ResourceUtils; -import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.URI; import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; +import java.util.Enumeration; /** * 插件 classLoader * @author starBlues * @version 3.0.0 */ -public class PluginClassLoader extends AbstractPluginClassLoader implements ResourceClear { - - private final Map> pluginClassCache = new ConcurrentHashMap<>(); - - private final String pluginId; - private final ClassLoader parent; - private final ResourceLoaderFactory resourceLoaderFactory; +public class PluginClassLoader extends GenericClassLoader { private MainResourceMatcher mainResourceMatcher; - - public PluginClassLoader(String pluginId, - Path classpath, - ClassLoader parentClassLoader, - MainResourcePatternDefiner mainResourcePatternDefiner) { - resourceLoaderFactory = new ResourceLoaderFactory(); - resourceLoaderFactory.addResource(classpath); - - this.pluginId = Assert.isNotEmpty(pluginId, "参数 pluginId 不能为空"); - this.parent = Assert.isNotNull(parentClassLoader, "参数 parentClassLoader 不能为空"); - MainResourcePatternDefiner patternDefiner = Assert.isNotNull(mainResourcePatternDefiner, - "参数 mainResourcePatternDefiner 不能为空"); - setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); + public PluginClassLoader(String name) { + this(name, null); } - public void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ - this.mainResourceMatcher = Assert.isNotNull(mainResourceMatcher, "参数 mainResourceMatcher 不能为空"); + public PluginClassLoader(String name, ClassLoader parentClassLoader) { + this(name, parentClassLoader, null); } - - public void addResource(File file) { - resourceLoaderFactory.addResource(file); - } - - public void addResource(Path path) { - resourceLoaderFactory.addResource(path); + public PluginClassLoader(String name, ClassLoader parentClassLoader, MainResourcePatternDefiner patternDefiner) { + super(name, parentClassLoader, new PluginResourceLoaderFactory()); + if(patternDefiner != null){ + setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); + } else { + setMainResourceMatcher(new ProhibitMainResourceMatcher()); + } } - - - public String getPluginId() { - return pluginId; + public void addResource(PluginDescriptor pluginDescriptor) throws Exception { + ((PluginResourceLoaderFactory) resourceLoaderFactory).addResource(pluginDescriptor); } - @Override - public Class loadClass(String className) throws ClassNotFoundException { - synchronized (getClassLoadingLock(className)) { - Class loadedClass = null; - if(mainResourceMatcher.match(className.replace(".", "/"))){ - try { - loadedClass = parent.loadClass(className); - } catch (Exception e){ - // 忽略 - } - } - if(loadedClass == null){ - loadedClass = findLoadedClass(className); - } - if (loadedClass != null) { - return loadedClass; - } - loadedClass = findPluginClass(className); - if (loadedClass != null) { - return loadedClass; - } - throw new ClassNotFoundException(className); - } + public void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ + this.mainResourceMatcher = Assert.isNotNull(mainResourceMatcher, "参数 mainResourceMatcher 不能为空"); } - private Class findPluginClass(String name) { - synchronized (pluginClassCache){ - Class aClass; - String formatClassName = formatClassName(name); - aClass = pluginClassCache.get(formatClassName); - if (aClass != null) { - return aClass; - } - - Resource resource = resourceLoaderFactory.findResource(formatClassName); - if(resource == null){ - return null; - } - byte[] bytes = resource.getBytes(); - aClass = defineClass(name, bytes, 0, bytes.length ); - if(aClass == null) { - return null; - } - if (aClass.getPackage() == null) { - int lastDotIndex = name.lastIndexOf( '.' ); - String packageName = (lastDotIndex >= 0) ? name.substring( 0, lastDotIndex) : ""; - definePackage(packageName, null, null, null, - null, null, null, null ); - } - pluginClassCache.put(name, aClass); - return aClass; - } - } @Override - public URL[] getURLs() { - List resources = resourceLoaderFactory.getResources(); - URL[] urls = new URL[resources.size()]; - for (int i = 0; i < resources.size(); i++) { - urls[i] = resources.get(i).getUrl(); + protected Class findClassFromParent(String className) throws ClassNotFoundException { + if(mainResourceMatcher.match(className.replace(".", "/"))){ + try { + return super.findClassFromParent(className); + } catch (Exception e){ + // 忽略 + } } - return urls; + return null; } - @Override - public InputStream getResourceAsStream(String name) { - name = formatResourceName(name); - InputStream inputStream = null; + protected InputStream findInputStreamFromParent(String name) { if(mainResourceMatcher.match(name)){ try { - inputStream = parent.getResourceAsStream(name); + return super.findInputStreamFromParent(name); } catch (Exception e){ // 忽略 } } - if(inputStream != null){ - return inputStream; - } - return resourceLoaderFactory.getInputStream(name); + return null; } @Override - public URL getResource(String name) { - name = formatResourceName(name); - URL url = null; + protected URL findResourceFromParent(String name) { if(mainResourceMatcher.match(name)){ - url = parent.getResource(name); - } - if(url != null){ - return url; - } - Resource resource = resourceLoaderFactory.findResource(name); - if(resource == null){ - return null; + return super.findResourceFromParent(name); } - return resource.getUrl(); + return null; } @Override - public Enumeration getResources(String name) throws IOException { - name = formatResourceName(name); - Vector vector = new Vector<>(); + protected Enumeration findResourcesFromParent(String name) throws IOException { if(mainResourceMatcher.match(name)){ - Enumeration enumeration = parent.getResources(name); - while (enumeration.hasMoreElements()){ - URL url = enumeration.nextElement(); - try { - URI uri = url.toURI(); - String path = Paths.get(uri).toString(); - if(mainResourceMatcher.matchSpringFactories(path)){ - vector.add(url); - } - } catch (Exception e) { - if(mainResourceMatcher.matchSpringFactories(url.getPath())){ - vector.add(url); - } - } - } - } - List resourceList = resourceLoaderFactory.findResources(name); - if(!ObjectUtils.isEmpty(resourceList)){ - for (Resource resource : resourceList) { - vector.add(resource.getUrl()); - } + return super.findResourcesFromParent(name); } - return vector.elements(); - } - - private String formatClassName(String className) { - className = className.replace( '/', '~' ); - className = className.replace( '.', '/' ) + ".class"; - className = className.replace( '~', '/' ); - return className; - } - - private String formatResourceName(String resourceName){ - if(ObjectUtils.isEmpty(resourceName)) { - return ResourceUtils.PACKAGE_SPLIT; - } - String[] split = resourceName.split("/"); - StringBuilder newPath = new StringBuilder(); - for (int i = 0; i < split.length; i++) { - String s = split[i]; - if("".equals(s)){ - continue; - } - if(i == 0){ - newPath = new StringBuilder(s); - } else { - newPath.append(ResourceUtils.PACKAGE_SPLIT).append(s); - } - } - if(resourceName.endsWith(ResourceUtils.PACKAGE_SPLIT)){ - newPath.append(ResourceUtils.PACKAGE_SPLIT); - } - return newPath.toString(); + return null; } @Override - public void clear(){ - synchronized (pluginClassCache){ - pluginClassCache.clear(); - resourceLoaderFactory.clear(); - if(mainResourceMatcher instanceof ResourceClear){ - ((ResourceClear) mainResourceMatcher).clear(); + public void close() throws IOException { + super.close(); + if(mainResourceMatcher instanceof AutoCloseable){ + try { + ((AutoCloseable) mainResourceMatcher).close(); + } catch (Exception e){ + throw new IOException(e); } } } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java new file mode 100644 index 0000000..2b6496f --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java @@ -0,0 +1,52 @@ +package com.gitee.starblues.core.classloader; + +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; + +import java.io.File; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginResourceLoaderFactory extends ResourceLoaderFactory{ + + + public synchronized void addResource(PluginDescriptor pluginDescriptor) throws Exception{ + PluginDescriptor.Type type = pluginDescriptor.getType(); + if(type == PluginDescriptor.Type.JAR || type == PluginDescriptor.Type.ZIP){ + NestedJarResourceLoader resourceLoader = new NestedJarResourceLoader(pluginDescriptor, this); + resourceLoader.init(); + addResourceLoader(resourceLoader); + } else if(type == PluginDescriptor.Type.DIR_OF_DEV || type == PluginDescriptor.Type.DIR_OF_PROD){ + addClasspath(pluginDescriptor); + addLibFile(pluginDescriptor); + } + } + + private void addClasspath(PluginDescriptor pluginDescriptor) throws Exception { + String pluginClassPath = pluginDescriptor.getPluginClassPath(); + File existFile = PluginFileUtils.getExistFile(pluginClassPath); + if(existFile != null){ + addResource(existFile); + } + } + + private void addLibFile(PluginDescriptor pluginDescriptor) throws Exception { + Set pluginLibPaths = pluginDescriptor.getPluginLibPaths(); + if(ObjectUtils.isEmpty(pluginLibPaths)){ + return; + } + for (String pluginLibPath : pluginLibPaths) { + File existFile = PluginFileUtils.getExistFile(pluginLibPath); + if(existFile != null){ + addResource(existFile); + } + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java new file mode 100644 index 0000000..525f6d1 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java @@ -0,0 +1,14 @@ +package com.gitee.starblues.core.classloader; + +/** + * 禁止匹配所有主程序资源 + * @author starBlues + * @version 3.0.0 + */ +public class ProhibitMainResourceMatcher implements MainResourceMatcher{ + @Override + public boolean match(String resourceUrl) { + return false; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java new file mode 100644 index 0000000..dca7448 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java @@ -0,0 +1,11 @@ +package com.gitee.starblues.core.classloader; + +import java.nio.file.Path; + +/** + * @author starBlues + * @version 1.0 + */ +public class RepeatResourceLoaderFactory extends ResourceLoaderFactory{ + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java index 8fc36df..338d958 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java @@ -13,13 +13,11 @@ public class Resource { private final String name; private final URL baseUrl; private final URL url; - private final byte[] bytes; - public Resource(String name, URL baseUrl, URL url, byte[] bytes) { + public Resource(String name, URL baseUrl, URL url) { this.name = name; this.baseUrl = baseUrl; this.url = url; - this.bytes = bytes; } public String getName() { @@ -34,11 +32,6 @@ public class Resource { return url; } - public byte[] getBytes() { - return bytes; - } - - void tryCloseUrlSystemFile(){ try { Paths.get(baseUrl.toURI()).getFileSystem().close(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java index 75db411..45f0494 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java @@ -1,6 +1,7 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.utils.PluginFileUtils; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.ResourceUtils; import java.io.File; import java.io.InputStream; @@ -12,7 +13,9 @@ import java.util.ArrayList; import java.util.List; /** + * 资源加载工厂 * @author starBlues + * @version 3.0.0 */ public class ResourceLoaderFactory extends AbstractResourceLoader { @@ -23,38 +26,43 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { } - public void addResource(String path) { + void addResourceLoader(AbstractResourceLoader resourceLoader){ + if(resourceLoader != null){ + resourceLoaders.add(resourceLoader); + } + } + + public void addResource(String path) throws Exception{ if(path == null || "".equals(path)){ return; } addResource(Paths.get(path)); } - public void addResource(File file) { + public void addResource(File file) throws Exception{ if(file == null){ return; } addResource(file.toPath()); } - public synchronized void addResource(Path path) { + public void addResource(Path path) throws Exception{ if(path == null){ return; } - try { - URL url = path.toUri().toURL(); - AbstractResourceLoader resourceLoader = null; - if(PluginFileUtils.isJarFile(path)) { - resourceLoader = new JarResourceLoader(url); - } else if(Files.isDirectory(path)){ - resourceLoader = new ClassPathLoader(url); - } - if(resourceLoader != null){ - resourceLoader.init(); - resourceLoaders.add(resourceLoader); - } - } catch (Exception e){ - e.printStackTrace(); + if(!Files.exists(path)){ + return; + } + URL url = path.toUri().toURL(); + AbstractResourceLoader resourceLoader = null; + if(ResourceUtils.isJarFile(path)) { + resourceLoader = new JarResourceLoader(url); + } else if(Files.isDirectory(path)){ + resourceLoader = new ClassPathLoader(url); + } + if(resourceLoader != null){ + resourceLoader.init(); + resourceLoaders.add(resourceLoader); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index 100c62b..0f43d8d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -1,15 +1,27 @@ package com.gitee.starblues.core.descriptor; + import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; -import java.util.Properties; +import java.nio.file.Paths; +import java.util.*; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PluginDescriptorKey.*; +import static com.gitee.starblues.common.PackageStructure.*; +import static com.gitee.starblues.common.utils.ManifestUtils.*; /** * 抽象的 PluginDescriptorLoader @@ -23,51 +35,87 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor @Override public PluginDescriptor load(Path location) throws PluginException { - Properties properties = null; + Manifest manifest = null; try { - properties = getProperties(location); - if(properties == null){ - logger.warn("路径[{}]没有发现引导文件[{}]", location, BOOTSTRAP_FILE_NAME); + manifest = getManifest(location); + if(manifest == null){ + logger.warn("路径[{}]没有发现[{}]", location, MANIFEST); return null; } - return create(properties, location); + return create(manifest, location); } catch (Exception e) { - throw new PluginException("获取解析[" + location + "]插件引导文件失败." + e.getMessage(), e); + logger.warn("路径[{}]中存在非法[{}]: {}", location, MANIFEST, e.getMessage()); + return null; } } + @Override + public void close() throws Exception { + + } + /** * 子类获取 Properties * @param location properties 路径 * @return Properties * @throws Exception 异常 */ - protected abstract Properties getProperties(Path location) throws Exception; + protected abstract Manifest getManifest(Path location) throws Exception; - protected PluginDescriptor create(Properties properties, Path path){ + protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception{ + Attributes attributes = manifest.getMainAttributes(); DefaultPluginDescriptor descriptor = new DefaultPluginDescriptor( - properties.getProperty(PLUGIN_ID), - properties.getProperty(PLUGIN_VERSION), - properties.getProperty(PLUGIN_CLASS), + getValue(attributes, PLUGIN_ID), + getValue(attributes, PLUGIN_VERSION), + getValue(attributes, PLUGIN_BOOTSTRAP_CLASS), path ); - descriptor.setPluginLibDir(properties.getProperty(PLUGIN_LIB_DIR)); - descriptor.setDescription(properties.getProperty(PLUGIN_DESCRIPTION)); - descriptor.setRequires(properties.getProperty(PLUGIN_REQUIRES)); - descriptor.setProvider(properties.getProperty(PLUGIN_PROVIDER)); - descriptor.setLicense(properties.getProperty(PLUGIN_LICENSE)); - descriptor.setConfigFileName(properties.getProperty(PLUGIN_CONFIG_FILE_NAME)); + descriptor.setManifest(manifest); + descriptor.setPluginClassPath(getValue(attributes, PLUGIN_PATH, false)); + descriptor.setPluginLibPath(getPluginLibPaths(path, attributes)); + descriptor.setDescription(getValue(attributes, PLUGIN_DESCRIPTION, false)); + descriptor.setRequires(getValue(attributes, PLUGIN_REQUIRES, false)); + descriptor.setProvider(getValue(attributes, PLUGIN_PROVIDER, false)); + descriptor.setLicense(getValue(attributes, PLUGIN_LICENSE, false)); + descriptor.setConfigFileName(getValue(attributes, PLUGIN_CONFIG_FILE_NAME, false)); return descriptor; } - protected Properties getProperties(InputStream inputStream) throws Exception{ - Properties properties = new Properties(); - try (InputStreamReader input = new InputStreamReader(inputStream, - StandardCharsets.UTF_8)) { - properties.load(input); + protected Set getPluginLibPaths(Path path, Attributes attributes) throws Exception{ + String libIndex = getValue(attributes, PLUGIN_LIB_INDEX); + if(ObjectUtils.isEmpty(libIndex)){ + return Collections.emptySet(); + } + File file = new File(libIndex); + if(!file.exists()){ + // 如果绝对路径不存在, 则判断相对路径 + String pluginPath = getValue(attributes, PLUGIN_PATH); + file = new File(CommonUtils.joiningFilePath(pluginPath, libIndex)); + } + if(!file.exists()){ + // 都不存在, 则返回为空 + return Collections.emptySet(); + } + try { + List paths = Files.readAllLines(file.toPath()); + if(!ObjectUtils.isEmpty(paths)){ + return new HashSet<>(paths); + } + } catch (IOException e) { + throw new Exception("Load plugin lib index path failure. " + libIndex, e); + } + return Collections.emptySet(); + } + + protected Manifest getManifest(InputStream inputStream) throws Exception{ + Manifest manifest = new Manifest(); + try { + manifest.read(inputStream); + return manifest; + } finally { + inputStream.close(); } - return properties; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java index 7882d18..578257d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java @@ -4,8 +4,10 @@ import com.gitee.starblues.utils.Assert; import java.nio.file.Path; import java.util.List; +import java.util.Set; +import java.util.jar.Manifest; -import static com.gitee.starblues.core.descriptor.PluginDescriptorLoader.*; +import static com.gitee.starblues.common.PluginDescriptorKey.*; /** * 默认插件描述者 @@ -17,10 +19,14 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ private final String pluginId; private final String pluginVersion; - private final String pluginClass; + private final String pluginBootstrapClass; private final Path pluginPath; - private String pluginLibDir; + private String pluginClassPath; + private Manifest manifest; + private Type type; + + private Set pluginLibPaths; private String description; private String requires; private String provider; @@ -32,7 +38,7 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ String pluginClass, Path pluginPath) { this.pluginId = Assert.isNotEmpty(pluginId, PLUGIN_ID + "不能为空"); this.pluginVersion = Assert.isNotEmpty(pluginVersion, PLUGIN_VERSION + "不能为空"); - this.pluginClass = Assert.isNotEmpty(pluginClass, PLUGIN_CLASS + "不能为空"); + this.pluginBootstrapClass = Assert.isNotEmpty(pluginClass, PLUGIN_BOOTSTRAP_CLASS + "不能为空"); this.pluginPath = Assert.isNotNull(pluginPath, "插件路径[pluginPath]不能为空"); } @@ -56,6 +62,18 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ this.configFileName = configFileName; } + void setPluginClassPath(String pluginClassPath) { + this.pluginClassPath = pluginClassPath; + } + + void setManifest(Manifest manifest){ + this.manifest = manifest; + } + + void setType(Type type) { + this.type = type; + } + @Override public String getPluginId() { return pluginId; @@ -67,8 +85,8 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ } @Override - public String getPluginClass() { - return pluginClass; + public String getPluginBootstrapClass() { + return pluginBootstrapClass; } @Override @@ -77,8 +95,13 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ } @Override - public String getPluginLibDir() { - return pluginLibDir; + public String getPluginClassPath() { + return pluginClassPath; + } + + @Override + public Set getPluginLibPaths() { + return pluginLibPaths; } @Override @@ -106,13 +129,22 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ return null; } + @Override + public Manifest getManifest() { + return manifest; + } + + @Override + public Type getType() { + return type; + } + @Override public String getConfigFileName() { return configFileName; } - public void setPluginLibDir(String pluginLibDir) { - this.pluginLibDir = pluginLibDir; + public void setPluginLibPath(Set pluginLibPaths) { + this.pluginLibPaths = pluginLibPaths; } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java index 92f4304..3898331 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java @@ -1,10 +1,18 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.common.utils.ManifestUtils; + import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; +import java.util.jar.Attributes; +import java.util.jar.Manifest; /** * 开发环境 PluginDescriptorLoader 加载者 @@ -13,16 +21,17 @@ import java.util.Properties; */ public class DevPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ + @Override - protected Properties getProperties(Path location) throws Exception { - String bootstrapFilePath = location.toString() + File.separator + BOOTSTRAP_FILE_NAME; - File file = new File(bootstrapFilePath); + protected Manifest getManifest(Path location) throws Exception { + String manifestPath = location.toString() + File.separator + PackageStructure.MANIFEST; + File file = new File(manifestPath); if(!file.exists()){ return null; } - Path path = Paths.get(bootstrapFilePath); + Path path = Paths.get(manifestPath); try { - return super.getProperties(Files.newInputStream(path)); + return super.getManifest(Files.newInputStream(path)); } finally { try { path.getFileSystem().close(); @@ -32,4 +41,10 @@ public class DevPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ } } + @Override + protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception { + final DefaultPluginDescriptor descriptor = super.create(manifest, path); + descriptor.setType(PluginDescriptor.Type.DIR_OF_DEV); + return descriptor; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java index 7513cea..96281be 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java @@ -2,6 +2,8 @@ package com.gitee.starblues.core.descriptor; import java.nio.file.Path; import java.util.List; +import java.util.Set; +import java.util.jar.Manifest; /** * @author starBlues @@ -19,7 +21,7 @@ public class EmptyPluginDescriptor implements PluginDescriptor{ } @Override - public String getPluginClass() { + public String getPluginBootstrapClass() { return null; } @@ -29,7 +31,12 @@ public class EmptyPluginDescriptor implements PluginDescriptor{ } @Override - public String getPluginLibDir() { + public String getPluginClassPath() { + return null; + } + + @Override + public Set getPluginLibPaths() { return null; } @@ -62,4 +69,14 @@ public class EmptyPluginDescriptor implements PluginDescriptor{ public List getPluginDependency() { return null; } + + @Override + public Manifest getManifest() { + return null; + } + + @Override + public Type getType() { + return null; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java index ff96f67..996ad5a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -2,6 +2,8 @@ package com.gitee.starblues.core.descriptor; import java.nio.file.Path; import java.util.List; +import java.util.Set; +import java.util.jar.Manifest; /** * 插件信息 @@ -26,7 +28,7 @@ public interface PluginDescriptor { * 获取插件引导类 * @return String */ - String getPluginClass(); + String getPluginBootstrapClass(); /** * 获取插件路径 @@ -35,10 +37,16 @@ public interface PluginDescriptor { Path getPluginPath(); /** - * 获取插件依赖jar包目录 + * 获取插件classes path路径 + * @return Path + */ + String getPluginClassPath(); + + /** + * 获取插件依赖的路径 * @return String */ - String getPluginLibDir(); + Set getPluginLibPaths(); /** * 获取插件描述 @@ -76,4 +84,42 @@ public interface PluginDescriptor { */ List getPluginDependency(); + /** + * 得到插件的 Manifest 文件 + * @return Manifest + */ + Manifest getManifest(); + + /** + * 得到插件类型 + * @return 插件类型 + */ + Type getType(); + + /** + * 插件类型 + */ + enum Type{ + /** + * jar文件 + */ + JAR, + + /** + * zip 文件 + */ + ZIP, + + /** + * 生产模式目录 + */ + DIR_OF_PROD, + + /** + * 开发模式目录 + */ + DIR_OF_DEV + } + + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java index 0071e01..38461e4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java @@ -9,21 +9,9 @@ import java.nio.file.Path; * @author starBlues * @version 3.0.0 */ -public interface PluginDescriptorLoader { +public interface PluginDescriptorLoader extends AutoCloseable{ - String BOOTSTRAP_FILE_NAME = "plugin.properties"; - String PLUGIN_ID = "plugin.id"; - String PLUGIN_CLASS = "plugin.class"; - String PLUGIN_VERSION = "plugin.version"; - String PLUGIN_LIB_DIR = "plugin.libDir"; - String PLUGIN_DESCRIPTION = "plugin.description"; - String PLUGIN_PROVIDER = "plugin.provider"; - String PLUGIN_DEPENDENCIES = "plugin.dependencies"; - - String PLUGIN_REQUIRES = "plugin.requires"; - String PLUGIN_LICENSE = "plugin.license"; - String PLUGIN_CONFIG_FILE_NAME = "plugin.configFileName"; /** * 加载 PluginDescriptor diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java new file mode 100644 index 0000000..cbc9b4e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -0,0 +1,110 @@ +package com.gitee.starblues.core.descriptor; + + +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.common.utils.ManifestUtils; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ResourceUtils; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.FileInputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PackageStructure.*; + + +/** + * 生产环境目录式插件 PluginDescriptorLoader 加载者 + * @author starBlues + * @version 3.0.0 + */ +public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ + + @Override + protected Manifest getManifest(Path location) throws Exception { + File file = new File(CommonUtils.joiningFilePath(location.toString(), resolvePath(PROD_MANIFEST_PATH))); + if(!file.exists()){ + return null; + } + Manifest manifest = new Manifest(); + try (FileInputStream fileInputStream = new FileInputStream(file)){ + manifest.read(fileInputStream); + return manifest; + } + } + + @Override + protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception { + DefaultPluginDescriptor descriptor = super.create(manifest, path); + descriptor.setType(PluginDescriptor.Type.DIR_OF_PROD); + String pluginClassPath = descriptor.getPluginClassPath(); + String pathStr = path.toFile().getPath(); + if(ObjectUtils.isEmpty(pluginClassPath) || Files.notExists(Paths.get(pluginClassPath))){ + descriptor.setPluginClassPath(CommonUtils.joiningPath( + pathStr, CLASSES_NAME + )); + } + return descriptor; + } + + @Override + protected Set getPluginLibPaths(Path path, Attributes attributes) throws Exception { + String pathStr = path.toFile().getPath(); + String libIndexFile = getExistLibIndexFile( + pathStr, ManifestUtils.getValue(attributes, PluginDescriptorKey.PLUGIN_LIB_INDEX) + ); + Set pluginLibPaths = new HashSet<>(); + if(libIndexFile == null){ + return Collections.emptySet(); + } + File libFile = new File(libIndexFile); + List libIndex = FileUtils.readLines(libFile, CHARSET_NAME); + if(ObjectUtils.isEmpty(libIndex)){ + return Collections.emptySet(); + } + for (String index : libIndex) { + index = resolvePath(index); + File file = new File(index); + if(!file.exists()){ + // 如果直接读取的路径不存在, 则从相对路径读取 + file = new File(CommonUtils.joiningFilePath( + pathStr, index + )); + } + if(file.exists()){ + pluginLibPaths.add(file.getPath()); + } + } + return pluginLibPaths; + } + + protected String getExistLibIndexFile(String rootPath, String libIndexPath){ + libIndexPath = resolvePath(libIndexPath); + if(ObjectUtils.isEmpty(libIndexPath)){ + // 如果配置为空, 直接从默认路径读取 + libIndexPath = CommonUtils.joiningFilePath(rootPath, resolvePath(PROD_LIB_INDEX_PATH)); + } else { + if(Files.exists(Paths.get(libIndexPath))){ + return libIndexPath; + } + libIndexPath = CommonUtils.joiningFilePath(rootPath, libIndexPath); + } + if(Files.exists(Paths.get(libIndexPath))){ + return libIndexPath; + } + return null; + } + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java new file mode 100644 index 0000000..c043a1b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -0,0 +1,76 @@ +package com.gitee.starblues.core.descriptor; + + +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.utils.ManifestUtils; +import com.gitee.starblues.utils.ObjectUtils; +import org.apache.commons.io.IOUtils; + +import java.io.InputStream; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_LIB_INDEX; + + +/** + * 生产环境打包好的插件 PluginDescriptorLoader 加载者 + * @author starBlues + * @version 3.0.0 + */ +public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorLoader{ + + private final PluginDescriptor.Type type; + private Set pluginLibPaths; + + public ProdPackagePluginDescriptorLoader(PluginDescriptor.Type type) { + this.type = type; + } + + @Override + protected Manifest getManifest(Path location) throws Exception { + try (JarFile jarFile = new JarFile(location.toFile())){ + Manifest manifest = jarFile.getManifest(); + pluginLibPaths = getPluginLibPaths(jarFile, manifest); + return manifest; + } + } + + @Override + protected Set getPluginLibPaths(Path path, Attributes attributes) throws Exception { + return pluginLibPaths; + } + + @Override + protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception { + final DefaultPluginDescriptor descriptor = super.create(manifest, path); + descriptor.setType(type); + return descriptor; + } + + protected Set getPluginLibPaths(JarFile jarFile, Manifest manifest) throws Exception { + Attributes attributes = manifest.getMainAttributes(); + String pluginLibIndex = ManifestUtils.getValue(attributes, PLUGIN_LIB_INDEX); + if(ObjectUtils.isEmpty(pluginLibIndex)){ + return Collections.emptySet(); + } + JarEntry jarEntry = jarFile.getJarEntry(pluginLibIndex); + if(jarEntry == null){ + return Collections.emptySet(); + } + InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); + List libPaths = IOUtils.readLines(jarFileInputStream, PackageStructure.CHARSET_NAME); + if(ObjectUtils.isEmpty(libPaths)){ + return Collections.emptySet(); + } + return new HashSet<>(libPaths); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index b6e968c..b85467d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -1,31 +1,39 @@ package com.gitee.starblues.core.descriptor; -import java.io.InputStream; +import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.utils.ResourceUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.nio.file.Path; -import java.util.Properties; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; /** - * 生产环境 PluginDescriptorLoader 加载者 * @author starBlues - * @version 3.0.0 + * @version 1.0 */ -public class ProdPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ +public class ProdPluginDescriptorLoader implements PluginDescriptorLoader{ + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private PluginDescriptorLoader target; @Override - protected Properties getProperties(Path location) throws Exception { - JarFile jarFile = new JarFile(location.toFile()); - JarEntry jarEntry = jarFile.getJarEntry(BOOTSTRAP_FILE_NAME); - if(jarEntry == null){ + public PluginDescriptor load(Path location) throws PluginException { + if(ResourceUtils.isJarFile(location)){ + target = new ProdPackagePluginDescriptorLoader(PluginDescriptor.Type.JAR); + } else if(ResourceUtils.isZipFile(location)){ + target = new ProdPackagePluginDescriptorLoader(PluginDescriptor.Type.ZIP); + } else if(ResourceUtils.isDirFile(location)){ + target = new ProdDirPluginDescriptorLoader(); + } else { + logger.warn("不能解析文件: {}", location); return null; } - try { - InputStream inputStream = jarFile.getInputStream(jarEntry); - return getProperties(inputStream); - } finally { - jarFile.close(); - } + return target.load(location); } + @Override + public void close() throws Exception { + target.close(); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java index a2d08d2..0c17947 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java @@ -1,15 +1,7 @@ package com.gitee.starblues.core.launcher; -import com.gitee.starblues.core.launcher.archive.Archive; import com.gitee.starblues.core.launcher.jar.JarFile; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - /** * @author starBlues @@ -17,10 +9,11 @@ import java.util.List; */ public abstract class AbstractLauncher implements Launcher { + @Override public R run(String... args) throws Exception { JarFile.registerUrlProtocolHandler(); - ClassLoader classLoader = createClassLoader(getClassPathArchivesIterator()); + ClassLoader classLoader = createClassLoader(); Thread thread = Thread.currentThread(); ClassLoader oldClassLoader = thread.getContextClassLoader(); try { @@ -31,21 +24,7 @@ public abstract class AbstractLauncher implements Launcher { } } - protected Iterator getClassPathArchivesIterator() throws Exception { - return Collections.emptyListIterator(); - } - - protected ClassLoader createClassLoader(Iterator archives) throws Exception { - List urls = new ArrayList<>(50); - while (archives.hasNext()) { - urls.add(archives.next().getUrl()); - } - return createClassLoader(urls.toArray(new URL[0])); - } - - protected ClassLoader createClassLoader(URL[] urls) throws Exception { - return new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); - } + protected abstract ClassLoader createClassLoader() throws Exception; /** * 子类实现具体的启动方法 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java deleted file mode 100644 index a199e21..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/ClasspathLauncher.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.core.launcher; - -import com.gitee.starblues.core.launcher.archive.Archive; - -import java.util.Iterator; - -/** - * @author starBlues - * @version 1.0 - */ -public class ClasspathLauncher extends AbstractLauncher{ - - - - - @Override - protected Iterator getClassPathArchivesIterator() throws Exception { - return super.getClassPathArchivesIterator(); - } - - @Override - protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { - Thread.currentThread().setContextClassLoader(classLoader); - return classLoader; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java index e4054bc..e86626b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java @@ -14,6 +14,7 @@ public class JavaMainResourcePatternDefiner implements MainResourcePatternDefine private final Set includes = new HashSet<>(); public JavaMainResourcePatternDefiner(){ + // TODO java 内部的包匹配, 未补充全 // == java == includes.add("java/**"); includes.add("javax/**"); @@ -24,17 +25,12 @@ public class JavaMainResourcePatternDefiner implements MainResourcePatternDefine } @Override - public Set getIncludeResourcePatterns() { + public Set getIncludePatterns() { return includes; } @Override - public Set getExcludeResourcePatterns() { - return null; - } - - @Override - public Set getSpringFactoriesPatterns() { + public Set getExcludePatterns() { return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java index d12f0dc..6463741 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core.launcher; +import com.gitee.starblues.core.classloader.GenericClassLoader; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.launcher.archive.Archive; import com.gitee.starblues.core.launcher.archive.ExplodedArchive; @@ -21,6 +22,7 @@ import java.util.List; */ public class MainProgramLauncher extends AbstractLauncher{ + private final SpringBootstrap springBootstrap; public MainProgramLauncher(SpringBootstrap springBootstrap) { @@ -28,36 +30,24 @@ public class MainProgramLauncher extends AbstractLauncher{ } @Override - protected ClassLoader createClassLoader(URL[] urls) throws Exception { - PluginClassLoader pluginClassLoader = new PluginClassLoader( - "main", null, MainProgramLauncher.class.getClassLoader(), - new JavaMainResourcePatternDefiner() + protected ClassLoader createClassLoader() throws Exception { + GenericClassLoader classLoader = new GenericClassLoader( + "MainProgramLauncherClassLoader", MainProgramLauncher.class.getClassLoader() ); - for (URL url : urls) { - pluginClassLoader.addResource(Paths.get(url.toURI())); - } - - return pluginClassLoader; + addResource(classLoader); + return classLoader; } - @Override - protected Iterator getClassPathArchivesIterator() throws Exception { - // TODO 生产环境下待定 + protected void addResource(GenericClassLoader classLoader) throws Exception{ String classPath = ManagementFactory.getRuntimeMXBean().getClassPath(); String[] split = classPath.split(";"); List archives = new ArrayList<>(); for (String s : split) { - Path path = Paths.get(s); - File file = path.toFile(); - if(PluginFileUtils.isJarFile(path)){ - archives.add(new JarFileArchive(file)); - } else { - archives.add(new ExplodedArchive(file)); - } + classLoader.addResource(s); } - return archives.iterator(); } + @Override protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { MethodRunner run = new MethodRunner(springBootstrap.getClass().getName(), "run", args); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java index 91dde0a..cddb80d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java @@ -28,11 +28,15 @@ public class MethodRunner { } public Object run(ClassLoader classLoader) throws Exception { + Class runClass = loadRunClass(classLoader); + return runMethod(runClass); + } + + protected Class loadRunClass(ClassLoader classLoader) throws Exception{ if(classLoader == null){ classLoader = Thread.currentThread().getContextClassLoader(); } - Class runClass = Class.forName(this.className, false, classLoader); - return runMethod(runClass); + return Class.forName(this.className, false, classLoader); } protected Object runMethod(Class runClass) throws Exception { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java index 25af38b..48ea41f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java @@ -77,7 +77,6 @@ public interface Archive extends Iterable, AutoCloseable { * {@link org.springframework.boot.loader.jar.JarFile} to access entries and * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. */ - @Deprecated @Override default void forEach(Consumer action) { Objects.requireNonNull(action); @@ -93,7 +92,6 @@ public interface Archive extends Iterable, AutoCloseable { * {@link org.springframework.boot.loader.jar.JarFile} to access entries and * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. */ - @Deprecated @Override default Spliterator spliterator() { return Spliterators.spliteratorUnknownSize(iterator(), 0); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java index 8b8160b..b7487ba 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java @@ -31,7 +31,7 @@ public class JarFile extends AbstractJarFile implements Iterable implements ResourceClear { +public class PluginLauncher extends AbstractLauncher { - private final PluginInteractive pluginInteractive; - private final PluginDescriptor pluginDescriptor; + protected final PluginInteractive pluginInteractive; + protected final PluginDescriptor pluginDescriptor; public PluginLauncher(PluginInteractive pluginInteractive) { this.pluginInteractive = pluginInteractive; @@ -26,44 +29,31 @@ public class PluginLauncher extends AbstractLauncher implements Resource } @Override - protected ClassLoader createClassLoader(URL[] urls) throws Exception { - String pluginLibDir = pluginDescriptor.getPluginLibDir(); - Path pluginPath = pluginDescriptor.getPluginPath(); + protected ClassLoader createClassLoader() throws Exception { + String pluginId = pluginDescriptor.getPluginId(); + MainResourcePatternDefiner mainResourceMatcher = new JavaMainResourcePatternDefiner() { + @Override + public Set getIncludePatterns() { + Set includeResourcePatterns = super.getIncludePatterns(); + includeResourcePatterns.add("com/gitee/starblues/**"); + includeResourcePatterns.add("org/springframework/web/**"); + return includeResourcePatterns; + } + }; PluginClassLoader pluginClassLoader = new PluginClassLoader( - "plugin", pluginPath, MainProgramLauncher.class.getClassLoader(), - new JavaMainResourcePatternDefiner(){ - @Override - public Set getIncludeResourcePatterns() { - Set includeResourcePatterns = super.getIncludeResourcePatterns(); - includeResourcePatterns.add("com/gitee/starblues/**"); - includeResourcePatterns.add("org/springframework/web/**"); - return includeResourcePatterns; - } - } + pluginId, MainProgramLauncher.class.getClassLoader(), mainResourceMatcher ); - File file = new File(pluginLibDir); - if(file.exists() && file.isDirectory()){ - File[] listFiles = file.listFiles(); - if(listFiles != null){ - for (File listFile : listFiles) { - pluginClassLoader.addResource(listFile); - } - } - - } + pluginClassLoader.addResource(pluginDescriptor); + //TODO 添加框架的引导 pluginClassLoader.addResource(Paths.get("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-bootstrap\\target\\classes")); - return pluginClassLoader; } - @Override - protected Object launch(ClassLoader classLoader, String... args) throws Exception { - return new PluginMethodRunner(pluginInteractive).run(classLoader); + protected SpringPluginHook launch(ClassLoader classLoader, String... args) throws Exception { + SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive).run(classLoader); + return new SpringPluginHookWrapper(springPluginHook, classLoader); } - @Override - public void clear() { - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java deleted file mode 100644 index 0451c49..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherManager.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.gitee.starblues.core.launcher.plugin; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PluginLauncherManager { - - - void start(PluginDescriptor pluginDescriptor) throws Exception; - - - void stop(String pluginId) throws Exception; - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java deleted file mode 100644 index c6d44b0..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncherStorage.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.gitee.starblues.core.launcher.plugin; - -import java.util.function.Supplier; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PluginLauncherStorage { - - - void add(String key, Object value); - - /** - * 添加注册的信息 - * @param key 注册信息key - * @param value 注册信息值 - */ - void addRegistryInfo(String key, Object value); - - /** - * 得到注册信息 - * @param key 注册信息key - * @return 注册信息的值 - */ - T getRegistryInfo(String key); - - /** - * 得到注册信息 - * @param key 注册信息key - * @param notExistCreate 不存在的话, 进行创建操作 - * @return 注册信息的值 - */ - T getRegistryInfo(String key, Supplier notExistCreate); - - - /** - * 移除注册信息 - * @param key 注册信息key - */ - void removeRegistryInfo(String key); - - /** - * 清除全部的注册信息 - */ - void clearRegistryInfo(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java index a916c67..d86727e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java @@ -1,25 +1,49 @@ package com.gitee.starblues.core.launcher.plugin; +import com.gitee.starblues.core.RuntimeMode; import com.gitee.starblues.core.launcher.MethodRunner; import com.gitee.starblues.utils.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** + * 插件方法运行器。 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginMethodRunner extends MethodRunner { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final String PLUGIN_RUN_METHOD_NAME = "run"; private final PluginInteractive pluginInteractive; public PluginMethodRunner(PluginInteractive pluginInteractive) { - super(pluginInteractive.getPluginDescriptor().getPluginClass(), PLUGIN_RUN_METHOD_NAME, new String[]{}); + super(pluginInteractive.getPluginDescriptor().getPluginBootstrapClass(), PLUGIN_RUN_METHOD_NAME, new String[]{}); this.pluginInteractive = pluginInteractive; } + @Override + protected Class loadRunClass(ClassLoader classLoader) throws Exception { + try { + return super.loadRunClass(classLoader); + } catch (Exception e){ + if(e instanceof ClassNotFoundException){ + String pluginId = pluginInteractive.getPluginDescriptor().getPluginId(); + String error = "插件[" + pluginId + "]没有发现" + "[" + className + "]引导类"; + if(pluginInteractive.getConfiguration().environment() == RuntimeMode.DEV){ + error = error + ", 请确保已经编译!"; + } + throw new ClassNotFoundException(error); + } + throw e; + } + } + @Override protected Object runMethod(Class runClass) throws Exception { Method runMethod = ReflectionUtils.findMethod(runClass, runMethodName, Class.class, String[].class); @@ -34,7 +58,9 @@ public class PluginMethodRunner extends MethodRunner { return runMethod.invoke(instance, runClass, this.args); } catch (Exception e){ String error = "Invoke failure: " - + ReflectionUtils.methodToString(runClass, runMethodName, runMethod.getParameterTypes()); + + ReflectionUtils.methodToString(runClass, runMethodName, runMethod.getParameterTypes()) + + ". " + e.getMessage(); + logger.error(error, e); throw new Exception(error); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java deleted file mode 100644 index 158c055..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginRegistryInfo.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.gitee.starblues.core.launcher.plugin; - -import com.gitee.starblues.spring.ApplicationContext; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PluginRegistryInfo { - - Object getApplicationContext(); - - PluginLauncher getPluginLauncher(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java index 8cfc5c0..38c0157 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java @@ -2,8 +2,9 @@ package com.gitee.starblues.core.launcher.plugin; import java.util.function.Supplier; /** + * 注册的信息接口 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface RegistryInfo { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java new file mode 100644 index 0000000..77971fc --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java @@ -0,0 +1,34 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.SpringPluginHook; + +/** + * @author starBlues + * @version 1.0 + */ +public class SpringPluginHookWrapper implements SpringPluginHook { + + private final SpringPluginHook target; + private final ClassLoader classLoader; + + public SpringPluginHookWrapper(SpringPluginHook target, + ClassLoader classLoader) { + this.target = target; + this.classLoader = classLoader; + } + + + @Override + public ApplicationContext getApplicationContext() { + return target.getApplicationContext(); + } + + @Override + public void close() throws Exception { + target.close(); + if(classLoader instanceof AutoCloseable){ + ((AutoCloseable)classLoader).close(); + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java deleted file mode 100644 index cb40692..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/DefaultPluginLoader.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.gitee.starblues.core.loader; - -import com.gitee.starblues.core.PluginState; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; -import com.gitee.starblues.core.classloader.PluginClassLoader; -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; -import org.springframework.util.ClassUtils; - -import java.io.File; -import java.lang.ref.WeakReference; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -/** - * 默认的插件加载者 - * @author starBlues - * @version 3.0.0 - */ -public class DefaultPluginLoader implements PluginLoader{ - - private final MainResourcePatternDefiner mainResourcePatternDefiner; - - private final List> classLoaderCache = new ArrayList<>(); - - public DefaultPluginLoader(MainResourcePatternDefiner mainResourcePatternDefiner) { - this.mainResourcePatternDefiner = Assert.isNotNull(mainResourcePatternDefiner, - "参数 mainResourcePatternDefiner 不能为空"); - } - - @Override - public PluginWrapperInside load(PluginDescriptor descriptor) throws Exception { - Assert.isNotNull(descriptor, "参数 PluginDescriptor 不能为空"); - PluginClassLoader classLoader = getClassLoader(descriptor); - installLib(classLoader, descriptor); - Class bootstrapClass = classLoader.loadClass(descriptor.getPluginClass()); - PluginWrapperInside pluginWrapperInside = new PluginWrapperInside( - descriptor.getPluginId(), - descriptor, - classLoader, - bootstrapClass, - descriptor.getPluginPath() - ); - pluginWrapperInside.setPluginState(PluginState.CREATED); - return pluginWrapperInside; - } - - protected synchronized PluginClassLoader getClassLoader(PluginDescriptor descriptor){ - String pluginId = descriptor.getPluginId(); - Path classPath = descriptor.getPluginPath(); - Iterator> iterator = classLoaderCache.iterator(); - PluginClassLoader pnClassLoader = null; - while (iterator.hasNext()){ - WeakReference weakReference = iterator.next(); - PluginClassLoader cacheClassLoader = weakReference.get(); - if(cacheClassLoader == null){ - iterator.remove(); - continue; - } - if(Objects.equals(pluginId, cacheClassLoader.getPluginId())){ - pnClassLoader = cacheClassLoader; - pnClassLoader.addResource(classPath.toFile()); - } - } - if(pnClassLoader == null){ - pnClassLoader = new PluginClassLoader(pluginId, classPath, getParentClassLoader(), - mainResourcePatternDefiner); - classLoaderCache.add(new WeakReference<>(pnClassLoader)); - } - return pnClassLoader; - } - - protected void installLib(PluginClassLoader classLoader, PluginDescriptor descriptor){ - String pluginLibDir = descriptor.getPluginLibDir(); - - if(ObjectUtils.isEmpty(pluginLibDir)){ - return; - } - File file = getExistLibFile(descriptor); - if(file == null){ - return; - } - addJarFile(classLoader, file); - if(file.isDirectory()){ - File[] files = file.listFiles(); - if(files == null || files.length == 0){ - return; - } - for (File subFile : files) { - addJarFile(classLoader, subFile); - } - } - } - - private File getExistLibFile(PluginDescriptor descriptor){ - String pluginLibDir = descriptor.getPluginLibDir(); - File file = new File(pluginLibDir); - if(file.exists()){ - return file; - } - String relativePath = CommonUtils.joiningFilePath(descriptor.getPluginPath().toString(), pluginLibDir); - file = new File(relativePath); - if(file.exists()){ - return file; - } - return null; - } - - - private void addJarFile(PluginClassLoader pnClassLoader, File file){ - if(!file.exists()){ - return; - } - if(PluginFileUtils.isJarFile(file.toPath())){ - pnClassLoader.addResource(file); - } - } - - protected ClassLoader getParentClassLoader(){ - ClassLoader cl = null; - try { - cl = Thread.currentThread().getContextClassLoader(); - } catch (Throwable ex) { - // 忽略 - } - if (cl == null) { - cl = ClassUtils.class.getClassLoader(); - if (cl == null) { - try { - cl = ClassLoader.getSystemClassLoader(); - } catch (Throwable ex) { - // 忽略 - } - } - } - return cl; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java deleted file mode 100644 index 74981d0..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/loader/PluginLoader.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.gitee.starblues.core.loader; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; - -/** - * 插件加载者 - * @author starBlues - * @version 3.0.0 - */ -public interface PluginLoader { - - - /** - * 根据插件描述加载插件 - * @param descriptor 插件描述 - * @return PluginWrapper - * @throws Exception 加载异常 - */ - PluginWrapperInside load(PluginDescriptor descriptor) throws Exception; - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java index c69f5df..cd06edf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java @@ -1,5 +1,7 @@ package com.gitee.starblues.core.scanner; +import com.gitee.starblues.common.PackageStructure; + import java.io.File; import java.nio.file.Files; import java.nio.file.Path; @@ -21,8 +23,8 @@ public class DevPathResolve implements PathResolve{ } protected void addCompilePackageName(){ - // 添加maven编译目录 - devCompilePackageNames.add("target".concat(File.separator).concat("classes")); + // 添加插件信息查询目录 + devCompilePackageNames.add("target".concat(File.separator).concat(PackageStructure.META_INF_NAME)); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java index 19bfad4..d65f3f9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java @@ -1,7 +1,10 @@ package com.gitee.starblues.core.scanner; +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; +import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -13,29 +16,41 @@ import java.util.List; */ public class ProdPathResolve implements PathResolve{ - private final List extensionNames = new ArrayList<>(); + private final List packageSuffix = new ArrayList<>(); public ProdPathResolve(){ - addExtensionName(".jar"); + // jar包 + addPackageSuffix(".jar"); + // zip包 + addPackageSuffix(".zip"); } - protected void addExtensionName(String extensionName){ - if(ObjectUtils.isEmpty(extensionName)){ + protected void addPackageSuffix(String name){ + if(ObjectUtils.isEmpty(name)){ return; } - // jar包 - extensionNames.add(extensionName); + packageSuffix.add(name); } @Override public Path resolve(Path path) { - String fileName = path.getFileName().toString(); - for (String extensionName : extensionNames) { - boolean exist = fileName.toLowerCase().endsWith(extensionName.toLowerCase()); + if(isDirPlugin(path)){ + return path; + } + String fileName = path.getFileName().toString().toLowerCase(); + for (String suffixName : packageSuffix) { + boolean exist = fileName.endsWith(suffixName.toLowerCase()); if(exist){ return path; } } return null; } + + protected boolean isDirPlugin(Path path){ + File file = new File(CommonUtils.joiningFilePath(path.toString(), PackageStructure.resolvePath( + PackageStructure.PROD_MANIFEST_PATH + ))); + return file.exists() && file.isFile(); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java index c513d7f..a679b37 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java @@ -49,11 +49,8 @@ public class IntegrationExtendPoint { @Bean @ConditionalOnMissingBean - public RealizeProvider realizeProvider(MainResourcePatternDefiner mainResourcePatternDefiner) { + public RealizeProvider realizeProvider() { DefaultRealizeProvider defaultRealizeProvider = new DefaultRealizeProvider(configuration.environment()); - if(mainResourcePatternDefiner != null){ - defaultRealizeProvider.setMainResourcePatternDefiner(mainResourcePatternDefiner); - } defaultRealizeProvider.init(); return defaultRealizeProvider; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java index 95bce6f..c6fc06a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java @@ -2,7 +2,6 @@ package com.gitee.starblues.integration; import com.gitee.starblues.integration.listener.PluginListener; -import org.pf4j.PluginStateListener; import java.util.List; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginStateListenerContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginStateListenerContext.java deleted file mode 100644 index edca121..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginStateListenerContext.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gitee.starblues.integration; - -import org.pf4j.PluginStateListener; - -import java.util.List; - -/** - * 插件状态监听器上下文 - * @author starBlues - * @version 2.4.4 - */ -public interface PluginStateListenerContext { - - - /** - * 添加pf4j状态监听者 - * @param pluginListener 插件 bean 监听者 - */ - void addPf4jStateListener(PluginStateListener pluginListener); - - - /** - * 添加pf4j状态监听者 - * @param pluginListenerClass 插件监听者Class类 - * @param 继承PluginListener的子类 - */ - void addPf4jStateListener(Class pluginListenerClass); - - /** - * 添加pf4j状态监听者 - * @param pluginListeners 插件 bean 监听者集合 - */ - void addPf4jStateListener(List pluginListeners); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java index 542711c..8387a1a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java @@ -3,8 +3,6 @@ package com.gitee.starblues.integration.application; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginListener; import com.gitee.starblues.integration.listener.PluginListenerFactory; -import com.gitee.starblues.integration.listener.PluginStateListenerFactory; -import org.pf4j.PluginStateListener; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.ApplicationContext; @@ -19,8 +17,6 @@ import java.util.List; public abstract class AbstractPluginApplication implements PluginApplication { protected final PluginListenerFactory listenerFactory = new PluginListenerFactory(); - protected final PluginStateListenerFactory pluginStateListenerFactory = new PluginStateListenerFactory(); - @Override public void addListener(PluginListener pluginListener) { @@ -42,26 +38,6 @@ public abstract class AbstractPluginApplication implements PluginApplication { } } - @Override - public void addPf4jStateListener(PluginStateListener pluginListener) { - pluginStateListenerFactory.addStateListener(pluginListener); - } - - @Override - public void addPf4jStateListener(Class pluginListenerClass) { - pluginStateListenerFactory.addStateListener(pluginListenerClass); - } - - @Override - public void addPf4jStateListener(List pluginListeners) { - if(pluginListeners == null || pluginListeners.isEmpty()){ - return; - } - for (PluginStateListener pluginListener : pluginListeners) { - this.pluginStateListenerFactory.addStateListener(pluginListener); - } - } - /** * 子类可通过Application 获取插件定义的配置 * @param applicationContext applicationContext diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java index c5b27cf..77f0f8a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java @@ -6,7 +6,6 @@ import com.gitee.starblues.integration.operator.EmptyPluginOperator; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.EmptyPluginUser; import com.gitee.starblues.integration.user.PluginUser; -import org.pf4j.PluginStateListener; import org.springframework.context.ApplicationContext; import java.util.List; @@ -47,19 +46,4 @@ public class EmptyPluginApplication implements PluginApplication{ public void addListener(List pluginListeners) { } - - @Override - public void addPf4jStateListener(PluginStateListener pluginListener) { - - } - - @Override - public void addPf4jStateListener(Class pluginListenerClass) { - - } - - @Override - public void addPf4jStateListener(List pluginListeners) { - - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java index 1c229dc..bd0b0a6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java @@ -1,7 +1,6 @@ package com.gitee.starblues.integration.application; import com.gitee.starblues.integration.PluginListenerContext; -import com.gitee.starblues.integration.PluginStateListenerContext; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.PluginUser; @@ -12,7 +11,7 @@ import org.springframework.context.ApplicationContext; * @author starBlues * @version 2.4.3 */ -public interface PluginApplication extends PluginListenerContext, PluginStateListenerContext { +public interface PluginApplication extends PluginListenerContext { /** * 初始化 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginStateListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginStateListenerFactory.java deleted file mode 100644 index d041ae4..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginStateListenerFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.gitee.starblues.integration.listener; - -import com.gitee.starblues.utils.SpringBeanUtils; -import org.pf4j.PluginStateListener; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * 插件状态监听器工厂 - * @author starBlues - * @version 2.4.4 - * @since 2021-06-09 - */ -public class PluginStateListenerFactory { - - private final List listeners = new ArrayList<>(); - private final List listenerClasses = new ArrayList<>(); - - public void addStateListener(PluginStateListener pluginStateListener){ - if(pluginStateListener == null){ - return; - } - listeners.add(pluginStateListener); - } - - public void addStateListener(Class pluginStateListenerClass){ - if(pluginStateListenerClass == null){ - return; - } - listenerClasses.add(pluginStateListenerClass); - } - - public List buildListenerClass(GenericApplicationContext applicationContext) { - if (applicationContext == null) { - return listeners; - } - synchronized (listenerClasses) { - if(listenerClasses.isEmpty()){ - return listeners; - } - // 搜索Spring容器中的监听器 - List pluginListeners = SpringBeanUtils.getBeans(applicationContext, PluginStateListener.class); - if(pluginListeners.isEmpty()){ - pluginListeners = new ArrayList<>(); - } - for (Class listenerClass : listenerClasses) { - // 兼容 spring 4.x - applicationContext.registerBeanDefinition(listenerClass.getName(), - BeanDefinitionBuilder.genericBeanDefinition(listenerClass).getBeanDefinition()); - T bean = applicationContext.getBean(listenerClass); - pluginListeners.add(bean); - } - for (PluginStateListener pluginListener : pluginListeners) { - boolean find = false; - for (PluginStateListener listener : listeners) { - if(Objects.equals(listener, pluginListener)){ - find = true; - break; - } - } - // 防止监听器重复注册 - if(!find){ - listeners.add(pluginListener); - } - } - listenerClasses.clear(); - } - return listeners; - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 8150999..6c828e5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -1,15 +1,11 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.DefaultPluginManager; -import com.gitee.starblues.core.PluginManager; -import com.gitee.starblues.core.RealizeProvider; +import com.gitee.starblues.core.*; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.launcher.plugin.*; -import com.gitee.starblues.core.loader.PluginWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; -import com.gitee.starblues.spring.*; +import com.gitee.starblues.utils.MsgUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; import org.slf4j.Logger; @@ -20,6 +16,7 @@ import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; /** * 默认的插件操作者 @@ -34,19 +31,17 @@ public class DefaultPluginOperator implements PluginOperator { private final IntegrationConfiguration configuration; private final PluginManager pluginManager; - private final PluginLauncherManager pluginLauncherManager; public DefaultPluginOperator(GenericApplicationContext applicationContext, RealizeProvider realizeProvider, IntegrationConfiguration configuration) { this.configuration = configuration; - this.pluginManager = new DefaultPluginManager(realizeProvider, configuration.pluginPath()); - this.pluginLauncherManager = new DefaultPluginLauncherManager(applicationContext, configuration); + this.pluginManager = new PluginLauncherManager(realizeProvider, applicationContext, configuration); } @Override - public synchronized boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception { + public synchronized boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException { if(isInit.get()){ throw new RuntimeException("插件已经被初始化了, 不能再初始化."); } @@ -74,12 +69,9 @@ public class DefaultPluginOperator implements PluginOperator { boolean isFoundException = false; for (PluginDescriptor descriptor : pluginDescriptors) { try { - //pluginManager.start(descriptor.getPluginId()); - pluginLauncherManager.start(descriptor); - //springPlugin.registry(pluginManager.getPluginWrapper(descriptor.getPluginId())); - log.info("启动插件[{}@{}]成功", descriptor.getPluginId(), descriptor.getPluginVersion()); - } catch (Exception e){ - log.error("启动插件[{}]失败. {}", descriptor.getPluginId(), e.getMessage(), e); + pluginManager.start(descriptor.getPluginId()); + } catch (PluginException e){ + log.error(e.getMessage(), e); isFoundException = true; } } @@ -100,73 +92,82 @@ public class DefaultPluginOperator implements PluginOperator { } @Override - public boolean verify(Path jarPath) throws Exception { + public boolean verify(Path jarPath) throws PluginException { return false; } @Override - public PluginInfo install(Path jarPath) throws Exception { + public PluginInfo install(Path jarPath) throws PluginException { return null; } @Override - public boolean uninstall(String pluginId, boolean isBackup) throws Exception { - return false; + public boolean uninstall(String pluginId, boolean isBackup) throws PluginException { + pluginManager.uninstall(pluginId); + return true; } @Override - public PluginInfo load(Path jarPath) throws Exception { + public PluginInfo load(Path jarPath) throws PluginException { return null; } @Override - public PluginInfo load(MultipartFile pluginFile) throws Exception { + public PluginInfo load(MultipartFile pluginFile) throws PluginException { return null; } @Override - public boolean unload(String pluginId, boolean isBackup) throws Exception { + public boolean unload(String pluginId, boolean isBackup) throws PluginException { return false; } @Override - public boolean start(String pluginId) throws Exception { + public boolean start(String pluginId) throws PluginException { return false; } @Override - public boolean stop(String pluginId) throws Exception { + public boolean stop(String pluginId) throws PluginException { return false; } @Override - public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception { + public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException { return null; } @Override - public boolean installConfigFile(Path configFilePath) throws Exception { + public boolean installConfigFile(Path configFilePath) throws PluginException { return false; } @Override - public boolean uploadConfigFile(MultipartFile configFile) throws Exception { + public boolean uploadConfigFile(MultipartFile configFile) throws PluginException { return false; } @Override - public boolean backupPlugin(Path backDirPath, String sign) throws Exception { + public boolean backupPlugin(Path backDirPath, String sign) throws PluginException { return false; } @Override - public boolean backupPlugin(String pluginId, String sign) throws Exception { + public boolean backupPlugin(String pluginId, String sign) throws PluginException { return false; } @Override public List getPluginInfo() { - return null; + List startedPlugins = pluginManager.getPluginWrappers(); + List pluginInfos = new ArrayList<>(); + if(startedPlugins == null){ + return pluginInfos; + } + return startedPlugins.stream() + .filter(Objects::nonNull) + .map(this::getPluginInfo) + .collect(Collectors.toList()); } @Override @@ -175,7 +176,7 @@ public class DefaultPluginOperator implements PluginOperator { } @Override - public Set getPluginFilePaths() throws Exception { + public Set getPluginFilePaths() { return null; } @@ -188,4 +189,16 @@ public class DefaultPluginOperator implements PluginOperator { public PluginWrapper getPluginWrapper(String pluginId) { return null; } + + + /** + * 通过PluginWrapper得到插件信息 + * @param pluginWrapper pluginWrapper + * @return PluginInfo + */ + private PluginInfo getPluginInfo(PluginWrapper pluginWrapper) { + return new PluginInfo(pluginWrapper.getPluginDescriptor(), pluginWrapper.getPluginState(), + pluginWrapper.getPluginPath().toAbsolutePath().toString(), + configuration.environment().toString()); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java index 4a197ae..eee1d6b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.PluginWrapper; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; import org.springframework.web.multipart.MultipartFile; @@ -14,73 +15,74 @@ import java.util.Set; * @version 1.0 */ public class EmptyPluginOperator implements PluginOperator{ + @Override - public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception { + public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException { return false; } @Override - public boolean verify(Path jarPath) throws Exception { + public boolean verify(Path jarPath) throws PluginException { return false; } @Override - public PluginInfo install(Path jarPath) throws Exception { + public PluginInfo install(Path jarPath) throws PluginException { return null; } @Override - public boolean uninstall(String pluginId, boolean isBackup) throws Exception { + public boolean uninstall(String pluginId, boolean isBackup) throws PluginException { return false; } @Override - public PluginInfo load(Path jarPath) throws Exception { + public PluginInfo load(Path jarPath) throws PluginException { return null; } @Override - public PluginInfo load(MultipartFile pluginFile) throws Exception { + public PluginInfo load(MultipartFile pluginFile) throws PluginException { return null; } @Override - public boolean unload(String pluginId, boolean isBackup) throws Exception { + public boolean unload(String pluginId, boolean isBackup) throws PluginException { return false; } @Override - public boolean start(String pluginId) throws Exception { + public boolean start(String pluginId) throws PluginException { return false; } @Override - public boolean stop(String pluginId) throws Exception { + public boolean stop(String pluginId) throws PluginException { return false; } @Override - public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception { + public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException { return null; } @Override - public boolean installConfigFile(Path configFilePath) throws Exception { + public boolean installConfigFile(Path configFilePath) throws PluginException { return false; } @Override - public boolean uploadConfigFile(MultipartFile configFile) throws Exception { + public boolean uploadConfigFile(MultipartFile configFile) throws PluginException { return false; } @Override - public boolean backupPlugin(Path backDirPath, String sign) throws Exception { + public boolean backupPlugin(Path backDirPath, String sign) throws PluginException { return false; } @Override - public boolean backupPlugin(String pluginId, String sign) throws Exception { + public boolean backupPlugin(String pluginId, String sign) throws PluginException { return false; } @@ -95,7 +97,7 @@ public class EmptyPluginOperator implements PluginOperator{ } @Override - public Set getPluginFilePaths() throws Exception { + public Set getPluginFilePaths() { return null; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java index ccf77b7..d240892 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.PluginWrapper; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; import org.springframework.web.multipart.MultipartFile; @@ -21,77 +22,77 @@ public interface PluginOperator { * 初始化插件。该方法只能执行一次。 * @param pluginInitializerListener 插件初始化监听者 * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception; + boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException; /** * 校验插件jar包 * @param jarPath 插件包的路径 * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 校验异常 + * @throws PluginException 校验异常 */ - boolean verify(Path jarPath) throws Exception; + boolean verify(Path jarPath) throws PluginException; /** * 通过路径安装插件(会启用), 该插件文件必须存在于服务器 [适用于生产环境] * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar * @param jarPath 插件路径 * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - PluginInfo install(Path jarPath) throws Exception; + PluginInfo install(Path jarPath) throws PluginException; /** * 卸载插件 [适用于生产环境] * @param pluginId 插件id * @param isBackup 是否备份原来的插件。备份文件命名规则为;[uninstall][时间]_原jar名.jar * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean uninstall(String pluginId, boolean isBackup) throws Exception; + boolean uninstall(String pluginId, boolean isBackup) throws PluginException; /** * 加载插件, 但不启动 [适用于生产环境] * @param jarPath 插件路径 * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - PluginInfo load(Path jarPath) throws Exception; + PluginInfo load(Path jarPath) throws PluginException; /** * 加载插件, 但不启动 [适用于生产环境] * @param pluginFile 插件文件 * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - PluginInfo load(MultipartFile pluginFile) throws Exception; + PluginInfo load(MultipartFile pluginFile) throws PluginException; /** * 配合load使用. 针对load的插件进行unload [适用于生产环境] * @param pluginId 插件id * @param isBackup 是否备份原来的插件。备份文件命名规则为;[uninstall][时间]_原jar名.jar * @return 成功返回true.不成功抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean unload(String pluginId, boolean isBackup) throws Exception; + boolean unload(String pluginId, boolean isBackup) throws PluginException; /** * 启用插件 [适用于生产环境、开发环境] * @param pluginId 插件id * @return 成功返回true.不成功抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean start(String pluginId) throws Exception; + boolean start(String pluginId) throws PluginException; /** * 停止插件 [适用于生产环境、开发环境] * @param pluginId 插件id * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean stop(String pluginId) throws Exception; + boolean stop(String pluginId) throws PluginException; /** @@ -99,18 +100,18 @@ public interface PluginOperator { * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar * @param pluginFile 插件文件 * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception; + PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException; /** * 通过路径安装插件的配置文件。该文件必须存在于服务器。[适用于生产环境] * 如果配置文件目录存在同名的配置文件, 系统会自动备份该配置文件。备份文件命名规则为;[install-config-backup][时间]_原jar名.jar * @param configFilePath 配置文件路径。 * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 安装异常 + * @throws PluginException 安装异常 */ - boolean installConfigFile(Path configFilePath) throws Exception; + boolean installConfigFile(Path configFilePath) throws PluginException; /** @@ -118,27 +119,27 @@ public interface PluginOperator { * 如果配置文件目录存在同名的配置文件, 系统会自动备份该配置文件。备份文件命名规则为;[upload-config-backup][时间]_原jar名.jar * @param configFile 配置文件 * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean uploadConfigFile(MultipartFile configFile) throws Exception; + boolean uploadConfigFile(MultipartFile configFile) throws PluginException; /** * 通过路径备份文件。可备份插件和插件的配置文件。[适用于生产环境] * @param backDirPath 备份的目录路径 * @param sign 备份文件的自定义标识 * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean backupPlugin(Path backDirPath, String sign) throws Exception; + boolean backupPlugin(Path backDirPath, String sign) throws PluginException; /** * 通过插件id备份插件。[适用于生产环境] * @param pluginId 插件id * @param sign 备份文件的自定义标识 * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - boolean backupPlugin(String pluginId, String sign) throws Exception; + boolean backupPlugin(String pluginId, String sign) throws PluginException; /** * 获取插件信息 [适用于生产环境、开发环境] @@ -154,11 +155,11 @@ public interface PluginOperator { PluginInfo getPluginInfo(String pluginId); /** - * 得到插件文件的路径 [适用于生产环境] + * 得到插件文件的路径 * @return 返回插件路径列表 - * @throws Exception 异常信息 + * @throws PluginException 异常信息 */ - Set getPluginFilePaths() throws Exception; + Set getPluginFilePaths(); /** * 得到所有插件的包装类 [适用于生产环境、开发环境] diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 6a1fef3..79d2bed 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -1,15 +1,12 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.loader.PluginWrapper; +import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.PluginWrapper; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.module.PluginInfo; -import com.gitee.starblues.realize.UnRegistryValidator; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; @@ -36,7 +33,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws Exception { + public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException { if(isDisable()){ return false; } @@ -44,7 +41,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean verify(Path jarPath) throws Exception { + public boolean verify(Path jarPath) throws PluginException { if(isDisable()){ return false; } @@ -52,7 +49,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo install(Path jarPath) throws Exception { + public PluginInfo install(Path jarPath) throws PluginException { if(isDisable()){ return null; } @@ -60,7 +57,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo load(Path jarPath) throws Exception { + public PluginInfo load(Path jarPath) throws PluginException { if(isDisable()){ return null; } @@ -68,7 +65,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo load(MultipartFile pluginFile) throws Exception { + public PluginInfo load(MultipartFile pluginFile) throws PluginException { if(isDisable()){ return null; } @@ -76,7 +73,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean unload(String pluginId, boolean isBackup) throws Exception { + public boolean unload(String pluginId, boolean isBackup) throws PluginException { if(isDisable()){ return false; } @@ -84,7 +81,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean uninstall(String pluginId, boolean isBackup) throws Exception { + public boolean uninstall(String pluginId, boolean isBackup) throws PluginException { if(isDisable()){ return false; } @@ -93,7 +90,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean start(String pluginId) throws Exception { + public boolean start(String pluginId) throws PluginException { if(isDisable()){ return false; } @@ -101,7 +98,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean stop(String pluginId) throws Exception { + public boolean stop(String pluginId) throws PluginException { if(isDisable()){ return false; } @@ -110,7 +107,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws Exception { + public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException { if(isDisable()){ return null; } @@ -118,7 +115,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean installConfigFile(Path configFilePath) throws Exception { + public boolean installConfigFile(Path configFilePath) throws PluginException { if(isDisable()){ return false; } @@ -126,7 +123,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean uploadConfigFile(MultipartFile configFile) throws Exception { + public boolean uploadConfigFile(MultipartFile configFile) throws PluginException { if(isDisable()){ return false; } @@ -134,7 +131,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean backupPlugin(Path backDirPath, String sign) throws Exception { + public boolean backupPlugin(Path backDirPath, String sign) throws PluginException { if(isDisable()){ return false; } @@ -142,7 +139,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean backupPlugin(String pluginId, String sign) throws Exception { + public boolean backupPlugin(String pluginId, String sign) throws PluginException { if(isDisable()){ return false; } @@ -166,7 +163,7 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public Set getPluginFilePaths() throws Exception { + public Set getPluginFilePaths() { if(isDisable()){ return Collections.emptySet(); } @@ -207,7 +204,7 @@ public class PluginOperatorWrapper implements PluginOperator{ * @param pluginId 插件id * @throws Exception 检查异常 */ - private void checkIsUnRegistry(String pluginId) throws Exception{ + private void checkIsUnRegistry(String pluginId) throws PluginException{ // ConfigurableApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); // if(pluginApplicationContext == null){ // log.error("Plugin '{}' Not found ApplicationContext. So cannot found and execute unRegistryValidator", diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java deleted file mode 100644 index cce1c05..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/ConfigPluginStatusProvider.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.gitee.starblues.integration.pf4j; - -import org.pf4j.PluginStatusProvider; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author starBlues - * @version 2.4.0 - */ -@Deprecated -public class ConfigPluginStatusProvider implements PluginStatusProvider { - - private Set enablePluginIds = new HashSet<>(); - private Set disabledPlugins = new HashSet<>(); - - public ConfigPluginStatusProvider() { - this(null, null); - } - - public ConfigPluginStatusProvider(Set enablePluginIds, - Set disabledPluginIds) { - if(enablePluginIds != null && !enablePluginIds.isEmpty()){ - this.enablePluginIds.addAll(enablePluginIds); - } - if(disabledPluginIds != null && !disabledPluginIds.isEmpty()){ - this.disabledPlugins.addAll(disabledPluginIds); - } - } - - - @Override - public boolean isPluginDisabled(String pluginId) { - if(disabledPlugins.contains("*")){ - return true; - } - if (disabledPlugins.contains(pluginId)) { - return true; - } - - return !enablePluginIds.isEmpty() && !enablePluginIds.contains(pluginId); - } - - @Override - public void disablePlugin(String pluginId) { - if (isPluginDisabled(pluginId)) { - return; - } - disabledPlugins.add(pluginId); - enablePluginIds.remove(pluginId); - } - - @Override - public void enablePlugin(String pluginId) { - if (!isPluginDisabled(pluginId)) { - return; - } - disabledPlugins.remove(pluginId); - enablePluginIds.add(pluginId); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java deleted file mode 100644 index 818d173..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/DefaultPf4jFactory.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.gitee.starblues.integration.pf4j; - -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.integration.pf4j.descriptor.ManifestPluginDescriptorFinderExtend; -import com.gitee.starblues.integration.pf4j.descriptor.ResolvePropertiesPluginDescriptorFinder; -import com.gitee.starblues.integration.pf4j.descriptor.ResourcesPluginDescriptorFinder; -import org.pf4j.*; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.stream.Collectors; - -/** - * 默认的插件集成工厂 - * @author starBlues - * @version 2.4.0 - */ -@Deprecated -public class DefaultPf4jFactory implements Pf4jFactory { - - private final IntegrationConfiguration configuration; - - public DefaultPf4jFactory(IntegrationConfiguration configuration) { - this.configuration = configuration; - } - - - @Override - public PluginManager getPluginManager() { - if(configuration == null){ - throw new NullPointerException("IntegrationConfiguration is null"); - } - RuntimeMode environment = null; - if(environment == null){ - throw new RuntimeException("Configuration RuntimeMode is null" + configuration.environment()); - } - List sortInitPluginIds = configuration.sortInitPluginIds(); - DefaultPluginManager defaultPluginManager = null; - - List pluginDir = configuration.pluginPath(); - List pluginDirPath = pluginDir.stream().map(Paths::get).collect(Collectors.toList()); - - if(RuntimeMode.DEVELOPMENT == environment){ - // 开发环境下的插件管理者 - defaultPluginManager = new DefaultPluginManager(pluginDirPath){ - - @Override - protected void initialize() { - super.initialize(); - dependencyResolver = new SortDependencyResolver(sortInitPluginIds, versionManager); - } - - @Override - public RuntimeMode getRuntimeMode() { - System.setProperty("pf4j.mode", RuntimeMode.DEVELOPMENT.toString()); - return RuntimeMode.DEVELOPMENT; - } - - @Override - protected PluginDescriptorFinder createPluginDescriptorFinder() { - return DefaultPf4jFactory.getPluginDescriptorFinder(RuntimeMode.DEVELOPMENT); - } - - @Override - protected PluginLoader createPluginLoader() { - return new CompoundPluginLoader() - .add(new DevelopmentPluginLoader(this), this::isDevelopment); - } - - @Override - protected PluginStatusProvider createPluginStatusProvider() { - return new ConfigPluginStatusProvider( - configuration.enablePluginIds(), - configuration.disablePluginIds()); - } - - @Override - public PluginState stopPlugin(String pluginId) { - return stopPlugin(pluginId, configuration.stopDependents()); - } - }; - } else if(RuntimeMode.DEPLOYMENT == environment){ - // 运行环境下的插件管理者 - defaultPluginManager = new DefaultPluginManager(pluginDirPath){ - - @Override - protected void initialize() { - super.initialize(); - dependencyResolver = new SortDependencyResolver(sortInitPluginIds, versionManager); - } - - @Override - protected PluginDescriptorFinder createPluginDescriptorFinder() { - return DefaultPf4jFactory.getPluginDescriptorFinder(RuntimeMode.DEPLOYMENT); - } - - @Override - protected PluginStatusProvider createPluginStatusProvider() { - return new ConfigPluginStatusProvider( - configuration.enablePluginIds(), - configuration.disablePluginIds()); - } - - @Override - protected PluginLoader createPluginLoader() { - return new CompoundPluginLoader() - .add(new JarPluginLoader(this), this::isNotDevelopment) - .add(new DefaultPluginLoader(this), this::isNotDevelopment); - } - - @Override - public PluginState stopPlugin(String pluginId) { - return stopPlugin(pluginId, configuration.stopDependents()); - } - - }; - } - if(defaultPluginManager == null){ - throw new RuntimeException("Not found run environment " + configuration.environment()); - } - defaultPluginManager.setSystemVersion(configuration.version()); - defaultPluginManager.setExactVersionAllowed(configuration.exactVersionAllowed()); - return defaultPluginManager; - } - - - public static PluginDescriptorFinder getPluginDescriptorFinder(RuntimeMode runtimeMode){ - if(runtimeMode == RuntimeMode.DEPLOYMENT){ - // 生产 - return new CompoundPluginDescriptorFinder() - .add(new ResourcesPluginDescriptorFinder(runtimeMode)) - .add(new ManifestPluginDescriptorFinderExtend()); - } else { - // 开发 - return new CompoundPluginDescriptorFinder() - .add(new ResourcesPluginDescriptorFinder(runtimeMode)) - .add(new ResolvePropertiesPluginDescriptorFinder()) - .add(new ManifestPluginDescriptorFinderExtend()); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java deleted file mode 100644 index 1b3eac1..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/JarPluginLoader.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.integration.pf4j; - -import org.pf4j.*; -import org.pf4j.util.FileUtils; - -import java.nio.file.Files; -import java.nio.file.Path; - -/** - * 生成环境下jar包的加载器 - * @author starBlues - * @version 2.4.0 - */ -@Deprecated -public class JarPluginLoader implements PluginLoader { - - protected PluginManager pluginManager; - - public JarPluginLoader(PluginManager pluginManager) { - this.pluginManager = pluginManager; - } - - @Override - public boolean isApplicable(Path pluginPath) { - return Files.exists(pluginPath) && FileUtils.isJarFile(pluginPath); - } - - @Override - public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) { - PluginClassLoader pluginClassLoader = - new PluginClassLoader(pluginManager, pluginDescriptor, - this.getClass().getClassLoader(), - ClassLoadingStrategy.APD); - pluginClassLoader.addFile(pluginPath.toFile()); - return pluginClassLoader; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java deleted file mode 100644 index b1b7c81..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/Pf4jFactory.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gitee.starblues.integration.pf4j; - -import com.gitee.starblues.integration.application.DefaultPluginApplication; -import org.pf4j.PluginManager; - -/** - * Pf4j 集成工厂。获取Pf4j的PluginManager对象 - * @author starBlues - * @version 2.2.0 - * @see DefaultPluginApplication - */ -@Deprecated -public interface Pf4jFactory { - - /** - * 得到插件管理者 - * @return 插件管理者 - */ - PluginManager getPluginManager(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java deleted file mode 100644 index 0b54e81..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/SortDependencyResolver.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.gitee.starblues.integration.pf4j; - -import org.pf4j.DependencyResolver; -import org.pf4j.PluginDescriptor; -import org.pf4j.VersionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.ReflectionUtils; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -/** - * 控制插件启动顺序 - * @author starBlues - * @version 2.4.0 - */ -@Deprecated -public class SortDependencyResolver extends DependencyResolver { - - private final static Logger LOGGER = LoggerFactory.getLogger(SortDependencyResolver.class); - - private final List sortInitPluginIds; - - public SortDependencyResolver(List sortInitPluginIds, VersionManager versionManager) { - super(versionManager); - this.sortInitPluginIds = sortInitPluginIds; - } - - @Override - public Result resolve(List plugins) { - Result resolve = super.resolve(plugins); - if(sortInitPluginIds == null || sortInitPluginIds.isEmpty()){ - return resolve; - } - List sortedPlugins = resolve.getSortedPlugins(); - List newSortPluginIds = new ArrayList<>(sortedPlugins.size()); - for (String sortPluginId : sortInitPluginIds) { - Iterator iterator = sortedPlugins.iterator(); - while (iterator.hasNext()){ - String id = iterator.next(); - if(Objects.equals(id, sortPluginId)){ - newSortPluginIds.add(id); - iterator.remove(); - } - } - } - if(!sortedPlugins.isEmpty()){ - newSortPluginIds.addAll(sortedPlugins); - } - - return getSortResult(resolve, newSortPluginIds); - } - - @SuppressWarnings("unchecked") - private Result getSortResult(Result resolve, List newSortPluginIds ){ - try { - Field sortedPluginsField = ReflectionUtils.findField(Result.class, "sortedPlugins"); - List sortedPlugins = null; - if(sortedPluginsField != null){ - if (!sortedPluginsField.isAccessible()) { - sortedPluginsField.setAccessible(true); - } - sortedPlugins = (List) sortedPluginsField.get(resolve); - } - if(sortedPlugins == null){ - return resolve; - } - sortedPlugins.clear(); - sortedPlugins.addAll(newSortPluginIds); - return resolve; - } catch (Exception e){ - LOGGER.error("Set plugin init sort failure. use default sort init plugin. " + e.getMessage()); - return resolve; - } - } - - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java deleted file mode 100644 index eaa04f7..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/DefaultPluginDescriptorExtend.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gitee.starblues.integration.pf4j.descriptor; - -import org.pf4j.DefaultPluginDescriptor; - -/** - * 扩展 DefaultPluginDescriptor 的功能 - * @author starBlues - * @version 2.4.5 - */ -@Deprecated -public class DefaultPluginDescriptorExtend extends DefaultPluginDescriptor implements PluginDescriptorExtend{ - - - private String configFileName; - private String configFileProfile; - - public DefaultPluginDescriptorExtend() { - super(); - } - - public DefaultPluginDescriptorExtend(String pluginId, String pluginDescription, String pluginClass, - String version, String requires, String provider, String license) { - super(pluginId, pluginDescription, pluginClass, version, requires, provider, license); - } - - @Override - public String getConfigFileName() { - return configFileName; - } - - @Override - public String getConfigFileProfile() { - return configFileProfile; - } - - public void setConfigFileName(String configFileName) { - this.configFileName = configFileName; - } - - public void setConfigFileProfile(String configFileProfile) { - this.configFileProfile = configFileProfile; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java deleted file mode 100644 index f6dee34..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ManifestPluginDescriptorFinderExtend.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gitee.starblues.integration.pf4j.descriptor; - -import org.pf4j.DefaultPluginDescriptor; -import org.pf4j.ManifestPluginDescriptorFinder; -import org.pf4j.PluginDescriptor; -import org.pf4j.util.StringUtils; - -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -/** - * 扩展 ManifestPluginDescriptorFinderExtend 的功能 - * @author starBlues - * @version 2.4.5 - */ -@Deprecated -public class ManifestPluginDescriptorFinderExtend extends ManifestPluginDescriptorFinder { - - public static final String PLUGIN_CONFIG_FILE_NAME = "Plugin-ConfigFileName"; - public static final String PLUGIN_CONFIG_FILE_PROFILE = "Plugin-ConfigFileProfile"; - - - @Override - protected PluginDescriptor createPluginDescriptor(Manifest manifest) { - DefaultPluginDescriptorExtend pluginDescriptor = (DefaultPluginDescriptorExtend) - super.createPluginDescriptor(manifest); - Attributes attributes = manifest.getMainAttributes(); - String configFileName = attributes.getValue(PLUGIN_CONFIG_FILE_NAME); - if (StringUtils.isNullOrEmpty(configFileName)) { - pluginDescriptor.setConfigFileName(configFileName); - } - String configFileProfile = attributes.getValue(PLUGIN_CONFIG_FILE_PROFILE); - if (!StringUtils.isNullOrEmpty(configFileProfile)) { - pluginDescriptor.setConfigFileProfile(configFileProfile); - } - return pluginDescriptor; - } - - @Override - protected DefaultPluginDescriptor createPluginDescriptorInstance() { - return new DefaultPluginDescriptorExtend(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java deleted file mode 100644 index da7708c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/PluginDescriptorExtend.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.integration.pf4j.descriptor; - -import org.pf4j.PluginDescriptor; - -/** - * 扩展 PluginDescriptor 的功能 - * @author starBlues - * @version 2.4.5 - */ -@Deprecated -public interface PluginDescriptorExtend extends PluginDescriptor { - - - /** - * 获取配置文件名称 - * @return 文件名称 - */ - String getConfigFileName(); - - /** - * 配置文件Profile - * @return Profile - */ - String getConfigFileProfile(); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java deleted file mode 100644 index f4bf3d7..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResolvePropertiesPluginDescriptorFinder.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.gitee.starblues.integration.pf4j.descriptor; - -import org.pf4j.DefaultPluginDescriptor; -import org.pf4j.PluginDescriptor; -import org.pf4j.PluginRuntimeException; -import org.pf4j.PropertiesPluginDescriptorFinder; -import org.pf4j.util.FileUtils; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Properties; - -/** - * 解决乱码问题 - * - * @author starBlues - * @version 2.4.5 - */ -@Deprecated -public class ResolvePropertiesPluginDescriptorFinder extends PropertiesPluginDescriptorFinder { - - @Override - protected Properties readProperties(Path pluginPath) { - Path propertiesPath = getPropertiesPath(pluginPath, propertiesFileName); - return getProperties(propertiesPath); - } - - @Override - protected PluginDescriptor createPluginDescriptor(Properties properties) { - DefaultPluginDescriptorExtend pluginDescriptor = (DefaultPluginDescriptorExtend) - super.createPluginDescriptor(properties); - return ResourcesPluginDescriptorFinder.resolvePluginDescriptor(properties, pluginDescriptor); - } - - @Override - protected DefaultPluginDescriptor createPluginDescriptorInstance() { - return new DefaultPluginDescriptorExtend(); - } - - public static Properties getProperties(Path propertiesPath){ - if (propertiesPath == null) { - throw new PluginRuntimeException("Cannot find the properties path"); - } - - if (Files.notExists(propertiesPath)) { - throw new PluginRuntimeException("Cannot find '{}' path", propertiesPath); - } - - Properties properties = new Properties(); - - try (InputStreamReader input = new InputStreamReader(Files.newInputStream(propertiesPath), - StandardCharsets.UTF_8)) { - properties.load(input); - } catch (IOException e) { - throw new PluginRuntimeException(e); - } finally { - FileUtils.closePath(propertiesPath); - } - - return properties; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java deleted file mode 100644 index 42e4125..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/pf4j/descriptor/ResourcesPluginDescriptorFinder.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.gitee.starblues.integration.pf4j.descriptor; - -import org.pf4j.DefaultPluginDescriptor; -import org.pf4j.PluginDescriptor; -import org.pf4j.PropertiesPluginDescriptorFinder; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; - - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Properties; - -/** - * 读取 resources 目录下的 plugin.properties 文件 - * @author starBlues - * @version 2.4.5 - */ -@Deprecated -public class ResourcesPluginDescriptorFinder extends PropertiesPluginDescriptorFinder { - - public static final String PLUGIN_CONFIG_FILE_NAME = "plugin.configFileName"; - public static final String PLUGIN_CONFIG_FILE_PROFILE = "plugin.configFileProfile"; - - private final RuntimeMode runtimeMode; - - public ResourcesPluginDescriptorFinder(RuntimeMode runtimeMode) { - this.runtimeMode = runtimeMode; - } - - - @Override - public boolean isApplicable(Path pluginPath) { - Path propFilePath = getPropFilePath(pluginPath); - return super.isApplicable(propFilePath); - } - - @Override - public PluginDescriptor find(Path pluginPath) { - Path propFilePath = getPropFilePath(pluginPath); - return super.find(propFilePath); - } - - @Override - protected Properties readProperties(Path pluginPath) { - Path propertiesPath = getPropertiesPath(pluginPath, propertiesFileName); - return ResolvePropertiesPluginDescriptorFinder.getProperties(propertiesPath); - } - - @Override - protected PluginDescriptor createPluginDescriptor(Properties properties) { - DefaultPluginDescriptorExtend pluginDescriptor = (DefaultPluginDescriptorExtend) - super.createPluginDescriptor(properties); - return resolvePluginDescriptor(properties, pluginDescriptor); - } - - static PluginDescriptor resolvePluginDescriptor(Properties properties, - DefaultPluginDescriptorExtend pluginDescriptor){ - String configFileName = properties.getProperty(PLUGIN_CONFIG_FILE_NAME); - if (!StringUtils.isNullOrEmpty(configFileName)) { - pluginDescriptor.setConfigFileName(configFileName); - } - - String configFileProfile = properties.getProperty(PLUGIN_CONFIG_FILE_PROFILE); - if (!StringUtils.isNullOrEmpty(configFileProfile)) { - pluginDescriptor.setConfigFileProfile(configFileProfile); - } - - return pluginDescriptor; - } - - @Override - protected DefaultPluginDescriptor createPluginDescriptorInstance() { - return new DefaultPluginDescriptorExtend(); - } - - private Path getPropFilePath(Path pluginPath){ - if(runtimeMode == RuntimeMode.DEPLOYMENT){ - // 生产环境 - return pluginPath; - } else { - // 开发环境 - return Paths.get(pluginPath.toString(), "src", "main", "resources"); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePlugin.java deleted file mode 100644 index 9d55eab..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePlugin.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.gitee.starblues.realize; - -import org.pf4j.Plugin; -import org.pf4j.PluginWrapper; - -/** - * 插件包要继承的抽象类。 - * 注意: 实现该类的子类无法使用依赖注入 - * @author starBlues - * @version 2.4.0 - */ -public abstract class BasePlugin extends Plugin { - - private final BasePluginExtend basePluginExtend; - private String springBootConfigFilePath; - - public BasePlugin(PluginWrapper wrapper) { - super(wrapper); - this.basePluginExtend = new BasePluginExtend(this); - } - - - @Override - public final void start() { - try { - startEvent(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - basePluginExtend.startEvent(); - } - } - - - @Override - public final void delete() { - try { - deleteEvent(); - } catch (Exception e){ - e.printStackTrace(); - } finally { - basePluginExtend.deleteEvent(); - } - - } - - @Override - public final void stop() { - try { - stopEvent(); - } catch (Exception e){ - e.printStackTrace(); - } finally { - basePluginExtend.startEvent(); - } - } - - /** - * 扫描包。默认为当前类包名。可重写自定义包名 - * @return 包名 - */ - public String scanPackage(){ - // 获取当前实现类的包名 - return this.getClass().getPackage().getName(); - } - - /** - * 得到插件扩展的信息 - * @return BasePluginExtend - */ - public final BasePluginExtend getBasePluginExtend() { - return basePluginExtend; - } - - /** - * 启动事件. Spring 容器都没有准备。无法使用注入。 - */ - protected void startEvent(){ - - } - - /** - * 删除事件. 在插件删除时触发。 - */ - protected void deleteEvent(){ - - } - - /** - * 停止事件. 在插件停止时触发。 - */ - protected void stopEvent(){ - - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePluginExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePluginExtend.java deleted file mode 100644 index 1a0ce32..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/BasePluginExtend.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gitee.starblues.realize; - -/** - * 扩展的BasePlugin信息 - * - * @author starBlues - * @version 2.4.0 - */ -public final class BasePluginExtend { - - private final BasePlugin basePlugin; - private Long startTimestamp; - private Long stopTimestamp; - - BasePluginExtend(BasePlugin basePlugin){ - this.basePlugin = basePlugin; - } - - public long getStartTimestamp() { - return startTimestamp; - } - - public Long getStopTimestamp() { - return stopTimestamp; - } - - void startEvent(){ - startTimestamp = System.currentTimeMillis(); - } - - void deleteEvent(){ - stopTimestamp = System.currentTimeMillis(); - } - - void stopEvent(){ - stopTimestamp = System.currentTimeMillis(); - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java index 09570e1..a3f600e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java @@ -2,8 +2,6 @@ package com.gitee.starblues.realize; import com.gitee.starblues.integration.operator.module.PluginInfo; import com.gitee.starblues.utils.SpringBeanUtils; -import org.pf4j.PluginManager; -import org.pf4j.PluginWrapper; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.context.ApplicationContext; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/OneselfListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/OneselfListener.java deleted file mode 100644 index ff7fc90..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/OneselfListener.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.gitee.starblues.realize; - -import com.gitee.starblues.utils.OrderPriority; - -/** - * 监听本插件模块事件的监听者接口 - * - * @author starBlues - * @version 2.4.0 - */ -public interface OneselfListener { - - /** - * 执行优先级。用于多个监听器的时候 - * @return OrderPriority - */ - OrderPriority order(); - - - /** - * 启动事件 - * @param basePlugin 当前插件实现的BasePlugin类 - */ - void startEvent(BasePlugin basePlugin); - - - /** - * 停止事件 - * @param basePlugin 当前插件实现的BasePlugin类 - */ - void stopEvent(BasePlugin basePlugin); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java index c7df513..bfd80d6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java @@ -4,7 +4,6 @@ import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.SpringBeanUtils; import org.springframework.context.ApplicationContext; -import javax.annotation.Resource; import java.util.List; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java index 59e226e..51b6184 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java @@ -7,8 +7,9 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** + * jdk 同类型参数的代理工厂 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JdkSameTypeParamProxyFactory implements ProxyFactory, InvocationHandler { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java index 2d765e8..439e7a5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java @@ -2,8 +2,9 @@ package com.gitee.starblues.spring; /** + * 主程序 ApplicationContext 接口 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface MainApplicationContext extends ApplicationContext { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java index 285b7c7..0e74bff 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java @@ -1,8 +1,9 @@ package com.gitee.starblues.spring; /** + * 主程序 ApplicationContext 的实现 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class MainApplicationContextProxy extends ApplicationContextProxy implements MainApplicationContext{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java deleted file mode 100644 index bc3586f..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/PluginSpringApplication.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gitee.starblues.spring; - -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.ResourceLoader; - -/** - * 插件 SpringApplication - * @author starBlues - * @version 3.0.0 - */ -public interface PluginSpringApplication { - - /** - * 运行 - * @return ConfigurableApplicationContext - * @throws Exception Exception - */ - GenericApplicationContext run() throws Exception; - - /** - * 关闭 - */ - void close(); - - - /** - * 得到 ApplicationContext - * @return GenericApplicationContext - */ - GenericApplicationContext getApplicationContext(); - - /** - * 得到 ResourceLoader - * @return ResourceLoader - */ - ResourceLoader getResourceLoader(); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java index 896a2cd..feb65e3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java @@ -7,6 +7,12 @@ package com.gitee.starblues.spring; */ public interface ProxyFactory { + /** + * 获取代理类 + * @param interfacesClass 需代理的接口 + * @param 代理实现的泛型 + * @return 代理实现 + */ T getObject(Class interfacesClass); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java index ea74c3d..e44ee69 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java @@ -3,8 +3,9 @@ package com.gitee.starblues.spring; import org.springframework.beans.factory.ListableBeanFactory; /** + * spring bean factory 封装接口 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface SpringBeanFactory extends ListableBeanFactory { } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java index b080647..04e737a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java @@ -1,11 +1,16 @@ package com.gitee.starblues.spring; /** + * 插件把柄接口 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface SpringPluginHook extends AutoCloseable{ + /** + * 返回插件 ApplicationContext + * @return ApplicationContext + */ ApplicationContext getApplicationContext(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java index 409ce4a..4bfa682 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java @@ -1,7 +1,7 @@ package com.gitee.starblues.spring.extract; import com.gitee.starblues.annotation.Extract; -import org.pf4j.util.StringUtils; +import com.gitee.starblues.utils.ObjectUtils; import java.util.Objects; @@ -69,20 +69,18 @@ public class ExtractCoordinate { return false; } ExtractCoordinate that = (ExtractCoordinate) o; - if(StringUtils.isNotNullOrEmpty(bus) && - StringUtils.isNotNullOrEmpty(scene) && - StringUtils.isNotNullOrEmpty(useCase)){ + if(!ObjectUtils.isEmpty(bus) && !ObjectUtils.isEmpty(scene) && !ObjectUtils.isEmpty(useCase)){ return Objects.equals(getBus(), that.getBus()) && Objects.equals(getScene(), that.getScene()) && Objects.equals(getUseCase(), that.getUseCase()); } - if(StringUtils.isNotNullOrEmpty(bus) && StringUtils.isNotNullOrEmpty(scene)){ + if(!ObjectUtils.isEmpty(bus) && !ObjectUtils.isEmpty(scene)){ return Objects.equals(getBus(), that.getBus()) && Objects.equals(getScene(), that.getScene()); } - if(StringUtils.isNotNullOrEmpty(bus)){ + if(!ObjectUtils.isEmpty(bus)){ return Objects.equals(getBus(), that.getBus()); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AopUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AopUtils.java deleted file mode 100644 index 9fd2bf6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AopUtils.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.gitee.starblues.utils; - -import org.pf4j.PluginWrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.aop.framework.ProxyProcessorSupport; -import org.springframework.context.ApplicationContext; -import org.springframework.util.ClassUtils; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * AOP 无法找到插件类的解决工具类(被遗弃) - * - * @author starBlues - * @version 2.4.0 - */ -@Deprecated -public class AopUtils { - - private static final Logger LOG = LoggerFactory.getLogger(AopUtils.class); - - private static AtomicBoolean isRecover = new AtomicBoolean(true); - - private static final List PROXY_WRAPPERS = new ArrayList<>(); - - private AopUtils(){} - - /** - * 解决AOP无法代理到插件类的问题 - * @param applicationContext 插件包装类 - */ - public static synchronized void registered(ApplicationContext applicationContext) { - Map beansOfType = applicationContext - .getBeansOfType(ProxyProcessorSupport.class); - if(beansOfType.isEmpty()){ - LOG.warn("Not found ProxyProcessorSupports, And Plugin AOP can't used"); - return; - } - for (ProxyProcessorSupport support : beansOfType.values()) { - if(support == null){ - continue; - } - ProxyWrapper proxyWrapper = new ProxyWrapper(); - proxyWrapper.setProxyProcessorSupport(support); - PROXY_WRAPPERS.add(proxyWrapper); - } - } - - /** - * 解决AOP无法代理到插件类的问题 - * @param pluginWrapper 插件包装类 - */ - public static synchronized void resolveAop(PluginWrapper pluginWrapper){ - if(PROXY_WRAPPERS.isEmpty()){ - LOG.warn("ProxyProcessorSupports is empty, And Plugin AOP can't used"); - return; - } - if(!isRecover.get()){ - throw new RuntimeException("Not invoking resolveAop(). And can not AopUtils.resolveAop"); - } - isRecover.set(false); - ClassLoader pluginClassLoader = pluginWrapper.getPluginClassLoader(); - for (ProxyWrapper proxyWrapper : PROXY_WRAPPERS) { - ProxyProcessorSupport proxyProcessorSupport = proxyWrapper.getProxyProcessorSupport(); - ClassLoader classLoader = getClassLoader(proxyProcessorSupport); - proxyWrapper.setOriginalClassLoader(classLoader); - proxyProcessorSupport.setProxyClassLoader(pluginClassLoader); - } - } - - /** - * 恢复AOP 的 BeanClassLoader - */ - public static synchronized void recoverAop(){ - if(PROXY_WRAPPERS.isEmpty()){ - return; - } - for (ProxyWrapper proxyWrapper : PROXY_WRAPPERS) { - ProxyProcessorSupport proxyProcessorSupport = proxyWrapper.getProxyProcessorSupport(); - proxyProcessorSupport.setProxyClassLoader(proxyWrapper.getOriginalClassLoader()); - } - isRecover.set(true); - } - - /** - * 反射获取代理支持处理者的ClassLoader属性值 - * @param proxyProcessorSupport proxyProcessorSupport - * @return ClassLoader - */ - private static ClassLoader getClassLoader(ProxyProcessorSupport proxyProcessorSupport){ - Class aClass = proxyProcessorSupport.getClass(); - while (aClass != null){ - if(aClass != ProxyProcessorSupport.class){ - aClass = aClass.getSuperclass(); - continue; - } - Field[] declaredFields = aClass.getDeclaredFields(); - if(declaredFields == null || declaredFields.length == 0){ - break; - } - for (Field field : declaredFields) { - if(Objects.equals("proxyClassLoader", field.getName()) || field.getType() == ClassLoader.class){ - field.setAccessible(true); - try { - Object o = field.get(proxyProcessorSupport); - if(o instanceof ClassLoader){ - return (ClassLoader) o; - } else { - LOG.warn("Get {} classLoader type not is ClassLoader type, And Return DefaultClassLoader", - aClass.getName()); - return ClassUtils.getDefaultClassLoader(); - } - } catch (IllegalAccessException e) { - LOG.error("Get {} classLoader failure {}, And Return DefaultClassLoader", - aClass.getName(), - e.getMessage()); - return ClassUtils.getDefaultClassLoader(); - } - } - } - - } - LOG.warn("Not found classLoader field, And Return DefaultClassLoader", - aClass.getName()); - return ClassUtils.getDefaultClassLoader(); - } - - - - /** - * 代理包装类 - */ - private static class ProxyWrapper{ - ProxyProcessorSupport proxyProcessorSupport; - ClassLoader originalClassLoader; - - ProxyProcessorSupport getProxyProcessorSupport() { - return proxyProcessorSupport; - } - - void setProxyProcessorSupport(ProxyProcessorSupport proxyProcessorSupport) { - this.proxyProcessorSupport = proxyProcessorSupport; - } - - ClassLoader getOriginalClassLoader() { - return originalClassLoader; - } - - void setOriginalClassLoader(ClassLoader originalClassLoader) { - this.originalClassLoader = originalClassLoader; - } - - @Override - public String toString() { - return "ProxyWrapper{" + - "proxyProcessorSupport=" + proxyProcessorSupport + - ", originalClassLoader=" + originalClassLoader + - '}'; - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java index 519b0b8..68b2973 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java @@ -1,10 +1,8 @@ package com.gitee.starblues.utils; import com.gitee.starblues.integration.IntegrationConfiguration; -import org.pf4j.util.StringUtils; import java.io.File; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.function.Function; @@ -13,7 +11,7 @@ import java.util.function.Function; * 通用工具 * * @author starBlues - * @version 2.2.1 + * @version 3.0.0 */ public class CommonUtils { @@ -115,7 +113,7 @@ public class CommonUtils { int length = paths.length; for (int i = 0; i < length; i++) { String path = paths[i]; - if(StringUtils.isNullOrEmpty(path)) { + if(ObjectUtils.isEmpty(path)) { continue; } if((i < length - 1) && path.endsWith("/")){ @@ -144,7 +142,7 @@ public class CommonUtils { int length = paths.length; for (int i = 0; i < length; i++) { String path = paths[i]; - if(StringUtils.isNullOrEmpty(path)) { + if(ObjectUtils.isEmpty(path)) { continue; } if(i > 0){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java new file mode 100644 index 0000000..8b31208 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java @@ -0,0 +1,20 @@ +package com.gitee.starblues.utils; + +import java.lang.reflect.Field; + +/** + * @author starBlues + * @version 1.0 + */ +@FunctionalInterface +public interface FieldFilter { + + /** + * 过滤 + * @param field 当前字段 + * @return true 允许, false 不允许 + */ + boolean filter(Field field); + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java new file mode 100644 index 0000000..d89ea4a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java @@ -0,0 +1,25 @@ +package com.gitee.starblues.utils; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; + +/** + * @author starBlues + * @version 3.0.0 + */ +public abstract class MsgUtils { + + private MsgUtils(){} + + public static String getPluginUnique(PluginDescriptor pluginDescriptor){ + return pluginDescriptor.getPluginId() + "@" + pluginDescriptor.getPluginVersion(); + } + + public static String getThrowableMsg(Throwable throwable){ + return ObjectUtils.isEmpty(throwable.getMessage()) ? "" : throwable.getMessage(); + } + + public static String getThrowableMsg(String message){ + return ObjectUtils.isEmpty(message) ? "" : message; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java index bdd2923..27afded 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java @@ -1,6 +1,5 @@ package com.gitee.starblues.utils; -import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; import java.lang.reflect.Array; @@ -55,7 +54,7 @@ public class ObjectUtils { return false; } - public static boolean hasText(@Nullable CharSequence str) { + public static boolean hasText(CharSequence str) { return (str != null && str.length() > 0 && containsText(str)); } @@ -73,16 +72,16 @@ public class ObjectUtils { } - public static String[] commaDelimitedListToStringArray(@Nullable String str) { + public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } - public static String[] delimitedListToStringArray(@Nullable String str, @Nullable String delimiter) { + public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, null); } public static String[] delimitedListToStringArray( - @Nullable String str, @Nullable String delimiter, @Nullable String charsToDelete) { + String str, String delimiter, String charsToDelete) { if (str == null) { return EMPTY_STRING_ARRAY; @@ -112,12 +111,12 @@ public class ObjectUtils { return toStringArray(result); } - public static String[] toStringArray(@Nullable Collection collection) { + public static String[] toStringArray(Collection collection) { return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); } - public static String deleteAny(String inString, @Nullable String charsToDelete) { + public static String deleteAny(String inString, String charsToDelete) { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; } @@ -140,16 +139,16 @@ public class ObjectUtils { return (str != null && !str.isEmpty()); } - public static String collectionToCommaDelimitedString(@Nullable Collection coll) { + public static String collectionToCommaDelimitedString(Collection coll) { return collectionToDelimitedString(coll, ","); } - public static String collectionToDelimitedString(@Nullable Collection coll, String delim) { + public static String collectionToDelimitedString(Collection coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } public static String collectionToDelimitedString( - @Nullable Collection coll, String delim, String prefix, String suffix) { + Collection coll, String delim, String prefix, String suffix) { if (CollectionUtils.isEmpty(coll)) { return ""; @@ -167,7 +166,7 @@ public class ObjectUtils { } - public static boolean containsElement(@Nullable Object[] array, Object element) { + public static boolean containsElement(Object[] array, Object element) { if (array == null) { return false; } @@ -179,7 +178,7 @@ public class ObjectUtils { return false; } - public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) { + public static boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } @@ -195,12 +194,12 @@ public class ObjectUtils { return false; } - public static boolean endsWithIgnoreCase(@Nullable String str, @Nullable String suffix) { + public static boolean endsWithIgnoreCase(String str, String suffix) { return (str != null && suffix != null && str.length() >= suffix.length() && str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length())); } - public static String getFilenameExtension(@Nullable String path) { + public static String getFilenameExtension(String path) { if (path == null) { return null; } @@ -287,7 +286,7 @@ public class ObjectUtils { } - public static String replace(String inString, String oldPattern, @Nullable String newPattern) { + public static String replace(String inString, String oldPattern, String newPattern) { if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { return inString; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java index b9d7388..def234d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java @@ -1,13 +1,11 @@ package com.gitee.starblues.utils; -import com.gitee.starblues.annotation.ConfigDefinition; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; +import com.gitee.starblues.core.RuntimeMode; /** * 插件配置工具类 * @author starBlues - * @version 2.4.3 + * @version 3.0.0 */ public class PluginConfigUtils { @@ -27,14 +25,14 @@ public class PluginConfigUtils { String prodSuffix, String devSuffix, RuntimeMode runtimeMode){ - if(StringUtils.isNullOrEmpty(fileName)){ + if(ObjectUtils.isEmpty(fileName)){ return null; } String suffix = ""; - if(runtimeMode == RuntimeMode.DEPLOYMENT){ + if(runtimeMode == RuntimeMode.PROD){ // 生产环境 suffix = prodSuffix; - } else if(runtimeMode == RuntimeMode.DEVELOPMENT){ + } else if(runtimeMode == RuntimeMode.DEV){ // 开发环境 suffix = devSuffix; } @@ -50,7 +48,7 @@ public class PluginConfigUtils { } public static String joinConfigFileName(String fileName, String suffix){ - if(StringUtils.isNullOrEmpty(fileName)){ + if(ObjectUtils.isEmpty(fileName)){ return null; } String fileNamePrefix; @@ -67,7 +65,7 @@ public class PluginConfigUtils { if(suffix == null){ suffix = ""; } - if(StringUtils.isNotNullOrEmpty(suffix) && !suffix.startsWith(DO)){ + if(ObjectUtils.isEmpty(suffix) && !suffix.startsWith(DO)){ suffix = DO + suffix; } return fileNamePrefix + suffix + fileNamePrefixSuffix; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java index d9230ac..6e311eb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java @@ -1,8 +1,7 @@ package com.gitee.starblues.utils; -import com.gitee.starblues.annotation.ConfigDefinition; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; + +import org.springframework.util.ResourceUtils; import java.io.File; import java.io.FileInputStream; @@ -13,14 +12,17 @@ import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.security.MessageDigest; import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; /** * 插件文件工具类 * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public final class PluginFileUtils { @@ -101,22 +103,20 @@ public final class PluginFileUtils { return path; } - /** - * 是否为 zip 文件 - * @param path 文件路径 - * @return boolean - */ - public static boolean isZipFile(Path path) { - return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".zip"); + public static File getExistFile(String pathStr){ + File file = new File(pathStr); + if(file.exists()){ + return file; + } + return null; } - /** - * 是否为 jar 文件 - * @param path 文件路径 - * @return boolean - */ - public static boolean isJarFile(Path path) { - return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".jar"); + public static File getExistFile(String pathStr, Supplier secondPathSupplier){ + File existFile = getExistFile(pathStr); + if(existFile != null){ + return existFile; + } + return getExistFile(secondPathSupplier.get()); } /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 9c9aab6..e207b9e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -27,10 +27,21 @@ public abstract class ReflectionUtils { } public static Field findField(Class clazz, String fieldName, Class fieldType) { - Objects.requireNonNull(clazz, "clazz must not be null"); if(fieldName == null && fieldType == null){ throw new IllegalArgumentException("fieldName or fieldType of the field must be specified"); } + return findField(clazz, (field)->{ + if ((fieldName == null || fieldName.equals(field.getName())) && + (fieldType == null || fieldType.equals(field.getType()))) { + return true; + } + return false; + }); + } + + public static Field findField(Class clazz, FieldFilter filter) { + Objects.requireNonNull(clazz, "clazz must not be null"); + Field[] declaredFields = clazz.getDeclaredFields(); if(declaredFields.length == 0){ @@ -38,13 +49,12 @@ public abstract class ReflectionUtils { } while (true){ for (Field field : declaredFields) { - if ((fieldName == null || fieldName.equals(field.getName())) && - (fieldType == null || fieldType.equals(field.getType()))) { + if(filter.filter(field)){ return field; } } clazz = clazz.getSuperclass(); - if(clazz == null){ + if(clazz == null || clazz == Object.class){ break; } declaredFields = clazz.getDeclaredFields(); @@ -61,16 +71,6 @@ public abstract class ReflectionUtils { public static Object getField(Object o, String fieldName, Class fieldType) { Class currentClass = o.getClass(); Field field = findField(currentClass, fieldName, fieldType); - while (true){ - if(field != null) { - break; - } - currentClass = currentClass.getSuperclass(); - if(currentClass == null){ - break; - } - field = findField(currentClass, fieldName, fieldType); - } if(field == null){ return null; } @@ -82,6 +82,7 @@ public abstract class ReflectionUtils { } } + public static void setField(Object o, String fieldName, Object value) { setField(o, fieldName, null, value); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 5e187a7..c849de4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -1,15 +1,14 @@ package com.gitee.starblues.utils; -import com.gitee.starblues.integration.IntegrationConfiguration; -import org.pf4j.PluginWrapper; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; import java.net.MalformedURLException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Consumer; /** * 对资源解析的工具类 @@ -21,6 +20,8 @@ public class ResourceUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class); + public static final String URL_PROTOCOL_FILE = "file"; + public final static String TYPE_FILE = "file"; public final static String TYPE_CLASSPATH = "classpath"; public final static String TYPE_PACKAGE = "package"; @@ -40,7 +41,7 @@ public class ResourceUtils { * @return 整合出完整的匹配路绝 */ public static String getMatchLocation(String locationMatch){ - if(StringUtils.isNullOrEmpty(locationMatch)){ + if(ObjectUtils.isEmpty(locationMatch)){ return null; } String classPathType = TYPE_CLASSPATH + TYPE_SPLIT; @@ -72,6 +73,45 @@ public class ResourceUtils { return locationMatch.startsWith(TYPE_PACKAGE + TYPE_SPLIT); } + /** + * 是否为 zip 文件 + * @param path 文件路径 + * @return boolean + */ + public static boolean isZipFile(Path path) { + return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".zip"); + } + + /** + * 是否为 jar 文件 + * @param path 文件路径 + * @return boolean + */ + public static boolean isJarFile(Path path) { + return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".jar"); + } + + public static boolean isDirFile(Path path) { + return path.toFile().isDirectory(); + } + + public static void listFile(File rootFile, Consumer consumerFile){ + if(rootFile == null || !rootFile.exists()){ + return; + } + final File[] listFiles = rootFile.listFiles(); + if(listFiles == null || listFiles.length == 0){ + return; + } + for (File listFile : listFiles) { + if(listFile.isDirectory()){ + listFile(listFile, consumerFile); + continue; + } + consumerFile.accept(listFile); + } + } + // /** // * 根据 ~ 标记获取, 得到绝对路径 // * @param pluginRegistryInfo pluginRegistryInfo diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java index d056975..d4e349e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java @@ -1,7 +1,6 @@ package com.gitee.starblues.utils; -import org.pf4j.PluginWrapper; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.util.ClassUtils; @@ -131,31 +130,4 @@ public class ScanUtils { }); } - - /** - * 扫描jar包中的类。 - * - * @param basePackage 包名 - * @param pluginWrapper jar的PluginWrapper - * @return 类全路径 - * @throws IOException 扫描异常 - */ - public static Set scanClassPackageName(String basePackage, PluginWrapper pluginWrapper) throws IOException { - String pluginPath = pluginWrapper.getPluginPath().toString(); - Set classPackageNames = new HashSet<>(); - try (JarFile jarFile = new JarFile(pluginPath)) { - Enumeration jarEntries = jarFile.entries(); - while (jarEntries.hasMoreElements()) { - JarEntry entry = jarEntries.nextElement(); - String jarEntryName = entry.getName(); - if (jarEntryName.contains(".class") && jarEntryName.replaceAll("/", ".").startsWith(basePackage)) { - String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replace("/", "."); - classPackageNames.add(className); - } - } - } - return classPackageNames; - } - - } diff --git a/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/PluginConfigUtilsTest.java b/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/PluginConfigUtilsTest.java deleted file mode 100644 index e350ce7..0000000 --- a/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/PluginConfigUtilsTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.gitee.starblues.utils; - -import org.junit.Assert; -import org.junit.Test; -import org.pf4j.RuntimeMode; - -/** - * @author starBlues - * @version 1.0 - */ -public class PluginConfigUtilsTest { - - - @Test - public void testGetConfigFileName(){ - String fileName = "fileName.yml"; - String prod = "prod"; - String dev = "dev"; - PluginConfigUtils.FileNamePack configFileName = PluginConfigUtils.getConfigFileName(fileName, - prod, dev, RuntimeMode.DEPLOYMENT); - Assert.assertNotNull(configFileName); - Assert.assertEquals(fileName, configFileName.getSourceFileName()); - Assert.assertEquals(prod, configFileName.getFileSuffix()); - - configFileName = PluginConfigUtils.getConfigFileName(fileName, - prod, dev, RuntimeMode.DEVELOPMENT); - Assert.assertNotNull(configFileName); - Assert.assertEquals(fileName, configFileName.getSourceFileName()); - Assert.assertEquals(dev, configFileName.getFileSuffix()); - } - - - @Test - public void testJoinConfigFileName_1(){ - String fileName = "fileName.yml"; - String suffix = "prod"; - String joinConfigFileName = PluginConfigUtils.joinConfigFileName(fileName, suffix); - Assert.assertNotNull(joinConfigFileName); - Assert.assertEquals("fileName-prod.yml", joinConfigFileName); - } - - @Test - public void testJoinConfigFileName_2(){ - String fileName = "fileName.yml"; - String suffix = ""; - String joinConfigFileName = PluginConfigUtils.joinConfigFileName(fileName, suffix); - Assert.assertNotNull(joinConfigFileName); - Assert.assertEquals("fileName.yml", joinConfigFileName); - } - - @Test - public void testJoinConfigFileName_3(){ - String fileName = "fileName.yml"; - String suffix = null; - String joinConfigFileName = PluginConfigUtils.joinConfigFileName(fileName, suffix); - Assert.assertNotNull(joinConfigFileName); - Assert.assertEquals("fileName.yml", joinConfigFileName); - } - - @Test - public void testJoinConfigFileName_4(){ - String fileName = null; - String suffix = null; - String joinConfigFileName = PluginConfigUtils.joinConfigFileName(fileName, suffix); - Assert.assertNull(joinConfigFileName); - } - -} diff --git a/springboot-plugin-maven-pack/pom.xml b/springboot-plugin-maven-pack/pom.xml new file mode 100644 index 0000000..b22ff75 --- /dev/null +++ b/springboot-plugin-maven-pack/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + com.gitee.starblues + springboot-plugin-maven-pack + 3.0.0-RELEASE + + + 8 + 3.0.0 + ${java.version} + ${java.version} + UTF-8 + UTF-8 + UTF-8 + + 3.8.4 + 3.6.2 + 3.2.0 + 1.21 + 2.11.0 + 1.18.20 + 3.8.1 + + 3.6.0 + + + + + com.gitee.starblues + spring-plugin-framework-common + ${project.version} + + + org.apache.maven + maven-plugin-api + ${maven-plugin-api.version} + + + org.apache.maven.plugin-tools + maven-plugin-annotations + ${maven-plugin-annotations.version} + + + org.apache.maven.shared + maven-common-artifact-filters + ${maven-common-artifact-filters.version} + + + org.apache.commons + commons-compress + ${commons-compress.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.projectlombok + lombok + ${lombok.version} + + + junit + junit + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + ${maven-plugin-plugin.version} + + + org.apache.maven.plugins + maven-shade-plugin + + + + com.gitee.starblues:spring-plugin-framework-common + + + + + + package + + shade + + + + + + + \ No newline at end of file diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java new file mode 100644 index 0000000..d6456dd --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -0,0 +1,61 @@ +package com.gitee.starblues.plugin.pack; + +import com.gitee.starblues.plugin.pack.filter.*; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; +import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; +import org.apache.maven.shared.artifact.filter.collection.FilterArtifacts; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +@EqualsAndHashCode(callSuper = true) +@Data +public abstract class AbstractDependencyFilterMojo extends AbstractMojo { + + + @Parameter(property = "springboot-plugin.includes") + private List includes; + + @Parameter(property = "springboot-plugin.excludes") + private List excludes; + + + protected final Set filterDependencies(Set dependencies, FilterArtifacts filters) + throws MojoExecutionException { + try { + Set filtered = new LinkedHashSet<>(dependencies); + filtered.retainAll(filters.filter(dependencies)); + return filtered; + } + catch (ArtifactFilterException ex) { + throw new MojoExecutionException(ex.getMessage(), ex); + } + } + + protected final FilterArtifacts getFilters(ArtifactsFilter... additionalFilters) { + FilterArtifacts filters = new FilterArtifacts(); + for (ArtifactsFilter additionalFilter : additionalFilters) { + filters.addFilter(additionalFilter); + } + if (!CommonUtils.isEmpty(includes)) { + filters.addFilter(new IncludeFilter(this.includes)); + } + if (!CommonUtils.isEmpty(excludes)) { + filters.addFilter(new ExcludeFilter(this.excludes)); + } + return filters; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java new file mode 100644 index 0000000..bd4be16 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java @@ -0,0 +1,72 @@ +package com.gitee.starblues.plugin.pack; + +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; + +import java.io.File; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +@EqualsAndHashCode(callSuper = true) +@Data +public abstract class AbstractPackagerMojo extends AbstractDependencyFilterMojo{ + + @Parameter(defaultValue = "${project}", readonly = true, required = true) + private MavenProject project; + + @Parameter(defaultValue = "${project.build.directory}", required = true) + private File outputDirectory; + + @Parameter(property = "springboot-plugin.pluginInfo", required = true) + private PluginInfo pluginInfo; + + @Parameter(property = "springboot-plugin.mode", defaultValue = "dev", required = true) + private String mode; + + @Parameter(property = "springboot-plugin.skip", defaultValue = "false") + private boolean skip; + + @Override + public final void execute() throws MojoExecutionException, MojoFailureException { + if(Constant.isPom(this.getProject().getPackaging())){ + getLog().debug("repackage goal could not be applied to pom project."); + return; + } + if (this.skip) { + getLog().debug("skipping plugin package."); + return; + } + checkPluginInfo(); + pack(); + } + + protected abstract void pack() throws MojoExecutionException, MojoFailureException; + + public final Set getDependencies() throws MojoExecutionException { + return filterDependencies(project.getArtifacts(), getFilters()); + } + + private void checkPluginInfo() throws MojoExecutionException { + if(pluginInfo == null){ + throw new MojoExecutionException("configuration.pluginInfo config cannot be empty"); + } + if(CommonUtils.isEmpty(pluginInfo.getId())){ + throw new MojoExecutionException("configuration.pluginInfo.id config cannot be empty"); + } + if(CommonUtils.isEmpty(pluginInfo.getBootstrapClass())){ + throw new MojoExecutionException("configuration.pluginInfo.bootstrapClass config cannot be empty"); + } + if(CommonUtils.isEmpty(pluginInfo.getVersion())){ + throw new MojoExecutionException("configuration.pluginInfo.version config cannot be empty"); + } + } +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java new file mode 100644 index 0000000..4716446 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -0,0 +1,200 @@ +package com.gitee.starblues.plugin.pack; + +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.plugin.pack.dev.DevConfig; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import lombok.Getter; +import org.apache.commons.io.FileUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.regex.Matcher; + +import static com.gitee.starblues.common.PackageStructure.*; +import static com.gitee.starblues.common.PluginDescriptorKey.*; +import static com.gitee.starblues.plugin.pack.Constant.SCOPE_PROVIDED; +import static com.gitee.starblues.plugin.pack.utils.CommonUtils.isEmpty; +import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; + +/** + * @author starBlues + * @version 1.0 + */ + +public class BasicRepackager implements Repackager{ + + @Getter + private String rootDir; + private String relativeManifestPath; + private String relativeLibIndexPath; + + protected final RepackageMojo repackageMojo; + + public BasicRepackager(RepackageMojo repackageMojo) { + this.repackageMojo = repackageMojo; + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + rootDir = createRootDir(); + relativeManifestPath = getRelativeManifestPath(); + relativeLibIndexPath = getRelativeLibIndexPath(); + try { + Manifest manifest = getManifest(); + writeManifest(manifest); + } catch (Exception e) { + repackageMojo.getLog().error(e.getMessage(), e); + throw new MojoFailureException(e); + } + } + + protected String getRelativeManifestPath(){ + return MANIFEST; + } + + protected String getRelativeLibIndexPath(){ + return LIB_INDEX_NAME; + } + + protected String createRootDir() throws MojoFailureException { + String rootDirPath = getBasicRootDir(); + File rootDir = new File(rootDirPath); + rootDir.deleteOnExit(); + if(rootDir.mkdir()){ + return rootDirPath; + } + throw new MojoFailureException("创建插件根目录失败. " + rootDirPath); + } + + protected String getBasicRootDir(){ + File outputDirectory = repackageMojo.getOutputDirectory(); + return joinPath(outputDirectory.getPath(), PackageStructure.META_INF_NAME); + } + + protected void writeManifest(Manifest manifest) throws Exception { + String manifestPath = CommonUtils.joinPath(rootDir, resolvePath(this.relativeManifestPath)); + File file = new File(manifestPath); + FileOutputStream outputStream = null; + try { + FileUtils.forceMkdirParent(file); + if(file.createNewFile()){ + outputStream = new FileOutputStream(file, false); + manifest.write(outputStream); + } + } finally { + if(outputStream != null){ + try { + outputStream.close(); + } catch (IOException e) { + repackageMojo.getLog().error(e.getMessage(), e); + } + } + } + } + + protected Manifest getManifest() throws Exception{ + PluginInfo pluginInfo = repackageMojo.getPluginInfo(); + Manifest manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue("Manifest-Version", "1.0"); + attributes.putValue(PLUGIN_ID, pluginInfo.getId()); + attributes.putValue(PLUGIN_BOOTSTRAP_CLASS, pluginInfo.getBootstrapClass()); + attributes.putValue(PLUGIN_VERSION, pluginInfo.getVersion()); + attributes.putValue(PLUGIN_PATH, getPluginPath()); + + String libFilePath = writeLibFile(); + if(!CommonUtils.isEmpty(libFilePath)){ + attributes.putValue(PLUGIN_LIB_INDEX, libFilePath); + } + String configFileName = pluginInfo.getConfigFileName(); + if(!isEmpty(configFileName)){ + attributes.putValue(PLUGIN_CONFIG_FILE_NAME, configFileName); + } + String provider = pluginInfo.getProvider(); + if(!isEmpty(provider)){ + attributes.putValue(PLUGIN_PROVIDER, provider); + } + String requires = pluginInfo.getRequires(); + if(!isEmpty(requires)){ + attributes.putValue(PLUGIN_REQUIRES, requires); + } + String dependencies = pluginInfo.getDependencies(); + if(!isEmpty(dependencies)){ + attributes.putValue(PLUGIN_DEPENDENCIES, dependencies); + } + String description = pluginInfo.getDescription(); + if(!isEmpty(description)){ + attributes.putValue(PLUGIN_DESCRIPTION, description); + } + String license = pluginInfo.getLicense(); + if(!isEmpty(license)){ + attributes.putValue(PLUGIN_LICENSE, license); + } + // TODO 未添加全 + return manifest; + } + + protected String getPluginPath(){ + DevConfig devConfig = repackageMojo.getDevConfig(); + if(devConfig != null && !isEmpty(devConfig.getPluginPath())){ + return devConfig.getPluginPath(); + } + return repackageMojo.getProject().getBuild().getOutputDirectory(); + } + + protected String writeLibFile() throws Exception{ + StringBuilder stringBuilder = new StringBuilder(); + Set libIndex = getLibIndexSet(); + for (String index : libIndex) { + stringBuilder.append(index).append("\n"); + } + String content = stringBuilder.toString(); + String path = joinPath(rootDir, resolvePath(relativeLibIndexPath)); + try { + File file = new File(path); + FileUtils.forceMkdirParent(file); + if(file.createNewFile()){ + FileUtils.write(file, content, "utf-8"); + return path; + } + throw new Exception(); + } catch (Exception e){ + throw new IOException("Create " + path + " file error"); + } + } + + protected Set getLibIndexSet() throws Exception { + Set dependencies = repackageMojo.getDependencies(); + Set libPaths = new HashSet<>(dependencies.size()); + for (Artifact artifact : dependencies) { + if(filterArtifact(artifact)){ + continue; + } + libPaths.add(getLibIndex(artifact)); + } + return libPaths; + } + + protected String getLibIndex(Artifact artifact){ + return artifact.getFile().getPath(); + } + + /** + * 过滤Artifact + * @param artifact Artifact + * @return 返回true表示被过滤掉 + */ + protected boolean filterArtifact(Artifact artifact){ + return SCOPE_PROVIDED.equalsIgnoreCase(artifact.getScope()); + } + + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java new file mode 100644 index 0000000..6a0d953 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -0,0 +1,25 @@ +package com.gitee.starblues.plugin.pack; + +/** + * @author starBlues + * @version 1.0 + */ +public class Constant { + + public static final String PACKAGING_POM = "pom"; + public static final String SCOPE_PROVIDED = "provided"; + public static final String MODE_DEV = "dev"; + public static final String MODE_PROD = "prod"; + + public static final String PACKAGE_TYPE_JAR = "jar"; + public static final String PACKAGE_TYPE_ZIP = "zip"; + public static final String PACKAGE_TYPE_DIR = "dir"; + + public static final String LIB_FILE_NAME = "lib"; + + + public static boolean isPom(String packageType){ + return PACKAGING_POM.equalsIgnoreCase(packageType); + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java new file mode 100644 index 0000000..7032c1a --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -0,0 +1,43 @@ +package com.gitee.starblues.plugin.pack; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * 插件信息A + * @author starBlues + * @version 3.0.0 + */ +@Data +public class PluginInfo { + + /** + * 插件id + */ + @Parameter(required = true) + private String id; + + /** + * 插件引导启动类 + */ + @Parameter(required = true) + private String bootstrapClass; + + /** + * 插件版本 + */ + @Parameter(required = true) + private String version; + + /** + * 插件配置文件名称 + */ + private String configFileName; + private String description; + private String provider; + private String requires; + private String dependencies; + private String license; + + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java new file mode 100644 index 0000000..f1592e7 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java @@ -0,0 +1,47 @@ +package com.gitee.starblues.plugin.pack; + +import com.gitee.starblues.plugin.pack.dev.DevConfig; +import com.gitee.starblues.plugin.pack.dev.DevRepackager; +import com.gitee.starblues.plugin.pack.prod.ProdConfig; +import com.gitee.starblues.plugin.pack.prod.ProdRepackager; +import lombok.Getter; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + * @author starBlues + * @version 1.0 + */ +@Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = true, + requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, + requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Getter +public class RepackageMojo extends AbstractPackagerMojo { + + + @Parameter(property = "springboot-plugin.devConfig") + private DevConfig devConfig; + + @Parameter(property = "springboot-plugin.prodConfig") + private ProdConfig prodConfig; + + @Override + protected void pack() throws MojoExecutionException, MojoFailureException { + String mode = getMode(); + + if(Constant.MODE_PROD.equalsIgnoreCase(mode)){ + new ProdRepackager(this).repackage(); + } else if(Constant.MODE_DEV.equalsIgnoreCase(mode)){ + new DevRepackager(this).repackage(); + } else { + throw new MojoExecutionException(mode +" model not supported, mode support : " + + Constant.MODE_DEV + "/" + Constant.MODE_PROD); + } + } + + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java new file mode 100644 index 0000000..8dda151 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java @@ -0,0 +1,16 @@ +package com.gitee.starblues.plugin.pack; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +/** + * @author starBlues + * @version 1.0 + */ +public interface Repackager { + + + void repackage() throws MojoExecutionException, MojoFailureException; + + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java new file mode 100644 index 0000000..9931b25 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java @@ -0,0 +1,22 @@ +package com.gitee.starblues.plugin.pack.dev; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * @author starBlues + * @version 1.0 + */ +@Data +public class Dependency { + + @Parameter(required = true) + private String groupId; + + @Parameter(required = true) + private String artifactId; + + @Parameter(required = true) + private String classesPath; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java new file mode 100644 index 0000000..a681bf0 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.plugin.pack.dev; + +import lombok.Data; + +import java.util.List; + +/** + * 开发模式配置 + * @author starBlues + * @version 3.0.0 + */ +@Data +public class DevConfig { + + /** + * 插件编译的class目录 + */ + private String pluginPath; + + /** + * 插件所有依赖存放的路径 + */ + private String libPath; + + /** + * 当前项目依赖其他模块的定义。 + * 主要定义依赖模块target->classes的目录, 方便开发调试 + */ + private List moduleDependencies; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java new file mode 100644 index 0000000..d0b6b7c --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java @@ -0,0 +1,69 @@ +package com.gitee.starblues.plugin.pack.dev; + +import com.gitee.starblues.plugin.pack.BasicRepackager; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import lombok.Getter; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; + +import java.util.*; + +/** + * @author starBlues + * @version 1.0 + */ +public class DevRepackager extends BasicRepackager { + + @Getter + private Map moduleDependencies = Collections.emptyMap(); + + public DevRepackager(RepackageMojo repackageMojo) { + super(repackageMojo); + } + + @Override + protected Set getLibIndexSet() throws Exception { + moduleDependencies = getModuleDependencies(repackageMojo.getDevConfig()); + Set libPaths = super.getLibIndexSet(); + for (Dependency dependency : moduleDependencies.values()) { + libPaths.add(dependency.getClassesPath()); + } + return libPaths; + } + + @Override + protected boolean filterArtifact(Artifact artifact) { + if(super.filterArtifact(artifact)){ + return true; + } + String moduleDependencyKey = getModuleDependencyKey(artifact.getGroupId(), artifact.getArtifactId()); + Dependency dependency = moduleDependencies.get(moduleDependencyKey); + return dependency != null && !CommonUtils.isEmpty(dependency.getClassesPath()); + } + + protected Map getModuleDependencies(DevConfig devConfig) { + Map moduleDependenciesMap = new HashMap<>(); + List moduleDependencies = devConfig.getModuleDependencies(); + if(CommonUtils.isEmpty(moduleDependencies)){ + return moduleDependenciesMap; + } + for (Dependency dependency : moduleDependencies) { + String moduleDependencyKey = getModuleDependencyKey(dependency.getGroupId(), + dependency.getArtifactId()); + if(moduleDependencyKey == null){ + continue; + } + moduleDependenciesMap.put(moduleDependencyKey, dependency); + } + return moduleDependenciesMap; + } + + protected String getModuleDependencyKey(String groupId, String artifactId){ + if(CommonUtils.isEmpty(groupId) || CommonUtils.isEmpty(artifactId)){ + return null; + } + return groupId + artifactId; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java new file mode 100644 index 0000000..4d43d71 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java @@ -0,0 +1,101 @@ +package com.gitee.starblues.plugin.pack.dev; + +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import org.apache.commons.compress.archivers.jar.JarArchiveEntry; +import org.apache.commons.compress.archivers.jar.JarArchiveInputStream; +import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * @author starBlues + * @version 1.0 + */ +public class LibCopy { + + private static final int UNIX_FILE_MODE = UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM; + + private static final int UNIX_DIR_MODE = UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM; + + private final String destDir; + + + public LibCopy(String destDir) { + this.destDir = destDir; + } + + public void copy(String libPath) throws Exception{ + copy(new File(libPath)); + } + + public void copy(File libFile) throws Exception{ + if(libFile == null || !libFile.exists()){ + return; + } + File destJarFile = new File(CommonUtils.joinPath(destDir, libFile.getName())); + if(!destJarFile.createNewFile()){ + return; + } + try (JarArchiveOutputStream outputStream = new JarArchiveOutputStream(new FileOutputStream(destJarFile)); + JarArchiveInputStream jarArchiveInputStream = new JarArchiveInputStream(new FileInputStream(libFile))) { + JarArchiveEntry entry = null; + while ((entry = jarArchiveInputStream.getNextJarEntry()) != null) { + String name = entry.getName(); + JarArchiveEntry newEntry = new JarArchiveEntry(name); + //copyAttribute(entry, newEntry); + //CopyByte crcAndSize = new CopyByte(jarArchiveInputStream); + //crcAndSize.setupStoredEntry(newEntry); + entry.setMethod(ZipEntry.STORED); + outputStream.putArchiveEntry(newEntry); + IOUtils.copy(jarArchiveInputStream, outputStream); + outputStream.closeArchiveEntry(); + } + outputStream.finish(); + } + } + + private void copyAttribute(JarArchiveEntry oldEntry, JarArchiveEntry newEntry){ + newEntry.setComment(oldEntry.getComment()); + newEntry.setTime(System.currentTimeMillis()); + } + + private static class CopyByte { + + private static final int BUFFER_SIZE = 32 * 1024; + + private final CRC32 crc = new CRC32(); + + private long size; + + public CopyByte(InputStream inputStream) throws IOException{ + copy(inputStream); + } + + void copy(InputStream inputStream) throws IOException { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + this.crc.update(buffer, 0, bytesRead); + this.size += bytesRead; + } + } + + void setupStoredEntry(JarArchiveEntry entry) { + entry.setSize(this.size); + entry.setCompressedSize(this.size); + entry.setCrc(this.crc.getValue()); + entry.setMethod(ZipEntry.STORED); + } + + } + + + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java new file mode 100644 index 0000000..c4c6ceb --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java @@ -0,0 +1,56 @@ +package com.gitee.starblues.plugin.pack.filter; + +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter; +import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @author starBlues + * @version 1.0 + */ +public abstract class DependencyFilter extends AbstractArtifactsFilter { + + private final List filters; + + public DependencyFilter(List dependencies) { + this.filters = dependencies; + } + + @Override + public Set filter(Set artifacts) throws ArtifactFilterException { + if(CommonUtils.isEmpty(artifacts)){ + return artifacts; + } + Set result = new HashSet<>(); + for (Artifact artifact : artifacts) { + if (!filter(artifact)) { + result.add(artifact); + } + } + return result; + } + + /** + * 子类过滤结果 + * @param artifact artifact + * @return boolean + */ + protected abstract boolean filter(Artifact artifact); + + protected final boolean equals(Artifact artifact, FilterableDependency dependency) { + if (!dependency.getGroupId().equals(artifact.getGroupId())) { + return false; + } + return dependency.getArtifactId().equals(artifact.getArtifactId()); + } + + protected final List getFilters() { + return this.filters; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java new file mode 100644 index 0000000..bc52362 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java @@ -0,0 +1,8 @@ +package com.gitee.starblues.plugin.pack.filter; + +/** + * @author starBlues + * @version 1.0 + */ +public class Exclude extends FilterableDependency{ +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java new file mode 100644 index 0000000..283c1ef --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java @@ -0,0 +1,32 @@ +package com.gitee.starblues.plugin.pack.filter; + +import org.apache.maven.artifact.Artifact; + +import java.util.Arrays; +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class ExcludeFilter extends DependencyFilter { + + public ExcludeFilter(Exclude... excludes) { + this(Arrays.asList(excludes)); + } + + public ExcludeFilter(List excludes) { + super(excludes); + } + + @Override + protected boolean filter(Artifact artifact) { + for (FilterableDependency dependency : getFilters()) { + if (equals(artifact, dependency)) { + return true; + } + } + return false; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java new file mode 100644 index 0000000..96cad7a --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java @@ -0,0 +1,19 @@ +package com.gitee.starblues.plugin.pack.filter; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * @author starBlues + * @version 1.0 + */ +@Data +public abstract class FilterableDependency { + + @Parameter(required = true) + private String groupId; + + @Parameter(required = true) + private String artifactId; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java new file mode 100644 index 0000000..675ccce --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java @@ -0,0 +1,8 @@ +package com.gitee.starblues.plugin.pack.filter; + +/** + * @author starBlues + * @version 1.0 + */ +public class Include extends FilterableDependency{ +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java new file mode 100644 index 0000000..9694403 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java @@ -0,0 +1,27 @@ +package com.gitee.starblues.plugin.pack.filter; + +import org.apache.maven.artifact.Artifact; + +import java.util.List; + +/** + * @author starBlues + * @version 1.0 + */ +public class IncludeFilter extends DependencyFilter { + + public IncludeFilter(List includes) { + super(includes); + } + + @Override + protected boolean filter(Artifact artifact) { + for (FilterableDependency dependency : getFilters()) { + if (equals(artifact, dependency)) { + return false; + } + } + return true; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java new file mode 100644 index 0000000..27193e0 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java @@ -0,0 +1,122 @@ +package com.gitee.starblues.plugin.pack.prod; + +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.dev.DevRepackager; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import org.apache.commons.io.FileUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.File; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PackageStructure.*; + +/** + * @author starBlues + * @version 1.0 + */ +public class DirPackageGenerator extends DevRepackager { + + private final ProdConfig prodConfig; + + + public DirPackageGenerator(RepackageMojo repackageMojo, ProdConfig prodConfig) { + super(repackageMojo); + this.prodConfig = prodConfig; + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + super.repackage(); + try { + resolveClasses(); + } catch (Exception e) { + repackageMojo.getLog().error(e.getMessage(), e); + throw new MojoFailureException(e); + } + } + + @Override + protected String createRootDir() throws MojoFailureException { + String fileName = prodConfig.getFileName(); + String dirPath = CommonUtils.joinPath(prodConfig.getOutputDirectory(), fileName); + File dirFile = new File(dirPath); + if(dirFile.exists() && dirFile.isFile()){ + int i = 0; + while (true){ + dirFile = new File(dirPath + "_" + i); + if(dirFile.exists() && dirFile.isFile()){ + i = i + 1; + continue; + } + break; + } + } + dirFile.deleteOnExit(); + if(!dirFile.mkdirs()){ + throw new MojoFailureException("Create package dir failure: " + dirFile.getPath()); + } + return dirFile.getPath(); + } + + @Override + protected String getRelativeManifestPath() { + return CommonUtils.joinPath(META_INF_NAME, MANIFEST); + } + + @Override + protected String getRelativeLibIndexPath() { + return CommonUtils.joinPath(META_INF_NAME, LIB_INDEX_NAME); + } + + @Override + protected Manifest getManifest() throws Exception { + Manifest manifest = super.getManifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, CLASSES_NAME); + attributes.putValue(PluginDescriptorKey.PLUGIN_LIB_INDEX, PROD_LIB_INDEX_PATH); + return manifest; + } + + protected void resolveClasses() throws Exception { + String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); + String path = CommonUtils.joinPath(getRootDir(), CLASSES_NAME); + File file = new File(path); + FileUtils.forceMkdir(file); + FileUtils.copyDirectory(new File(buildDir), file); + } + + @Override + protected Set getLibIndexSet() throws Exception { + Set dependencies = repackageMojo.getDependencies(); + String libDir = createLibDir(); + Set dependencyIndexNames = new HashSet<>(dependencies.size()); + for (Artifact artifact : dependencies) { + if(filterArtifact(artifact)){ + continue; + } + File artifactFile = artifact.getFile(); + FileUtils.copyFile(artifactFile, new File(CommonUtils.joinPath(libDir, artifactFile.getName()))); + dependencyIndexNames.add(PackageStructure.PROD_LIB_PATH + artifactFile.getName()); + } + return dependencyIndexNames; + } + + protected String createLibDir() throws IOException { + String dir = CommonUtils.joinPath(getRootDir(), PackageStructure.LIB_NAME); + File file = new File(dir); + if(file.mkdir()){ + return dir; + } + throw new IOException("Create " + PackageStructure.LIB_NAME + " dir failure"); + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java new file mode 100644 index 0000000..5502bcb --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java @@ -0,0 +1,43 @@ +package com.gitee.starblues.plugin.pack.prod; + +import com.gitee.starblues.plugin.pack.RepackageMojo; +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.compress.archivers.jar.JarArchiveEntry; +import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.*; + +/** + * @author starBlues + * @version 1.0 + */ +public class JarPackageGenerator extends ZipProdRepackager { + + + public JarPackageGenerator(RepackageMojo repackageMojo, ProdConfig prodConfig) { + super(repackageMojo, prodConfig); + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + super.repackage(); + } + + @Override + protected String getPackageFileSuffix() { + return "jar"; + } + + @Override + protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { + return new JarArchiveOutputStream(new FileOutputStream(packFile)); + } + + @Override + protected ZipArchiveEntry getArchiveEntry(String name) { + return new JarArchiveEntry(name); + } +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java new file mode 100644 index 0000000..585beee --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java @@ -0,0 +1,14 @@ +package com.gitee.starblues.plugin.pack.prod; + +import java.io.IOException; +import java.io.InputStream; + +/** + * @author starBlues + * @version 1.0 + */ +public interface JarWriter { + + void writeEntry(String name, InputStream inputStream) throws IOException; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java new file mode 100644 index 0000000..989abc0 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java @@ -0,0 +1,13 @@ +package com.gitee.starblues.plugin.pack.prod; + +import org.apache.maven.plugin.MojoFailureException; + +/** + * @author starBlues + * @version 1.0 + */ +public interface PackageGenerator { + + void pack() throws MojoFailureException; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java new file mode 100644 index 0000000..a29f306 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java @@ -0,0 +1,42 @@ +package com.gitee.starblues.plugin.pack.prod; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * 生产环境打包配置 + * @author starBlues + * @version 3.0.0 + */ +@Data +public class ProdConfig { + + + /** + * 打包类型。默认jar包 + */ + @Parameter(required = true, defaultValue = "jar") + private String packageType = "jar"; + + /** + * 文件名称。默认 pluginId-version.jar + */ + private String fileName; + + /** + * 输出文件目录。默认target + */ + private String outputDirectory; + + /** + * 是否将依赖导入包中. 默认打入 + */ + @Parameter(required = true, defaultValue = "true") + private Boolean includeDependencies = true; + + /** + * 生成环境依赖包的路径。默认 lib + */ + private String libPath; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java new file mode 100644 index 0000000..367f3cf --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java @@ -0,0 +1,79 @@ +package com.gitee.starblues.plugin.pack.prod; + +import com.gitee.starblues.plugin.pack.Constant; +import com.gitee.starblues.plugin.pack.PluginInfo; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.Repackager; +import com.gitee.starblues.plugin.pack.dev.DevRepackager; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import lombok.Getter; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + + +/** + * @author starBlues + * @version 1.0 + */ +public class ProdRepackager implements Repackager { + + @Getter + private ProdConfig prodConfig; + + private final RepackageMojo repackageMojo; + private final Repackager repackager; + + public ProdRepackager(RepackageMojo repackageMojo) { + this.repackageMojo = repackageMojo; + this.repackager = new DevRepackager(repackageMojo); + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + repackager.repackage(); + this.prodConfig = getProdConfig(repackageMojo); + String packageType = prodConfig.getPackageType(); + Repackager repackager = null; + if(Constant.PACKAGE_TYPE_ZIP.equalsIgnoreCase(packageType)){ + // jar + repackager = new ZipProdRepackager(repackageMojo, prodConfig); + } else if(Constant.PACKAGE_TYPE_JAR.equalsIgnoreCase(packageType)){ + repackager = new JarPackageGenerator(repackageMojo, prodConfig); + } else if(Constant.PACKAGE_TYPE_DIR.equalsIgnoreCase(packageType)){ + repackager = new DirPackageGenerator(repackageMojo, prodConfig); + } else { + throw new MojoFailureException("Not found packageType:" + packageType); + } + repackager.repackage(); + } + + + protected ProdConfig getProdConfig(RepackageMojo repackageMojo){ + ProdConfig prodConfig = repackageMojo.getProdConfig(); + if(prodConfig == null){ + prodConfig = new ProdConfig(); + } + if(CommonUtils.isEmpty(prodConfig.getPackageType())){ + prodConfig.setPackageType(Constant.PACKAGE_TYPE_JAR); + } + String fileName = prodConfig.getFileName(); + if(CommonUtils.isEmpty(fileName)) { + PluginInfo pluginInfo = repackageMojo.getPluginInfo(); + prodConfig.setFileName(pluginInfo.getId() + "-" + pluginInfo.getVersion()); + } + String outputDirectory = prodConfig.getOutputDirectory(); + if(CommonUtils.isEmpty(outputDirectory)){ + prodConfig.setOutputDirectory(repackageMojo.getOutputDirectory().getPath()); + } + Boolean includeDependencies = prodConfig.getIncludeDependencies(); + if(includeDependencies == null){ + prodConfig.setIncludeDependencies(true); + } + String libPath = prodConfig.getLibPath(); + if(CommonUtils.isEmpty(libPath)){ + prodConfig.setLibPath(Constant.LIB_FILE_NAME); + } + return prodConfig; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java new file mode 100644 index 0000000..74a7968 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -0,0 +1,288 @@ +package com.gitee.starblues.plugin.pack.prod; + +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.dev.Dependency; +import com.gitee.starblues.plugin.pack.dev.DevConfig; +import com.gitee.starblues.plugin.pack.dev.DevRepackager; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.compress.archivers.jar.JarArchiveEntry; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; + +import static com.gitee.starblues.common.PackageStructure.*; +import static com.gitee.starblues.plugin.pack.Constant.SCOPE_PROVIDED; +import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; + +/** + * @author starBlues + * @version 1.0 + */ +public class ZipProdRepackager extends DevRepackager { + + private static final int UNIX_FILE_MODE = UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM; + + private static final int UNIX_DIR_MODE = UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM; + + protected final ProdConfig prodConfig; + + protected ArchiveOutputStream outputStream; + + public ZipProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { + super(repackageMojo); + this.prodConfig = prodConfig; + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + File packageFile = getPackageFile(); + try { + outputStream = getOutputStream(packageFile); + super.repackage(); + resolveClasses(); + resolveDependencies(); + outputStream.finish(); + String rootDir = getRootDir(); + try { + FileUtils.deleteDirectory(new File(rootDir)); + } catch (IOException e) { + // 忽略 + } + repackageMojo.getLog().info("Success package prod zip file : " + packageFile.getPath()); + } catch (Exception e){ + repackageMojo.getLog().error(e.getMessage(), e); + throw new MojoFailureException(e); + } finally { + if(outputStream != null){ + IOUtils.closeQuietly(outputStream); + } + } + } + + protected File getPackageFile() throws MojoFailureException { + String fileSuffix = getPackageFileSuffix(); + String path = getPackageFilePath(); + File file = new File(path + "." + fileSuffix); + + if(file.exists()){ + int i = 0; + while (true){ + file = new File(path + "_" + i + "." + fileSuffix); + if(file.exists()){ + i = i + 1; + continue; + } + break; + } + } + try { + if(file.createNewFile()){ + return file; + } + throw new IOException("Create file '" + file.getPath() + "' failure."); + } catch (IOException e) { + repackageMojo.getLog().error(e.getMessage(), e); + throw new MojoFailureException("Create prod package file failure"); + } + } + + protected String getPackageFileSuffix(){ + return "zip"; + } + + protected String getPackageFilePath(){ + return CommonUtils.joinPath(prodConfig.getOutputDirectory(), prodConfig.getFileName()); + } + + protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { + return new ZipArchiveOutputStream(new FileOutputStream(packFile)); + } + + @Override + protected String getBasicRootDir(){ + File outputDirectory = repackageMojo.getOutputDirectory(); + return joinPath(outputDirectory.getPath(), UUID.randomUUID().toString()); + } + + @Override + protected Map getModuleDependencies(DevConfig devConfig) { + // 将项目中模块依赖置为空 + return Collections.emptyMap(); + } + + @Override + protected String getPluginPath() { + return CLASSES_NAME + SEPARATOR; + } + + @Override + protected String getLibIndex(Artifact artifact){ + return PROD_LIB_PATH + artifact.getFile().getName(); + } + + @Override + protected boolean filterArtifact(Artifact artifact) { + return SCOPE_PROVIDED.equalsIgnoreCase(artifact.getScope()); + } + + protected void resolveClasses() throws Exception { + String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); + copyFileToPackage(new File(buildDir), ""); + } + + @Override + protected Manifest getManifest() throws Exception { + Manifest manifest = super.getManifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, PROD_CLASSES_PATH); + attributes.putValue(PluginDescriptorKey.PLUGIN_LIB_INDEX, PROD_LIB_INDEX_PATH); + return manifest; + } + + @Override + protected void writeManifest(Manifest manifest) throws Exception { + putDirEntry(META_INF_NAME + SEPARATOR); + outputStream.putArchiveEntry(getArchiveEntry(PROD_MANIFEST_PATH)); + manifest.write(outputStream); + outputStream.closeArchiveEntry(); + } + + protected void resolveDependencies() throws Exception { + Set dependencies = repackageMojo.getDependencies(); + String libDirEntryName = createLibEntry(); + Set dependencyIndexNames = new HashSet<>(dependencies.size()); + for (Artifact artifact : dependencies) { + if(filterArtifact(artifact)){ + continue; + } + String dependencyIndexName = writeDependency(artifact.getFile(), libDirEntryName, outputStream); + dependencyIndexNames.add(dependencyIndexName); + } + writeLibIndexFile(dependencyIndexNames); + } + + protected String createLibEntry() throws Exception { + String libDirEntryName = PROD_LIB_PATH; + putDirEntry(libDirEntryName); + return libDirEntryName; + } + + protected String writeDependency(File dependencyFile, String libDirEntryName, + ArchiveOutputStream outputStream) throws Exception { + String indexName = libDirEntryName + dependencyFile.getName(); + ZipArchiveEntry entry = getArchiveEntry(indexName); + entry.setTime(System.currentTimeMillis()); + entry.setUnixMode(indexName.endsWith("/") ? UNIX_DIR_MODE : UNIX_FILE_MODE); + entry.getGeneralPurposeBit().useUTF8ForNames(true); + try(FileInputStream inputStream = new FileInputStream(dependencyFile)){ + new CrcAndSize(inputStream).setupStoredEntry(entry); + } + try (FileInputStream inputStream = new FileInputStream(dependencyFile)){ + outputStream.putArchiveEntry(entry); + IOUtils.copy(inputStream, outputStream); + outputStream.closeArchiveEntry(); + } + return indexName; + } + + protected void writeLibIndexFile(Set dependencyIndexNames) throws Exception { + StringBuilder content = new StringBuilder(); + for (String dependencyIndexName : dependencyIndexNames) { + content.append(dependencyIndexName).append("\n"); + } + final byte[] bytes = content.toString().getBytes(StandardCharsets.UTF_8); + try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)){ + putInputStreamEntry(byteArrayInputStream, PROD_LIB_INDEX_PATH); + } + } + + protected void copyFileToPackage(File file, String rootDir) throws Exception { + if(CommonUtils.isEmpty(rootDir)){ + rootDir = file.getName(); + } + if (file.isDirectory()) { + File[] childFiles = file.listFiles(); + rootDir = rootDir + "/"; + putDirEntry(rootDir); + if(childFiles == null){ + return; + } + for (File childFile : childFiles) { + copyFileToPackage(childFile, rootDir + childFile.getName()); + } + } else { + putFileEntry(file, rootDir); + } + } + + protected void putFileEntry(File destFile, String rootDir) throws Exception { + if(!destFile.exists()){ + throw new FileNotFoundException("Not found file : " + destFile.getPath()); + } + outputStream.putArchiveEntry(getArchiveEntry(rootDir)); + FileUtils.copyFile(destFile, outputStream); + outputStream.closeArchiveEntry(); + } + + protected void putInputStreamEntry(InputStream inputStream, String name) throws Exception { + outputStream.putArchiveEntry(getArchiveEntry(name)); + IOUtils.copy(inputStream, outputStream); + outputStream.closeArchiveEntry(); + } + + protected void putDirEntry(String dir) throws IOException { + outputStream.putArchiveEntry(getArchiveEntry(dir)); + outputStream.closeArchiveEntry(); + } + + protected ZipArchiveEntry getArchiveEntry(String name){ + return new ZipArchiveEntry(name); + } + + private static class CrcAndSize { + + private static final int BUFFER_SIZE = 32 * 1024; + + private final CRC32 crc = new CRC32(); + + private long size; + + CrcAndSize(InputStream inputStream) throws IOException { + load(inputStream); + } + + private void load(InputStream inputStream) throws IOException { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + this.crc.update(buffer, 0, bytesRead); + this.size += bytesRead; + } + } + + void setupStoredEntry(ZipArchiveEntry entry) { + entry.setSize(this.size); + entry.setCompressedSize(this.size); + entry.setCrc(this.crc.getValue()); + entry.setMethod(ZipEntry.STORED); + } + + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java new file mode 100644 index 0000000..01d286e --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java @@ -0,0 +1,98 @@ +package com.gitee.starblues.plugin.pack.utils; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Array; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; + +/** + * Object 工具类 + * @author starBlues + * @version 3.0.0 + */ +public class CommonUtils { + + + private CommonUtils(){} + + + public static boolean isEmpty(CharSequence cs) { + return cs == null || cs.length() == 0; + } + + public static boolean isEmpty(Object obj) { + if (obj == null) { + return true; + } + + if (obj instanceof Optional) { + return !((Optional) obj).isPresent(); + } + if (obj instanceof CharSequence) { + return ((CharSequence) obj).length() == 0; + } + if (obj.getClass().isArray()) { + return Array.getLength(obj) == 0; + } + if (obj instanceof Collection) { + return ((Collection) obj).isEmpty(); + } + if (obj instanceof Map) { + return ((Map) obj).isEmpty(); + } + return false; + } + + public static boolean hasText(CharSequence str) { + return (str != null && str.length() > 0 && containsText(str)); + } + + public static boolean hasLength(String str) { + return (str != null && !str.isEmpty()); + } + + /** + * 拼接file路径 + * @param paths 拼接的路径 + * @return 拼接的路径 + */ + public static String joinPath(String ...paths){ + if(paths == null || paths.length == 0){ + return ""; + } + StringBuilder stringBuilder = new StringBuilder(); + int length = paths.length; + for (int i = 0; i < length; i++) { + String path = paths[i]; + if(isEmpty(path)) { + continue; + } + if(i > 0){ + if(path.startsWith(File.separator) || path.startsWith("/") || + path.startsWith("\\") || path.startsWith("//")){ + stringBuilder.append(path); + } else { + stringBuilder.append(File.separator).append(path); + } + } else { + stringBuilder.append(path); + } + } + + return stringBuilder.toString(); + } + + + 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; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml b/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml new file mode 100644 index 0000000..95a7027 --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml @@ -0,0 +1,133 @@ + + + + + + Spring Boot Plugin Maven Pack + com.gitee.starblues + springboot-plugin-maven-pack + 3.0.0-RELEASE + springboot-plugin + false + true + + + repackage + Repackage existing JAR and WAR archives so that they can be executed from the command + line using {@literal java -jar}. With <code>layout=NONE</code> can also be used simply + to package a JAR with nested dependencies (and no main class, so not executable). + compile+runtime + false + true + false + false + false + true + package + com.gitee.starblues.plugin.pack.RepackageMojo + java + per-lookup + once-per-session + 1.0.0 + compile+runtime + true + + + project + org.apache.maven.project.MavenProject + 1.0.0 + true + false + The Maven project. + + + outputDirectory + java.io.File + 1.0.0 + true + true + Directory containing the generated archive. + + + includes + java.util.List + 1.2.0 + false + true + Collection of artifact definitions to include. The {@link Include} element defines + mandatory {@code groupId} and {@code artifactId} properties and an optional + mandatory {@code groupId} and {@code artifactId} properties and an optional + {@code classifier} property. + + + excludes + java.util.List + 1.1.0 + false + true + Collection of artifact definitions to exclude. The {@link Exclude} element defines + mandatory {@code groupId} and {@code artifactId} properties and an optional + {@code classifier} property. + + + skip + boolean + 1.2.0 + false + true + Skip the execution. + + + mode + string + 3.0.0 + true + true + 打包模式: dev/prod ,默认为dev + + + pluginInfo + com.gitee.starblues.plugin.pack.PluginInfo + 3.0.0 + false + true + 插件信息 + + + devConfig + com.gitee.starblues.plugin.pack.dev.DevConfig + 3.0.0 + false + true + dev打包模式配置 + + + prodConfig + com.gitee.starblues.plugin.pack.prod.ProdConfig + 3.0.0 + false + true + prod打包模式配置 + + + + + + + + + ${springboot-plugin.includes} + ${springboot-plugin.excludes} + + + + + + org.apache.maven.project.MavenProjectHelper + projectHelper + + + + + + \ No newline at end of file -- Gitee From 128591494d68e0fe29d63c848651c20a5450f749 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Tue, 18 Jan 2022 17:55:45 +0800 Subject: [PATCH 21/37] add plugin update --- .../bootstrap/ConfigurePluginEnvironment.java | 5 +- .../bootstrap/DefaultSpringPluginHook.java | 19 +- .../bootstrap/PluginListableBeanFactory.java | 2 +- .../bootstrap/PluginOneselfInteractive.java | 13 +- .../processor/DefaultProcessorContext.java | 5 +- .../PluginControllerRegistryProcessor.java | 17 +- .../bootstrap/processor/ProcessorContext.java | 3 +- .../bootstrap/utils/DestroyUtils.java | 46 +- .../starblues/core/DefaultPluginChecker.java | 5 +- ...side.java => DefaultPluginInsideInfo.java} | 27 +- .../starblues/core/DefaultPluginManager.java | 553 +++++++++++++----- .../starblues/core/PluginConfiguration.java | 24 +- .../gitee/starblues/core/PluginException.java | 29 +- .../{PluginWrapper.java => PluginInfo.java} | 6 +- .../gitee/starblues/core/PluginInfoFace.java | 53 ++ .../starblues/core/PluginInsideInfo.java | 31 + .../starblues/core/PluginLauncherManager.java | 33 +- .../gitee/starblues/core/PluginManager.java | 59 +- .../com/gitee/starblues/core/PluginState.java | 10 +- .../starblues/core/PluginWrapperFace.java | 39 -- .../classloader/AbstractResourceLoader.java | 22 +- .../core/classloader/ClassPathLoader.java | 22 +- .../core/classloader/GenericClassLoader.java | 63 +- .../core/classloader/JarResourceLoader.java | 6 + .../classloader/NestedJarResourceLoader.java | 19 +- .../core/classloader/PluginClassLoader.java | 3 +- .../PluginResourceLoaderFactory.java | 9 +- .../starblues/core/classloader/Resource.java | 10 + .../classloader/ResourceLoaderFactory.java | 10 +- .../AbstractPluginDescriptorLoader.java | 6 +- .../DefaultInsidePluginDescriptor.java | 93 +++ .../descriptor/DefaultPluginDescriptor.java | 47 +- .../descriptor/DevPluginDescriptorLoader.java | 6 +- .../descriptor/EmptyPluginDescriptor.java | 37 +- .../descriptor/InsidePluginDescriptor.java | 57 ++ .../core/descriptor/PluginDescriptor.java | 34 +- .../descriptor/PluginDescriptorLoader.java | 2 +- .../ProdDirPluginDescriptorLoader.java | 16 +- .../ProdPackagePluginDescriptorLoader.java | 11 +- .../ProdPluginDescriptorLoader.java | 2 +- .../exception/PluginDisabledException.java | 23 + .../core/launcher/AbstractLauncher.java | 2 +- .../core/launcher/MainProgramLauncher.java | 39 +- .../core/launcher/PluginResourceStorage.java | 117 ++++ .../starblues/core/launcher/jar/Handler.java | 42 +- .../starblues/core/launcher/jar/JarFile.java | 4 +- .../core/launcher/jar/JarFileWrapper.java | 54 +- .../starblues/core/launcher/jar/JarTest2.java | 26 - .../core/launcher/jar/JarURLConnection.java | 35 +- .../plugin/DefaultPluginInteractive.java | 7 +- .../launcher/plugin/PluginInteractive.java | 3 +- .../core/launcher/plugin/PluginLauncher.java | 7 +- .../plugin/SpringPluginHookWrapper.java | 11 +- .../core/scanner/ComposePathResolve.java | 47 ++ .../starblues/core/scanner/PathResolve.java | 2 +- .../core/scanner/ProdPathResolve.java | 7 +- .../AutoIntegrationConfiguration.java | 41 +- .../PluginInitializerListenerFactory.java | 2 +- .../operator/DefaultPluginOperator.java | 328 ++++++++--- .../operator/EmptyPluginOperator.java | 51 +- .../integration/operator/PluginOperator.java | 99 ++-- .../operator/PluginOperatorWrapper.java | 84 +-- .../upload/UploadByInputStreamParam.java | 36 ++ .../upload/UploadByMultipartFileParam.java | 22 + .../operator/upload/UploadParam.java | 82 +++ .../com/gitee/starblues/utils/MsgUtils.java | 5 + .../starblues/utils/PluginFileUtils.java | 125 +++- .../starblues/utils/ReflectionUtils.java | 11 +- .../gitee/starblues/utils/ResourceUtils.java | 77 ++- .../pack/AbstractDependencyFilterMojo.java | 5 +- .../plugin/pack/BasicRepackager.java | 1 - .../gitee/starblues/plugin/pack/Constant.java | 3 +- .../starblues/plugin/pack/PluginInfo.java | 2 +- .../starblues/plugin/pack/dev/LibCopy.java | 101 ---- .../plugin/pack/prod/ProdRepackager.java | 3 +- 75 files changed, 2025 insertions(+), 933 deletions(-) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{PluginWrapperInside.java => DefaultPluginInsideInfo.java} (50%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{PluginWrapper.java => PluginInfo.java} (86%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarTest2.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java delete mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 99b36dc..815a89a 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -1,5 +1,6 @@ package com.gitee.starblues.bootstrap; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; @@ -28,9 +29,9 @@ class ConfigurePluginEnvironment { public static final String MBEAN_DOMAIN_PROPERTY_NAME = "spring.liveBeansView.mbeanDomain"; - private final PluginDescriptor pluginDescriptor; + private final InsidePluginDescriptor pluginDescriptor; - ConfigurePluginEnvironment(PluginDescriptor pluginDescriptor) { + ConfigurePluginEnvironment(InsidePluginDescriptor pluginDescriptor) { this.pluginDescriptor = Assert.isNotNull(pluginDescriptor, "pluginDescriptor 不能为空"); } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java index 0c8d80c..e55bcd8 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -2,9 +2,14 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.bootstrap.utils.DestroyUtils; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.ApplicationContextProxy; import com.gitee.starblues.spring.SpringPluginHook; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.io.support.SpringFactoriesLoader; + +import java.util.Map; /** * @author starBlues @@ -23,9 +28,17 @@ public class DefaultSpringPluginHook implements SpringPluginHook { @Override public void close() throws Exception{ - pluginProcessor.close(processorContext); - processorContext.getApplicationContext().close(); - processorContext.clearRegistryInfo(); + try { + pluginProcessor.close(processorContext); + GenericApplicationContext applicationContext = processorContext.getApplicationContext(); + if(applicationContext != null){ + applicationContext.close(); + } + processorContext.clearRegistryInfo(); + DestroyUtils.destroyAll(null, SpringFactoriesLoader.class, "cache", Map.class); + } catch (Exception e){ + e.printStackTrace(); + } } @Override diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java index 6f1da23..9ec2c5e 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -72,7 +72,7 @@ public class PluginListableBeanFactory extends DefaultListableBeanFactory { field.setAccessible(true); try { Object o = field.get(this); - DestroyUtils.destroy(o); + DestroyUtils.destroyAll(o); } catch (IllegalAccessException e) { // 忽略 } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index 64648e8..8fb0dd4 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -1,9 +1,6 @@ package com.gitee.starblues.bootstrap; -import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; -import com.gitee.starblues.core.descriptor.EmptyPluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.*; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.integration.IntegrationConfiguration; @@ -21,7 +18,7 @@ import java.nio.file.Paths; */ public class PluginOneselfInteractive implements PluginInteractive { - private final PluginDescriptor pluginDescriptor; + private final InsidePluginDescriptor pluginDescriptor; private final MainApplicationContext mainApplicationContext; private final IntegrationConfiguration configuration; private final InvokeSupperCache invokeSupperCache; @@ -37,7 +34,7 @@ public class PluginOneselfInteractive implements PluginInteractive { @Override - public PluginDescriptor getPluginDescriptor() { + public InsidePluginDescriptor getPluginDescriptor() { return pluginDescriptor; } @@ -63,8 +60,8 @@ public class PluginOneselfInteractive implements PluginInteractive { - private PluginDescriptor createPluginDescriptor(){ - PluginDescriptor pluginDescriptor; + private InsidePluginDescriptor createPluginDescriptor(){ + InsidePluginDescriptor pluginDescriptor; try (PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader()){ pluginDescriptor = pluginDescriptorLoader.load( Paths.get(this.getClass().getResource("/").toURI())); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 4034cd4..27cd8ee 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -1,6 +1,7 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.plugin.CacheRegistryInfo; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; @@ -47,7 +48,7 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces } @Override - public PluginDescriptor getPluginDescriptor() { + public InsidePluginDescriptor getPluginDescriptor() { return pluginInteractive.getPluginDescriptor(); } @@ -79,7 +80,7 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces @Override public GenericApplicationContext getApplicationContext() { if(applicationContext == null){ - throw new IllegalStateException("GenericApplicationContext 未初始化!"); + return null; } return applicationContext; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java index c7c532a..04c3142 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java @@ -1,12 +1,10 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; +import com.gitee.starblues.bootstrap.utils.DestroyUtils; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.SpringBeanFactory; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ReflectionUtils; +import com.gitee.starblues.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; @@ -16,6 +14,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import java.lang.reflect.Method; @@ -35,6 +34,7 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor private RequestMappingHandlerMapping requestMappingHandlerMapping; private Method getMappingForMethod; + private RequestMappingHandlerAdapter handlerAdapter; private final AtomicBoolean canRegistered = new AtomicBoolean(false); @@ -43,6 +43,8 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor public void initialize(ProcessorContext processorContext) throws ProcessorException { SpringBeanFactory mainBeanFactory = processorContext.getMainBeanFactory(); this.requestMappingHandlerMapping = mainBeanFactory.getBean(RequestMappingHandlerMapping.class); + this.handlerAdapter = SpringBeanUtilsV3.getExistBean(processorContext.getMainApplicationContext(), + RequestMappingHandlerAdapter.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); if(getMappingForMethod == null){ @@ -150,6 +152,12 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor requestMappingHandlerMapping.unregisterMapping(requestMappingInfo); } } + if(handlerAdapter != null){ + Class beanClass = controllerBeanWrapper.getBeanClass(); + DestroyUtils.destroyValue(handlerAdapter, "sessionAttributesHandlerCache", beanClass); + DestroyUtils.destroyValue(handlerAdapter, "initBinderCache", beanClass); + DestroyUtils.destroyValue(handlerAdapter, "modelAttributeCache", beanClass); + } } /** @@ -229,6 +237,7 @@ public class PluginControllerRegistryProcessor implements SpringPluginProcessor ControllerWrapper controllerWrapper = new ControllerWrapper(); controllerWrapper.setPathPrefix(newPath); controllerWrapper.setBeanName(beanName); + controllerWrapper.setBeanClass(aClass); controllerWrappers.add(controllerWrapper); } catch (Exception e) { LOG.error("插件 [{}] Controller 类[{}] 注册异常. {}", pluginId, aClass.getName(), e.getMessage(), e); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index a187fbd..d564552 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -2,6 +2,7 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.core.launcher.plugin.RegistryInfo; @@ -28,7 +29,7 @@ public interface ProcessorContext extends RegistryInfo { * 得到插件信息 PluginDescriptor * @return PluginDescriptor */ - PluginDescriptor getPluginDescriptor(); + InsidePluginDescriptor getPluginDescriptor(); /** * 得到启动的class类 diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java index cedb10b..a69d418 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java @@ -3,7 +3,9 @@ package com.gitee.starblues.bootstrap.utils; import com.gitee.starblues.utils.ReflectionUtils; import java.util.Collection; +import java.util.Iterator; import java.util.Map; +import java.util.Objects; /** * @author starBlues @@ -13,21 +15,45 @@ public class DestroyUtils { private DestroyUtils(){} + public static void destroyAll(Object object, String fieldName, Class fieldType){ + destroyAll(object, object.getClass(), fieldName, fieldType); + } + + public static void destroyAll(Object object, Class objectClass, String fieldName, Class fieldType){ + try { + Object fieldObject = ReflectionUtils.getField(object, objectClass, fieldName, fieldType); + if(fieldObject == null){ + return; + } + destroyAll(fieldObject); + } catch (Exception e){ + // 忽略 + } + } + + public static void destroyValue(Object object, String fieldName, Object value){ + destroyValue(object, object.getClass(), fieldName, value); + } - public static void destroy(Object o, String fieldName, Class fieldType){ + public static void destroyValue(Object object, Class objectClass, String fieldName, Object value){ + destroyValue(object, objectClass, fieldName, null, value); + } + + + public static void destroyValue(Object object, Class objectClass, String fieldName, Class fieldType, Object value){ try { - Object fieldObject = ReflectionUtils.getField(o, fieldName, fieldType); + Object fieldObject = ReflectionUtils.getField(object, objectClass, fieldName, fieldType); if(fieldObject == null){ return; } - destroy(fieldObject); + destroyValue(fieldObject, value); } catch (Exception e){ // 忽略 } } @SuppressWarnings("all") - public static void destroy(Object object){ + public static void destroyAll(Object object){ if(object == null){ return; } @@ -43,4 +69,16 @@ public class DestroyUtils { } } + @SuppressWarnings("all") + public static void destroyValue(Object object, Object value){ + if(object == null){ + return; + } + if(object instanceof Map){ + ((Map)object).remove(value); + } else if (object instanceof Collection){ + ((Collection) object).removeIf(next -> Objects.equals(next, value)); + } + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java index ad32cfe..637d630 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java @@ -3,6 +3,7 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; +import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; @@ -16,10 +17,10 @@ public class DefaultPluginChecker implements PluginChecker{ @Override public void check(Path path) throws Exception { if(path == null){ - throw new Exception("path 文件路径不能为空"); + throw new FileNotFoundException("path 文件路径不能为空"); } if(Files.notExists(path)){ - throw new Exception("不存在文件: " + path.toString()); + throw new FileNotFoundException("不存在文件: " + path.toString()); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperInside.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java similarity index 50% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperInside.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java index 46d7629..df0a622 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperInside.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java @@ -1,26 +1,24 @@ package com.gitee.starblues.core; -import com.gitee.starblues.core.descriptor.PluginDescriptor; - -import java.nio.file.Path; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; /** - * 内部的 + * 默认的内部PluginWrapperInside实现 * @author starBlues + * @version 3.0.0 */ -public class PluginWrapperInside implements PluginWrapper { +public class DefaultPluginInsideInfo implements PluginInsideInfo { private final String pluginId; - private final PluginDescriptor pluginDescriptor; - private final Path pluginPath; + private final InsidePluginDescriptor pluginDescriptor; private PluginState pluginState; - public PluginWrapperInside(PluginDescriptor pluginDescriptor) { + public DefaultPluginInsideInfo(InsidePluginDescriptor pluginDescriptor) { this.pluginId = pluginDescriptor.getPluginId(); this.pluginDescriptor = pluginDescriptor; - this.pluginPath = pluginDescriptor.getPluginPath(); } + @Override public void setPluginState(PluginState pluginState) { this.pluginState = pluginState; } @@ -31,13 +29,18 @@ public class PluginWrapperInside implements PluginWrapper { } @Override - public PluginDescriptor getPluginDescriptor() { + public InsidePluginDescriptor getPluginDescriptor() { return pluginDescriptor; } @Override - public Path getPluginPath() { - return pluginPath; + public PluginInfo toPluginInfo() { + return new PluginInfoFace(this); + } + + @Override + public String getPluginPath() { + return pluginDescriptor.getPluginPath(); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 728e490..9e50dda 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -1,20 +1,27 @@ package com.gitee.starblues.core; -import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.MsgUtils; -import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.core.exception.PluginDisabledException; +import com.gitee.starblues.core.scanner.ComposePathResolve; +import com.gitee.starblues.core.scanner.DevPathResolve; +import com.gitee.starblues.core.scanner.PathResolve; +import com.gitee.starblues.core.scanner.ProdPathResolve; +import com.gitee.starblues.integration.operator.PluginOperator; +import com.gitee.starblues.utils.*; +import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; /** * 抽象的插件管理者 @@ -28,12 +35,16 @@ public class DefaultPluginManager implements PluginManager{ private final RealizeProvider provider; private final List pluginRootDirs; - private PluginConfiguration configuration = new PluginConfiguration(); + private final PathResolve pathResolve; private final AtomicBoolean loaded = new AtomicBoolean(false); - private final Map startedPlugins = new ConcurrentHashMap<>(); - private final Map resolvedPlugins = new ConcurrentHashMap<>(); + private final Map startedPlugins = new ConcurrentHashMap<>(); + private final Map resolvedPlugins = new ConcurrentHashMap<>(); + + private Set disabledPluginIds; + private List sortedPluginIds; + public DefaultPluginManager(RealizeProvider realizeProvider, String ...pluginRootDirs) { this(realizeProvider, pluginRootDirs == null ? null : Arrays.asList(pluginRootDirs)); @@ -47,28 +58,37 @@ public class DefaultPluginManager implements PluginManager{ } else { this.pluginRootDirs = pluginRootDirs; } + this.pathResolve = new ComposePathResolve(new DevPathResolve(), new ProdPathResolve()); + } + + public void setDisabledPluginIds(Set disabledPluginIds) { + this.disabledPluginIds = disabledPluginIds; + } + + public void setSortedPluginIds(List sortedPluginIds) { + this.sortedPluginIds = sortedPluginIds; } - public void setConfiguration(PluginConfiguration configuration) { - this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); + @Override + public List getPluginsRoots() { + return new ArrayList<>(pluginRootDirs); } @Override - public List getPluginsRoots() { - return pluginRootDirs.stream() - .filter(Objects::nonNull) - .map(Paths::get) - .collect(Collectors.toList()); + public String getDefaultPluginRoot() { + return pluginRootDirs.stream().findFirst().orElseThrow(()->{ + return new PluginException("插件根路径未配置"); + }); } @Override - public synchronized List loadPlugins() { + public synchronized List loadPlugins() { if(loaded.get()){ throw new RuntimeException("已经加载过了插件, 不能在重复调用: loadPlugins"); } try { if(ObjectUtils.isEmpty(pluginRootDirs)){ - log.warn("插件根目录为空, 无法发现插件."); + log.warn("插件根目录为空, 无法加载插件."); return Collections.emptyList(); } List scanPluginPaths = provider.getPluginScanner().scan(pluginRootDirs); @@ -81,234 +101,479 @@ public class DefaultPluginManager implements PluginManager{ log.warn(warn.toString(), pluginRootDirs); return Collections.emptyList(); } - List result = new ArrayList<>(scanPluginPaths.size()); + Map pluginInfoMap = new LinkedHashMap<>(scanPluginPaths.size()); for (Path path : scanPluginPaths) { try { - PluginDescriptor descriptor = load(path); - if(descriptor != null){ - result.add(descriptor); + PluginInsideInfo pluginInfo = loadPlugin(path, false); + if(pluginInfo != null){ + pluginInfoMap.put(pluginInfo.getPluginId(), pluginInfo.toPluginInfo()); } } catch (PluginException e) { - log.error("从路径[{}]加载插件失败. {}", path, e.getMessage(), e); + log.error("加载插件包失败: {}. {}", path, e.getMessage(), e); } } - return result; + return getSortPlugin(pluginInfoMap); } finally { loaded.set(true); } } @Override - public boolean verify(Path jarPath) { + public boolean verify(Path pluginPath) { + Assert.isNotNull(pluginPath, "参数pluginPath不能为空"); try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ - provider.getPluginChecker().check(jarPath); - PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(jarPath); + provider.getPluginChecker().check(pluginPath); + PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); if(pluginDescriptor == null){ return false; } provider.getPluginChecker().check(pluginDescriptor); return true; } catch (Exception e) { - log.error("插件jar包校验失败. [{}]" , jarPath, e); + log.error("插件jar包校验失败: {}" , pluginPath, e); return false; } } @Override - public synchronized PluginDescriptor load(Path pluginPath) throws PluginException { - try { - provider.getPluginChecker().check(pluginPath); - } catch (Exception e) { - throw new PluginException("非法插件: " + pluginPath, e); + public PluginInfo parse(Path pluginPath) throws PluginException { + PluginInsideInfo pluginInsideInfo = loadFromPath(pluginPath); + if(pluginInsideInfo == null){ + throw new PluginException("非法插件包: " + pluginPath); } - try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ - PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); - if(pluginDescriptor == null){ - return null; + return pluginInsideInfo.toPluginInfo(); + } + + @Override + public synchronized PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException { + Assert.isNotNull(pluginPath, "参数pluginPath不能为空"); + String sourcePluginPath = pluginPath.toString(); + try { + // 解析插件 + PluginInfo pluginInfo = parse(pluginPath); + // 检查是否存在当前插件 + PluginInsideInfo plugin = getPlugin(pluginInfo.getPluginId()); + if(plugin != null){ + // 已经存在该插件 + throw new PluginException("加载插件包[" + pluginPath + "]失败. 已经存在该插件: " + + MsgUtils.getPluginUnique(plugin.getPluginDescriptor())); } - String pluginId = pluginDescriptor.getPluginId(); - if(resolvedPlugins.containsKey(pluginId) || startedPlugins.containsKey(pluginId)){ - log.error("已经存在插件: {}", pluginId); + // 拷贝插件 + pluginPath = copyPlugin(pluginPath, unpackPlugin); + // 加载插件 + PluginInsideInfo pluginInsideInfo = loadPlugin(pluginPath, true); + if(pluginInsideInfo != null){ + return pluginInsideInfo.toPluginInfo(); + } else { return null; } - resolvedPlugins.put(pluginDescriptor.getPluginId(), pluginDescriptor); - log.info("加载插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); - return pluginDescriptor; - } catch (Exception e){ - throw new PluginException("加载插件失败"); + } catch (Exception e) { + throw PluginException.getPluginException(e, ()-> { + throw new PluginException("插件包加载失败: " + sourcePluginPath, e); + }); } - } @Override public synchronized void unLoad(String pluginId) { + Assert.isNotNull(pluginId, "参数pluginId不能为空"); resolvedPlugins.remove(pluginId); } @Override - public synchronized PluginDescriptor install(Path pluginPath) throws PluginException { - PluginDescriptor pluginDescriptor = load(pluginPath); - if(pluginDescriptor == null){ - throw new PluginException("安装[" + pluginPath + "]插件包失败."); + public synchronized PluginInfo install(Path pluginPath, boolean unpackPlugin) throws PluginException { + Assert.isNotNull(pluginPath, "参数pluginPath不能为空"); + PluginInfo loadPluginInfo = load(pluginPath, unpackPlugin); + if(loadPluginInfo == null){ + throw new PluginException("插件包安装失败: " + pluginPath); } try { - log.info("安装插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); - return start(pluginDescriptor); + PluginInsideInfo pluginInsideInfo = resolvedPlugins.get(loadPluginInfo.getPluginId()); + start(pluginInsideInfo); + log.info("安装插件[{}]成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); + return pluginInsideInfo.toPluginInfo(); } catch (Exception e){ - unLoad(pluginDescriptor.getPluginId()); - throw new PluginException("安装启动[" + pluginPath + "]插件包失败."); + if(e instanceof PluginDisabledException){ + throw (PluginDisabledException)e; + } + throw PluginException.getPluginException(e, ()-> { + unLoad(loadPluginInfo.getPluginId()); + throw new PluginException("插件包安装失败: " + pluginPath); + }); } } @Override public synchronized void uninstall(String pluginId) throws PluginException { - PluginWrapperInside pluginWrapper = startedPlugins.get(pluginId); - PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); - if(pluginWrapper == null && pluginDescriptor == null){ + Assert.isNotNull(pluginId, "参数pluginId不能为空"); + PluginInsideInfo wrapperInside = getPlugin(pluginId); + if(wrapperInside == null){ throw new PluginException("没有发现插件: " + pluginId); } - if(pluginWrapper != null){ - if(pluginWrapper.getPluginState() == PluginState.STARTED){ - try { - stop(pluginWrapper); - } catch (Exception e) { - throw new PluginException("停止", pluginId, e); - } + if(wrapperInside.getPluginState() == PluginState.STARTED){ + try { + stop(wrapperInside); + } catch (Exception e) { + throw PluginException.getPluginException(e, ()-> new PluginException("停止", pluginId, e)); } - startedPlugins.remove(pluginId); - pluginDescriptor = pluginWrapper.getPluginDescriptor(); } + startedPlugins.remove(pluginId); resolvedPlugins.remove(pluginId); - System.gc(); - log.info("卸载插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); + MsgUtils.info(log, wrapperInside.getPluginDescriptor(), "卸载成功"); } @Override - public synchronized void upgrade(Path pluginPath) throws PluginException { - PluginDescriptor upgradePluginDescriptor = load(pluginPath); - if(upgradePluginDescriptor == null){ - throw new PluginException("解析[" + pluginPath + "]插件更新包失败."); - } - String pluginId = upgradePluginDescriptor.getPluginId(); - PluginWrapper pluginWrapper = startedPlugins.get(pluginId); - PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); - if(pluginWrapper == null && pluginDescriptor == null){ - throw new PluginException("没有发现插件: " + pluginId + ", 无法更新."); - } - String oldPluginVersion; - if(pluginDescriptor != null){ - oldPluginVersion = pluginDescriptor.getPluginVersion(); - } else { - oldPluginVersion = pluginWrapper.getPluginDescriptor().getPluginVersion(); + public synchronized PluginInfo upgrade(Path pluginPath, boolean unpackPlugin) throws PluginException { + Assert.isNotNull(pluginPath, "参数pluginPath不能为空"); + // 解析插件包 + PluginInfo upgradePlugin = parse(pluginPath); + if(upgradePlugin == null){ + throw new PluginException("非法插件包: " + pluginPath); } - int compareVersion = provider.getVersionInspector().compareTo(oldPluginVersion, - upgradePluginDescriptor.getPluginVersion()); - if(compareVersion < 0){ - throw new PluginException("更新插件包[" + upgradePluginDescriptor.getPluginVersion() + "]版本不能小于等于:" - + oldPluginVersion); + // 检查插件是否被禁用 + checkDisabled(upgradePlugin, "更新"); + String pluginId = upgradePlugin.getPluginId(); + // 得到旧插件 + PluginInsideInfo oldPlugin = getPlugin(pluginId); + if(oldPlugin == null){ + // 旧插件为空, 则直接安装新插件 + return install(pluginPath, unpackPlugin); } - if(pluginDescriptor != null){ - // 说明插件没有被启动 - resolvedPlugins.put(pluginId, upgradePluginDescriptor); - } else { + // 检查插件版本 + PluginDescriptor upgradePluginDescriptor = upgradePlugin.getPluginDescriptor(); + checkVersion(oldPlugin.getPluginDescriptor().getPluginVersion(), upgradePluginDescriptor.getPluginVersion()); + if(oldPlugin.getPluginState() == PluginState.STARTED){ + // 如果插件被启动, 则卸载旧的插件 uninstall(pluginId); + } else if(oldPlugin.getPluginState() == PluginState.LOADED){ + // 如果插件被load + unLoad(pluginId); } try { - start(upgradePluginDescriptor); + // 安装新插件 + install(pluginPath, unpackPlugin); log.info("更新插件[{}]成功", MsgUtils.getPluginUnique(upgradePluginDescriptor)); + return upgradePlugin; } catch (Exception e){ - throw new PluginException("更新启动", pluginId, e); + throw PluginException.getPluginException(e, ()-> new PluginException(upgradePluginDescriptor, "更新失败", e)); } } @Override - public synchronized PluginDescriptor start(String pluginId) throws PluginException { - PluginDescriptor pluginDescriptor = resolvedPlugins.get(pluginId); - if(pluginDescriptor == null){ + public synchronized PluginInfo start(String pluginId) throws PluginException { + if(ObjectUtils.isEmpty(pluginId)){ + return null; + } + PluginInsideInfo pluginInsideInfo = getPlugin(pluginId); + if(pluginInsideInfo == null){ throw new PluginException("没有发现插件: " + pluginId); } try { - start(pluginDescriptor); - log.info("启动插件[{}]成功", MsgUtils.getPluginUnique(pluginDescriptor)); - return pluginDescriptor; + start(pluginInsideInfo); + log.info("启动插件[{}]成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); + return pluginInsideInfo.toPluginInfo(); } catch (Exception e){ - throw new PluginException("启动", pluginId, e); + throw PluginException.getPluginException(e, ()-> new PluginException(pluginInsideInfo.getPluginDescriptor(), "启动失败", e)); } } @Override - public synchronized PluginDescriptor stop(String pluginId) throws PluginException { - PluginWrapperInside pluginWrapper = startedPlugins.get(pluginId); - if(pluginWrapper == null){ + public synchronized PluginInfo stop(String pluginId) throws PluginException { + if(ObjectUtils.isEmpty(pluginId)){ + return null; + } + PluginInsideInfo pluginInsideInfo = startedPlugins.get(pluginId); + if(pluginInsideInfo == null){ throw new PluginException("没有发现插件: " + pluginId); } try { - stop(pluginWrapper); - log.info("停止插件[{}]成功", MsgUtils.getPluginUnique(pluginWrapper.getPluginDescriptor())); - return pluginWrapper.getPluginDescriptor(); + stop(pluginInsideInfo); + log.info("停止插件[{}]成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); + return pluginInsideInfo.toPluginInfo(); } catch (Exception e) { - throw new PluginException("停止插件 [" + pluginId + "] 失败. ", e); + throw PluginException.getPluginException(e, ()-> new PluginException(pluginInsideInfo.getPluginDescriptor(), "停止失败", e)); } } @Override - public List getPluginDescriptors() { - List pluginDescriptors = new ArrayList<>(resolvedPlugins.values()); - for (PluginWrapper value : startedPlugins.values()) { - pluginDescriptors.add(value.getPluginDescriptor()); + public synchronized PluginInfo getPluginInfo(String pluginId) { + if(ObjectUtils.isEmpty(pluginId)){ + return null; + } + PluginInsideInfo wrapperInside = startedPlugins.get(pluginId); + if(wrapperInside == null){ + wrapperInside = resolvedPlugins.get(pluginId); + } + if(wrapperInside != null){ + return wrapperInside.toPluginInfo(); + } else { + return null; } - return pluginDescriptors; } @Override - public PluginDescriptor getPluginDescriptor(String pluginId) { - PluginWrapper pluginWrapper = startedPlugins.get(pluginId); - if(pluginWrapper != null){ - return pluginWrapper.getPluginDescriptor(); + public synchronized List getPluginInfos() { + List pluginDescriptors = new ArrayList<>( + resolvedPlugins.size() + startedPlugins.size()); + for (PluginInsideInfo wrapperInside : startedPlugins.values()) { + pluginDescriptors.add(wrapperInside.toPluginInfo()); + } + for (PluginInsideInfo wrapperInside : resolvedPlugins.values()) { + pluginDescriptors.add(wrapperInside.toPluginInfo()); } - return resolvedPlugins.get(pluginId); + return pluginDescriptors; } - @Override - public List getPluginWrappers() { - List pluginWrappers = new ArrayList<>(startedPlugins.size()); - for (PluginWrapper value : startedPlugins.values()) { - pluginWrappers.add(new PluginWrapperFace(value)); + protected PluginInsideInfo loadPlugin(Path pluginPath, boolean resolvePath) { + if(resolvePath){ + Path sourcePluginPath = pluginPath; + pluginPath = pathResolve.resolve(pluginPath); + if(pluginPath == null){ + throw new PluginException("未发现插件: " + sourcePluginPath); + } + } + PluginInsideInfo pluginInsideInfo = loadFromPath(pluginPath); + if(pluginInsideInfo == null){ + throw new PluginException("路径中未发现合法插件"); } - return pluginWrappers; + String pluginId = pluginInsideInfo.getPluginId(); + if(resolvedPlugins.containsKey(pluginId)){ + throw new PluginException(pluginInsideInfo.getPluginDescriptor(), "已经被加载"); + } + resolvedPlugins.put(pluginId, pluginInsideInfo); + MsgUtils.info(log, pluginInsideInfo.getPluginDescriptor(), "加载成功"); + return pluginInsideInfo; } - @Override - public PluginWrapper getPluginWrapper(String pluginId) { - return startedPlugins.get(pluginId); + protected PluginInsideInfo loadFromPath(Path pluginPath) { + try { + provider.getPluginChecker().check(pluginPath); + } catch (Exception e) { + throw PluginException.getPluginException(e, ()-> { + return new PluginException("非法插件包. " + e.getMessage(), e); + }); + } + + try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ + InsidePluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); + if(pluginDescriptor == null){ + throw new PluginException("非法插件包: " + pluginPath); + } + String pluginId = pluginDescriptor.getPluginId(); + PluginInsideInfo pluginInsideInfo = new DefaultPluginInsideInfo(pluginDescriptor); + if(isDisabled(pluginId)){ + pluginInsideInfo.setPluginState(PluginState.DISABLED); + } else { + pluginInsideInfo.setPluginState(PluginState.LOADED); + } + return pluginInsideInfo; + } catch (Exception e){ + throw PluginException.getPluginException(e, ()-> new PluginException("加载插件失败")); + } } - protected PluginDescriptor start(PluginDescriptor pluginDescriptor) throws Exception { - String pluginId = pluginDescriptor.getPluginId(); - if(startedPlugins.containsKey(pluginId)){ - throw new PluginException("已经存在插件: " + MsgUtils.getPluginUnique(pluginDescriptor)); + /** + * 拷贝插件文件到插件根目录 + * @param pluginPath 源插件文件路径 + * @param unpackPlugin 是否解压插件包. 只有为压缩类型包才可解压 + * @return 拷贝后的插件路径 + * @throws IOException IO 异常 + */ + protected Path copyPlugin(Path pluginPath, boolean unpackPlugin) throws IOException { + if(isDev()){ + return pluginPath; } - provider.getPluginChecker().check(pluginDescriptor); - PluginWrapperInside pluginWrapper = new PluginWrapperInside(pluginDescriptor); - pluginWrapper.setPluginState(PluginState.RESOLVED); - start(pluginWrapper); - return pluginDescriptor; + File targetFile = pluginPath.toFile(); + if(!targetFile.exists()) { + throw new PluginException("不存在插件文件: " + pluginPath); + } + String targetFileName = targetFile.getName(); + // 先判断当前插件文件是否在插件目录中 + File pluginRootDir = null; + for (String dir : pluginRootDirs) { + File rootDir = new File(dir); + if(targetFile.getParentFile().compareTo(rootDir) == 0){ + pluginRootDir = rootDir; + break; + } + } + String resolvePluginFileName = unpackPlugin ? PluginFileUtils.getFileName(targetFile) : targetFileName; + Path resultPath = null; + if(pluginRootDir != null){ + // 在根目录中存在 + if(targetFile.isFile() && unpackPlugin){ + // 需要解压, 检查解压后的文件名称是否存在同名文件 + checkExistFile(pluginRootDir, resolvePluginFileName); + String unpackPluginPath = CommonUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName); + PluginFileUtils.decompressZip(targetFile.getPath(), unpackPluginPath); + resultPath = Paths.get(unpackPluginPath); + PluginFileUtils.deleteFile(targetFile); + } else { + resultPath = targetFile.toPath(); + } + } else { + File pluginFile = pluginPath.toFile(); + pluginRootDir = new File(getDefaultPluginRoot()); + File pluginRootDirFile = new File(getDefaultPluginRoot()); + // 检查是否存在同名文件 + checkExistFile(pluginRootDirFile, resolvePluginFileName); + targetFile = Paths.get(CommonUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName)).toFile(); + if(pluginFile.isFile()){ + if(unpackPlugin){ + // 需要解压 + String unpackPluginPath = CommonUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName); + PluginFileUtils.decompressZip(pluginFile.getPath(), unpackPluginPath); + resultPath = Paths.get(unpackPluginPath); + } else { + FileUtils.copyFile(pluginFile, targetFile); + resultPath = targetFile.toPath(); + } + } else { + FileUtils.copyDirectory(pluginFile, targetFile); + resultPath = targetFile.toPath(); + } + } + return resultPath; } - protected void start(PluginWrapperInside pluginWrapper) throws Exception{ - String pluginId = pluginWrapper.getPluginId(); - pluginWrapper.setPluginState(PluginState.STARTED); - startedPlugins.put(pluginId, pluginWrapper); + + /** + * 统一启动插件操作 + * @param pluginInsideInfo PluginInsideInfo + * @throws Exception 启动异常 + */ + protected void start(PluginInsideInfo pluginInsideInfo) throws Exception{ + Assert.isNotNull(pluginInsideInfo, "pluginInsideInfo 参数不能为空"); + String pluginId = pluginInsideInfo.getPluginId(); + InsidePluginDescriptor pluginDescriptor = pluginInsideInfo.getPluginDescriptor(); + checkCanStarted(pluginInsideInfo); + provider.getPluginChecker().check(pluginDescriptor); + pluginInsideInfo.setPluginState(PluginState.STARTED); + startedPlugins.put(pluginId, pluginInsideInfo); resolvedPlugins.remove(pluginId); } - protected void stop(PluginWrapperInside pluginWrapper) throws Exception{ - String pluginId = pluginWrapper.getPluginId(); - pluginWrapper.setPluginState(PluginState.STOPPED); - resolvedPlugins.put(pluginId, pluginWrapper.getPluginDescriptor()); + /** + * 统一停止插件操作 + * @param pluginInsideInfo PluginInsideInfo + * @throws Exception 启动异常 + */ + protected void stop(PluginInsideInfo pluginInsideInfo) throws Exception{ + checkCanStopped(pluginInsideInfo); + String pluginId = pluginInsideInfo.getPluginId(); + pluginInsideInfo.setPluginState(PluginState.STOPPED); + resolvedPlugins.put(pluginId, pluginInsideInfo); startedPlugins.remove(pluginId); } + /** + * 根据配置重新排序插件 + * @param pluginInfos 未排序的查询信息 + * @return 排序的插件信息 + */ + protected List getSortPlugin(Map pluginInfos){ + if (ObjectUtils.isEmpty(sortedPluginIds)) { + return new ArrayList<>(pluginInfos.values()); + } + List sortPluginInfos = new ArrayList<>(); + for (String sortedPluginId : sortedPluginIds) { + PluginInfo pluginInfo = pluginInfos.get(sortedPluginId); + if(pluginInfo != null){ + sortPluginInfos.add(pluginInfo); + pluginInfos.remove(sortedPluginId); + } + } + sortPluginInfos.addAll(pluginInfos.values()); + return sortPluginInfos; + } + + protected PluginInsideInfo getPlugin(String pluginId){ + PluginInsideInfo wrapperInside = startedPlugins.get(pluginId); + if(wrapperInside == null){ + wrapperInside = resolvedPlugins.get(pluginId); + } + return wrapperInside; + } + + /** + * 是否是开发环境 + * @return boolean + */ + private boolean isDev(){ + return provider.getRuntimeMode() == RuntimeMode.DEV; + } + + /** + * 检查是否目录中是否存在同名插件 + * @param dirFile 目录文件 + * @param pluginFileName 检查的插件名 + */ + private void checkExistFile(File dirFile, String pluginFileName) { + if(ResourceUtils.existFile(dirFile, pluginFileName)){ + // 插件根目录存在同名插件文件 + throw getExistFileException(dirFile.getPath(), pluginFileName); + } + } + + private PluginException getExistFileException(String rootPath, String pluginFileName){ + return new PluginException("插件目录[" + rootPath + "]存在同名文件: " + pluginFileName); + } + + /** + * 检查比较插件版本 + * @param oldPluginVersion 旧插件版本 + * @param newPluginVersion 新插件版本 + */ + protected void checkVersion(String oldPluginVersion, String newPluginVersion){ + int compareVersion = provider.getVersionInspector().compareTo(oldPluginVersion, newPluginVersion); + if(compareVersion <= 0){ + throw new PluginException("插件包版本[" + newPluginVersion + "]必须大于:" + + oldPluginVersion); + } + } + + /** + * 检查插件是否可启动 + * @param pluginInsideInfo PluginInfo + */ + private void checkCanStarted(PluginInfo pluginInsideInfo){ + checkDisabled(pluginInsideInfo, "启动"); + PluginState pluginState = pluginInsideInfo.getPluginState(); + if(pluginState == PluginState.STARTED){ + throw new PluginException(pluginInsideInfo.getPluginDescriptor(), "已经启动, 不能再启动"); + } + } + + /** + * 检查插件是否能停止 + * @param pluginInsideInfo PluginInfo + */ + private void checkCanStopped(PluginInfo pluginInsideInfo){ + checkDisabled(pluginInsideInfo, "停止"); + PluginState pluginState = pluginInsideInfo.getPluginState(); + if(pluginState != PluginState.STARTED){ + throw new PluginException(pluginInsideInfo.getPluginDescriptor(), "没有启动, 不能停止"); + } + } + + /** + * 检查插件是否被禁用 + * @param pluginInsideInfo PluginInfo + */ + private void checkDisabled(PluginInfo pluginInsideInfo, String opType){ + if(pluginInsideInfo.getPluginState() == PluginState.DISABLED || isDisabled(pluginInsideInfo.getPluginId())){ + throw new PluginDisabledException(pluginInsideInfo.getPluginDescriptor(), opType); + } + } + + /** + * 插件是否被禁用 + * @param pluginId 插件id + * @return boolean + */ + private boolean isDisabled(String pluginId){ + return disabledPluginIds != null && disabledPluginIds.contains(pluginId); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java index 3c801a3..07f5cb6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java @@ -10,31 +10,37 @@ import java.util.Set; */ public class PluginConfiguration { - private Set disabledPluginId; - private List sortedPluginId; + private Set disabledPluginIds; + private List sortedPluginIds; - public void setDisabledPluginIds(Set disabledPluginId) { - this.disabledPluginId = disabledPluginId; + public void setDisabledPluginIds(Set disabledPluginIds) { + this.disabledPluginIds = disabledPluginIds; } public void setSortedPluginId(List sortedPluginId) { - this.sortedPluginId = sortedPluginId; + this.sortedPluginIds = sortedPluginIds; } + + public boolean isDisabled(String pluginId){ + return disabledPluginIds != null && disabledPluginIds.contains(pluginId); + } + + /** * 得到禁用的插件id * @return Set */ - public Set getDisabledPluginId(){ - return disabledPluginId; + public Set getDisabledPluginIds(){ + return disabledPluginIds; } /** * 得到按照循序启动的插件id * @return Set */ - public List getSortedPluginId(){ - return sortedPluginId; + public List getSortedPluginIds(){ + return sortedPluginIds; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java index b17652a..a450b0f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java @@ -3,6 +3,8 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.MsgUtils; +import java.util.function.Supplier; + /** * 插件异常 @@ -19,25 +21,34 @@ public class PluginException extends RuntimeException{ super(message); } + public PluginException(Throwable cause) { + super(cause); + } + public PluginException(String message, Throwable cause) { super(message, cause); } - public PluginException(String opType, PluginDescriptor pluginDescriptor, Throwable cause) { - this(opType, MsgUtils.getPluginUnique(pluginDescriptor), cause); + public PluginException(PluginDescriptor pluginDescriptor, String opType, Throwable cause) { + this(MsgUtils.getPluginUnique(pluginDescriptor), opType, cause); } - public PluginException(String opType, PluginDescriptor pluginDescriptor, String message) { - this(opType, MsgUtils.getPluginUnique(pluginDescriptor), message); + public PluginException(PluginDescriptor pluginDescriptor, String message) { + this(MsgUtils.getPluginUnique(pluginDescriptor), message); } - public PluginException(String opType, String pluginId, Throwable cause) { - super(opType + "插件[" + pluginId + "]失败. " + MsgUtils.getThrowableMsg(cause), cause); + public PluginException(String pluginId, String opType, Throwable cause) { + super("插件[" + pluginId + "]" + opType + "失败. " + MsgUtils.getThrowableMsg(cause), cause); } - public PluginException(String opType, String pluginId, String message) { - super(opType + "插件[" + pluginId + "]失败. " + MsgUtils.getThrowableMsg(message)); + public PluginException(String pluginId, String message) { + super("插件[" + pluginId + "]" + MsgUtils.getThrowableMsg(message)); } - + public static PluginException getPluginException(Throwable throwable, Supplier getException){ + if(throwable instanceof PluginException){ + return (PluginException) throwable; + } + return getException.get(); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java similarity index 86% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapper.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java index ebf4150..6b7537a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java @@ -2,14 +2,12 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import java.nio.file.Path; - /** * 插件包装 * @author starBlues * @version 3.0.0 */ -public interface PluginWrapper { +public interface PluginInfo { /** * 得到插件id @@ -27,7 +25,7 @@ public interface PluginWrapper { * 得到插件路径 * @return Path */ - Path getPluginPath(); + String getPluginPath(); /** * 得到插件状态 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java new file mode 100644 index 0000000..32ad7d6 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java @@ -0,0 +1,53 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.Assert; + +/** + * 外部 PluginWrapperFace + * @author starBlues + * @version 3.0.0 + */ +public class PluginInfoFace implements PluginInfo { + + private final PluginDescriptor pluginDescriptor; + private final PluginState pluginState; + + public PluginInfoFace(PluginInsideInfo pluginInsideInfo) { + Assert.isNotNull(pluginInsideInfo, "参数 pluginWrapperInside 不能为空"); + this.pluginDescriptor = pluginInsideInfo.getPluginDescriptor().toPluginDescriptor(); + this.pluginState = pluginInsideInfo.getPluginState(); + } + + public PluginInfoFace(PluginDescriptor pluginDescriptor, PluginState pluginState) { + Assert.isNotNull(pluginDescriptor, "参数 pluginDescriptor 不能为空"); + Assert.isNotNull(pluginState, "参数 pluginState 不能为空"); + if(pluginDescriptor instanceof InsidePluginDescriptor){ + this.pluginDescriptor = ((InsidePluginDescriptor)pluginDescriptor).toPluginDescriptor(); + } else { + this.pluginDescriptor = pluginDescriptor; + } + this.pluginState = pluginState; + } + + @Override + public String getPluginId() { + return pluginDescriptor.getPluginId(); + } + + @Override + public PluginDescriptor getPluginDescriptor() { + return pluginDescriptor; + } + + @Override + public String getPluginPath() { + return pluginDescriptor.getPluginPath(); + } + + @Override + public PluginState getPluginState() { + return pluginState; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java new file mode 100644 index 0000000..28d92f9 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.core; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; + +/** + * 内部的 PluginWrapper + * @version 3.0.0 + * @author starBlues + */ +public interface PluginInsideInfo extends PluginInfo { + + /** + * 设置插件状态 + * @param pluginState 插件状态 + */ + void setPluginState(PluginState pluginState); + + /** + * 得到插件描述 + * @return PluginDescriptor + */ + @Override + InsidePluginDescriptor getPluginDescriptor(); + + /** + * 转换为插件信息 + * @return PluginInfo + */ + PluginInfo toPluginInfo(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index 61e94e0..cfda374 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; @@ -37,25 +38,33 @@ public class PluginLauncherManager extends DefaultPluginManager{ applicationContext); this.configuration = configuration; this.invokeSupperCache = new DefaultInvokeSupperCache(); + setDisabledPluginIds(configuration.disablePluginIds()); + setSortedPluginIds(configuration.sortInitPluginIds()); } @Override - protected void start(PluginWrapperInside pluginWrapper) throws Exception { - super.start(pluginWrapper); - PluginDescriptor pluginDescriptor = pluginWrapper.getPluginDescriptor(); - PluginInteractive pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, - mainApplicationContext, configuration, invokeSupperCache); - PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive); - SpringPluginHook springPluginHook = pluginLauncher.run(); - RegistryPluginInfo registryPluginInfo = new RegistryPluginInfo(pluginDescriptor, springPluginHook); - pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), registryPluginInfo); + protected void start(PluginInsideInfo pluginInsideInfo) throws Exception { + super.start(pluginInsideInfo); + try { + InsidePluginDescriptor pluginDescriptor = pluginInsideInfo.getPluginDescriptor(); + PluginInteractive pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, + mainApplicationContext, configuration, invokeSupperCache); + PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive); + SpringPluginHook springPluginHook = pluginLauncher.run(); + RegistryPluginInfo registryPluginInfo = new RegistryPluginInfo(pluginDescriptor, springPluginHook); + pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), registryPluginInfo); + } catch (Exception e){ + // 启动失败, 进行停止 + super.stop(pluginInsideInfo); + throw e; + } } @Override - protected void stop(PluginWrapperInside pluginWrapper) throws Exception { - String pluginId = pluginWrapper.getPluginId(); + protected void stop(PluginInsideInfo pluginInsideInfo) throws Exception { + String pluginId = pluginInsideInfo.getPluginId(); RegistryPluginInfo registryPluginInfo = pluginRegistryInfoMap.get(pluginId); if(registryPluginInfo == null){ throw new PluginException("没有发现插件 '" + pluginId + "' 信息"); @@ -63,7 +72,7 @@ public class PluginLauncherManager extends DefaultPluginManager{ registryPluginInfo.getSpringPluginHook().close(); invokeSupperCache.remove(pluginId); pluginRegistryInfoMap.remove(pluginId); - super.stop(pluginWrapper); + super.stop(pluginInsideInfo); } private static class RegistryPluginInfo{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java index 96792d0..3561e47 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -1,7 +1,5 @@ package com.gitee.starblues.core; -import com.gitee.starblues.core.descriptor.PluginDescriptor; - import java.nio.file.Path; import java.util.List; @@ -15,28 +13,43 @@ public interface PluginManager { * 得到插件root目录 * @return List */ - List getPluginsRoots(); + List getPluginsRoots(); + + /** + * 得到插件默认的根路径 + * @return String + */ + String getDefaultPluginRoot(); /** * 加载配置目录中全部插件 * @return 加载的插件信息 */ - List loadPlugins(); + List loadPlugins(); /** - * 校验插件jar包 - * @param jarPath 插件jar包 + * 校验插件包 + * @param pluginPath 插件包路径 * @return 校验结果. true 成功, false 失败 */ - boolean verify(Path jarPath); + boolean verify(Path pluginPath); + + /** + * 解析插件包 + * @param pluginPath 插件包路基 + * @return 解析的插件信息 + * @throws PluginException 插件异常 + */ + PluginInfo parse(Path pluginPath) throws PluginException; /** - * 安装具体插件路径来加载插件 + * 根据具体插件路径来加载插件. * @param pluginPath 插件路径 + * @param unpackPlugin 是否解压插件文件 * @return 加载的插件信息 * @throws PluginException 插件异常 */ - PluginDescriptor load(Path pluginPath) throws PluginException; + PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException; /** * 卸载加载插件 @@ -47,10 +60,11 @@ public interface PluginManager { /** * 安装路径直接安装插件, 并启动 * @param pluginPath 插件路径 + * @param unpackPlugin 是否解压插件文件 * @return 安装的插件信息 * @throws PluginException 插件异常 */ - PluginDescriptor install(Path pluginPath) throws PluginException; + PluginInfo install(Path pluginPath, boolean unpackPlugin) throws PluginException; /** * 卸载插件 @@ -62,9 +76,11 @@ public interface PluginManager { /** * 更新已经安装的插件 * @param pluginPath 新版本插件路径 + * @param unpackPlugin 是否解压要更新的插件文件 * @throws PluginException 插件异常 + * @return PluginInfo 更新的插件信息 */ - void upgrade(Path pluginPath) throws PluginException; + PluginInfo upgrade(Path pluginPath, boolean unpackPlugin) throws PluginException; /** * 启动处于 RESOLVED 状态的插件 @@ -72,7 +88,7 @@ public interface PluginManager { * @return PluginDescriptor * @throws PluginException 插件异常 */ - PluginDescriptor start(String pluginId) throws PluginException; + PluginInfo start(String pluginId) throws PluginException; /** * 停止启动的插件 @@ -80,32 +96,19 @@ public interface PluginManager { * @return PluginDescriptor * @throws PluginException 插件异常 */ - PluginDescriptor stop(String pluginId) throws PluginException; - - /** - * 得到全部的插件信息 - * @return List PluginDescriptor - */ - List getPluginDescriptors(); + PluginInfo stop(String pluginId) throws PluginException; /** * 根据插件id获取插件描述信息 * @param pluginId 插件id * @return PluginDescriptor */ - PluginDescriptor getPluginDescriptor(String pluginId); + PluginInfo getPluginInfo(String pluginId); /** * 得到全部的插件信息 * @return List PluginWrapper */ - List getPluginWrappers(); - - /** - * 根据插件id获取插件 PluginWrapper - * @param pluginId 插件id - * @return PluginWrapper - */ - PluginWrapper getPluginWrapper(String pluginId); + List getPluginInfos(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java index ac616b1..ed21df8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java @@ -8,20 +8,14 @@ package com.gitee.starblues.core; public enum PluginState { /** - * 创建状态 - */ - CREATED("CREATED"), - - - /** - * 禁用状态 + * 被禁用状态 */ DISABLED("DISABLED"), /** * 被加载了 */ - RESOLVED("LOADED"), + LOADED("LOADED"), /** * 启动状态 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java deleted file mode 100644 index b945c35..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginWrapperFace.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.gitee.starblues.core; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; - -import java.nio.file.Path; - -/** - * 外部 PluginWrapperFace - * @author starBlues - * @version 3.0.0 - */ -public class PluginWrapperFace implements PluginWrapper { - - private final PluginWrapper pluginWrapper; - - public PluginWrapperFace(PluginWrapper pluginWrapper) { - this.pluginWrapper = pluginWrapper; - } - - @Override - public String getPluginId() { - return pluginWrapper.getPluginId(); - } - - @Override - public PluginDescriptor getPluginDescriptor() { - return pluginWrapper.getPluginDescriptor(); - } - - @Override - public Path getPluginPath() { - return pluginWrapper.getPluginPath(); - } - - @Override - public PluginState getPluginState() { - return pluginWrapper.getPluginState(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index 80240e6..f277c44 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -1,11 +1,9 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.utils.ResourceUtils; import org.apache.commons.io.IOUtils; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; @@ -75,6 +73,20 @@ public abstract class AbstractResourceLoader { resourceCache.clear(); } - + protected byte[] getClassBytes(String path, InputStream inputStream, boolean isClose) throws Exception{ + if(!ResourceUtils.isClass(path)){ + return null; + } + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + try { + IOUtils.copy(inputStream, byteArrayOutputStream); + return byteArrayOutputStream.toByteArray(); + } finally { + if(isClose){ + IOUtils.closeQuietly(inputStream); + } + IOUtils.closeQuietly(byteArrayOutputStream); + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java index 0038d5d..7234f52 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -3,7 +3,9 @@ package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ResourceUtils; +import org.apache.commons.io.IOUtils; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.MalformedURLException; @@ -57,23 +59,23 @@ public class ClassPathLoader extends AbstractResourceLoader{ private void loadResource(File file, String packageName) throws Exception{ if(file.isDirectory()){ - addResource(file, packageName + ResourceUtils.PACKAGE_SPLIT, null); - return; - } - try (FileInputStream fileInputStream = new FileInputStream(file)) { - byte[] bytes = new byte[(int) file.length()]; - - if (fileInputStream.read(bytes) != -1) { - addResource(file, packageName, bytes); - } + addResource(file, packageName + ResourceUtils.PACKAGE_SPLIT); + } else { + addResource(file, packageName); } } - private void addResource(File file, String packageName, byte[] bytes) throws MalformedURLException { + private void addResource(File file, String packageName) throws Exception { Resource resource = new Resource( file.getName(), url, new URL(url.toString() + packageName) ); + if(file.exists() && file.isFile()){ + resource.setBytes(getClassBytes(file.getPath(), new FileInputStream(file), true)); + } addResource(packageName, resource); } + + + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java index 9841a44..96f5a42 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java @@ -1,6 +1,5 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ResourceUtils; @@ -65,6 +64,10 @@ public class GenericClassLoader extends URLClassLoader { resourceLoaderFactory.addResource(path); } + public void addResource(URL url) throws Exception { + resourceLoaderFactory.addResource(url); + } + @Override public Class loadClass(String className) throws ClassNotFoundException { synchronized (getClassLoadingLock(className)) { @@ -104,30 +107,16 @@ public class GenericClassLoader extends URLClassLoader { if (aClass != null) { return aClass; } - - InputStream inputStream = resourceLoaderFactory.getInputStream(formatClassName); - if(inputStream == null){ - return null; + Resource resource = resourceLoaderFactory.findResource(formatClassName); + byte[] bytes = null; + if(resource != null){ + bytes = resource.getBytes(); } - ByteArrayOutputStream byteArrayOutputStream = null; - byte[] bytes; - try { - if(inputStream instanceof ByteArrayInputStream){ - ByteArrayInputStream arrayInputStream = (ByteArrayInputStream) inputStream; - bytes = IOUtils.readFully(inputStream, arrayInputStream.available()); - } else { - byteArrayOutputStream = new ByteArrayOutputStream(); - IOUtils.copy(inputStream, byteArrayOutputStream); - bytes = byteArrayOutputStream.toByteArray(); - } - } catch (Exception e){ - e.printStackTrace(); + if(bytes == null || bytes.length == 0){ + bytes = getClassByte(formatClassName); + } + if(bytes == null || bytes.length == 0){ return null; - } finally { - IOUtils.closeQuietly(inputStream); - if(byteArrayOutputStream != null){ - IOUtils.closeQuietly(byteArrayOutputStream); - } } aClass = defineClass(name, bytes, 0, bytes.length ); if(aClass == null) { @@ -144,6 +133,34 @@ public class GenericClassLoader extends URLClassLoader { } } + private byte[] getClassByte(String formatClassName){ + InputStream inputStream = resourceLoaderFactory.getInputStream(formatClassName); + if(inputStream == null){ + return null; + } + ByteArrayOutputStream byteArrayOutputStream = null; + byte[] bytes = null; + try { + if(inputStream instanceof ByteArrayInputStream){ + ByteArrayInputStream arrayInputStream = (ByteArrayInputStream) inputStream; + bytes = IOUtils.readFully(inputStream, arrayInputStream.available()); + } else { + byteArrayOutputStream = new ByteArrayOutputStream(); + IOUtils.copy(inputStream, byteArrayOutputStream); + bytes = byteArrayOutputStream.toByteArray(); + } + return bytes; + } catch (Exception e){ + e.printStackTrace(); + return null; + } finally { + IOUtils.closeQuietly(inputStream); + if(byteArrayOutputStream != null){ + IOUtils.closeQuietly(byteArrayOutputStream); + } + } + } + @Override public URL[] getURLs() { List resources = resourceLoaderFactory.getResources(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index 7cf8028..d100ff6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -1,7 +1,11 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.utils.ResourceUtils; import org.apache.commons.io.IOUtils; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; import java.net.URL; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; @@ -35,7 +39,9 @@ public class JarResourceLoader extends AbstractResourceLoader{ String name = jarEntry.getName(); URL url = new URL(baseUrl.toString() + name); Resource resource = new Resource(name, baseUrl, url); + resource.setBytes(getClassBytes(name, jarInputStream, false)); addResource(name, resource); + jarInputStream.closeEntry(); } } finally { IOUtils.closeQuietly(jarInputStream); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java index bc46cde..6d34c50 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java @@ -1,16 +1,16 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import java.io.InputStream; import java.net.URL; -import java.util.ArrayList; import java.util.Enumeration; -import java.util.List; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; +import java.util.zip.ZipEntry; /** * @author starBlues @@ -18,11 +18,12 @@ import java.util.jar.JarInputStream; */ public class NestedJarResourceLoader extends AbstractResourceLoader{ - private final PluginDescriptor pluginDescriptor; + private final InsidePluginDescriptor pluginDescriptor; private final ResourceLoaderFactory resourceLoaderFactory; - public NestedJarResourceLoader(PluginDescriptor pluginDescriptor, ResourceLoaderFactory resourceLoaderFactory) throws Exception { - super(new URL("jar:" + pluginDescriptor.getPluginPath().toUri().toURL() + "!/")); + public NestedJarResourceLoader(InsidePluginDescriptor pluginDescriptor, + ResourceLoaderFactory resourceLoaderFactory) throws Exception { + super(new URL("jar:" + pluginDescriptor.getInsidePluginPath().toUri().toURL() + "!/")); this.pluginDescriptor = pluginDescriptor; this.resourceLoaderFactory = resourceLoaderFactory; } @@ -30,7 +31,7 @@ public class NestedJarResourceLoader extends AbstractResourceLoader{ @Override public void init() throws Exception { super.init(); - try (JarFile jarFile = new JarFile(pluginDescriptor.getPluginPath().toFile())) { + try (JarFile jarFile = new JarFile(pluginDescriptor.getInsidePluginPath().toFile())) { addClassPath(jarFile); addLib(jarFile); } @@ -48,6 +49,7 @@ public class NestedJarResourceLoader extends AbstractResourceLoader{ String realName = jarEntry.getName().replace(classesPath, ""); URL url = new URL(baseUrl.toString() + jarEntry.getName()); Resource resource = new Resource(realName, baseUrl, url); + resource.setBytes(getClassBytes(realName, jarFile.getInputStream(jarEntry), true)); addResource(realName, resource); } } @@ -57,6 +59,9 @@ public class NestedJarResourceLoader extends AbstractResourceLoader{ Set pluginLibPaths = pluginDescriptor.getPluginLibPaths(); for (String pluginLibPath : pluginLibPaths) { jarEntry = jarFile.getJarEntry(pluginLibPath); + if (jarEntry.getMethod() != ZipEntry.STORED) { + throw new PluginException("插件依赖压缩方式错误, 必须是: 存储(stored)压缩方式"); + } InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); URL url = new URL(baseUrl.toString() + pluginLibPath + "!/"); JarResourceLoader jarResourceLoader = new JarResourceLoader(url, new JarInputStream(jarFileInputStream)); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index 742047f..ee832a8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; @@ -34,7 +35,7 @@ public class PluginClassLoader extends GenericClassLoader { } } - public void addResource(PluginDescriptor pluginDescriptor) throws Exception { + public void addResource(InsidePluginDescriptor pluginDescriptor) throws Exception { ((PluginResourceLoaderFactory) resourceLoaderFactory).addResource(pluginDescriptor); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java index 2b6496f..b7c10e9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java @@ -1,6 +1,7 @@ package com.gitee.starblues.core.classloader; import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; @@ -16,19 +17,19 @@ import java.util.Set; public class PluginResourceLoaderFactory extends ResourceLoaderFactory{ - public synchronized void addResource(PluginDescriptor pluginDescriptor) throws Exception{ + public synchronized void addResource(InsidePluginDescriptor pluginDescriptor) throws Exception{ PluginDescriptor.Type type = pluginDescriptor.getType(); if(type == PluginDescriptor.Type.JAR || type == PluginDescriptor.Type.ZIP){ NestedJarResourceLoader resourceLoader = new NestedJarResourceLoader(pluginDescriptor, this); resourceLoader.init(); addResourceLoader(resourceLoader); - } else if(type == PluginDescriptor.Type.DIR_OF_DEV || type == PluginDescriptor.Type.DIR_OF_PROD){ + } else if(type == PluginDescriptor.Type.DIR || type == PluginDescriptor.Type.DEV){ addClasspath(pluginDescriptor); addLibFile(pluginDescriptor); } } - private void addClasspath(PluginDescriptor pluginDescriptor) throws Exception { + private void addClasspath(InsidePluginDescriptor pluginDescriptor) throws Exception { String pluginClassPath = pluginDescriptor.getPluginClassPath(); File existFile = PluginFileUtils.getExistFile(pluginClassPath); if(existFile != null){ @@ -36,7 +37,7 @@ public class PluginResourceLoaderFactory extends ResourceLoaderFactory{ } } - private void addLibFile(PluginDescriptor pluginDescriptor) throws Exception { + private void addLibFile(InsidePluginDescriptor pluginDescriptor) throws Exception { Set pluginLibPaths = pluginDescriptor.getPluginLibPaths(); if(ObjectUtils.isEmpty(pluginLibPaths)){ return; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java index 338d958..79ad636 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java @@ -14,6 +14,8 @@ public class Resource { private final URL baseUrl; private final URL url; + private byte[] bytes; + public Resource(String name, URL baseUrl, URL url) { this.name = name; this.baseUrl = baseUrl; @@ -32,6 +34,14 @@ public class Resource { return url; } + public byte[] getBytes() { + return bytes; + } + + public void setBytes(byte[] bytes) { + this.bytes = bytes; + } + void tryCloseUrlSystemFile(){ try { Paths.get(baseUrl.toURI()).getFileSystem().close(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java index 45f0494..e73c008 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java @@ -1,6 +1,5 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.ResourceUtils; import java.io.File; @@ -25,7 +24,6 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { super(null); } - void addResourceLoader(AbstractResourceLoader resourceLoader){ if(resourceLoader != null){ resourceLoaders.add(resourceLoader); @@ -54,10 +52,14 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { return; } URL url = path.toUri().toURL(); + addResource(url); + } + + public void addResource(URL url) throws Exception{ AbstractResourceLoader resourceLoader = null; - if(ResourceUtils.isJarFile(path)) { + if(ResourceUtils.isJarFileURL(url)) { resourceLoader = new JarResourceLoader(url); - } else if(Files.isDirectory(path)){ + } else if(ResourceUtils.isFileURL(url)){ resourceLoader = new ClassPathLoader(url); } if(resourceLoader != null){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index 0f43d8d..99a0f99 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -34,7 +34,7 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor @Override - public PluginDescriptor load(Path location) throws PluginException { + public InsidePluginDescriptor load(Path location) throws PluginException { Manifest manifest = null; try { manifest = getManifest(location); @@ -62,9 +62,9 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor */ protected abstract Manifest getManifest(Path location) throws Exception; - protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception{ + protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception{ Attributes attributes = manifest.getMainAttributes(); - DefaultPluginDescriptor descriptor = new DefaultPluginDescriptor( + DefaultInsidePluginDescriptor descriptor = new DefaultInsidePluginDescriptor( getValue(attributes, PLUGIN_ID), getValue(attributes, PLUGIN_VERSION), getValue(attributes, PLUGIN_BOOTSTRAP_CLASS), diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java new file mode 100644 index 0000000..82710ea --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -0,0 +1,93 @@ +package com.gitee.starblues.core.descriptor; + +import java.nio.file.Path; +import java.util.Set; +import java.util.jar.Manifest; + +/** + * 内部的默认插件描述者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor implements InsidePluginDescriptor{ + + private final Path pluginPath; + private final String pluginFileName; + + private String pluginClassPath; + private Manifest manifest; + private String configFileName; + private Set pluginLibPaths; + + public DefaultInsidePluginDescriptor(String pluginId, String pluginVersion, String pluginClass, Path pluginPath) { + super(pluginId, pluginVersion, pluginClass, pluginPath.toAbsolutePath().toString()); + this.pluginPath = pluginPath; + this.pluginFileName = pluginPath.toFile().getName(); + } + + public void setPluginClassPath(String pluginClassPath) { + this.pluginClassPath = pluginClassPath; + } + + public void setManifest(Manifest manifest){ + this.manifest = manifest; + } + + public void setPluginLibPath(Set pluginLibPaths) { + this.pluginLibPaths = pluginLibPaths; + } + + public void setConfigFileName(String configFileName) { + this.configFileName = configFileName; + } + + + @Override + public String getPluginClassPath() { + return pluginClassPath; + } + + @Override + public Set getPluginLibPaths() { + return pluginLibPaths; + } + + @Override + public String getConfigFileName() { + return configFileName; + } + + @Override + public Path getInsidePluginPath() { + return pluginPath; + } + + @Override + public String getPluginFileName() { + return pluginFileName; + } + + @Override + public Manifest getManifest() { + return manifest; + } + + @Override + public PluginDescriptor toPluginDescriptor() { + Path pluginPath = getInsidePluginPath(); + if(getType() == Type.DEV) { + // dev模式 插件路径展示项目目录 + pluginPath = pluginPath.getParent().getParent(); + } + DefaultPluginDescriptor descriptor = new DefaultPluginDescriptor( + getPluginId(), getPluginVersion(), getPluginBootstrapClass(), pluginPath.toAbsolutePath().toString() + ); + descriptor.setType(getType()); + descriptor.setDescription(getDescription()); + descriptor.setProvider(getProvider()); + descriptor.setRequires(getRequires()); + descriptor.setLicense(getLicense()); + return descriptor; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java index 578257d..100e6c1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java @@ -20,22 +20,18 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ private final String pluginId; private final String pluginVersion; private final String pluginBootstrapClass; - private final Path pluginPath; + private final String pluginPath; - private String pluginClassPath; - private Manifest manifest; - private Type type; - private Set pluginLibPaths; + private Type type; private String description; private String requires; private String provider; private String license; - private String configFileName; public DefaultPluginDescriptor(String pluginId, String pluginVersion, - String pluginClass, Path pluginPath) { + String pluginClass, String pluginPath) { this.pluginId = Assert.isNotEmpty(pluginId, PLUGIN_ID + "不能为空"); this.pluginVersion = Assert.isNotEmpty(pluginVersion, PLUGIN_VERSION + "不能为空"); this.pluginBootstrapClass = Assert.isNotEmpty(pluginClass, PLUGIN_BOOTSTRAP_CLASS + "不能为空"); @@ -58,18 +54,6 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ this.license = license; } - void setConfigFileName(String configFileName) { - this.configFileName = configFileName; - } - - void setPluginClassPath(String pluginClassPath) { - this.pluginClassPath = pluginClassPath; - } - - void setManifest(Manifest manifest){ - this.manifest = manifest; - } - void setType(Type type) { this.type = type; } @@ -90,20 +74,10 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ } @Override - public Path getPluginPath() { + public String getPluginPath() { return pluginPath; } - @Override - public String getPluginClassPath() { - return pluginClassPath; - } - - @Override - public Set getPluginLibPaths() { - return pluginLibPaths; - } - @Override public String getDescription() { return description; @@ -129,22 +103,9 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ return null; } - @Override - public Manifest getManifest() { - return manifest; - } - @Override public Type getType() { return type; } - @Override - public String getConfigFileName() { - return configFileName; - } - - public void setPluginLibPath(Set pluginLibPaths) { - this.pluginLibPaths = pluginLibPaths; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java index 3898331..8d51456 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java @@ -42,9 +42,9 @@ public class DevPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ } @Override - protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception { - final DefaultPluginDescriptor descriptor = super.create(manifest, path); - descriptor.setType(PluginDescriptor.Type.DIR_OF_DEV); + protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { + final DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); + descriptor.setType(PluginDescriptor.Type.DEV); return descriptor; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java index 96281be..f4f557a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java @@ -9,7 +9,7 @@ import java.util.jar.Manifest; * @author starBlues * @version 3.0.0 */ -public class EmptyPluginDescriptor implements PluginDescriptor{ +public class EmptyPluginDescriptor implements InsidePluginDescriptor{ @Override public String getPluginId() { return null; @@ -26,37 +26,42 @@ public class EmptyPluginDescriptor implements PluginDescriptor{ } @Override - public Path getPluginPath() { + public String getPluginPath() { return null; } @Override - public String getPluginClassPath() { + public String getDescription() { return null; } @Override - public Set getPluginLibPaths() { + public String getRequires() { return null; } @Override - public String getDescription() { + public String getProvider() { return null; } @Override - public String getRequires() { + public String getLicense() { return null; } @Override - public String getProvider() { + public List getPluginDependency() { return null; } @Override - public String getLicense() { + public Type getType() { + return null; + } + + @Override + public Manifest getManifest() { return null; } @@ -66,17 +71,27 @@ public class EmptyPluginDescriptor implements PluginDescriptor{ } @Override - public List getPluginDependency() { + public Path getInsidePluginPath() { return null; } @Override - public Manifest getManifest() { + public String getPluginFileName() { return null; } @Override - public Type getType() { + public String getPluginClassPath() { + return null; + } + + @Override + public Set getPluginLibPaths() { + return null; + } + + @Override + public PluginDescriptor toPluginDescriptor() { return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java new file mode 100644 index 0000000..47ce9b3 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java @@ -0,0 +1,57 @@ +package com.gitee.starblues.core.descriptor; + +import java.nio.file.Path; +import java.util.Set; +import java.util.jar.Manifest; + +/** + * @author starBlues + * @version 1.0 + */ +public interface InsidePluginDescriptor extends PluginDescriptor{ + + /** + * 得到插件的 Manifest 文件 + * @return Manifest + */ + Manifest getManifest(); + + + /** + * 获取插件配置文件名称 + * @return String + */ + String getConfigFileName(); + + /** + * 得到内部的插件路径 + * @return Path + */ + Path getInsidePluginPath(); + + /** + * 获取插件文件名称 + * @return String + */ + String getPluginFileName(); + + + /** + * 获取插件classes path路径 + * @return Path + */ + String getPluginClassPath(); + + /** + * 获取插件依赖的路径 + * @return String + */ + Set getPluginLibPaths(); + + /** + * 转换为 PluginDescriptor + * @return PluginDescriptor + */ + PluginDescriptor toPluginDescriptor(); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java index 996ad5a..5166f27 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -1,9 +1,6 @@ package com.gitee.starblues.core.descriptor; -import java.nio.file.Path; import java.util.List; -import java.util.Set; -import java.util.jar.Manifest; /** * 插件信息 @@ -34,19 +31,7 @@ public interface PluginDescriptor { * 获取插件路径 * @return Path */ - Path getPluginPath(); - - /** - * 获取插件classes path路径 - * @return Path - */ - String getPluginClassPath(); - - /** - * 获取插件依赖的路径 - * @return String - */ - Set getPluginLibPaths(); + String getPluginPath(); /** * 获取插件描述 @@ -72,30 +57,19 @@ public interface PluginDescriptor { */ String getLicense(); - /** - * 获取插件配置文件名称 - * @return String - */ - String getConfigFileName(); - /** * 获取当前插件依赖 * @return List */ List getPluginDependency(); - /** - * 得到插件的 Manifest 文件 - * @return Manifest - */ - Manifest getManifest(); - /** * 得到插件类型 * @return 插件类型 */ Type getType(); + /** * 插件类型 */ @@ -113,12 +87,12 @@ public interface PluginDescriptor { /** * 生产模式目录 */ - DIR_OF_PROD, + DIR, /** * 开发模式目录 */ - DIR_OF_DEV + DEV; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java index 38461e4..4b56072 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java @@ -19,7 +19,7 @@ public interface PluginDescriptorLoader extends AutoCloseable{ * @return PluginDescriptor * @throws PluginException 加载异常 */ - PluginDescriptor load(Path location) throws PluginException; + InsidePluginDescriptor load(Path location) throws PluginException; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java index cbc9b4e..c4a2517 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -44,16 +44,14 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade } @Override - protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception { - DefaultPluginDescriptor descriptor = super.create(manifest, path); - descriptor.setType(PluginDescriptor.Type.DIR_OF_PROD); - String pluginClassPath = descriptor.getPluginClassPath(); + protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { + DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); + descriptor.setType(PluginDescriptor.Type.DIR); String pathStr = path.toFile().getPath(); - if(ObjectUtils.isEmpty(pluginClassPath) || Files.notExists(Paths.get(pluginClassPath))){ - descriptor.setPluginClassPath(CommonUtils.joiningPath( - pathStr, CLASSES_NAME - )); - } + descriptor.setPluginClassPath(CommonUtils.joiningPath( + pathStr, CLASSES_NAME + )); + System.out.println(descriptor.getPluginClassPath()); return descriptor; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java index c043a1b..20ed6f9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -4,6 +4,7 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.common.utils.ManifestUtils; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; import org.apache.commons.io.IOUtils; import java.io.InputStream; @@ -37,7 +38,11 @@ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorL @Override protected Manifest getManifest(Path location) throws Exception { try (JarFile jarFile = new JarFile(location.toFile())){ - Manifest manifest = jarFile.getManifest(); + JarEntry jarEntry = jarFile.getJarEntry(PackageStructure.PROD_MANIFEST_PATH); + // TODO + InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); + Manifest manifest = PluginFileUtils.getManifest(jarFileInputStream); + jarFileInputStream.close(); pluginLibPaths = getPluginLibPaths(jarFile, manifest); return manifest; } @@ -49,8 +54,8 @@ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorL } @Override - protected DefaultPluginDescriptor create(Manifest manifest, Path path) throws Exception { - final DefaultPluginDescriptor descriptor = super.create(manifest, path); + protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { + DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); descriptor.setType(type); return descriptor; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index b85467d..a82412b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -18,7 +18,7 @@ public class ProdPluginDescriptorLoader implements PluginDescriptorLoader{ private PluginDescriptorLoader target; @Override - public PluginDescriptor load(Path location) throws PluginException { + public InsidePluginDescriptor load(Path location) throws PluginException { if(ResourceUtils.isJarFile(location)){ target = new ProdPackagePluginDescriptorLoader(PluginDescriptor.Type.JAR); } else if(ResourceUtils.isZipFile(location)){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java new file mode 100644 index 0000000..e252786 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java @@ -0,0 +1,23 @@ +package com.gitee.starblues.core.exception; + +import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.MsgUtils; +import com.gitee.starblues.utils.ObjectUtils; + +/** + * 插件被禁用异常 + * @author starBlues + * @version 3.0.0 + */ +public class PluginDisabledException extends PluginException { + + public PluginDisabledException(PluginDescriptor pluginDescriptor) { + this(pluginDescriptor, null); + } + + public PluginDisabledException(PluginDescriptor pluginDescriptor, String opType) { + super("插件[" + MsgUtils.getPluginUnique(pluginDescriptor) + "]已被禁用, 不能" + + (!ObjectUtils.isEmpty(opType) ? opType : "操作")); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java index 0c17947..62abe3a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java @@ -1,7 +1,7 @@ package com.gitee.starblues.core.launcher; -import com.gitee.starblues.core.launcher.jar.JarFile; +import com.gitee.starblues.core.launcher.jar.JarFile; /** * @author starBlues diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java index 6463741..f2f99fc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java @@ -1,20 +1,12 @@ package com.gitee.starblues.core.launcher; import com.gitee.starblues.core.classloader.GenericClassLoader; -import com.gitee.starblues.core.classloader.PluginClassLoader; -import com.gitee.starblues.core.launcher.archive.Archive; -import com.gitee.starblues.core.launcher.archive.ExplodedArchive; -import com.gitee.starblues.core.launcher.archive.JarFileArchive; -import com.gitee.starblues.utils.PluginFileUtils; +import com.gitee.starblues.utils.ObjectUtils; -import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import java.net.URLClassLoader; +import java.util.Objects; /** * @author starBlues @@ -22,6 +14,7 @@ import java.util.List; */ public class MainProgramLauncher extends AbstractLauncher{ + private static final String MAIN_CLASS_LOADER_NAME = "MainProgramLauncherClassLoader"; private final SpringBootstrap springBootstrap; @@ -32,7 +25,7 @@ public class MainProgramLauncher extends AbstractLauncher{ @Override protected ClassLoader createClassLoader() throws Exception { GenericClassLoader classLoader = new GenericClassLoader( - "MainProgramLauncherClassLoader", MainProgramLauncher.class.getClassLoader() + MAIN_CLASS_LOADER_NAME, MainProgramLauncher.class.getClassLoader() ); addResource(classLoader); return classLoader; @@ -40,10 +33,19 @@ public class MainProgramLauncher extends AbstractLauncher{ protected void addResource(GenericClassLoader classLoader) throws Exception{ String classPath = ManagementFactory.getRuntimeMXBean().getClassPath(); - String[] split = classPath.split(";"); - List archives = new ArrayList<>(); - for (String s : split) { - classLoader.addResource(s); + if(!ObjectUtils.isEmpty(classPath)){ + String[] classPathStr = classPath.split(";"); + for (String path : classPathStr) { + classLoader.addResource(path); + } + } + ClassLoader sourceClassLoader = Thread.currentThread().getContextClassLoader(); + if(sourceClassLoader instanceof URLClassLoader){ + URLClassLoader urlClassLoader = (URLClassLoader) sourceClassLoader; + final URL[] urLs = urlClassLoader.getURLs(); + for (URL url : urLs) { + classLoader.addResource(url); + } } } @@ -54,4 +56,9 @@ public class MainProgramLauncher extends AbstractLauncher{ run.run(classLoader); return classLoader; } + + private static boolean isStartupOfJar() { + String protocol = MainProgramLauncher.class.getResource("").getProtocol(); + return Objects.equals(protocol, "jar"); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java new file mode 100644 index 0000000..af93722 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java @@ -0,0 +1,117 @@ +package com.gitee.starblues.core.launcher; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.launcher.jar.AbstractJarFile; +import com.gitee.starblues.core.launcher.jar.JarFile; +import com.gitee.starblues.core.launcher.jar.JarFileWrapper; +import org.apache.commons.io.IOUtils; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 1.0 + */ +public class PluginResourceStorage { + + public static Map pluginResourceStorage = new ConcurrentHashMap<>(); + + + public static void addPlugin(InsidePluginDescriptor descriptor){ + if(pluginResourceStorage.containsKey(descriptor.getPluginId())){ + return; + } + pluginResourceStorage.put(descriptor.getPluginId(), new Storage(descriptor)); + } + + + public static void removePlugin(String pluginId){ + Storage storage = pluginResourceStorage.get(pluginId); + if(storage == null){ + return; + } + IOUtils.closeQuietly(storage); + pluginResourceStorage.remove(pluginId); + } + + public static void addJarFile(AbstractJarFile jarFile){ + pluginResourceStorage.forEach((k,v)->{ + v.addJarFile(jarFile.getName(), jarFile); + }); + } + + public static void addRootJarFile(File file, JarFile jarFile){ + pluginResourceStorage.forEach((k,v)->{ + v.addRootJarFile(file, jarFile); + }); + } + + public static JarFile getRootJarFile(File file){ + for (Storage value : pluginResourceStorage.values()) { + JarFile jarFile = value.getRootJarFile(file); + if(jarFile != null){ + return jarFile; + } + } + return null; + } + + + private static class Storage implements Closeable { + private final InsidePluginDescriptor descriptor; + private final Map rootJarFileMap = new ConcurrentHashMap<>(); + private final Map> jarFileMap = new ConcurrentHashMap<>(); + + public Storage(InsidePluginDescriptor descriptor) { + this.descriptor = descriptor; + } + + public void addJarFile(String name, AbstractJarFile jarFile){ + if(name == null || jarFile == null){ + return; + } + String pluginFileName = descriptor.getPluginFileName(); + if(name.contains(pluginFileName)){ + List jarFiles = jarFileMap.computeIfAbsent(name, k -> new ArrayList<>()); + jarFiles.add(jarFile); + } + } + + public void addRootJarFile(File file, JarFile jarFile){ + String pluginFileName = descriptor.getPluginFileName(); + String absolutePath = file.getAbsolutePath(); + if(absolutePath.contains(pluginFileName)){ + rootJarFileMap.put(file, jarFile); + } + } + + public JarFile getRootJarFile(File file){ + return rootJarFileMap.get(file); + } + + @Override + public void close() throws IOException { + for (List value : jarFileMap.values()) { + for (AbstractJarFile jarFile : value) { + if(jarFile == null){ + continue; + } + if(jarFile instanceof JarFileWrapper){ + ((JarFileWrapper)jarFile).canClosed(); + } + IOUtils.closeQuietly(jarFile); + } + } + jarFileMap.clear(); + rootJarFileMap.clear(); + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java index 23ba9c7..e44956f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java @@ -1,9 +1,13 @@ package com.gitee.starblues.core.launcher.jar; +import com.gitee.starblues.core.launcher.PluginResourceStorage; + import java.io.File; import java.io.IOException; import java.lang.ref.SoftReference; import java.net.*; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; @@ -61,15 +65,17 @@ public class Handler extends URLStreamHandler { @Override protected URLConnection openConnection(URL url) throws IOException { + URLConnection jarURLConnection = null; if (this.jarFile != null && isUrlInJarFile(url, this.jarFile)) { - return JarURLConnection.get(url, this.jarFile); - } - try { - return JarURLConnection.get(url, getRootJarFileFromUrl(url)); - } - catch (Exception ex) { - return openFallbackConnection(url, ex); + jarURLConnection = JarURLConnection.get(url, this.jarFile); + } else { + try { + jarURLConnection = JarURLConnection.get(url, getRootJarFileFromUrl(url)); + } catch (Exception ex) { + jarURLConnection = openFallbackConnection(url, ex); + } } + return jarURLConnection; } private boolean isUrlInJarFile(URL url, JarFile jarFile) throws MalformedURLException { @@ -83,8 +89,7 @@ public class Handler extends URLStreamHandler { URLConnection connection = openFallbackTomcatConnection(url); connection = (connection != null) ? connection : openFallbackContextConnection(url); return (connection != null) ? connection : openFallbackHandlerConnection(url); - } - catch (Exception ex) { + } catch (Exception ex) { if (reason instanceof IOException) { log(false, "Unable to open fallback handler", ex); throw (IOException) reason; @@ -148,8 +153,7 @@ public class Handler extends URLStreamHandler { if (jarContextUrl != null) { return new URL(jarContextUrl, url.toExternalForm()).openConnection(); } - } - catch (Exception ex) { + } catch (Exception ex) { } return null; } @@ -307,7 +311,7 @@ public class Handler extends URLStreamHandler { @Override protected boolean sameFile(URL u1, URL u2) { - if (!u1.getProtocol().equals("jar") || !u2.getProtocol().equals("jar")) { + if (!"jar".equals(u1.getProtocol()) || !"jar".equals(u2.getProtocol())) { return false; } int separator1 = u1.getFile().indexOf(SEPARATOR); @@ -355,15 +359,13 @@ public class Handler extends URLStreamHandler { throw new IllegalStateException("Not a file URL"); } File file = new File(URI.create(name)); - Map cache = rootFileCache.get(); - JarFile result = (cache != null) ? cache.get(file) : null; - if (result == null) { - result = new JarFile(file); - addToRootFileCache(file, result); + JarFile jarFile = PluginResourceStorage.getRootJarFile(file); + if (jarFile == null) { + jarFile = new JarFile(file); + PluginResourceStorage.addRootJarFile(file, jarFile); } - return result; - } - catch (Exception ex) { + return jarFile; + } catch (Exception ex) { throw new IOException("Unable to open root Jar file '" + name + "'", ex); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java index b7487ba..bc4315f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java @@ -255,8 +255,7 @@ public class JarFile extends AbstractJarFile implements Iterable> inputStreamCache; + + private final AtomicBoolean canClosed = new AtomicBoolean(false); + JarFileWrapper(JarFile parent) throws IOException { super(parent.getRootJarFile().getFile()); this.parent = parent; - super.close(); + this.parentName = UUID.randomUUID().toString() + parent.getName(); + this.inputStreamCache = new ConcurrentHashMap<>(); } @Override @@ -67,12 +79,16 @@ public class JarFileWrapper extends AbstractJarFile { @Override InputStream getInputStream() throws IOException { - return this.parent.getInputStream(); + InputStream inputStream = this.parent.getInputStream(); + addInputStream(parentName, inputStream); + return inputStream; } @Override public synchronized InputStream getInputStream(ZipEntry ze) throws IOException { - return this.parent.getInputStream(ze); + InputStream inputStream = this.parent.getInputStream(ze); + addInputStream(ze.getName(), inputStream); + return inputStream; } @Override @@ -95,6 +111,36 @@ public class JarFileWrapper extends AbstractJarFile { return this.parent.getName(); } + @Override + public void close() throws IOException { + super.close(); + if(canClosed.get()){ + for (List inputStreams : inputStreamCache.values()) { + if(ObjectUtils.isEmpty(inputStreams)){ + continue; + } + for (InputStream inputStream : inputStreams) { + if(inputStream == null){ + continue; + } + IOUtils.closeQuietly(inputStream); + } + } + parent.close(); + } + } + + public void canClosed(){ + canClosed.set(true); + } + + private void addInputStream(String name, InputStream inputStream){ + if(inputStream != null){ + List inputStreams = inputStreamCache.computeIfAbsent(name, k -> new ArrayList<>()); + inputStreams.add(inputStream); + } + } + static JarFile unwrap(java.util.jar.JarFile jarFile) { if (jarFile instanceof JarFile) { return (JarFile) jarFile; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarTest2.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarTest2.java deleted file mode 100644 index 38b29b3..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarTest2.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.core.launcher.jar; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; - -/** - * @author starBlues - * @version 1.0 - */ -public class JarTest2 { - - public static void main(String[] args) throws IOException { - File file = new File("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-framework-example\\example-plugins-basic\\example-basic-1\\target\\example-basic-1-1.0.0-SNAPSHOT_0.jar"); - File file2 = new File("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-framework-example\\example-plugins-basic\\example-basic-1\\target\\plugin\\lib\\aspectjweaver-1.9.6.jar"); - JarInputStream jarStream = new JarInputStream(new BufferedInputStream(new FileInputStream(file2))); - JarEntry jarEntry = null; - while ((jarEntry = jarStream.getNextJarEntry()) != null) { - System.out.println(jarEntry.getName()); - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java index 77cb617..4a834b0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java @@ -1,8 +1,15 @@ package com.gitee.starblues.core.launcher.jar; +import com.gitee.starblues.core.launcher.PluginResourceStorage; +import org.apache.commons.io.IOUtils; + import java.io.*; import java.net.*; import java.security.Permission; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * @author starBlues @@ -125,7 +132,7 @@ public class JarURLConnection extends java.net.JarURLConnection { } @Override - public InputStream getInputStream() throws IOException { + public synchronized InputStream getInputStream() throws IOException { if (this.jarFile == null) { throw FILE_NOT_FOUND_EXCEPTION; } @@ -137,6 +144,7 @@ public class JarURLConnection extends java.net.JarURLConnection { : this.jarFile.getInputStream(this.jarEntry)); if (inputStream == null) { throwFileNotFound(this.jarEntryName, this.jarFile); + return null; } return inputStream; } @@ -168,8 +176,7 @@ public class JarURLConnection extends java.net.JarURLConnection { } java.util.jar.JarEntry entry = getJarEntry(); return (entry != null) ? (int) entry.getSize() : -1; - } - catch (IOException ex) { + } catch (IOException ex) { return -1; } } @@ -204,8 +211,7 @@ public class JarURLConnection extends java.net.JarURLConnection { try { java.util.jar.JarEntry entry = getJarEntry(); return (entry != null) ? entry.getTime() : 0; - } - catch (IOException ex) { + } catch (IOException ex) { return 0; } } @@ -236,7 +242,9 @@ public class JarURLConnection extends java.net.JarURLConnection { && !jarFile.containsEntry(jarEntryName.toString())) { return NOT_FOUND_CONNECTION; } - return new JarURLConnection(url, new JarFileWrapper(jarFile), jarEntryName); + JarFileWrapper jarFileWrapper = new JarFileWrapper(jarFile); + PluginResourceStorage.addJarFile(jarFileWrapper); + return new JarURLConnection(url, jarFileWrapper, jarEntryName); } private static int indexOfRootSpec(StringSequence file, String pathFromRoot) { @@ -280,10 +288,17 @@ public class JarURLConnection extends java.net.JarURLConnection { if (source.isEmpty() || (source.indexOf('%') < 0)) { return source; } - ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length()); - write(source.toString(), bos); - // AsciiBytes is what is used to store the JarEntries so make it symmetric - return new StringSequence(AsciiBytes.toString(bos.toByteArray())); + ByteArrayOutputStream bos = null; + try { + bos = new ByteArrayOutputStream(source.length()); + write(source.toString(), bos); + // AsciiBytes is what is used to store the JarEntries so make it symmetric + return new StringSequence(AsciiBytes.toString(bos.toByteArray())); + } finally { + if(bos != null){ + IOUtils.closeQuietly(bos); + } + } } private void write(String source, ByteArrayOutputStream outputStream) { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java index 3b03aae..e2f9c9f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core.launcher.plugin; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; @@ -15,13 +16,13 @@ import com.gitee.starblues.spring.invoke.InvokeSupperCache; */ public class DefaultPluginInteractive implements PluginInteractive{ - private final PluginDescriptor pluginDescriptor; + private final InsidePluginDescriptor pluginDescriptor; private final MainApplicationContext mainApplicationContext; private final IntegrationConfiguration configuration; private final InvokeSupperCache invokeSupperCache; private final OpExtractFactory opExtractFactory; - public DefaultPluginInteractive(PluginDescriptor pluginDescriptor, + public DefaultPluginInteractive(InsidePluginDescriptor pluginDescriptor, MainApplicationContext mainApplicationContext, IntegrationConfiguration configuration, InvokeSupperCache invokeSupperCache) { @@ -39,7 +40,7 @@ public class DefaultPluginInteractive implements PluginInteractive{ @Override - public PluginDescriptor getPluginDescriptor() { + public InsidePluginDescriptor getPluginDescriptor() { return pluginDescriptor; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java index de839ba..c0467d6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core.launcher.plugin; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; @@ -17,7 +18,7 @@ public interface PluginInteractive { * 获取插件信息 * @return PluginDescriptor */ - PluginDescriptor getPluginDescriptor(); + InsidePluginDescriptor getPluginDescriptor(); /** * 获取主程序的 MainApplicationContext diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index a37a273..2c28259 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -2,10 +2,12 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.classloader.PluginClassLoader; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.AbstractLauncher; import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; import com.gitee.starblues.core.launcher.MainProgramLauncher; +import com.gitee.starblues.core.launcher.PluginResourceStorage; import com.gitee.starblues.spring.SpringPluginHook; import com.gitee.starblues.utils.ObjectUtils; @@ -21,7 +23,7 @@ import java.util.Set; public class PluginLauncher extends AbstractLauncher { protected final PluginInteractive pluginInteractive; - protected final PluginDescriptor pluginDescriptor; + protected final InsidePluginDescriptor pluginDescriptor; public PluginLauncher(PluginInteractive pluginInteractive) { this.pluginInteractive = pluginInteractive; @@ -51,8 +53,9 @@ public class PluginLauncher extends AbstractLauncher { @Override protected SpringPluginHook launch(ClassLoader classLoader, String... args) throws Exception { + PluginResourceStorage.addPlugin(pluginDescriptor); SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive).run(classLoader); - return new SpringPluginHookWrapper(springPluginHook, classLoader); + return new SpringPluginHookWrapper(springPluginHook, pluginDescriptor, classLoader); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java index 77971fc..afcbcff 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java @@ -1,5 +1,8 @@ package com.gitee.starblues.core.launcher.plugin; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.launcher.PluginResourceStorage; +import com.gitee.starblues.core.launcher.jar.Handler; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; @@ -10,11 +13,14 @@ import com.gitee.starblues.spring.SpringPluginHook; public class SpringPluginHookWrapper implements SpringPluginHook { private final SpringPluginHook target; + private final InsidePluginDescriptor descriptor; private final ClassLoader classLoader; public SpringPluginHookWrapper(SpringPluginHook target, + InsidePluginDescriptor descriptor, ClassLoader classLoader) { this.target = target; + this.descriptor = descriptor; this.classLoader = classLoader; } @@ -26,9 +32,12 @@ public class SpringPluginHookWrapper implements SpringPluginHook { @Override public void close() throws Exception { - target.close(); + if(target != null){ + target.close(); + } if(classLoader instanceof AutoCloseable){ ((AutoCloseable)classLoader).close(); } + PluginResourceStorage.removePlugin(descriptor.getPluginId()); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java new file mode 100644 index 0000000..ff300c7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java @@ -0,0 +1,47 @@ +package com.gitee.starblues.core.scanner; + +import com.gitee.starblues.utils.ObjectUtils; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * 组合的PathResolve + * @author starBlues + * @version 1.0 + */ +public class ComposePathResolve implements PathResolve{ + + private final List pathResolves; + + public ComposePathResolve(PathResolve ...pathResolves) { + this(Arrays.asList(pathResolves)); + } + + public ComposePathResolve(List pathResolves) { + if(ObjectUtils.isEmpty(pathResolves)){ + this.pathResolves = new ArrayList<>(); + } else { + this.pathResolves = pathResolves; + } + } + + public void addPathResolve(PathResolve pathResolve){ + if(pathResolve != null){ + pathResolves.add(pathResolve); + } + } + + @Override + public Path resolve(Path path) { + for (PathResolve pathResolve : pathResolves) { + Path resolvePath = pathResolve.resolve(path); + if(resolvePath != null){ + return resolvePath; + } + } + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java index 5397ba7..3961ac9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java @@ -3,7 +3,7 @@ package com.gitee.starblues.core.scanner; import java.nio.file.Path; /** - * 目录解决器 + * 从路径中发现合适的插件 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java index d65f3f9..3ce507c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java @@ -48,7 +48,12 @@ public class ProdPathResolve implements PathResolve{ } protected boolean isDirPlugin(Path path){ - File file = new File(CommonUtils.joiningFilePath(path.toString(), PackageStructure.resolvePath( + File file = path.toFile(); + if(file.isFile()){ + return false; + } + + file = new File(CommonUtils.joiningFilePath(path.toString(), PackageStructure.resolvePath( PackageStructure.PROD_MANIFEST_PATH ))); return file.exists() && file.isFile(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index bfe7f1a..9c7c137 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -166,7 +166,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String uploadTempPath() { - if(!ObjectUtils.isEmpty(uploadTempPath)){ + if(ObjectUtils.isEmpty(uploadTempPath)){ return super.uploadTempPath(); } return uploadTempPath; @@ -174,7 +174,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String backupPath() { - if(!ObjectUtils.isEmpty(backupPath)){ + if(ObjectUtils.isEmpty(backupPath)){ return super.backupPath(); } return backupPath; @@ -190,7 +190,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String pluginRestPathPrefix() { - if(!ObjectUtils.isEmpty(pluginRestPathPrefix)){ + if(ObjectUtils.isEmpty(pluginRestPathPrefix)){ return super.pluginRestPathPrefix(); } else { return pluginRestPathPrefix; @@ -280,9 +280,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio } public List getPluginPath() { - if(ObjectUtils.isEmpty(pluginPath)){ - return super.pluginPath(); - } return pluginPath; } @@ -298,14 +295,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.pluginConfigFilePath = pluginConfigFilePath; } - public Boolean getEnablePluginRestController() { - return enablePluginRestController; - } - - public void setEnablePluginRestController(Boolean enablePluginRestController) { - this.enablePluginRestController = enablePluginRestController; - } - public String getPluginRestPathPrefix() { return pluginRestPathPrefix; } @@ -314,6 +303,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.pluginRestPathPrefix = pluginRestPathPrefix; } + public Boolean getEnablePluginRestController() { + return enablePluginRestController; + } + + public void setEnablePluginRestController(Boolean enablePluginRestController) { + this.enablePluginRestController = enablePluginRestController; + } + public Boolean getEnablePluginIdRestPathPrefix() { return enablePluginIdRestPathPrefix; } @@ -362,6 +359,14 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.exactVersionAllowed = exactVersionAllowed; } + public Boolean getStopDependents() { + return stopDependents; + } + + public void setStopDependents(Boolean stopDependents) { + this.stopDependents = stopDependents; + } + public Set getEnablePluginIds() { return enablePluginIds; } @@ -393,12 +398,4 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio public void setEnableWebSocket(Boolean enableWebSocket) { this.enableWebSocket = enableWebSocket; } - - public Boolean getStopDependents() { - return stopDependents; - } - - public void setStopDependents(Boolean stopDependents) { - this.stopDependents = stopDependents; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java index 747c84d..32a1075 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java @@ -60,7 +60,7 @@ public class PluginInitializerListenerFactory implements PluginInitializerListen * 添加监听者 * @param pluginInitializerListener pluginInitializerListener */ - public void addPluginInitializerListeners(PluginInitializerListener pluginInitializerListener){ + public void addListener(PluginInitializerListener pluginInitializerListener){ if(pluginInitializerListener != null){ pluginInitializerListeners.add(pluginInitializerListener); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 6c828e5..6a354c1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -1,22 +1,32 @@ package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.*; -import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginDisabledException; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.operator.module.PluginInfo; -import com.gitee.starblues.utils.MsgUtils; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; +import com.gitee.starblues.integration.listener.PluginInitializerListenerFactory; +import com.gitee.starblues.integration.operator.upload.UploadByInputStreamParam; +import com.gitee.starblues.integration.operator.upload.UploadByMultipartFileParam; +import com.gitee.starblues.integration.operator.upload.UploadParam; +import com.gitee.starblues.utils.*; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.multipart.MultipartFile; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; /** * 默认的插件操作者 @@ -26,51 +36,58 @@ import java.util.stream.Collectors; public class DefaultPluginOperator implements PluginOperator { protected final Logger log = LoggerFactory.getLogger(this.getClass()); + private final static DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + private final AtomicBoolean isInit = new AtomicBoolean(false); private final IntegrationConfiguration configuration; private final PluginManager pluginManager; + private final PluginInitializerListenerFactory pluginInitializerListenerFactory; public DefaultPluginOperator(GenericApplicationContext applicationContext, RealizeProvider realizeProvider, IntegrationConfiguration configuration) { this.configuration = configuration; this.pluginManager = new PluginLauncherManager(realizeProvider, applicationContext, configuration); + this.pluginInitializerListenerFactory = new PluginInitializerListenerFactory(applicationContext); } - @Override public synchronized boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException { if(isInit.get()){ throw new RuntimeException("插件已经被初始化了, 不能再初始化."); } try { - //pluginInitializerListenerFactory.addPluginInitializerListeners(pluginInitializerListener); - log.info("开始初始化加载插件: '{}'", pluginManager.getPluginsRoots().toString()); + log.info("插件加载环境: {}", configuration.environment().toString()); + pluginInitializerListenerFactory.addListener(pluginInitializerListener); + List pluginsRoots = pluginManager.getPluginsRoots(); + if(pluginsRoots.isEmpty()){ + return true; + } + log.info("开始加载插件, 插件根路径为: \n{}", String.join("\n", pluginsRoots)); // 触发插件初始化监听器 - //pluginInitializerListenerFactory.before(); + pluginInitializerListenerFactory.before(); if(!configuration.enable()){ log.info("插件功能已被禁用!"); // 如果禁用的话, 直接返回 - //pluginInitializerListenerFactory.complete(); + pluginInitializerListenerFactory.complete(); return false; } - - // 启动前, 清除空文件 - PluginFileUtils.cleanEmptyFile(pluginManager.getPluginsRoots()); - // 开始加载插件 - List pluginDescriptors = pluginManager.loadPlugins(); - if(ObjectUtils.isEmpty(pluginDescriptors)){ - //pluginInitializerListenerFactory.complete(); + List pluginInfos = pluginManager.loadPlugins(); + if(ObjectUtils.isEmpty(pluginInfos)){ return false; } boolean isFoundException = false; - for (PluginDescriptor descriptor : pluginDescriptors) { + for (PluginInfo pluginInfo : pluginInfos) { try { - pluginManager.start(descriptor.getPluginId()); - } catch (PluginException e){ + pluginManager.start(pluginInfo.getPluginId()); + } catch (Exception e){ + if(e instanceof PluginDisabledException){ + log.info(e.getMessage()); + continue; + } log.error(e.getMessage(), e); isFoundException = true; } @@ -78,127 +95,284 @@ public class DefaultPluginOperator implements PluginOperator { isInit.set(true); if(isFoundException){ log.error("插件初始化失败"); - //pluginInitializerListenerFactory.failure(new Exception("插件初始化失败")); + pluginInitializerListenerFactory.failure(new PluginException("插件初始化存在异常")); return false; } else { - log.info("插件初始化成功"); - //pluginInitializerListenerFactory.complete(); + pluginInitializerListenerFactory.complete(); + log.info("插件初始化完成"); return true; } } catch (Exception e){ - //pluginInitializerListenerFactory.failure(e); + pluginInitializerListenerFactory.failure(e); throw e; } } @Override public boolean verify(Path jarPath) throws PluginException { - return false; + return pluginManager.verify(jarPath); } @Override - public PluginInfo install(Path jarPath) throws PluginException { - return null; + public PluginInfo parse(Path pluginPath) throws PluginException { + return pluginManager.parse(pluginPath); } @Override - public boolean uninstall(String pluginId, boolean isBackup) throws PluginException { - pluginManager.uninstall(pluginId); - return true; + public PluginInfo install(Path jarPath, boolean unpackPlugin) throws PluginException { + return pluginManager.install(jarPath, unpackPlugin); } @Override - public PluginInfo load(Path jarPath) throws PluginException { - return null; + public void uninstall(String pluginId, boolean isDelete, boolean isBackup) throws PluginException { + uninstallBackup(pluginId, isDelete, isBackup); } @Override - public PluginInfo load(MultipartFile pluginFile) throws PluginException { - return null; + public PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException { + return pluginManager.load(jarPath, unpackPlugin); } @Override public boolean unload(String pluginId, boolean isBackup) throws PluginException { - return false; + pluginManager.unLoad(pluginId); + return true; } @Override public boolean start(String pluginId) throws PluginException { - return false; + return pluginManager.start(pluginId) != null; } @Override public boolean stop(String pluginId) throws PluginException { - return false; + return pluginManager.stop(pluginId) != null; } @Override - public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException { - return null; + public PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException { + if(isDev()){ + throw new RuntimeException("开发环境下不能上传插件"); + } + Assert.isNotNull(uploadParam, "参数 uploadParam 不能为空"); + try { + if(uploadParam instanceof UploadByInputStreamParam){ + UploadByInputStreamParam param = (UploadByInputStreamParam) uploadParam; + return uploadPlugin(param.getPluginFileName(), param.getInputStream(), + param.isBackOldPlugin(), param.isUnpackPlugin()); + } else if(uploadParam instanceof UploadByMultipartFileParam){ + UploadByMultipartFileParam param = (UploadByMultipartFileParam) uploadParam; + MultipartFile file = param.getPluginMultipartFile(); + return uploadPlugin(file.getOriginalFilename(), file.getInputStream(), + param.isBackOldPlugin(), param.isUnpackPlugin()); + } else { + throw new PluginException("不支持上传参数: " + uploadParam.getClass().getName()); + } + } catch (Exception e) { + throw PluginException.getPluginException(e, ()-> new PluginException(e.getMessage(), e)); + } } @Override - public boolean installConfigFile(Path configFilePath) throws PluginException { - return false; + public Path backupPlugin(Path backDirPath, String sign) throws PluginException { + if(isDev()){ + throw new RuntimeException("Plugin cannot backup in the 'dev' environment"); + } + Objects.requireNonNull(backDirPath); + return backup(backDirPath, sign, false); } @Override - public boolean uploadConfigFile(MultipartFile configFile) throws PluginException { - return false; + public Path backupPlugin(String pluginId, String sign) throws PluginException { + if(isDev()){ + throw new RuntimeException("Plugin cannot backup in the 'dev' environment"); + } + PluginInfo pluginInfo = getPluginInfo(pluginId); + return backupPlugin(Paths.get(pluginInfo.getPluginPath()), sign); } @Override - public boolean backupPlugin(Path backDirPath, String sign) throws PluginException { - return false; + public List getPluginInfo() { + return pluginManager.getPluginInfos(); } @Override - public boolean backupPlugin(String pluginId, String sign) throws PluginException { - return false; + public PluginInfo getPluginInfo(String pluginId) { + return pluginManager.getPluginInfo(pluginId); } - @Override - public List getPluginInfo() { - List startedPlugins = pluginManager.getPluginWrappers(); - List pluginInfos = new ArrayList<>(); - if(startedPlugins == null){ - return pluginInfos; + /** + * 卸载插件 + * @param pluginId 插件id + * @param isDelete 是否删除插件 + * @param isBackup 是否备份插件 + * @return 如果备份插件, 则返回备份后的插件路径 + */ + protected Path uninstallBackup(String pluginId, boolean isDelete, boolean isBackup){ + PluginInfo pluginInfo = pluginManager.getPluginInfo(pluginId); + if(pluginInfo == null){ + throw new PluginException(pluginId, "没有发现"); + } + pluginManager.uninstall(pluginId); + if(!isDelete || isDev()){ + return null; + } + // 删除插件 + Path pluginPath = Paths.get(pluginInfo.getPluginPath()); + Path backupPath = null; + if(isBackup){ + // 将插件文件移到备份文件中 + backupPath = backup(pluginPath, "uninstall", true); } - return startedPlugins.stream() - .filter(Objects::nonNull) - .map(this::getPluginInfo) - .collect(Collectors.toList()); + return backupPath; } - @Override - public PluginInfo getPluginInfo(String pluginId) { - return null; + protected PluginInfo uploadPlugin(String pluginFileName, InputStream inputStream, + boolean isBackOldPlugin, boolean isUnpackPluginFile) throws Exception{ + // 获取文件的后缀名 + if(ObjectUtils.isEmpty(pluginFileName)){ + throw new PluginException("上传的插件文件名称不能为空"); + } + //检查文件格式是否合法 + if(!ResourceUtils.isJar(pluginFileName) && !ResourceUtils.isZip(pluginFileName)){ + throw new PluginException("插件文件类型错误, 请上传 jar/zip 类型文件"); + } + + String tempPathString = CommonUtils.joiningFilePath(configuration.uploadTempPath(), pluginFileName); + Path tempFilePath = Paths.get(tempPathString); + File tempFile = PluginFileUtils.createExistFile(tempFilePath); + // 将上传的插件拷贝到临时目录 + try (FileOutputStream outputStream = new FileOutputStream(tempFile)){ + IOUtils.copy(inputStream, outputStream); + } + try { + // 解析该插件包 + PluginInfo uploadPluginInfo = parse(tempFilePath); + if(uploadPluginInfo == null){ + Exception exception = new Exception(pluginFileName + " 文件校验失败"); + verifyFailureDelete(tempFilePath, exception); + throw exception; + } + PluginInfo oldPluginInfo = getPluginInfo(uploadPluginInfo.getPluginId()); + PluginInfo pluginInfo = null; + if(oldPluginInfo != null){ + // 判断版本 + Path oldPluginPath = Paths.get(oldPluginInfo.getPluginPath()); + if(isBackOldPlugin){ + // 先备份一次旧插件 + backupPlugin(oldPluginPath, "upload"); + } + // 然后进入更新模式 + pluginInfo = pluginManager.upgrade(tempFilePath, isUnpackPluginFile); + } else { + // 不存在则进入安装插件模式 + pluginInfo = pluginManager.install(tempFilePath, isUnpackPluginFile); + } + return pluginInfo; + } catch (Exception e){ + // 出现异常, 删除刚才上传的临时文件 + verifyFailureDelete(tempFilePath, e); + throw e; + } finally { + IOUtils.closeQuietly(inputStream); + // 删除临时文件 + tempFile.deleteOnExit(); + } } - @Override - public Set getPluginFilePaths() { - return null; + /** + * 备份 + * @param sourcePath 源文件的路径 + * @param sign 文件标志 + * @param deletedSourceFile 是否删除源文件 + * @return 返回备份的插件路径 + */ + protected Path backup(Path sourcePath, String sign, boolean deletedSourceFile) { + try { + if(isDev()){ + // 如果是开发环境, 则不进行备份 + return null; + } + if(sourcePath == null){ + return null; + } + if(!Files.exists(sourcePath)){ + log.error("Path '{}' does not exist", sourcePath.toString()); + return null; + } + File sourceFile = sourcePath.toFile(); + touchBackupPath(); + String targetPathStr = configuration.backupPath() + File.separator; + if(!ObjectUtils.isEmpty(sign)){ + targetPathStr = targetPathStr + sign; + } + targetPathStr = targetPathStr + "_" + getNowTimeByFormat() + "_" +sourceFile.getName(); + Path targetPath = Paths.get(targetPathStr); + File targetFile = targetPath.toFile(); + copyFile(sourceFile, targetFile); + log.info("备份插件文件到: {}", targetFile.getAbsolutePath()); + if(deletedSourceFile){ + if(sourceFile.isFile()){ + FileUtils.delete(sourceFile); + } else { + FileUtils.deleteDirectory(sourceFile); + } + } + return targetPath; + } catch (IOException e) { + log.error("Backup plugin jar '{}' failure. {}", sourcePath.toString(), e.getMessage(), e); + return null; + } } - @Override - public List getPluginWrapper() { - return null; + private void copyFile(File sourceFile, File targetFile) throws IOException { + if(sourceFile.isDirectory()){ + FileUtils.copyDirectory(sourceFile, targetFile); + } else if(sourceFile.isFile()){ + FileUtils.copyFile(sourceFile, targetFile); + } } - @Override - public PluginWrapper getPluginWrapper(String pluginId) { - return null; + + /** + * 校验文件失败后, 删除临时文件 + * @param tempPluginFile 临时文件路径 + * @param e 异常信息 + * @throws Exception Exception + */ + protected void verifyFailureDelete(Path tempPluginFile, Exception e) throws Exception { + try { + Files.deleteIfExists(tempPluginFile); + }catch (IOException e1){ + log.error("删除临时文件失败: {}. {}", tempPluginFile, e.getMessage()); + } } + /** + * 获取现在的时间 + * @return String + */ + protected String getNowTimeByFormat(){ + LocalDateTime localDateTime = LocalDateTime.now(); + return FORMAT.format(localDateTime); + } /** - * 通过PluginWrapper得到插件信息 - * @param pluginWrapper pluginWrapper - * @return PluginInfo + * 是否是开发环境 + * @return bolean */ - private PluginInfo getPluginInfo(PluginWrapper pluginWrapper) { - return new PluginInfo(pluginWrapper.getPluginDescriptor(), pluginWrapper.getPluginState(), - pluginWrapper.getPluginPath().toAbsolutePath().toString(), - configuration.environment().toString()); + protected boolean isDev(){ + return configuration.environment() == RuntimeMode.DEV; + } + + protected void touchBackupPath() throws IOException { + String backupPath = configuration.backupPath(); + final File file = new File(backupPath); + if(file.exists()){ + return; + } + FileUtils.forceMkdir(file); } + + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java index eee1d6b..e7f9abc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java @@ -1,9 +1,9 @@ package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.PluginException; -import com.gitee.starblues.core.PluginWrapper; +import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.operator.module.PluginInfo; +import com.gitee.starblues.integration.operator.upload.UploadParam; import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; @@ -16,6 +16,7 @@ import java.util.Set; */ public class EmptyPluginOperator implements PluginOperator{ + @Override public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException { return false; @@ -27,22 +28,21 @@ public class EmptyPluginOperator implements PluginOperator{ } @Override - public PluginInfo install(Path jarPath) throws PluginException { + public PluginInfo parse(Path pluginPath) throws PluginException { return null; } @Override - public boolean uninstall(String pluginId, boolean isBackup) throws PluginException { - return false; + public PluginInfo install(Path jarPath, boolean unpackPlugin) throws PluginException { + return null; } @Override - public PluginInfo load(Path jarPath) throws PluginException { - return null; + public void uninstall(String pluginId, boolean isDelete, boolean isBackup) throws PluginException { } @Override - public PluginInfo load(MultipartFile pluginFile) throws PluginException { + public PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException { return null; } @@ -62,52 +62,27 @@ public class EmptyPluginOperator implements PluginOperator{ } @Override - public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException { - return null; - } - - @Override - public boolean installConfigFile(Path configFilePath) throws PluginException { - return false; - } - - @Override - public boolean uploadConfigFile(MultipartFile configFile) throws PluginException { - return false; - } - - @Override - public boolean backupPlugin(Path backDirPath, String sign) throws PluginException { - return false; - } - - @Override - public boolean backupPlugin(String pluginId, String sign) throws PluginException { - return false; - } - - @Override - public List getPluginInfo() { + public PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException { return null; } @Override - public PluginInfo getPluginInfo(String pluginId) { + public Path backupPlugin(Path backDirPath, String sign) throws PluginException { return null; } @Override - public Set getPluginFilePaths() { + public Path backupPlugin(String pluginId, String sign) throws PluginException { return null; } @Override - public List getPluginWrapper() { + public List getPluginInfo() { return null; } @Override - public PluginWrapper getPluginWrapper(String pluginId) { + public PluginInfo getPluginInfo(String pluginId) { return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java index d240892..44d5f8b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java @@ -1,11 +1,14 @@ package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.PluginException; -import com.gitee.starblues.core.PluginWrapper; +import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.operator.module.PluginInfo; +import com.gitee.starblues.integration.operator.upload.UploadByInputStreamParam; +import com.gitee.starblues.integration.operator.upload.UploadByMultipartFileParam; +import com.gitee.starblues.integration.operator.upload.UploadParam; import org.springframework.web.multipart.MultipartFile; +import java.io.InputStream; import java.nio.file.Path; import java.util.List; import java.util.Set; @@ -34,39 +37,41 @@ public interface PluginOperator { */ boolean verify(Path jarPath) throws PluginException; + /** + * 解析插件包 + * @param pluginPath 插件包路基 + * @return 解析的插件信息 + * @throws PluginException 插件异常 + */ + PluginInfo parse(Path pluginPath) throws PluginException; + /** * 通过路径安装插件(会启用), 该插件文件必须存在于服务器 [适用于生产环境] * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar * @param jarPath 插件路径 + * @param unpackPlugin 是否解压插件包. (如果插件包为压缩包时生效) * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null * @throws PluginException 异常信息 */ - PluginInfo install(Path jarPath) throws PluginException; + PluginInfo install(Path jarPath, boolean unpackPlugin) throws PluginException; /** * 卸载插件 [适用于生产环境] * @param pluginId 插件id - * @param isBackup 是否备份原来的插件。备份文件命名规则为;[uninstall][时间]_原jar名.jar - * @return 成功: 返回true; 失败: 抛出异常或者返回false + * @param isDelete 卸载后是否删除插件文件. + * @param isBackup 删除插件文件前, 是否备份插件文件。备份文件命名规则为;[uninstall][时间]_原jar名.jar * @throws PluginException 异常信息 */ - boolean uninstall(String pluginId, boolean isBackup) throws PluginException; + void uninstall(String pluginId, boolean isDelete, boolean isBackup) throws PluginException; /** * 加载插件, 但不启动 [适用于生产环境] * @param jarPath 插件路径 + * @param unpackPlugin 是否解压插件包. (如果插件包为压缩包时生效) * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null * @throws PluginException 异常信息 */ - PluginInfo load(Path jarPath) throws PluginException; - - /** - * 加载插件, 但不启动 [适用于生产环境] - * @param pluginFile 插件文件 - * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null - * @throws PluginException 异常信息 - */ - PluginInfo load(MultipartFile pluginFile) throws PluginException; + PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException; /** * 配合load使用. 针对load的插件进行unload [适用于生产环境] @@ -93,53 +98,40 @@ public interface PluginOperator { * @throws PluginException 异常信息 */ boolean stop(String pluginId) throws PluginException; - /** - * 上传插件并启用插件。[适用于生产环境] - * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar - * @param pluginFile 插件文件 + * 上传插件. + * 如果不存在相同插件(插件id不相同), 则正常上传到插件目录, 然后加载、启动。 + * 如果存在相同插件(插件id相同) + * 相同插件在启动状态, 则进入更新模式, 满足上传的插件包版本必须大于已启动的插件版本, 系统会自动卸载旧版本, 安装新版本。 + * 相同插件不在启动状态, 则进入覆盖模式, 会对旧插件进行备份(可根据isBackOldPlugin配置不备份), 然后上传新插件包到插件目录, 然后加载、启动。 + * 如果存在同文件名称插件, 系统会抛出异常, 建议重命名插件名称, 再上传。 + * + * @param uploadParam 上传参数 * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null * @throws PluginException 异常信息 + * @see UploadByInputStreamParam + * @see UploadByMultipartFileParam */ - PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException; - - /** - * 通过路径安装插件的配置文件。该文件必须存在于服务器。[适用于生产环境] - * 如果配置文件目录存在同名的配置文件, 系统会自动备份该配置文件。备份文件命名规则为;[install-config-backup][时间]_原jar名.jar - * @param configFilePath 配置文件路径。 - * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws PluginException 安装异常 - */ - boolean installConfigFile(Path configFilePath) throws PluginException; - - - /** - * 上传配置文件。[适用于生产环境] - * 如果配置文件目录存在同名的配置文件, 系统会自动备份该配置文件。备份文件命名规则为;[upload-config-backup][时间]_原jar名.jar - * @param configFile 配置文件 - * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws PluginException 异常信息 - */ - boolean uploadConfigFile(MultipartFile configFile) throws PluginException; + PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException; /** * 通过路径备份文件。可备份插件和插件的配置文件。[适用于生产环境] * @param backDirPath 备份的目录路径 * @param sign 备份文件的自定义标识 - * @return 成功: 返回true; 失败: 抛出异常或者返回false + * @return 备份插件的路径 * @throws PluginException 异常信息 */ - boolean backupPlugin(Path backDirPath, String sign) throws PluginException; + Path backupPlugin(Path backDirPath, String sign) throws PluginException; /** * 通过插件id备份插件。[适用于生产环境] * @param pluginId 插件id * @param sign 备份文件的自定义标识 - * @return 成功: 返回true; 失败: 抛出异常或者返回false + * @return 备份插件的路径 * @throws PluginException 异常信息 */ - boolean backupPlugin(String pluginId, String sign) throws PluginException; + Path backupPlugin(String pluginId, String sign) throws PluginException; /** * 获取插件信息 [适用于生产环境、开发环境] @@ -154,25 +146,4 @@ public interface PluginOperator { */ PluginInfo getPluginInfo(String pluginId); - /** - * 得到插件文件的路径 - * @return 返回插件路径列表 - * @throws PluginException 异常信息 - */ - Set getPluginFilePaths(); - - /** - * 得到所有插件的包装类 [适用于生产环境、开发环境] - * @return 返回插件包装类集合 - */ - List getPluginWrapper(); - - /** - * 通过插件id得到插件的包装类 [适用于生产环境、开发环境] - * @param pluginId 插件id - * @return 返回插件包装类集合 - */ - PluginWrapper getPluginWrapper(String pluginId); - - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 79d2bed..3de3890 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -1,10 +1,10 @@ package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.PluginException; -import com.gitee.starblues.core.PluginWrapper; +import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.operator.module.PluginInfo; +import com.gitee.starblues.integration.operator.upload.UploadParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; @@ -49,44 +49,44 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo install(Path jarPath) throws PluginException { + public PluginInfo parse(Path pluginPath) throws PluginException { if(isDisable()){ return null; } - return pluginOperator.install(jarPath); + return pluginOperator.parse(pluginPath); } @Override - public PluginInfo load(Path jarPath) throws PluginException { + public PluginInfo install(Path jarPath, boolean unpackPlugin) throws PluginException { if(isDisable()){ return null; } - return pluginOperator.install(jarPath); + return pluginOperator.install(jarPath, unpackPlugin); } @Override - public PluginInfo load(MultipartFile pluginFile) throws PluginException { + public boolean unload(String pluginId, boolean isBackup) throws PluginException { if(isDisable()){ - return null; + return false; } - return pluginOperator.load(pluginFile); + return pluginOperator.unload(pluginId, isBackup); } @Override - public boolean unload(String pluginId, boolean isBackup) throws PluginException { + public void uninstall(String pluginId, boolean isDelete, boolean isBackup) throws PluginException { if(isDisable()){ - return false; + return; } - return pluginOperator.unload(pluginId, isBackup); + checkIsUnRegistry(pluginId); + pluginOperator.uninstall(pluginId, isDelete, isBackup); } @Override - public boolean uninstall(String pluginId, boolean isBackup) throws PluginException { + public PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException { if(isDisable()){ - return false; + return null; } - checkIsUnRegistry(pluginId); - return pluginOperator.uninstall(pluginId, isBackup); + return pluginOperator.install(jarPath, unpackPlugin); } @Override @@ -107,41 +107,25 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo uploadPluginAndStart(MultipartFile pluginFile) throws PluginException { + public PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException { if(isDisable()){ return null; } - return pluginOperator.uploadPluginAndStart(pluginFile); - } - - @Override - public boolean installConfigFile(Path configFilePath) throws PluginException { - if(isDisable()){ - return false; - } - return pluginOperator.installConfigFile(configFilePath); - } - - @Override - public boolean uploadConfigFile(MultipartFile configFile) throws PluginException { - if(isDisable()){ - return false; - } - return pluginOperator.uploadConfigFile(configFile); + return pluginOperator.uploadPlugin(uploadParam); } @Override - public boolean backupPlugin(Path backDirPath, String sign) throws PluginException { + public Path backupPlugin(Path backDirPath, String sign) throws PluginException { if(isDisable()){ - return false; + return null; } return pluginOperator.backupPlugin(backDirPath, sign); } @Override - public boolean backupPlugin(String pluginId, String sign) throws PluginException { + public Path backupPlugin(String pluginId, String sign) throws PluginException { if(isDisable()){ - return false; + return null; } return pluginOperator.backupPlugin(pluginId, sign); } @@ -162,30 +146,6 @@ public class PluginOperatorWrapper implements PluginOperator{ return pluginOperator.getPluginInfo(pluginId); } - @Override - public Set getPluginFilePaths() { - if(isDisable()){ - return Collections.emptySet(); - } - return pluginOperator.getPluginFilePaths(); - } - - @Override - public List getPluginWrapper() { - if(isDisable()){ - return Collections.emptyList(); - } - return pluginOperator.getPluginWrapper(); - } - - @Override - public PluginWrapper getPluginWrapper(String pluginId) { - if(isDisable()){ - return null; - } - return pluginOperator.getPluginWrapper(pluginId); - } - /** * 是否被禁用 * @return true 禁用 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java new file mode 100644 index 0000000..e485c87 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java @@ -0,0 +1,36 @@ +package com.gitee.starblues.integration.operator.upload; + +import com.gitee.starblues.utils.Assert; + +import java.io.InputStream; + +/** + * InputStream 上传插件参数 + * @author starBlues + * @version 3.0.0 + */ +public class UploadByInputStreamParam extends UploadParam{ + + /** + * 插件文件名称 + */ + private final String pluginFileName; + + /** + * 插件输入流 + */ + private final InputStream inputStream; + + public UploadByInputStreamParam(String pluginFileName, InputStream inputStream) { + this.pluginFileName = Assert.isNotEmpty(pluginFileName, "参数pluginFileName不能为空"); + this.inputStream = Assert.isNotNull(inputStream, "参数inputStream不能为空"); + } + + public String getPluginFileName() { + return pluginFileName; + } + + public InputStream getInputStream() { + return inputStream; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java new file mode 100644 index 0000000..581a5cd --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java @@ -0,0 +1,22 @@ +package com.gitee.starblues.integration.operator.upload; + +import com.gitee.starblues.utils.Assert; +import org.springframework.web.multipart.MultipartFile; + +/** + * 上传插件参数 + * @author starBlues + * @version 1.0 + */ +public class UploadByMultipartFileParam extends UploadParam{ + + private final MultipartFile pluginMultipartFile; + + public UploadByMultipartFileParam(MultipartFile pluginMultipartFile) { + this.pluginMultipartFile = Assert.isNotNull(pluginMultipartFile, "参数pluginMultipartFile不能为空"); + } + + public MultipartFile getPluginMultipartFile() { + return pluginMultipartFile; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java new file mode 100644 index 0000000..0839b53 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java @@ -0,0 +1,82 @@ +package com.gitee.starblues.integration.operator.upload; + +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; + +/** + * + * 上传插件参数 + * @author starBlues + * @version 3.0.0 + */ +public abstract class UploadParam { + + /** + * 上传后是否启动插件. 默认启动 + */ + private boolean isStartPlugin = true; + + /** + * 如果存在旧插件, 是否备份旧插件 + */ + private boolean isBackOldPlugin = true; + + /** + * 是否解压插件文件 + */ + private boolean isUnpackPlugin = false; + + protected UploadParam(){} + + public static UploadByInputStreamParam byInputStream(String pluginFileName, InputStream inputStream){ + return new UploadByInputStreamParam(pluginFileName, inputStream); + } + + public static UploadByMultipartFileParam byMultipartFile(MultipartFile pluginMultipartFile){ + return new UploadByMultipartFileParam(pluginMultipartFile); + } + + /** + * 设置上传后是否启动插件. 默认 true + * @param isStartPlugin true: 启动, false 不启动 + * @return UploadParam + */ + public UploadParam setStartPlugin(boolean isStartPlugin) { + this.isStartPlugin = isStartPlugin; + return this; + } + + /** + * 设置是否备份旧插件. 默认: true + * @param isBackOldPlugin true: 备份, false 不备份 + * @return UploadParam + */ + public UploadParam setBackOldPlugin(boolean isBackOldPlugin) { + this.isBackOldPlugin = isBackOldPlugin; + return this; + } + + /** + * 设置是否解压插件. 默认: false + * @param isUnpackPlugin true: 解压, false 不解压 + * @return UploadParam + */ + public UploadParam setUnpackPlugin(boolean isUnpackPlugin) { + this.isUnpackPlugin = isUnpackPlugin; + return this; + } + + public boolean isStartPlugin() { + return isStartPlugin; + } + + public boolean isBackOldPlugin() { + return isBackOldPlugin; + } + + public boolean isUnpackPlugin() { + return isUnpackPlugin; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java index d89ea4a..3a7c759 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java @@ -1,6 +1,7 @@ package com.gitee.starblues.utils; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import org.slf4j.Logger; /** * @author starBlues @@ -22,4 +23,8 @@ public abstract class MsgUtils { return ObjectUtils.isEmpty(message) ? "" : message; } + public static void info(Logger logger, PluginDescriptor pluginDescriptor, String msg){ + logger.info("插件[{}]{}", getPluginUnique(pluginDescriptor), msg); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java index 6e311eb..24a58df 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java @@ -1,22 +1,27 @@ package com.gitee.starblues.utils; -import org.springframework.util.ResourceUtils; +import com.gitee.starblues.common.PackageStructure; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; +import java.io.*; import java.math.BigInteger; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; +import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; +import java.util.Enumeration; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; /** * 插件文件工具类 @@ -43,23 +48,18 @@ public final class PluginFileUtils { } catch (Exception e) { e.printStackTrace(); } finally { - if(null != in) { - try { - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + IOUtils.closeQuietly(in); } return value; } - public static void cleanEmptyFile(List paths){ + public static void cleanEmptyFile(List paths){ if(ObjectUtils.isEmpty(paths)){ return; } - for (Path path : paths) { + for (String pathStr : paths) { + Path path = Paths.get(pathStr); if(!Files.exists(path)){ continue; } @@ -92,7 +92,7 @@ public final class PluginFileUtils { * @return 插件路径 * @throws IOException 没有发现文件异常 */ - public static Path createExistFile(Path path) throws IOException { + public static File createExistFile(Path path) throws IOException { Path parent = path.getParent(); if(!Files.exists(parent)){ Files.createDirectories(parent); @@ -100,7 +100,7 @@ public final class PluginFileUtils { if(!Files.exists(path)){ Files.createFile(path); } - return path; + return path.toFile(); } public static File getExistFile(String pathStr){ @@ -119,6 +119,20 @@ public final class PluginFileUtils { return getExistFile(secondPathSupplier.get()); } + /** + * 得到文件名称 + * @param file 原始文件 + * @return String + */ + public static String getFileName(File file){ + String fileName = file.getName(); + if(!file.exists() | file.isDirectory()){ + return fileName; + } + return getFileName(fileName); + } + + /** * 得到文件名称 * @param fileName 原始文件名称. 比如: file.txt @@ -135,4 +149,83 @@ public final class PluginFileUtils { } } + public static Manifest getManifest(InputStream inputStream) throws IOException { + Manifest manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + List lines = IOUtils.readLines(inputStream, PackageStructure.CHARSET_NAME); + for (String line : lines) { + String[] split = line.split(":"); + if(split.length == 2){ + String key = split[0]; + String value = split[1]; + attributes.putValue(trim(key), trim(value)); + } + } + return manifest; + } + + private static String trim(String value){ + if(ObjectUtils.isEmpty(value)){ + return value; + } + return value.trim(); + } + + public static void deleteFile(File file) throws IOException { + if(file == null || !file.exists()){ + return; + } + if(file.isDirectory()){ + FileUtils.deleteDirectory(file); + } else { + FileUtils.delete(file); + } + } + + public static void decompressZip(String zipPath, String targetDir) throws IOException { + File zipFile = new File(zipPath); + if(!ResourceUtils.isZip(zipPath) && !ResourceUtils.isJar(zipPath)){ + throw new IOException("文件[" + zipFile.getName() + "]非压缩包, 不能解压"); + } + File targetDirFile = new File(targetDir); + if(!targetDirFile.exists()){ + targetDirFile.mkdirs(); + } + try (ZipFile zip = new ZipFile(zipFile, Charset.forName(PackageStructure.CHARSET_NAME))) { + Enumeration zipEnumeration = zip.entries(); + ZipEntry zipEntry = null; + while (zipEnumeration.hasMoreElements()) { + zipEntry = zipEnumeration.nextElement(); + String zipEntryName = zipEntry.getName(); + String currentZipPath = PackageStructure.resolvePath(zipEntryName); + String currentTargetPath = CommonUtils.joiningFilePath(targetDir, currentZipPath); + //判断路径是否存在,不存在则创建文件路径 + if (zipEntry.isDirectory()) { + FileUtils.forceMkdir(new File(currentTargetPath)); + continue; + } + InputStream in = null; + FileOutputStream out = null; + try { + in = zip.getInputStream(zipEntry); + out = new FileOutputStream(currentTargetPath); + IOUtils.copy(in, out); + } finally { + if (in != null) { + IOUtils.closeQuietly(in); + } + if (out != null) { + IOUtils.closeQuietly(out); + } + } + } + } + } + + public static void main(String[] args) throws IOException { + decompressZip("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-framework-example\\plugin\\example-basic-1-1.0.0-SNAPSHOT_0.zip", + + "D:\\etc\\kitte\\springboot-plugin-framework-parent\\springboot-plugin-framework\\src\\main\\java\\com\\gitee\\starblues\\integration\\operator"); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index e207b9e..7cee3ce 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -64,19 +64,18 @@ public abstract class ReflectionUtils { } - public static Object getField(Object o, String fieldName) { - return getField(o, fieldName, null); + public static Object getField(Object object, Class objectClass, String fieldName) { + return getField(object, objectClass, fieldName, null); } - public static Object getField(Object o, String fieldName, Class fieldType) { - Class currentClass = o.getClass(); - Field field = findField(currentClass, fieldName, fieldType); + public static Object getField(Object object, Class objectClass, String fieldName, Class fieldType) { + Field field = findField(objectClass, fieldName, fieldType); if(field == null){ return null; } field.setAccessible(true); try { - return field.get(o); + return field.get(object); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index c849de4..11f09da 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -8,6 +8,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Objects; import java.util.function.Consumer; /** @@ -35,6 +36,12 @@ public class ResourceUtils { public static final String PACKAGE_SPLIT = "/"; + public static final String JAR_FILE_EXTENSION = ".jar"; + public static final String ZIP_FILE_EXTENSION = ".zip"; + public static final String CLASS_FILE_EXTENSION = ".class"; + public static final String URL_PROTOCOL_VFSFILE = "vfsfile"; + public static final String URL_PROTOCOL_VFS = "vfs"; + /** * 获取匹配路绝 * @param locationMatch 原始匹配路径。规则为: file:xxx, classpath:xxx , package:xxx @@ -62,24 +69,40 @@ public class ResourceUtils { } public static boolean isClasspath(String locationMatch){ + if(ObjectUtils.isEmpty(locationMatch)){ + return false; + } return locationMatch.startsWith(TYPE_CLASSPATH + TYPE_SPLIT); } public static boolean isFile(String locationMatch){ + if(ObjectUtils.isEmpty(locationMatch)){ + return false; + } return locationMatch.startsWith(TYPE_FILE + TYPE_SPLIT); } public static boolean isPackage(String locationMatch){ + if(ObjectUtils.isEmpty(locationMatch)){ + return false; + } return locationMatch.startsWith(TYPE_PACKAGE + TYPE_SPLIT); } + public static boolean isClass(String path){ + if(ObjectUtils.isEmpty(path)){ + return false; + } + return path.toLowerCase().endsWith(CLASS_FILE_EXTENSION); + } + /** * 是否为 zip 文件 * @param path 文件路径 * @return boolean */ public static boolean isZipFile(Path path) { - return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".zip"); + return Files.isRegularFile(path) && isZip(path.toString()); } /** @@ -88,13 +111,62 @@ public class ResourceUtils { * @return boolean */ public static boolean isJarFile(Path path) { - return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".jar"); + return Files.isRegularFile(path) && isJar(path.toString()); + } + + /** + * 是否为 zip 文件 + * @param name 文件名称 + * @return boolean + */ + public static boolean isZip(String name) { + return name != null && name.toLowerCase().endsWith(ZIP_FILE_EXTENSION); + } + + /** + * 是否为 jar 文件 + * @param name 文件名称 + * @return boolean + */ + public static boolean isJar(String name) { + return name != null && name.toLowerCase().endsWith(JAR_FILE_EXTENSION); } public static boolean isDirFile(Path path) { return path.toFile().isDirectory(); } + public static boolean isJarFileURL(URL url) { + return (URL_PROTOCOL_FILE.equals(url.getProtocol()) && + url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION)); + } + + public static boolean isFileURL(URL url) { + String protocol = url.getProtocol(); + return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) || + URL_PROTOCOL_VFS.equals(protocol)); + } + + + public static boolean existFile(File rootFile, String checkFileName){ + if(rootFile == null || !rootFile.exists()){ + return false; + } + final File[] listFiles = rootFile.listFiles(); + if(listFiles == null || listFiles.length == 0){ + return false; + } + for (File listFile : listFiles) { + if(Objects.equals(listFile.getName(), checkFileName)){ + return true; + } + if(listFile.isDirectory()){ + return existFile(listFile, checkFileName); + } + } + return false; + } + public static void listFile(File rootFile, Consumer consumerFile){ if(rootFile == null || !rootFile.exists()){ return; @@ -112,6 +184,7 @@ public class ResourceUtils { } } + // /** // * 根据 ~ 标记获取, 得到绝对路径 // * @param pluginRegistryInfo pluginRegistryInfo diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java index d6456dd..675a976 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -1,6 +1,9 @@ package com.gitee.starblues.plugin.pack; -import com.gitee.starblues.plugin.pack.filter.*; +import com.gitee.starblues.plugin.pack.filter.Exclude; +import com.gitee.starblues.plugin.pack.filter.ExcludeFilter; +import com.gitee.starblues.plugin.pack.filter.Include; +import com.gitee.starblues.plugin.pack.filter.IncludeFilter; import com.gitee.starblues.plugin.pack.utils.CommonUtils; import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index 4716446..b6196c5 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -16,7 +16,6 @@ import java.util.HashSet; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; -import java.util.regex.Matcher; import static com.gitee.starblues.common.PackageStructure.*; import static com.gitee.starblues.common.PluginDescriptorKey.*; diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java index 6a0d953..5da716a 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -8,6 +8,7 @@ public class Constant { public static final String PACKAGING_POM = "pom"; public static final String SCOPE_PROVIDED = "provided"; + public static final String MODE_DEV = "dev"; public static final String MODE_PROD = "prod"; @@ -15,8 +16,6 @@ public class Constant { public static final String PACKAGE_TYPE_ZIP = "zip"; public static final String PACKAGE_TYPE_DIR = "dir"; - public static final String LIB_FILE_NAME = "lib"; - public static boolean isPom(String packageType){ return PACKAGING_POM.equalsIgnoreCase(packageType); diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java index 7032c1a..4cbfaaa 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -4,7 +4,7 @@ import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; /** - * 插件信息A + * 插件信息 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java deleted file mode 100644 index 4d43d71..0000000 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/LibCopy.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.gitee.starblues.plugin.pack.dev; - -import com.gitee.starblues.plugin.pack.utils.CommonUtils; -import org.apache.commons.compress.archivers.jar.JarArchiveEntry; -import org.apache.commons.compress.archivers.jar.JarArchiveInputStream; -import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream; -import org.apache.commons.compress.archivers.zip.UnixStat; -import org.apache.commons.io.IOUtils; - -import java.io.*; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import java.util.zip.CRC32; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** - * @author starBlues - * @version 1.0 - */ -public class LibCopy { - - private static final int UNIX_FILE_MODE = UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM; - - private static final int UNIX_DIR_MODE = UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM; - - private final String destDir; - - - public LibCopy(String destDir) { - this.destDir = destDir; - } - - public void copy(String libPath) throws Exception{ - copy(new File(libPath)); - } - - public void copy(File libFile) throws Exception{ - if(libFile == null || !libFile.exists()){ - return; - } - File destJarFile = new File(CommonUtils.joinPath(destDir, libFile.getName())); - if(!destJarFile.createNewFile()){ - return; - } - try (JarArchiveOutputStream outputStream = new JarArchiveOutputStream(new FileOutputStream(destJarFile)); - JarArchiveInputStream jarArchiveInputStream = new JarArchiveInputStream(new FileInputStream(libFile))) { - JarArchiveEntry entry = null; - while ((entry = jarArchiveInputStream.getNextJarEntry()) != null) { - String name = entry.getName(); - JarArchiveEntry newEntry = new JarArchiveEntry(name); - //copyAttribute(entry, newEntry); - //CopyByte crcAndSize = new CopyByte(jarArchiveInputStream); - //crcAndSize.setupStoredEntry(newEntry); - entry.setMethod(ZipEntry.STORED); - outputStream.putArchiveEntry(newEntry); - IOUtils.copy(jarArchiveInputStream, outputStream); - outputStream.closeArchiveEntry(); - } - outputStream.finish(); - } - } - - private void copyAttribute(JarArchiveEntry oldEntry, JarArchiveEntry newEntry){ - newEntry.setComment(oldEntry.getComment()); - newEntry.setTime(System.currentTimeMillis()); - } - - private static class CopyByte { - - private static final int BUFFER_SIZE = 32 * 1024; - - private final CRC32 crc = new CRC32(); - - private long size; - - public CopyByte(InputStream inputStream) throws IOException{ - copy(inputStream); - } - - void copy(InputStream inputStream) throws IOException { - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead; - while ((bytesRead = inputStream.read(buffer)) != -1) { - this.crc.update(buffer, 0, bytesRead); - this.size += bytesRead; - } - } - - void setupStoredEntry(JarArchiveEntry entry) { - entry.setSize(this.size); - entry.setCompressedSize(this.size); - entry.setCrc(this.crc.getValue()); - entry.setMethod(ZipEntry.STORED); - } - - } - - - -} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java index 367f3cf..96dc33e 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java @@ -1,5 +1,6 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.PluginInfo; import com.gitee.starblues.plugin.pack.RepackageMojo; @@ -71,7 +72,7 @@ public class ProdRepackager implements Repackager { } String libPath = prodConfig.getLibPath(); if(CommonUtils.isEmpty(libPath)){ - prodConfig.setLibPath(Constant.LIB_FILE_NAME); + prodConfig.setLibPath(PackageStructure.LIB_NAME); } return prodConfig; } -- Gitee From 3f09bb4ce12c8ca165c57824a1c15c85f370ba01 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Wed, 19 Jan 2022 17:29:20 +0800 Subject: [PATCH 22/37] add plugin patterns --- .../starblues/common/PackageStructure.java | 8 +- .../starblues/common/PluginDescriptorKey.java | 2 +- .../DefaultMainResourceMatcher.java | 12 ++- .../AbstractPluginDescriptorLoader.java | 25 +++-- .../DefaultInsidePluginDescriptor.java | 23 ++++- .../descriptor/EmptyPluginDescriptor.java | 10 ++ .../descriptor/InsidePluginDescriptor.java | 12 +++ .../descriptor/PluginResourcesConfig.java | 89 ++++++++++++++++++ .../ProdDirPluginDescriptorLoader.java | 28 +++--- .../ProdPackagePluginDescriptorLoader.java | 32 +++---- .../JavaMainResourcePatternDefiner.java | 45 +++++++-- .../core/launcher/MainProgramLauncher.java | 29 +++--- .../core/launcher/plugin/PluginLauncher.java | 19 ++-- .../PluginMainResourcePatternDefiner.java | 50 ++++++++++ .../plugin/pack/AbstractPackagerMojo.java | 9 +- .../plugin/pack/BasicRepackager.java | 91 +++++++++++++++---- .../plugin/pack/LoadMainResourcePattern.java | 20 ++++ .../plugin/pack/dev/DevRepackager.java | 8 +- .../plugin/pack/prod/DirPackageGenerator.java | 8 +- .../plugin/pack/prod/ZipProdRepackager.java | 36 +++++--- .../main/resources/META-INF/maven/plugin.xml | 9 ++ 21 files changed, 432 insertions(+), 133 deletions(-) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java create mode 100644 springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java index 344abcd..62b4cd1 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java @@ -25,11 +25,15 @@ public abstract class PackageStructure { public static final String MANIFEST = "MANIFEST.MF"; - public static final String LIB_INDEX_NAME = "lib.index"; + public static final String RESOURCES_DEFINE_NAME = "RESOURCES.CONF"; + + public static final String RESOURCES_DEFINE_DEPENDENCIES = "dependencies.index"; + public static final String RESOURCES_DEFINE_LOAD_MAIN_INCLUDES = "load.main.resources.includes"; + public static final String RESOURCES_DEFINE_LOAD_MAIN_EXCLUDES = "load.main.resources.excludes"; public static final String PROD_MANIFEST_PATH = META_INF_NAME + SEPARATOR + MANIFEST; - public static final String PROD_LIB_INDEX_PATH = META_INF_NAME + SEPARATOR + LIB_INDEX_NAME; + public static final String PROD_RESOURCES_DEFINE_PATH = META_INF_NAME + SEPARATOR + RESOURCES_DEFINE_NAME; public static final String PROD_CLASSES_PATH = CLASSES_NAME + SEPARATOR; diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java index cad8f4b..140cd43 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java @@ -24,7 +24,7 @@ public class PluginDescriptorKey { /** System create prop **/ public static final String PLUGIN_PATH = "Plugin-Path"; - public static final String PLUGIN_LIB_INDEX = "Plugin-Lib-Index"; + public static final String PLUGIN_RESOURCES_CONFIG = "Plugin-Resources-Config"; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java index 5da26c9..2064850 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java @@ -14,18 +14,20 @@ import java.util.Set; */ public class DefaultMainResourceMatcher implements MainResourceMatcher{ - private final MainResourcePatternDefiner mainResourcePatternDefiner; + private final Set includePatterns; + private final Set excludePatterns; + private final PathMatcher pathMatcher; public DefaultMainResourceMatcher(MainResourcePatternDefiner mainResourcePatternDefiner) { - this.mainResourcePatternDefiner = mainResourcePatternDefiner; + this.includePatterns = mainResourcePatternDefiner.getIncludePatterns(); + this.excludePatterns = mainResourcePatternDefiner.getExcludePatterns(); this.pathMatcher = new AntPathMatcher(); } @Override public boolean match(String resourceUrl) { - Set resourcePatterns = mainResourcePatternDefiner.getIncludePatterns(); - return match(resourcePatterns, resourceUrl); + return match(includePatterns, resourceUrl); } private boolean match(Collection patterns, String url){ @@ -36,7 +38,7 @@ public class DefaultMainResourceMatcher implements MainResourceMatcher{ for (String pattern : patterns) { boolean match = pathMatcher.match(pattern, url); if(match){ - return !excludeMatch(mainResourcePatternDefiner.getExcludePatterns(), url); + return !excludeMatch(excludePatterns, url); } } return false; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index 99a0f99..47b2133 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -10,11 +10,8 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -70,9 +67,14 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor getValue(attributes, PLUGIN_BOOTSTRAP_CLASS), path ); + PluginResourcesConfig pluginResourcesConfig = getPluginResourcesConfig(path, attributes); + + descriptor.setPluginLibPath(pluginResourcesConfig.getDependenciesIndex()); + descriptor.setIncludeMainResourcePatterns(pluginResourcesConfig.getLoadMainResourceIncludes()); + descriptor.setExcludeMainResourcePatterns(pluginResourcesConfig.getLoadMainResourceExcludes()); + descriptor.setManifest(manifest); descriptor.setPluginClassPath(getValue(attributes, PLUGIN_PATH, false)); - descriptor.setPluginLibPath(getPluginLibPaths(path, attributes)); descriptor.setDescription(getValue(attributes, PLUGIN_DESCRIPTION, false)); descriptor.setRequires(getValue(attributes, PLUGIN_REQUIRES, false)); descriptor.setProvider(getValue(attributes, PLUGIN_PROVIDER, false)); @@ -82,10 +84,10 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor } - protected Set getPluginLibPaths(Path path, Attributes attributes) throws Exception{ - String libIndex = getValue(attributes, PLUGIN_LIB_INDEX); + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception{ + String libIndex = getValue(attributes, PLUGIN_RESOURCES_CONFIG); if(ObjectUtils.isEmpty(libIndex)){ - return Collections.emptySet(); + return new PluginResourcesConfig(); } File file = new File(libIndex); if(!file.exists()){ @@ -95,17 +97,14 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor } if(!file.exists()){ // 都不存在, 则返回为空 - return Collections.emptySet(); + return new PluginResourcesConfig(); } try { - List paths = Files.readAllLines(file.toPath()); - if(!ObjectUtils.isEmpty(paths)){ - return new HashSet<>(paths); - } + List lines = Files.readAllLines(file.toPath()); + return PluginResourcesConfig.parse(lines); } catch (IOException e) { throw new Exception("Load plugin lib index path failure. " + libIndex, e); } - return Collections.emptySet(); } protected Manifest getManifest(InputStream inputStream) throws Exception{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java index 82710ea..9333736 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -18,6 +18,8 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple private Manifest manifest; private String configFileName; private Set pluginLibPaths; + private Set includeMainResourcePatterns; + private Set excludeMainResourcePatterns; public DefaultInsidePluginDescriptor(String pluginId, String pluginVersion, String pluginClass, Path pluginPath) { super(pluginId, pluginVersion, pluginClass, pluginPath.toAbsolutePath().toString()); @@ -33,14 +35,21 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple this.manifest = manifest; } + public void setConfigFileName(String configFileName) { + this.configFileName = configFileName; + } + public void setPluginLibPath(Set pluginLibPaths) { this.pluginLibPaths = pluginLibPaths; } - public void setConfigFileName(String configFileName) { - this.configFileName = configFileName; + public void setIncludeMainResourcePatterns(Set includeMainResourcePatterns) { + this.includeMainResourcePatterns = includeMainResourcePatterns; } + public void setExcludeMainResourcePatterns(Set excludeMainResourcePatterns) { + this.excludeMainResourcePatterns = excludeMainResourcePatterns; + } @Override public String getPluginClassPath() { @@ -52,6 +61,16 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple return pluginLibPaths; } + @Override + public Set getIncludeMainResourcePatterns() { + return includeMainResourcePatterns; + } + + @Override + public Set getExcludeMainResourcePatterns() { + return excludeMainResourcePatterns; + } + @Override public String getConfigFileName() { return configFileName; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java index f4f557a..58c943c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java @@ -90,6 +90,16 @@ public class EmptyPluginDescriptor implements InsidePluginDescriptor{ return null; } + @Override + public Set getIncludeMainResourcePatterns() { + return null; + } + + @Override + public Set getExcludeMainResourcePatterns() { + return null; + } + @Override public PluginDescriptor toPluginDescriptor() { return null; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java index 47ce9b3..0b207b0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java @@ -48,6 +48,18 @@ public interface InsidePluginDescriptor extends PluginDescriptor{ */ Set getPluginLibPaths(); + /** + * 设置当前插件包含主程序加载资源的匹配 + * @return Set + */ + Set getIncludeMainResourcePatterns(); + + /** + * 设置当前插件排除从主程序加载资源的匹配 + * @return Set + */ + Set getExcludeMainResourcePatterns(); + /** * 转换为 PluginDescriptor * @return PluginDescriptor diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java new file mode 100644 index 0000000..40ab957 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java @@ -0,0 +1,89 @@ +package com.gitee.starblues.core.descriptor; + +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.utils.ObjectUtils; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * 插件 ResourcesDefine 文件定义 + * @author starBlues + * @version 3.0.0 + */ +public class PluginResourcesConfig { + + private Set dependenciesIndex; + private Set loadMainResourceIncludes; + private Set loadMainResourceExcludes; + + public static PluginResourcesConfig parse(List fileLines){ + final PluginResourcesConfig pluginResourcesConfig = new PluginResourcesConfig(); + if(ObjectUtils.isEmpty(fileLines)){ + return pluginResourcesConfig; + } + + Set dependenciesIndex = new HashSet<>(); + Set loadMainResourceIncludes = new HashSet<>(); + Set loadMainResourceExcludes = new HashSet<>(); + + int i = 0; + + for (String fileLine : fileLines) { + if(ObjectUtils.isEmpty(fileLine)){ + continue; + } + if(Objects.equals(fileLine, PackageStructure.RESOURCES_DEFINE_DEPENDENCIES)){ + i = 1; + continue; + } else if(Objects.equals(fileLine, PackageStructure.RESOURCES_DEFINE_LOAD_MAIN_INCLUDES)){ + i = 2; + continue; + } else if(Objects.equals(fileLine, PackageStructure.RESOURCES_DEFINE_LOAD_MAIN_EXCLUDES)){ + i = 3; + continue; + } + if(i == 1){ + dependenciesIndex.add(fileLine); + } else if(i == 2){ + loadMainResourceIncludes.add(fileLine); + } else if(i == 3){ + loadMainResourceExcludes.add(fileLine); + } + } + pluginResourcesConfig.setDependenciesIndex(dependenciesIndex); + pluginResourcesConfig.setLoadMainResourceIncludes(loadMainResourceIncludes); + pluginResourcesConfig.setLoadMainResourceExcludes(loadMainResourceExcludes); + return pluginResourcesConfig; + } + + + public Set getDependenciesIndex() { + return dependenciesIndex; + } + + public void setDependenciesIndex(Set dependenciesIndex) { + this.dependenciesIndex = dependenciesIndex; + } + + public Set getLoadMainResourceIncludes() { + return loadMainResourceIncludes; + } + + public void setLoadMainResourceIncludes(Set loadMainResourceIncludes) { + this.loadMainResourceIncludes = loadMainResourceIncludes; + } + + public Set getLoadMainResourceExcludes() { + return loadMainResourceExcludes; + } + + public void setLoadMainResourceExcludes(Set loadMainResourceExcludes) { + this.loadMainResourceExcludes = loadMainResourceExcludes; + } + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java index c4a2517..af2abda 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -56,21 +56,22 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade } @Override - protected Set getPluginLibPaths(Path path, Attributes attributes) throws Exception { + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception { String pathStr = path.toFile().getPath(); - String libIndexFile = getExistLibIndexFile( - pathStr, ManifestUtils.getValue(attributes, PluginDescriptorKey.PLUGIN_LIB_INDEX) + String libIndexFile = getExistResourcesConfFile( + pathStr, ManifestUtils.getValue(attributes, PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG) ); - Set pluginLibPaths = new HashSet<>(); + if(libIndexFile == null){ - return Collections.emptySet(); + return new PluginResourcesConfig(); } File libFile = new File(libIndexFile); - List libIndex = FileUtils.readLines(libFile, CHARSET_NAME); - if(ObjectUtils.isEmpty(libIndex)){ - return Collections.emptySet(); - } - for (String index : libIndex) { + List lines = FileUtils.readLines(libFile, CHARSET_NAME); + PluginResourcesConfig pluginResourcesConfig = PluginResourcesConfig.parse(lines); + + Set dependenciesIndex = pluginResourcesConfig.getDependenciesIndex(); + Set pluginLibPaths = new HashSet<>(); + for (String index : dependenciesIndex) { index = resolvePath(index); File file = new File(index); if(!file.exists()){ @@ -83,14 +84,15 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade pluginLibPaths.add(file.getPath()); } } - return pluginLibPaths; + pluginResourcesConfig.setDependenciesIndex(pluginLibPaths); + return pluginResourcesConfig; } - protected String getExistLibIndexFile(String rootPath, String libIndexPath){ + protected String getExistResourcesConfFile(String rootPath, String libIndexPath){ libIndexPath = resolvePath(libIndexPath); if(ObjectUtils.isEmpty(libIndexPath)){ // 如果配置为空, 直接从默认路径读取 - libIndexPath = CommonUtils.joiningFilePath(rootPath, resolvePath(PROD_LIB_INDEX_PATH)); + libIndexPath = CommonUtils.joiningFilePath(rootPath, resolvePath(PROD_RESOURCES_DEFINE_PATH)); } else { if(Files.exists(Paths.get(libIndexPath))){ return libIndexPath; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java index 20ed6f9..281c28d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -9,16 +9,13 @@ import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.nio.file.Path; -import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; -import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_LIB_INDEX; +import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG; /** @@ -29,7 +26,7 @@ import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_LIB_INDEX; public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorLoader{ private final PluginDescriptor.Type type; - private Set pluginLibPaths; + private PluginResourcesConfig pluginResourcesConfig; public ProdPackagePluginDescriptorLoader(PluginDescriptor.Type type) { this.type = type; @@ -43,14 +40,14 @@ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorL InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); Manifest manifest = PluginFileUtils.getManifest(jarFileInputStream); jarFileInputStream.close(); - pluginLibPaths = getPluginLibPaths(jarFile, manifest); + pluginResourcesConfig = getPluginResourcesConfig(jarFile, manifest); return manifest; } } @Override - protected Set getPluginLibPaths(Path path, Attributes attributes) throws Exception { - return pluginLibPaths; + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception { + return pluginResourcesConfig; } @Override @@ -60,22 +57,19 @@ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorL return descriptor; } - protected Set getPluginLibPaths(JarFile jarFile, Manifest manifest) throws Exception { + protected PluginResourcesConfig getPluginResourcesConfig(JarFile jarFile, Manifest manifest) throws Exception { Attributes attributes = manifest.getMainAttributes(); - String pluginLibIndex = ManifestUtils.getValue(attributes, PLUGIN_LIB_INDEX); - if(ObjectUtils.isEmpty(pluginLibIndex)){ - return Collections.emptySet(); + String pluginResourcesConf = ManifestUtils.getValue(attributes, PLUGIN_RESOURCES_CONFIG); + if(ObjectUtils.isEmpty(pluginResourcesConf)){ + return new PluginResourcesConfig(); } - JarEntry jarEntry = jarFile.getJarEntry(pluginLibIndex); + JarEntry jarEntry = jarFile.getJarEntry(pluginResourcesConf); if(jarEntry == null){ - return Collections.emptySet(); + return new PluginResourcesConfig(); } InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); - List libPaths = IOUtils.readLines(jarFileInputStream, PackageStructure.CHARSET_NAME); - if(ObjectUtils.isEmpty(libPaths)){ - return Collections.emptySet(); - } - return new HashSet<>(libPaths); + List lines = IOUtils.readLines(jarFileInputStream, PackageStructure.CHARSET_NAME); + return PluginResourcesConfig.parse(lines); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java index e86626b..3d967da 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java @@ -6,22 +6,53 @@ import java.util.HashSet; import java.util.Set; /** + * java 内部包匹配定义 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JavaMainResourcePatternDefiner implements MainResourcePatternDefiner { - private final Set includes = new HashSet<>(); + protected final Set includes = new HashSet<>(); public JavaMainResourcePatternDefiner(){ - // TODO java 内部的包匹配, 未补充全 - // == java == + // java 内部的包匹配定义 + addJava(); + addJavax(); + addSun(); + addJdk(); + addJavaXml(); + } + + protected void addJava(){ includes.add("java/**"); + } + + protected void addJavax(){ includes.add("javax/**"); - includes.add("sun/**"); - includes.add("org/xml/**"); + includes.add("org/ietf/jgss/**"); + } + + protected void addJdk(){ includes.add("jdk/**"); - includes.add("org/w3c/**"); + // jdk.internal.vm.compiler + includes.add("org/graalvm/**"); + // jdk.internal.vm.compiler.management + includes.add("org/graalvm/compiler/hotspot/management/**"); + // jdk.hotspot.agent + includes.add("images/toolbarButtonGraphics/general/**"); + includes.add("toolbarButtonGraphics/**"); + } + + protected void addJavaXml(){ + // jdk.xml.dom + includes.add("org/w3c/dom/**"); + includes.add("org/xml/sax/**"); + includes.add("org/jcp/xml/dsig/internal**"); + } + + protected void addSun(){ + includes.add("com/sun/**"); + includes.add("sun/**"); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java index f2f99fc..7c43592 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java @@ -9,8 +9,9 @@ import java.net.URLClassLoader; import java.util.Objects; /** + * 主程序启动者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class MainProgramLauncher extends AbstractLauncher{ @@ -24,13 +25,22 @@ public class MainProgramLauncher extends AbstractLauncher{ @Override protected ClassLoader createClassLoader() throws Exception { - GenericClassLoader classLoader = new GenericClassLoader( - MAIN_CLASS_LOADER_NAME, MainProgramLauncher.class.getClassLoader() - ); + GenericClassLoader classLoader = new GenericClassLoader(MAIN_CLASS_LOADER_NAME, getParentClassLoader()); addResource(classLoader); return classLoader; } + @Override + protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { + MethodRunner run = new MethodRunner(springBootstrap.getClass().getName(), "run", args); + run.run(classLoader); + return classLoader; + } + + protected ClassLoader getParentClassLoader(){ + return MainProgramLauncher.class.getClassLoader(); + } + protected void addResource(GenericClassLoader classLoader) throws Exception{ String classPath = ManagementFactory.getRuntimeMXBean().getClassPath(); if(!ObjectUtils.isEmpty(classPath)){ @@ -50,15 +60,4 @@ public class MainProgramLauncher extends AbstractLauncher{ } - @Override - protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { - MethodRunner run = new MethodRunner(springBootstrap.getClass().getName(), "run", args); - run.run(classLoader); - return classLoader; - } - - private static boolean isStartupOfJar() { - String protocol = MainProgramLauncher.class.getResource("").getProtocol(); - return Objects.equals(protocol, "jar"); - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 2c28259..01585be 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -24,33 +24,30 @@ public class PluginLauncher extends AbstractLauncher { protected final PluginInteractive pluginInteractive; protected final InsidePluginDescriptor pluginDescriptor; + protected final PluginMainResourcePatternDefiner mainResourcePatternDefiner; public PluginLauncher(PluginInteractive pluginInteractive) { this.pluginInteractive = pluginInteractive; this.pluginDescriptor = pluginInteractive.getPluginDescriptor(); + this.mainResourcePatternDefiner = new PluginMainResourcePatternDefiner(pluginDescriptor); } @Override protected ClassLoader createClassLoader() throws Exception { String pluginId = pluginDescriptor.getPluginId(); - MainResourcePatternDefiner mainResourceMatcher = new JavaMainResourcePatternDefiner() { - @Override - public Set getIncludePatterns() { - Set includeResourcePatterns = super.getIncludePatterns(); - includeResourcePatterns.add("com/gitee/starblues/**"); - includeResourcePatterns.add("org/springframework/web/**"); - return includeResourcePatterns; - } - }; PluginClassLoader pluginClassLoader = new PluginClassLoader( - pluginId, MainProgramLauncher.class.getClassLoader(), mainResourceMatcher + pluginId, getParentClassLoader(), mainResourcePatternDefiner ); - pluginClassLoader.addResource(pluginDescriptor); //TODO 添加框架的引导 pluginClassLoader.addResource(Paths.get("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-bootstrap\\target\\classes")); + pluginClassLoader.addResource(pluginDescriptor); return pluginClassLoader; } + protected ClassLoader getParentClassLoader(){ + return PluginLauncher.class.getClassLoader(); + } + @Override protected SpringPluginHook launch(ClassLoader classLoader, String... args) throws Exception { PluginResourceStorage.addPlugin(pluginDescriptor); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java new file mode 100644 index 0000000..e8f4174 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -0,0 +1,50 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; +import com.gitee.starblues.utils.ObjectUtils; + +import java.util.Set; + +/** + * 定义插件从主程序加载资源的匹配 + * @author starBlues + * @version 3.0.0 + */ +public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDefiner { + + private static final String FRAMEWORK = "com/gitee/starblues/**"; + private static final String SPRING_WEB = "org/springframework/web/**"; + + private final InsidePluginDescriptor descriptor; + + public PluginMainResourcePatternDefiner(InsidePluginDescriptor descriptor) { + this.descriptor = descriptor; + } + + @Override + public Set getIncludePatterns() { + Set includeResourcePatterns = super.getIncludePatterns(); + includeResourcePatterns.add(FRAMEWORK); + includeResourcePatterns.add(SPRING_WEB); + + // 配置插件自定义从主程序加载的资源匹配 + Set includeMainResourcePatterns = descriptor.getIncludeMainResourcePatterns(); + if(ObjectUtils.isEmpty(includeMainResourcePatterns)){ + return includeResourcePatterns; + } + + for (String includeMainResourcePattern : includeMainResourcePatterns) { + if(ObjectUtils.isEmpty(includeMainResourcePattern)){ + continue; + } + includeResourcePatterns.add(includeMainResourcePattern); + } + return includeResourcePatterns; + } + + @Override + public Set getExcludePatterns() { + return descriptor.getExcludeMainResourcePatterns(); + } +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java index bd4be16..2dbf1ee 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java @@ -26,15 +26,18 @@ public abstract class AbstractPackagerMojo extends AbstractDependencyFilterMojo{ @Parameter(defaultValue = "${project.build.directory}", required = true) private File outputDirectory; - @Parameter(property = "springboot-plugin.pluginInfo", required = true) - private PluginInfo pluginInfo; - @Parameter(property = "springboot-plugin.mode", defaultValue = "dev", required = true) private String mode; @Parameter(property = "springboot-plugin.skip", defaultValue = "false") private boolean skip; + @Parameter(property = "springboot-plugin.pluginInfo", required = true) + private PluginInfo pluginInfo; + + @Parameter(property = "springboot-plugin.loadMainResourcePattern", required = false) + private LoadMainResourcePattern loadMainResourcePattern; + @Override public final void execute() throws MojoExecutionException, MojoFailureException { if(Constant.isPom(this.getProject().getPackaging())){ diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index b6196c5..895a46c 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -12,6 +12,7 @@ import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.jar.Attributes; @@ -33,7 +34,9 @@ public class BasicRepackager implements Repackager{ @Getter private String rootDir; private String relativeManifestPath; - private String relativeLibIndexPath; + private String relativeResourcesDefinePath; + + private File resourcesDefineFile; protected final RepackageMojo repackageMojo; @@ -45,7 +48,7 @@ public class BasicRepackager implements Repackager{ public void repackage() throws MojoExecutionException, MojoFailureException { rootDir = createRootDir(); relativeManifestPath = getRelativeManifestPath(); - relativeLibIndexPath = getRelativeLibIndexPath(); + relativeResourcesDefinePath = getRelativeResourcesDefinePath(); try { Manifest manifest = getManifest(); writeManifest(manifest); @@ -59,8 +62,8 @@ public class BasicRepackager implements Repackager{ return MANIFEST; } - protected String getRelativeLibIndexPath(){ - return LIB_INDEX_NAME; + protected String getRelativeResourcesDefinePath(){ + return RESOURCES_DEFINE_NAME; } protected String createRootDir() throws MojoFailureException { @@ -109,9 +112,9 @@ public class BasicRepackager implements Repackager{ attributes.putValue(PLUGIN_VERSION, pluginInfo.getVersion()); attributes.putValue(PLUGIN_PATH, getPluginPath()); - String libFilePath = writeLibFile(); - if(!CommonUtils.isEmpty(libFilePath)){ - attributes.putValue(PLUGIN_LIB_INDEX, libFilePath); + String resourcesDefineFilePath = writeResourcesDefineFile(); + if(!CommonUtils.isEmpty(resourcesDefineFilePath)){ + attributes.putValue(PLUGIN_RESOURCES_CONFIG, resourcesDefineFilePath); } String configFileName = pluginInfo.getConfigFileName(); if(!isEmpty(configFileName)){ @@ -149,28 +152,39 @@ public class BasicRepackager implements Repackager{ return repackageMojo.getProject().getBuild().getOutputDirectory(); } - protected String writeLibFile() throws Exception{ - StringBuilder stringBuilder = new StringBuilder(); - Set libIndex = getLibIndexSet(); - for (String index : libIndex) { - stringBuilder.append(index).append("\n"); - } - String content = stringBuilder.toString(); - String path = joinPath(rootDir, resolvePath(relativeLibIndexPath)); + protected String writeResourcesDefineFile() throws Exception{ + resourcesDefineFile = createResourcesDefineFile(); + writeDependenciesIndex(); + writeLoadMainResources(); + return resourcesDefineFile.getPath(); + } + + protected File createResourcesDefineFile() throws IOException { + String path = joinPath(rootDir, resolvePath(relativeResourcesDefinePath)); try { File file = new File(path); FileUtils.forceMkdirParent(file); if(file.createNewFile()){ - FileUtils.write(file, content, "utf-8"); - return path; + return file; } - throw new Exception(); + throw new IOException("Create " + path + " file error"); } catch (Exception e){ throw new IOException("Create " + path + " file error"); } } - protected Set getLibIndexSet() throws Exception { + protected void writeDependenciesIndex() throws Exception { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(RESOURCES_DEFINE_DEPENDENCIES).append("\n"); + Set libIndex = getDependenciesIndexSet(); + for (String index : libIndex) { + stringBuilder.append(index).append("\n"); + } + String content = stringBuilder.toString(); + FileUtils.write(resourcesDefineFile, content, CHARSET_NAME, true); + } + + protected Set getDependenciesIndexSet() throws Exception { Set dependencies = repackageMojo.getDependencies(); Set libPaths = new HashSet<>(dependencies.size()); for (Artifact artifact : dependencies) { @@ -186,6 +200,45 @@ public class BasicRepackager implements Repackager{ return artifact.getFile().getPath(); } + protected void writeLoadMainResources() throws Exception { + String loadMainResources = getLoadMainResources(); + if(CommonUtils.isEmpty(loadMainResources)){ + return; + } + FileUtils.write(resourcesDefineFile, loadMainResources, CHARSET_NAME, true); + } + + protected String getLoadMainResources(){ + LoadMainResourcePattern loadMainResourcePattern = repackageMojo.getLoadMainResourcePattern(); + if(loadMainResourcePattern == null){ + return null; + } + String[] includes = loadMainResourcePattern.getIncludes(); + String[] excludes = loadMainResourcePattern.getExcludes(); + StringBuilder stringBuilder = new StringBuilder(); + addLoadMainResources(stringBuilder, RESOURCES_DEFINE_LOAD_MAIN_INCLUDES, includes); + addLoadMainResources(stringBuilder, RESOURCES_DEFINE_LOAD_MAIN_EXCLUDES, excludes); + return stringBuilder.toString(); + } + + private void addLoadMainResources(StringBuilder stringBuilder, String header, String[] patterns){ + if(CommonUtils.isEmpty(patterns)){ + return; + } + Set patternSet = new HashSet<>(Arrays.asList(patterns)); + stringBuilder.append(header).append("\n"); + for (String patternStr : patternSet) { + if(CommonUtils.isEmpty(patternStr)){ + continue; + } + stringBuilder.append(resolvePattern(patternStr)).append("\n"); + } + } + + protected String resolvePattern(String patternStr){ + return patternStr.replace(".", "/"); + } + /** * 过滤Artifact * @param artifact Artifact diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java new file mode 100644 index 0000000..d2d296d --- /dev/null +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java @@ -0,0 +1,20 @@ +package com.gitee.starblues.plugin.pack; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * 从主程序加载资源配置 + * @author starBlues + * @version 3.0.0 + */ +@Data +public class LoadMainResourcePattern { + + @Parameter(name = "includes") + private String[] includes; + + @Parameter(name = "excludes") + private String[] excludes; + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java index d0b6b7c..87f29a6 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java @@ -23,13 +23,13 @@ public class DevRepackager extends BasicRepackager { } @Override - protected Set getLibIndexSet() throws Exception { + protected Set getDependenciesIndexSet() throws Exception { moduleDependencies = getModuleDependencies(repackageMojo.getDevConfig()); - Set libPaths = super.getLibIndexSet(); + Set dependenciesIndexSet = super.getDependenciesIndexSet(); for (Dependency dependency : moduleDependencies.values()) { - libPaths.add(dependency.getClassesPath()); + dependenciesIndexSet.add(dependency.getClassesPath()); } - return libPaths; + return dependenciesIndexSet; } @Override diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java index 27193e0..76fc6c5 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java @@ -73,8 +73,8 @@ public class DirPackageGenerator extends DevRepackager { } @Override - protected String getRelativeLibIndexPath() { - return CommonUtils.joinPath(META_INF_NAME, LIB_INDEX_NAME); + protected String getRelativeResourcesDefinePath() { + return CommonUtils.joinPath(META_INF_NAME, RESOURCES_DEFINE_NAME); } @Override @@ -82,7 +82,7 @@ public class DirPackageGenerator extends DevRepackager { Manifest manifest = super.getManifest(); Attributes attributes = manifest.getMainAttributes(); attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, CLASSES_NAME); - attributes.putValue(PluginDescriptorKey.PLUGIN_LIB_INDEX, PROD_LIB_INDEX_PATH); + attributes.putValue(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); return manifest; } @@ -95,7 +95,7 @@ public class DirPackageGenerator extends DevRepackager { } @Override - protected Set getLibIndexSet() throws Exception { + protected Set getDependenciesIndexSet() throws Exception { Set dependencies = repackageMojo.getDependencies(); String libDir = createLibDir(); Set dependencyIndexNames = new HashSet<>(dependencies.size()); diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java index 74a7968..d0366aa 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -56,7 +56,7 @@ public class ZipProdRepackager extends DevRepackager { outputStream = getOutputStream(packageFile); super.repackage(); resolveClasses(); - resolveDependencies(); + resolveResourcesDefine(); outputStream.finish(); String rootDir = getRootDir(); try { @@ -151,7 +151,7 @@ public class ZipProdRepackager extends DevRepackager { Manifest manifest = super.getManifest(); Attributes attributes = manifest.getMainAttributes(); attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, PROD_CLASSES_PATH); - attributes.putValue(PluginDescriptorKey.PLUGIN_LIB_INDEX, PROD_LIB_INDEX_PATH); + attributes.putValue(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); return manifest; } @@ -163,7 +163,24 @@ public class ZipProdRepackager extends DevRepackager { outputStream.closeArchiveEntry(); } - protected void resolveDependencies() throws Exception { + protected void resolveResourcesDefine() throws Exception{ + Set dependencyIndexNames = resolveDependencies(); + StringBuilder content = new StringBuilder(); + content.append(RESOURCES_DEFINE_DEPENDENCIES).append("\n"); + for (String dependencyIndexName : dependencyIndexNames) { + content.append(dependencyIndexName).append("\n"); + } + String loadMainResources = super.getLoadMainResources(); + if(!CommonUtils.isEmpty(loadMainResources)){ + content.append(loadMainResources).append("\n"); + } + final byte[] bytes = content.toString().getBytes(StandardCharsets.UTF_8); + try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)){ + putInputStreamEntry(byteArrayInputStream, PROD_RESOURCES_DEFINE_PATH); + } + } + + protected Set resolveDependencies() throws Exception { Set dependencies = repackageMojo.getDependencies(); String libDirEntryName = createLibEntry(); Set dependencyIndexNames = new HashSet<>(dependencies.size()); @@ -174,7 +191,7 @@ public class ZipProdRepackager extends DevRepackager { String dependencyIndexName = writeDependency(artifact.getFile(), libDirEntryName, outputStream); dependencyIndexNames.add(dependencyIndexName); } - writeLibIndexFile(dependencyIndexNames); + return dependencyIndexNames; } protected String createLibEntry() throws Exception { @@ -201,17 +218,6 @@ public class ZipProdRepackager extends DevRepackager { return indexName; } - protected void writeLibIndexFile(Set dependencyIndexNames) throws Exception { - StringBuilder content = new StringBuilder(); - for (String dependencyIndexName : dependencyIndexNames) { - content.append(dependencyIndexName).append("\n"); - } - final byte[] bytes = content.toString().getBytes(StandardCharsets.UTF_8); - try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)){ - putInputStreamEntry(byteArrayInputStream, PROD_LIB_INDEX_PATH); - } - } - protected void copyFileToPackage(File file, String rootDir) throws Exception { if(CommonUtils.isEmpty(rootDir)){ rootDir = file.getName(); diff --git a/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml b/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml index 95a7027..c3ae287 100644 --- a/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml +++ b/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml @@ -93,6 +93,14 @@ true 插件信息 + + loadMainResourcePattern + com.gitee.starblues.plugin.pack.LoadMainResourcePattern + 3.0.0 + false + true + 从主程序加载资源的定义 + devConfig com.gitee.starblues.plugin.pack.dev.DevConfig @@ -116,6 +124,7 @@ + ${springboot-plugin.includes} ${springboot-plugin.excludes} -- Gitee From e765ac3aa3986de356cb2c06fa7936126951854a Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sun, 23 Jan 2022 11:20:25 +0800 Subject: [PATCH 23/37] add static resource and thymeleaf --- springboot-plugin-bootstrap/pom.xml | 34 +- .../bootstrap/ConfigurePluginEnvironment.java | 1 - .../bootstrap/DefaultSpringPluginHook.java | 13 + .../bootstrap/PluginOneselfInteractive.java | 3 +- .../ComposeSpringPluginProcessor.java | 10 +- .../processor/DefaultProcessorContext.java | 8 + .../bootstrap/processor/ProcessorContext.java | 10 +- .../processor/SpringPluginProcessor.java | 39 +- .../PluginControllerRegistryProcessor.java | 5 +- .../PluginInterceptorsProcessor.java | 5 +- .../web/PluginStaticResourceProcessor.java | 56 +++ .../thymeleaf/PluginThymeleafProcessor.java | 41 ++ .../web/thymeleaf/ThymeleafConfigParse.java | 57 +++ .../bootstrap/utils/DestroyUtils.java | 3 +- .../bootstrap/utils/ProcessorUtils.java | 25 ++ .../resources/thymeleaf/ThymeleafConfig.java | 95 ----- springboot-plugin-framework/pom.xml | 26 +- .../starblues/core/PluginLauncherManager.java | 16 +- .../classloader/CacheMainResourceMatcher.java | 3 +- .../core/classloader/GenericClassLoader.java | 3 +- .../core/classloader/JarResourceLoader.java | 4 - .../PluginResourceLoaderFactory.java | 5 +- .../ProhibitMainResourceMatcher.java | 1 + .../AbstractExecutableArchiveLauncher.java | 8 - .../core/launcher/AbstractLauncher.java | 8 +- .../starblues/core/launcher/Launcher.java | 3 +- .../core/launcher/MainMethodRunner.java | 3 +- .../core/launcher/MainProgramLauncher.java | 1 - .../starblues/core/launcher/MethodRunner.java | 3 +- .../core/launcher/PluginResourceStorage.java | 19 +- .../core/launcher/SpringBootstrap.java | 12 +- .../core/launcher/SpringMainBootstrap.java | 3 +- .../core/launcher/plugin/PluginLauncher.java | 41 +- .../PluginMainResourcePatternDefiner.java | 12 +- .../plugin/SpringPluginHookWrapper.java | 36 +- .../involved/DefaultPluginLaunchInvolved.java | 31 ++ .../plugin/involved/PluginLaunchInvolved.java | 68 ++++ .../involved/PluginLaunchInvolvedFactory.java | 99 +++++ .../DefaultIntegrationConfiguration.java | 1 + .../integration/IntegrationConfiguration.java | 2 + .../integration/IntegrationExtendPoint.java | 37 +- .../operator/DefaultPluginOperator.java | 18 +- .../starblues/spring/ApplicationContext.java | 3 +- .../spring/ApplicationContextProxy.java | 3 +- .../CacheJdkSameTypeParamProxyFactory.java | 8 +- .../spring/GenericApplicationContext.java | 3 +- .../starblues/spring/SpringPluginHook.java | 15 + .../com/gitee/starblues/spring/WebConfig.java | 30 ++ .../starblues/spring/web/PluginResource.java | 168 +++++++++ .../web/PluginStaticResourceConfig.java | 43 +++ .../web/PluginStaticResourceResolver.java | 349 ++++++++++++++++++ .../PluginStaticResourceWebMvcConfigurer.java | 38 ++ .../thymeleaf/PluginThymeleafInvolved.java | 120 ++++++ .../spring/web/thymeleaf/ThymeleafConfig.java | 108 ++++++ .../gitee/starblues/utils/ResourceUtils.java | 20 + .../pack/AbstractDependencyFilterMojo.java | 15 +- 56 files changed, 1590 insertions(+), 201 deletions(-) rename springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/{ => web}/PluginControllerRegistryProcessor.java (98%) rename springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/{ => web}/PluginInterceptorsProcessor.java (95%) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index ba2cf73..c3b3096 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -17,23 +17,22 @@ UTF-8 3.8.1 + 3.0.0-RELEASE + 1.7.7 2.5.0 5.3.2 + 4.0.1 2.11.3 - - org.slf4j - slf4j-api - ${slf4j.version} - com.gitee.starblues - spring-plugin-framework-common - ${project.version} + springboot-plugin-framework + 3.0.0-RELEASE + provided @@ -51,16 +50,23 @@ - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + true - com.gitee.starblues - springboot-plugin-framework - 3.0.0-RELEASE - provided + org.slf4j + slf4j-api + ${slf4j.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 815a89a..89a15a7 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -1,7 +1,6 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java index e55bcd8..8f5ec6e 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -2,10 +2,13 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; import com.gitee.starblues.bootstrap.utils.DestroyUtils; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.ApplicationContextProxy; import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.spring.WebConfig; +import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.support.SpringFactoriesLoader; @@ -45,4 +48,14 @@ public class DefaultSpringPluginHook implements SpringPluginHook { public ApplicationContext getApplicationContext() { return new ApplicationContextProxy(processorContext.getApplicationContext().getBeanFactory()); } + + @Override + public WebConfig getWebConfig() { + return processorContext.getWebConfig(); + } + + @Override + public ThymeleafConfig getThymeleafConfig() { + return processorContext.getRegistryInfo(PluginThymeleafProcessor.CONFIG_KEY); + } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index 8fb0dd4..d856382 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -13,8 +13,9 @@ import com.gitee.starblues.spring.invoke.InvokeSupperCache; import java.nio.file.Paths; /** + * 插件自己的Interactive * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginOneselfInteractive implements PluginInteractive { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index a62b3dc..d3daeeb 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -2,6 +2,10 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; import com.gitee.starblues.bootstrap.annotation.DisablePluginWeb; +import com.gitee.starblues.bootstrap.processor.web.PluginControllerRegistryProcessor; +import com.gitee.starblues.bootstrap.processor.web.PluginInterceptorsProcessor; +import com.gitee.starblues.bootstrap.processor.web.PluginStaticResourceProcessor; +import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; @@ -14,8 +18,9 @@ import java.util.List; import java.util.stream.Collectors; /** + * 组合的处理器 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { @@ -143,8 +148,11 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { if(disablePluginWeb != null){ return; } + context.getWebConfig().setEnable(true); processors.add(new PluginControllerRegistryProcessor()); processors.add(new PluginInterceptorsProcessor()); + processors.add(new PluginStaticResourceProcessor()); + processors.add(new PluginThymeleafProcessor()); } private void processException(SpringPluginProcessor processor, String executeType, diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 27cd8ee..5f0db4c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -8,6 +8,7 @@ import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringBeanFactory; +import com.gitee.starblues.spring.WebConfig; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; @@ -27,6 +28,7 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces private final ResourceLoader resourceLoader; private final IntegrationConfiguration configuration; + private final WebConfig webConfig; private GenericApplicationContext applicationContext; @@ -40,6 +42,7 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces this.resourceLoader = new DefaultResourceLoader(this.classLoader); this.mainApplicationContext = pluginInteractive.getMainApplicationContext(); this.configuration = pluginInteractive.getConfiguration(); + this.webConfig = new WebConfig(); } @Override @@ -95,6 +98,11 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces return resourceLoader; } + @Override + public WebConfig getWebConfig() { + return webConfig; + } + @Override public void setApplicationContext(GenericApplicationContext applicationContext) { this.applicationContext = applicationContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index d564552..ccb2966 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -9,13 +9,15 @@ import com.gitee.starblues.core.launcher.plugin.RegistryInfo; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringBeanFactory; +import com.gitee.starblues.spring.WebConfig; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ResourceLoader; /** + * 处理者上下文 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface ProcessorContext extends RegistryInfo { @@ -80,6 +82,12 @@ public interface ProcessorContext extends RegistryInfo { */ ResourceLoader getResourceLoader(); + /** + * 获取 WebConfig + * @return WebConfig + */ + WebConfig getWebConfig(); + /** * set 当前插件的 ApplicationContext * @param applicationContext GenericApplicationContext diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java index 06675ae..fd12d6d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java @@ -4,38 +4,75 @@ import com.gitee.starblues.utils.Order; import com.gitee.starblues.utils.OrderPriority; /** + * spring plugin 处理器 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface SpringPluginProcessor extends Order { + /** + * 初始化时 + * @param context ProcessorContext + * @throws ProcessorException 处理异常 + */ default void initialize(ProcessorContext context) throws ProcessorException{ } + /** + * 刷新上下文前 + * @param context ProcessorContext + * @throws ProcessorException 处理异常 + */ default void refreshBefore(ProcessorContext context) throws ProcessorException{ } + /** + * 刷新上下文后 + * @param context ProcessorContext + * @throws ProcessorException 处理异常 + */ default void refreshAfter(ProcessorContext context) throws ProcessorException{ } + /** + * 启动失败 + * @param context ProcessorContext + * @throws ProcessorException 处理异常 + */ default void failure(ProcessorContext context) throws ProcessorException{ } + /** + * 关闭容器时 + * @param context ProcessorContext + * @throws ProcessorException 处理异常 + */ default void close(ProcessorContext context) throws ProcessorException{ } + /** + * 执行顺序 + * @return OrderPriority + */ @Override default OrderPriority order(){ return OrderPriority.getLowPriority(); } + /** + * 处理器运行模式 + * @return RunMode + */ RunMode runMode(); + /** + * 运行模式 + */ enum RunMode{ /** * 全部运行 diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerRegistryProcessor.java similarity index 98% rename from springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerRegistryProcessor.java index 04c3142..9c1de3e 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginControllerRegistryProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerRegistryProcessor.java @@ -1,5 +1,8 @@ -package com.gitee.starblues.bootstrap.processor; +package com.gitee.starblues.bootstrap.processor.web; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorException; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; import com.gitee.starblues.bootstrap.utils.DestroyUtils; import com.gitee.starblues.integration.IntegrationConfiguration; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java similarity index 95% rename from springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginInterceptorsProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java index 35b2098..26b4cab 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java @@ -1,5 +1,8 @@ -package com.gitee.starblues.bootstrap.processor; +package com.gitee.starblues.bootstrap.processor.web; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorException; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; import com.gitee.starblues.bootstrap.processor.interceptor.PluginInterceptorRegister; import com.gitee.starblues.bootstrap.processor.interceptor.PluginInterceptorRegistry; import com.gitee.starblues.bootstrap.utils.SpringBeanUtils; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java new file mode 100644 index 0000000..ee0b196 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java @@ -0,0 +1,56 @@ +package com.gitee.starblues.bootstrap.processor.web; + +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorException; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +import java.util.HashSet; +import java.util.Set; + +/** + * 插件web资源处理器. 获取资源配置 + * @author starBlues + * @version 3.0.0 + */ +public class PluginStaticResourceProcessor implements SpringPluginProcessor { + + + /** + * 静态文件配置前缀 + * 静态文件路径 + * classpath: static/ + * file: D://path/test + */ + private final static String STATIC_LOCATIONS = "spring.resources.static-locations"; + + + @Override + public void refreshBefore(ProcessorContext context) throws ProcessorException { + GenericApplicationContext applicationContext = context.getApplicationContext(); + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + String property = environment.getProperty(STATIC_LOCATIONS); + if(ObjectUtils.isEmpty(property)){ + return; + } + String[] staticLocations = property.split(","); + if (ObjectUtils.isEmpty(staticLocations)) { + return; + } + Set staticLocationsSet = new HashSet<>(staticLocations.length); + for (String staticLocation : staticLocations) { + if(ObjectUtils.isEmpty(staticLocation)){ + continue; + } + staticLocationsSet.add(staticLocation); + } + context.getWebConfig().setResourceLocations(staticLocationsSet); + } + + @Override + public RunMode runMode() { + return RunMode.PLUGIN; + } +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java new file mode 100644 index 0000000..37e19c7 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java @@ -0,0 +1,41 @@ +package com.gitee.starblues.bootstrap.processor.web.thymeleaf; + +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorException; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.GenericApplicationContext; + +/** + * 插件 Thymeleaf 注册 + * @author starBlues + * @version 3.0.0 + */ +public class PluginThymeleafProcessor implements SpringPluginProcessor { + + private static final Logger logger = LoggerFactory.getLogger(PluginThymeleafProcessor.class); + + public static final String CONFIG_KEY = "ThymeleafConfig"; + + + @Override + public void refreshBefore(ProcessorContext context) throws ProcessorException { + GenericApplicationContext applicationContext = context.getApplicationContext(); + ThymeleafConfig thymeleafConfig = ThymeleafConfigParse.parse(applicationContext.getEnvironment()); + context.addRegistryInfo(CONFIG_KEY, thymeleafConfig); + } + + @Override + public void close(ProcessorContext context) throws ProcessorException { + context.removeRegistryInfo(CONFIG_KEY); + } + + @Override + public RunMode runMode() { + return RunMode.PLUGIN; + } + + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java new file mode 100644 index 0000000..8e93e60 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java @@ -0,0 +1,57 @@ +package com.gitee.starblues.bootstrap.processor.web.thymeleaf; + +import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; +import com.gitee.starblues.utils.ObjectUtils; +import org.springframework.core.env.Environment; + +/** + * 解析ThymeleafConfig配置 + * @author starBlues + * @version 3.0.0 + */ +public class ThymeleafConfigParse { + + private static final String KEY_PREFIX = "spring.thymeleaf."; + + + public static final String ENABLED = KEY_PREFIX + "enabled"; + private static final String PREFIX = KEY_PREFIX + "prefix"; + private static final String SUFFIX = KEY_PREFIX + "suffix"; + private static final String MODE = KEY_PREFIX + "mode"; + private static final String CACHE = KEY_PREFIX + "cache"; + private static final String TEMPLATE_RESOLVER_ORDER = KEY_PREFIX + "templateResolverOrder"; + + + public static ThymeleafConfig parse(Environment environment){ + ThymeleafConfig thymeleafConfig = new ThymeleafConfig(); + String enabled = environment.getProperty(ENABLED); + if(!ObjectUtils.isEmpty(enabled) && !Boolean.parseBoolean(enabled)) { + thymeleafConfig.setEnabled(false); + return thymeleafConfig; + } + String prefix = environment.getProperty(PREFIX); + if(!ObjectUtils.isEmpty(prefix)){ + thymeleafConfig.setPrefix(prefix); + } + String suffix = environment.getProperty(SUFFIX); + if(!ObjectUtils.isEmpty(suffix)){ + thymeleafConfig.setSuffix(suffix); + } + String mode = environment.getProperty(MODE); + if(!ObjectUtils.isEmpty(mode)){ + thymeleafConfig.setMode(mode); + } + String cache = environment.getProperty(CACHE); + if(!ObjectUtils.isEmpty(cache)){ + thymeleafConfig.setCache(Boolean.getBoolean(cache)); + } + String templateResolverOrder = environment.getProperty(TEMPLATE_RESOLVER_ORDER); + if(!ObjectUtils.isEmpty(templateResolverOrder)){ + thymeleafConfig.setTemplateResolverOrder(Integer.getInteger(templateResolverOrder)); + } + return thymeleafConfig; + } + + + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java index a69d418..6a104d3 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java @@ -8,8 +8,9 @@ import java.util.Map; import java.util.Objects; /** + * 销毁工具类 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DestroyUtils { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java new file mode 100644 index 0000000..556f0da --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java @@ -0,0 +1,25 @@ +package com.gitee.starblues.bootstrap.utils; + +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; + +import java.util.List; +import java.util.function.Supplier; + +/** + * ProcessorUtils + * @author starBlues + * @version 3.0.0 + */ +public class ProcessorUtils { + + public static void add(List pluginProcessors, Supplier supplier){ + try { + SpringPluginProcessor pluginProcessor = supplier.get(); + pluginProcessors.add(pluginProcessor); + } catch (Throwable e){ + // 忽略 + } + } + + +} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java index 3b11388..c632611 100644 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java +++ b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java @@ -12,100 +12,5 @@ import java.nio.charset.StandardCharsets; public class ThymeleafConfig { - public static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; - public static final String DEFAULT_PREFIX = "templates/"; - - public static final String DEFAULT_SUFFIX = ".html"; - - /** - * 存放模板引擎的前缀 - */ - private String prefix = DEFAULT_PREFIX; - - /** - * 模板引擎文件的后缀 - */ - private String suffix = DEFAULT_SUFFIX; - - /** - * 模型引入的模型 - * @see TemplateMode - */ - private TemplateMode mode = TemplateMode.HTML; - - /** - * 模板引擎的编码 - */ - private Charset encoding = DEFAULT_ENCODING; - - /** - * 是否启用模板引擎的缓存 - */ - private Boolean cache = true; - - /** - * 模板解析器的执行顺序, 数字越小越先执行 - */ - private Integer templateResolverOrder; - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getSuffix() { - return suffix; - } - - public void setSuffix(String suffix) { - this.suffix = suffix; - } - - public TemplateMode getMode() { - return mode; - } - - public void setMode(String mode) { - this.mode = TemplateMode.parse(mode); - } - - public Charset getEncoding() { - return encoding; - } - - public void setEncoding(String encoding) { - this.encoding = Charset.forName(encoding); - } - - public Boolean getCache() { - return cache; - } - - public void setCache(Boolean cache) { - this.cache = cache; - } - - public Integer getTemplateResolverOrder() { - return templateResolverOrder; - } - - public void setTemplateResolverOrder(Integer templateResolverOrder) { - this.templateResolverOrder = templateResolverOrder; - } - - @Override - public String toString() { - return "ThymeleafConfig{" + - "prefix='" + prefix + '\'' + - ", suffix='" + suffix + '\'' + - ", mode=" + mode.name() + - ", encoding=" + encoding.name() + - ", cache=" + cache + - ", templateResolverOrder=" + templateResolverOrder + - '}'; - } } diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index d2d43d5..9d4f4d8 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -66,9 +66,10 @@ 2.10.1 1.7.7 + 2.11.0 - 5.0.7.RELEASE - 2.4.1 + 5.0.7.RELEASE + 2.4.1 2.10.5 1.5.2 4.0.1 @@ -92,23 +93,38 @@ commons-io commons-io - 2.11.0 + ${commons-io.version} org.springframework.boot spring-boot - ${spring-boot-version} + ${spring-boot.version} provided org.springframework spring-webmvc - ${spring-version} + ${spring.version} provided + + org.thymeleaf + thymeleaf-spring5 + 3.0.12.RELEASE + provided + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + true + + io.springfox springfox-spring-web diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index cfda374..a6e33c3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -5,6 +5,8 @@ import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginLauncher; +import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; +import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolvedFactory; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.MainApplicationContextProxy; @@ -13,6 +15,7 @@ import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; import com.gitee.starblues.spring.invoke.InvokeSupperCache; import org.springframework.context.support.GenericApplicationContext; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -25,9 +28,10 @@ public class PluginLauncherManager extends DefaultPluginManager{ private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); private final MainApplicationContext mainApplicationContext; + private final GenericApplicationContext mainGenericApplicationContext; private final IntegrationConfiguration configuration; private final InvokeSupperCache invokeSupperCache; - + private final PluginLaunchInvolved pluginLaunchInvolved; public PluginLauncherManager(RealizeProvider realizeProvider, GenericApplicationContext applicationContext, @@ -36,12 +40,20 @@ public class PluginLauncherManager extends DefaultPluginManager{ this.mainApplicationContext = new MainApplicationContextProxy( applicationContext.getBeanFactory(), applicationContext); + this.mainGenericApplicationContext = applicationContext; this.configuration = configuration; this.invokeSupperCache = new DefaultInvokeSupperCache(); + this.pluginLaunchInvolved = new PluginLaunchInvolvedFactory(); + setDisabledPluginIds(configuration.disablePluginIds()); setSortedPluginIds(configuration.sortInitPluginIds()); } + @Override + public synchronized List loadPlugins() { + this.pluginLaunchInvolved.initialize(mainGenericApplicationContext, configuration); + return super.loadPlugins(); + } @Override protected void start(PluginInsideInfo pluginInsideInfo) throws Exception { @@ -50,7 +62,7 @@ public class PluginLauncherManager extends DefaultPluginManager{ InsidePluginDescriptor pluginDescriptor = pluginInsideInfo.getPluginDescriptor(); PluginInteractive pluginInteractive = new DefaultPluginInteractive(pluginDescriptor, mainApplicationContext, configuration, invokeSupperCache); - PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive); + PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive, pluginLaunchInvolved); SpringPluginHook springPluginHook = pluginLauncher.run(); RegistryPluginInfo registryPluginInfo = new RegistryPluginInfo(pluginDescriptor, springPluginHook); pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), registryPluginInfo); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java index 2edc8f2..709b713 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java @@ -5,8 +5,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * 可缓存的 ResourceMatcher * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class CacheMainResourceMatcher extends DefaultMainResourceMatcher implements AutoCloseable { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java index 96f5a42..884295d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java @@ -16,8 +16,9 @@ import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; /** + * 基本的 ClassLoader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class GenericClassLoader extends URLClassLoader { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index d100ff6..8f2679c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -1,11 +1,7 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.utils.ResourceUtils; import org.apache.commons.io.IOUtils; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; import java.net.URL; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java index b7c10e9..60efb80 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java @@ -1,9 +1,7 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; @@ -11,8 +9,9 @@ import java.io.File; import java.util.Set; /** + * 插件资源加载者工厂 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginResourceLoaderFactory extends ResourceLoaderFactory{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java index 525f6d1..23c29d6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java @@ -6,6 +6,7 @@ package com.gitee.starblues.core.classloader; * @version 3.0.0 */ public class ProhibitMainResourceMatcher implements MainResourceMatcher{ + @Override public boolean match(String resourceUrl) { return false; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java deleted file mode 100644 index 4c59727..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractExecutableArchiveLauncher.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.gitee.starblues.core.launcher; - -/** - * @author starBlues - * @version 1.0 - */ -public abstract class AbstractExecutableArchiveLauncher { -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java index 62abe3a..3b49ec6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java @@ -4,8 +4,9 @@ package com.gitee.starblues.core.launcher; import com.gitee.starblues.core.launcher.jar.JarFile; /** + * 抽象的启动引导者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public abstract class AbstractLauncher implements Launcher { @@ -24,6 +25,11 @@ public abstract class AbstractLauncher implements Launcher { } } + /** + * 创建classloader + * @return ClassLoader + * @throws Exception 创建异常 + */ protected abstract ClassLoader createClassLoader() throws Exception; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java index 87b973c..94ef259 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java @@ -1,8 +1,9 @@ package com.gitee.starblues.core.launcher; /** + * 启动引导器 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface Launcher { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java index b4a5293..1f9085a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java @@ -1,8 +1,9 @@ package com.gitee.starblues.core.launcher; /** + * 主程序方法启动者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class MainMethodRunner extends MethodRunner{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java index 7c43592..26c4514 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java @@ -6,7 +6,6 @@ import com.gitee.starblues.utils.ObjectUtils; import java.lang.management.ManagementFactory; import java.net.URL; import java.net.URLClassLoader; -import java.util.Objects; /** * 主程序启动者 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java index cddb80d..24a560a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java @@ -7,8 +7,9 @@ import java.lang.reflect.Method; import java.util.StringJoiner; /** + * 反射运行方法 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class MethodRunner { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java index af93722..4aa74d5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java @@ -15,45 +15,46 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * 插件资源存储者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginResourceStorage { - public static Map pluginResourceStorage = new ConcurrentHashMap<>(); + public final static Map STORAGES = new ConcurrentHashMap<>(); public static void addPlugin(InsidePluginDescriptor descriptor){ - if(pluginResourceStorage.containsKey(descriptor.getPluginId())){ + if(STORAGES.containsKey(descriptor.getPluginId())){ return; } - pluginResourceStorage.put(descriptor.getPluginId(), new Storage(descriptor)); + STORAGES.put(descriptor.getPluginId(), new Storage(descriptor)); } public static void removePlugin(String pluginId){ - Storage storage = pluginResourceStorage.get(pluginId); + Storage storage = STORAGES.get(pluginId); if(storage == null){ return; } IOUtils.closeQuietly(storage); - pluginResourceStorage.remove(pluginId); + STORAGES.remove(pluginId); } public static void addJarFile(AbstractJarFile jarFile){ - pluginResourceStorage.forEach((k,v)->{ + STORAGES.forEach((k,v)->{ v.addJarFile(jarFile.getName(), jarFile); }); } public static void addRootJarFile(File file, JarFile jarFile){ - pluginResourceStorage.forEach((k,v)->{ + STORAGES.forEach((k,v)->{ v.addRootJarFile(file, jarFile); }); } public static JarFile getRootJarFile(File file){ - for (Storage value : pluginResourceStorage.values()) { + for (Storage value : STORAGES.values()) { JarFile jarFile = value.getRootJarFile(file); if(jarFile != null){ return jarFile; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java index 5d63a45..d4d2e79 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java @@ -1,14 +1,16 @@ package com.gitee.starblues.core.launcher; /** + * 主程序实现该接口引导启动SpringBoot * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface SpringBootstrap { - - String RUN_METHOD_NAME = "run"; - - + /** + * 启动 + * @param args 启动参数 + * @throws Exception 启动异常 + */ void run(String[] args) throws Exception; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java index d797b80..3d1bade 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java @@ -5,8 +5,9 @@ import com.gitee.starblues.utils.Assert; import java.util.concurrent.CountDownLatch; /** + * 主程序引导器 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class SpringMainBootstrap { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 01585be..6fd8ca0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -1,19 +1,17 @@ package com.gitee.starblues.core.launcher.plugin; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.AbstractLauncher; -import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; -import com.gitee.starblues.core.launcher.MainProgramLauncher; import com.gitee.starblues.core.launcher.PluginResourceStorage; +import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; +import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolvedFactory; import com.gitee.starblues.spring.SpringPluginHook; -import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.spring.web.PluginStaticResourceResolver; -import java.io.File; import java.nio.file.Paths; -import java.util.Set; +import java.util.Map; +import java.util.WeakHashMap; /** * 插件启动引导类 @@ -22,25 +20,41 @@ import java.util.Set; */ public class PluginLauncher extends AbstractLauncher { + private static final Map CLASS_LOADER_CACHE = new WeakHashMap<>(); + protected final PluginInteractive pluginInteractive; protected final InsidePluginDescriptor pluginDescriptor; protected final PluginMainResourcePatternDefiner mainResourcePatternDefiner; - public PluginLauncher(PluginInteractive pluginInteractive) { + protected final PluginLaunchInvolved pluginLaunchInvolved; + + public PluginLauncher(PluginInteractive pluginInteractive, + PluginLaunchInvolved pluginLaunchInvolved) { this.pluginInteractive = pluginInteractive; this.pluginDescriptor = pluginInteractive.getPluginDescriptor(); this.mainResourcePatternDefiner = new PluginMainResourcePatternDefiner(pluginDescriptor); + this.pluginLaunchInvolved = pluginLaunchInvolved; } @Override protected ClassLoader createClassLoader() throws Exception { + PluginClassLoader pluginClassLoader = getPluginClassLoader(); + //TODO 添加框架的引导 + pluginClassLoader.addResource(Paths.get("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-bootstrap\\target\\classes")); + pluginClassLoader.addResource(pluginDescriptor); + return pluginClassLoader; + } + + protected synchronized PluginClassLoader getPluginClassLoader(){ String pluginId = pluginDescriptor.getPluginId(); + PluginClassLoader classLoader = CLASS_LOADER_CACHE.get(pluginId); + if(classLoader != null){ + return classLoader; + } PluginClassLoader pluginClassLoader = new PluginClassLoader( pluginId, getParentClassLoader(), mainResourcePatternDefiner ); - //TODO 添加框架的引导 - pluginClassLoader.addResource(Paths.get("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-bootstrap\\target\\classes")); - pluginClassLoader.addResource(pluginDescriptor); + CLASS_LOADER_CACHE.put(pluginId, pluginClassLoader); return pluginClassLoader; } @@ -50,9 +64,10 @@ public class PluginLauncher extends AbstractLauncher { @Override protected SpringPluginHook launch(ClassLoader classLoader, String... args) throws Exception { - PluginResourceStorage.addPlugin(pluginDescriptor); + pluginLaunchInvolved.before(pluginDescriptor, classLoader); SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive).run(classLoader); - return new SpringPluginHookWrapper(springPluginHook, pluginDescriptor, classLoader); + pluginLaunchInvolved.after(pluginDescriptor, classLoader, springPluginHook); + return new SpringPluginHookWrapper(springPluginHook, pluginDescriptor, pluginLaunchInvolved, classLoader); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index e8f4174..6e88efe 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -4,6 +4,7 @@ import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; import com.gitee.starblues.utils.ObjectUtils; +import java.util.HashSet; import java.util.Set; /** @@ -16,6 +17,8 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef private static final String FRAMEWORK = "com/gitee/starblues/**"; private static final String SPRING_WEB = "org/springframework/web/**"; + public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; + private final InsidePluginDescriptor descriptor; public PluginMainResourcePatternDefiner(InsidePluginDescriptor descriptor) { @@ -27,6 +30,7 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef Set includeResourcePatterns = super.getIncludePatterns(); includeResourcePatterns.add(FRAMEWORK); includeResourcePatterns.add(SPRING_WEB); + includeResourcePatterns.add("org/springframework/ui/**"); // 配置插件自定义从主程序加载的资源匹配 Set includeMainResourcePatterns = descriptor.getIncludeMainResourcePatterns(); @@ -45,6 +49,12 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef @Override public Set getExcludePatterns() { - return descriptor.getExcludeMainResourcePatterns(); + Set excludeResourcePatterns = new HashSet<>(); + Set excludeMainResourcePatterns = descriptor.getExcludeMainResourcePatterns(); + if(!ObjectUtils.isEmpty(excludeMainResourcePatterns)){ + excludeResourcePatterns.addAll(excludeMainResourcePatterns); + } + excludeResourcePatterns.add(FACTORIES_RESOURCE_LOCATION); + return excludeResourcePatterns; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java index afcbcff..7e6cf83 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java @@ -1,43 +1,53 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.launcher.PluginResourceStorage; -import com.gitee.starblues.core.launcher.jar.Handler; +import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.spring.WebConfig; +import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; +import com.gitee.starblues.utils.ResourceUtils; /** + * SpringPluginHook-Wrapper * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class SpringPluginHookWrapper implements SpringPluginHook { private final SpringPluginHook target; private final InsidePluginDescriptor descriptor; + private final PluginLaunchInvolved pluginLaunchInvolved; private final ClassLoader classLoader; - public SpringPluginHookWrapper(SpringPluginHook target, - InsidePluginDescriptor descriptor, + public SpringPluginHookWrapper(SpringPluginHook target, InsidePluginDescriptor descriptor, + PluginLaunchInvolved pluginLaunchInvolved, ClassLoader classLoader) { this.target = target; this.descriptor = descriptor; + this.pluginLaunchInvolved = pluginLaunchInvolved; this.classLoader = classLoader; } - @Override public ApplicationContext getApplicationContext() { return target.getApplicationContext(); } + @Override + public WebConfig getWebConfig() { + return target.getWebConfig(); + } + + @Override + public ThymeleafConfig getThymeleafConfig() { + return null; + } + @Override public void close() throws Exception { - if(target != null){ - target.close(); - } - if(classLoader instanceof AutoCloseable){ - ((AutoCloseable)classLoader).close(); - } - PluginResourceStorage.removePlugin(descriptor.getPluginId()); + pluginLaunchInvolved.close(descriptor, classLoader); + ResourceUtils.closeQuietly(target); + ResourceUtils.closeQuietly(classLoader); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java new file mode 100644 index 0000000..743042e --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java @@ -0,0 +1,31 @@ +package com.gitee.starblues.core.launcher.plugin.involved; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.launcher.PluginResourceStorage; +import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.spring.web.PluginStaticResourceResolver; + +/** + * 默认的插件启动介入者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginLaunchInvolved implements PluginLaunchInvolved{ + + @Override + public void before(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { + PluginResourceStorage.addPlugin(descriptor); + } + + @Override + public void after(InsidePluginDescriptor descriptor, ClassLoader classLoader, SpringPluginHook pluginHook) throws Exception { + PluginStaticResourceResolver.parse(descriptor, classLoader, pluginHook.getWebConfig()); + } + + @Override + public void close(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { + String pluginId = descriptor.getPluginId(); + PluginResourceStorage.removePlugin(pluginId); + PluginStaticResourceResolver.remove(pluginId); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java new file mode 100644 index 0000000..ffa9f7a --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java @@ -0,0 +1,68 @@ +package com.gitee.starblues.core.launcher.plugin.involved; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.utils.OrderPriority; +import org.springframework.context.support.GenericApplicationContext; + +/** + * 插件启动前后介入 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginLaunchInvolved { + + /** + * 初始化。仅调用一次 + * @param applicationContext 主程序GenericApplicationContext + * @param configuration 集成配置 + */ + default void initialize(GenericApplicationContext applicationContext, IntegrationConfiguration configuration){} + + /** + * 启动之前 + * @param descriptor 插件信息 + * @param classLoader 插件classloader + * @throws Exception 执行异常 + */ + default void before(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception{} + + /** + * 启动之后 + * @param descriptor 插件信息 + * @param classLoader 插件classloader + * @param pluginHook 启动成功后插件返回的钩子 + * @throws Exception 执行异常 + */ + default void after(InsidePluginDescriptor descriptor, ClassLoader classLoader, + SpringPluginHook pluginHook) throws Exception{} + + /** + * 启动失败 + * @param descriptor 插件信息 + * @param classLoader 插件classloader + * @param throwable 异常信息 + * @throws Exception 执行异常 + */ + default void failure(InsidePluginDescriptor descriptor, ClassLoader classLoader, Throwable throwable) throws Exception{} + + /** + * 关闭的时候 + * @param descriptor 插件信息 + * @param classLoader 插件classloader + * @throws Exception 执行异常 + */ + default void close(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception{} + + /** + * 执行顺序 + * @return OrderPriority + */ + default OrderPriority order(){ + return OrderPriority.getMiddlePriority(); + } + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java new file mode 100644 index 0000000..3c8ff5c --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java @@ -0,0 +1,99 @@ +package com.gitee.starblues.core.launcher.plugin.involved; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.GenericApplicationContext; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * 插件启动介入工厂 + * @author starBlues + * @version 3.0.0 + */ +public class PluginLaunchInvolvedFactory implements PluginLaunchInvolved{ + + private static final Logger logger = LoggerFactory.getLogger(PluginLaunchInvolvedFactory.class); + + private List pluginLaunchInvolvedList; + + + @Override + public void initialize(GenericApplicationContext applicationContext, IntegrationConfiguration configuration) { + this.pluginLaunchInvolvedList = getPluginLaunchInvolvedList(applicationContext); + for (PluginLaunchInvolved pluginLaunchInvolved : pluginLaunchInvolvedList) { + try { + pluginLaunchInvolved.initialize(applicationContext, configuration); + } catch (Exception e){ + logger.error("[{}] execute initialize exception : {}", + pluginLaunchInvolved.getClass().getName(), e.getMessage(), e); + } + } + } + + protected List getPluginLaunchInvolvedList(GenericApplicationContext applicationContext){ + List pluginLaunchInvolvedList = getDefaultPluginLaunchInvolved(); + if(pluginLaunchInvolvedList == null){ + pluginLaunchInvolvedList = new ArrayList<>(); + } + Map pluginLaunchInvolvedMap = applicationContext.getBeansOfType(PluginLaunchInvolved.class); + if(!ObjectUtils.isEmpty(pluginLaunchInvolvedMap)){ + pluginLaunchInvolvedList.addAll(pluginLaunchInvolvedMap.values()); + } + pluginLaunchInvolvedList.sort(CommonUtils.orderPriority(PluginLaunchInvolved::order)); + return pluginLaunchInvolvedList; + } + + protected List getDefaultPluginLaunchInvolved(){ + List defaultPluginLaunchInvolved = new ArrayList<>(); + defaultPluginLaunchInvolved.add(new DefaultPluginLaunchInvolved()); + return defaultPluginLaunchInvolved; + } + + @Override + public void before(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { + for (PluginLaunchInvolved pluginLaunchInvolved : pluginLaunchInvolvedList) { + pluginLaunchInvolved.before(descriptor, classLoader); + } + } + + @Override + public void after(InsidePluginDescriptor descriptor, ClassLoader classLoader, SpringPluginHook pluginHook) throws Exception { + for (PluginLaunchInvolved pluginLaunchInvolved : pluginLaunchInvolvedList) { + pluginLaunchInvolved.after(descriptor, classLoader, pluginHook); + } + } + + @Override + public void failure(InsidePluginDescriptor descriptor, ClassLoader classLoader, Throwable throwable) throws Exception { + for (PluginLaunchInvolved pluginLaunchInvolved : pluginLaunchInvolvedList) { + try { + pluginLaunchInvolved.failure(descriptor, classLoader, throwable); + } catch (Exception e){ + logger.error("[{}] execute failure exception : {}", + pluginLaunchInvolved.getClass().getName(), e.getMessage(), e); + } + } + } + + @Override + public void close(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { + for (PluginLaunchInvolved pluginLaunchInvolved : pluginLaunchInvolvedList) { + try { + pluginLaunchInvolved.close(descriptor, classLoader); + } catch (Exception e){ + logger.error("[{}] execute close exception : {}", + pluginLaunchInvolved.getClass().getName(), e.getMessage(), e); + } + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index 12b9e46..7643b23 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; +import org.springframework.http.CacheControl; import java.util.ArrayList; import java.util.List; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index 50e6d63..66efc34 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -2,6 +2,7 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; +import org.springframework.http.CacheControl; import java.util.List; import java.util.Set; @@ -125,6 +126,7 @@ public interface IntegrationConfiguration { */ boolean enableWebSocket(); + /** * 停止插件时, 是否停止依赖的插件 * @return 停止返回true,不停止返回false diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java index a679b37..ee932c3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java @@ -10,9 +10,19 @@ import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; import com.gitee.starblues.spring.extract.ExtractFactory; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import com.gitee.starblues.spring.web.PluginStaticResourceConfig; +import com.gitee.starblues.spring.web.PluginStaticResourceResolver; +import com.gitee.starblues.spring.web.PluginStaticResourceWebMvcConfigurer; +import com.gitee.starblues.spring.web.thymeleaf.PluginThymeleafInvolved; +import org.springframework.boot.autoconfigure.condition.*; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.support.GenericApplicationContext; +import org.springframework.web.servlet.resource.ResourceResolver; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; /** * 集成扩展点 @@ -61,6 +71,31 @@ public class IntegrationExtendPoint { return new DefaultMainResourcePatternDefiner(configuration.mainPackage()); } + @Bean + @ConditionalOnClass(ResourceResolver.class) + @ConditionalOnWebApplication + @ConditionalOnMissingBean + public PluginStaticResourceWebMvcConfigurer pluginWebResourceResolver(PluginStaticResourceConfig resourceConfig){ + return new PluginStaticResourceWebMvcConfigurer(resourceConfig); + } + + @Bean + @ConditionalOnClass(ResourceResolver.class) + @ConditionalOnWebApplication + @ConditionalOnMissingBean + public PluginStaticResourceConfig pluginStaticResourceConfig(){ + return new PluginStaticResourceConfig(); + } + + @Bean + @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class }) + @ConditionalOnWebApplication + @ConditionalOnProperty(name = "spring.thymeleaf.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnMissingBean + public PluginThymeleafInvolved pluginThymeleafInvolved(){ + return new PluginThymeleafInvolved(); + } + @Bean public ExtractFactory extractFactory(){ return ExtractFactory.getInstant(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 6a354c1..337d3b9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -8,6 +8,7 @@ import com.gitee.starblues.integration.listener.PluginInitializerListenerFactory import com.gitee.starblues.integration.operator.upload.UploadByInputStreamParam; import com.gitee.starblues.integration.operator.upload.UploadByMultipartFileParam; import com.gitee.starblues.integration.operator.upload.UploadParam; +import com.gitee.starblues.spring.web.PluginStaticResourceConfig; import com.gitee.starblues.utils.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -40,6 +41,7 @@ public class DefaultPluginOperator implements PluginOperator { private final AtomicBoolean isInit = new AtomicBoolean(false); + private final GenericApplicationContext applicationContext; private final IntegrationConfiguration configuration; private final PluginManager pluginManager; @@ -48,6 +50,7 @@ public class DefaultPluginOperator implements PluginOperator { public DefaultPluginOperator(GenericApplicationContext applicationContext, RealizeProvider realizeProvider, IntegrationConfiguration configuration) { + this.applicationContext = applicationContext; this.configuration = configuration; this.pluginManager = new PluginLauncherManager(realizeProvider, applicationContext, configuration); this.pluginInitializerListenerFactory = new PluginInitializerListenerFactory(applicationContext); @@ -65,7 +68,7 @@ public class DefaultPluginOperator implements PluginOperator { if(pluginsRoots.isEmpty()){ return true; } - log.info("开始加载插件, 插件根路径为: \n{}", String.join("\n", pluginsRoots)); + initBeforeLogPrint(); // 触发插件初始化监听器 pluginInitializerListenerFactory.before(); if(!configuration.enable()){ @@ -108,6 +111,19 @@ public class DefaultPluginOperator implements PluginOperator { } } + /** + * 初始化之前日志打印 + */ + private void initBeforeLogPrint() { + List pluginsRoots = pluginManager.getPluginsRoots(); + log.info("开始加载插件, 插件根路径为: \n{}", String.join("\n", pluginsRoots)); + PluginStaticResourceConfig resourceConfig = SpringBeanUtils.getExistBean(applicationContext, + PluginStaticResourceConfig.class); + if(resourceConfig != null){ + resourceConfig.logPathPrefix(); + } + } + @Override public boolean verify(Path jarPath) throws PluginException { return pluginManager.verify(jarPath); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java index 741e6a8..bb727ef 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java @@ -1,8 +1,9 @@ package com.gitee.starblues.spring; /** + * 自定义ApplicationContext * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface ApplicationContext extends AutoCloseable { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java index 5381a46..2f3fb2a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java @@ -1,8 +1,9 @@ package com.gitee.starblues.spring; /** + * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ApplicationContextProxy extends GenericApplicationContext{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java index 2d5c3f8..0761121 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java @@ -7,8 +7,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * 可缓存的代理工厂 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class CacheJdkSameTypeParamProxyFactory extends JdkSameTypeParamProxyFactory{ @@ -36,9 +37,4 @@ public class CacheJdkSameTypeParamProxyFactory extends JdkSameTypeParamProxyFact return targetMethod.invoke(target, args); } - - - - - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java index 0b9c8ef..f40ea4f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java @@ -3,8 +3,9 @@ package com.gitee.starblues.spring; import com.gitee.starblues.utils.Assert; /** + * 基本的ApplicationContext * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class GenericApplicationContext implements ApplicationContext{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java index 04e737a..1c05f51 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java @@ -1,5 +1,8 @@ package com.gitee.starblues.spring; + +import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; + /** * 插件把柄接口 * @author starBlues @@ -13,4 +16,16 @@ public interface SpringPluginHook extends AutoCloseable{ */ ApplicationContext getApplicationContext(); + /** + * 得到插件中对 web 的配置 + * @return WebConfig + */ + WebConfig getWebConfig(); + + /** + * 获取插件中对 Thymeleaf 的配置 + * @return ThymeleafConfig + */ + ThymeleafConfig getThymeleafConfig(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java new file mode 100644 index 0000000..89a26f8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.spring; + +import java.util.Set; + +/** + * 插件中对web的配置 + * @author starBlues + * @version 3.0.0 + */ +public class WebConfig { + + private boolean enable = false; + private Set resourceLocations = null; + + public void setEnable(boolean enable) { + this.enable = enable; + } + + public boolean isEnable() { + return enable; + } + + public Set getResourceLocations() { + return resourceLocations; + } + + public void setResourceLocations(Set resourceLocations) { + this.resourceLocations = resourceLocations; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java new file mode 100644 index 0000000..6767fae --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java @@ -0,0 +1,168 @@ +package com.gitee.starblues.spring.web; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.NestedIOException; +import org.springframework.core.io.Resource; +import org.springframework.util.ClassUtils; +import org.springframework.util.ResourceUtils; +import org.springframework.util.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; + +/** + * 插件资源实现类.主要是对Spring中的抽象的Resource实现. + * 功能: 主要是获取插件包中的文件资源。 + * @author starBlues + * @version 3.0.0 + */ +public class PluginResource implements Resource { + + private final static Logger log = LoggerFactory.getLogger(PluginResource.class); + + private ClassLoader classLoader = ClassUtils.getDefaultClassLoader(); + private final PluginDescriptor pluginDescriptor; + + private final long lastModified; + private final String path; + + + /** + * 相对Classpath 路径 + * @param path 路径 + * @param pluginDescriptor pluginDescriptor + */ + public PluginResource(String path, PluginDescriptor pluginDescriptor) { + String pathToUse = StringUtils.cleanPath(path); + if (pathToUse.startsWith("/")) { + pathToUse = pathToUse.substring(1); + } + this.path = pathToUse; + this.pluginDescriptor = pluginDescriptor; + this.lastModified = System.currentTimeMillis(); + } + + public void setClassLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + @Override + public InputStream getInputStream() throws IOException { + return classLoader.getResourceAsStream(path); + } + + + @Override + public long contentLength() throws IOException { + URL url = getURL(); + if (ResourceUtils.isFileURL(url)) { + return getFile().length(); + } + if(ResourceUtils.isJarURL(url)){ + URLConnection con = getURL().openConnection(); + return con.getContentLength(); + } + return 0L; + } + + @Override + public long lastModified() throws IOException { + return lastModified; + } + + + @Override + public Resource createRelative(String relativePath) { + throw new RuntimeException("This method is not supported"); + } + + @Override + public String getFilename() { + return StringUtils.getFilename(this.path); + } + + @Override + public String getDescription() { + return pluginDescriptor.getDescription(); + } + + @Override + public boolean exists() { + try { + URL url = getURL(); + if(url == null){ + return false; + } + if (ResourceUtils.isFileURL(url)) { + return getFile().exists(); + } + if (contentLength() >= 0) { + return true; + } + InputStream is = getInputStream(); + is.close(); + return true; + } catch (Exception e){ + log.debug(e.getMessage(), e); + return false; + } + } + + @Override + public boolean isReadable() { + try { + URL url = getURL(); + if (ResourceUtils.isFileURL(url)) { + File file = getFile(); + return (file.canRead() && !file.isDirectory()); + } else { + return true; + } + } catch (Exception e) { + log.debug(e.getMessage(), e); + return false; + } + } + + @Override + public boolean isOpen() { + return false; + } + + + + @Override + public File getFile() throws IOException { + URL url = getURL(); + if (ResourceUtils.isJarURL(url)) { + URL actualUrl = ResourceUtils.extractArchiveURL(url); + return ResourceUtils.getFile(actualUrl, "Jar URL"); + } else { + return ResourceUtils.getFile(url, getDescription()); + } + } + + @Override + public URL getURL() throws IOException { + return classLoader.getResource(path); + } + + @Override + public URI getURI() throws IOException { + URL url = getURL(); + try { + return ResourceUtils.toURI(url); + } catch (URISyntaxException ex) { + throw new NestedIOException("Invalid URI [" + url + "]", ex); + } + } + +} + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java new file mode 100644 index 0000000..ff86eff --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java @@ -0,0 +1,43 @@ +package com.gitee.starblues.spring.web; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.CacheControl; + +/** + * 插件PluginStaticResourceConfig + * @author starBlues + * @version 3.0.0 + */ +public class PluginStaticResourceConfig { + + public static final String DEFAULT_PLUGIN_STATIC_RESOURCE_PATH_PREFIX = "static-plugin"; + private static final Logger log = LoggerFactory.getLogger(PluginStaticResourceConfig.class); + + private String pathPrefix = DEFAULT_PLUGIN_STATIC_RESOURCE_PATH_PREFIX; + private CacheControl cacheControl = CacheControl.noCache(); + + public PluginStaticResourceConfig(){ + + } + + public String getPathPrefix() { + return pathPrefix; + } + + public void setPathPrefix(String pathPrefix) { + this.pathPrefix = pathPrefix; + } + + public CacheControl getCacheControl() { + return cacheControl; + } + + public void setCacheControl(CacheControl cacheControl) { + this.cacheControl = cacheControl; + } + + public void logPathPrefix(){ + log.info("插件静态资源访问前缀配置为: /{}/{pluginId}", pathPrefix); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java new file mode 100644 index 0000000..8d344f4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java @@ -0,0 +1,349 @@ +package com.gitee.starblues.spring.web; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.spring.WebConfig; +import com.gitee.starblues.utils.MsgUtils; +import com.gitee.starblues.utils.ObjectUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.FileUrlResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.resource.AbstractResourceResolver; +import org.springframework.web.servlet.resource.ResourceResolverChain; + +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +/** + * 插件web静态资源Resolver + * @author starBlues + * @version 3.0.0 + */ +public class PluginStaticResourceResolver extends AbstractResourceResolver { + + private final static Logger logger = LoggerFactory.getLogger(PluginStaticResourceResolver.class); + + private final static String RESOLVED_RESOURCE_CACHE_KEY_PREFIX = "resolvedPluginResource:"; + + private final static Map PLUGIN_RESOURCE_MAP = new ConcurrentHashMap<>(); + + public PluginStaticResourceResolver() { + } + + + @Override + protected Resource resolveResourceInternal(HttpServletRequest request, + String requestPath, List locations, + ResourceResolverChain chain) { + + int startOffset = (requestPath.startsWith("/") ? 1 : 0); + int endOffset = requestPath.indexOf('/', 1); + if (endOffset != -1) { + String pluginId = requestPath.substring(startOffset, endOffset); + String partialPath = requestPath.substring(endOffset + 1); + PluginStaticResource pluginResource = PLUGIN_RESOURCE_MAP.get(pluginId); + + if(pluginResource == null){ + return null; + } + + String key = computeKey(request, requestPath); + // 先判断缓存中是否存在。 + Resource resource = pluginResource.getCacheResource(key); + if(resource != null){ + return resource; + } + + // 从classpath 获取资源 + resource = resolveClassPath(pluginResource, partialPath); + if(resource != null){ + pluginResource.putCacheResource(key, resource); + return resource; + } + + // 从外置文件路径获取资源 + resource = resolveFilePath(pluginResource, partialPath); + if(resource != null){ + pluginResource.putCacheResource(key, resource); + return resource; + } + return null; + + } + return chain.resolveResource(request, requestPath, locations); + } + + /** + * 解决 ClassPath 的资源文件。也就是插件中定义的 classpath:/xx/xx/ 配置 + * @param pluginResource 插件资源配置Bean + * @param partialPath 部分路径 + * @return 资源。没有发现则返回null + */ + private Resource resolveClassPath(PluginStaticResource pluginResource, String partialPath){ + Set classPaths = pluginResource.getClassPaths(); + if(classPaths == null || classPaths.isEmpty()){ + return null; + } + + ClassLoader pluginClassLoader = pluginResource.getPluginClassLoader(); + for (String classPath : classPaths) { + try { + PluginResource resource = new PluginResource(classPath + partialPath, pluginResource.getPluginDescriptor()); + resource.setClassLoader(pluginClassLoader); + if(resource.exists()){ + return resource; + } + } catch (Exception e){ + logger.debug("Get static resources of classpath '{}' error.", classPath, e); + } + } + return null; + } + + /** + * 解决插件中配置的绝对文件路径的文件资源。也就是插件中定义的 file:D://xx/xx/ 配置 + * @param pluginResource 插件资源配置Bean + * @param partialPath 部分路径 + * @return 资源。没有发现则返回null + */ + private Resource resolveFilePath(PluginStaticResource pluginResource, String partialPath) { + Set filePaths = pluginResource.getFilePaths(); + if(filePaths == null || filePaths.isEmpty()){ + return null; + } + + for (String filePath : filePaths) { + Path fullPath = Paths.get(filePath + partialPath); + if(!Files.exists(fullPath)){ + continue; + } + try { + FileUrlResource fileUrlResource = new FileUrlResource(fullPath.toString()); + if(fileUrlResource.exists()){ + return fileUrlResource; + } + } catch (Exception e) { + logger.debug("Get static resources of path '{}' error.", fullPath, e); + } + } + return null; + } + + + @Override + protected String resolveUrlPathInternal(String resourceUrlPath, + List locations, + ResourceResolverChain chain) { + return null; + } + + /** + * 计算key + * @param request request + * @param requestPath 请求路径 + * @return 返回key + */ + protected String computeKey(HttpServletRequest request, String requestPath) { + StringBuilder key = new StringBuilder(RESOLVED_RESOURCE_CACHE_KEY_PREFIX); + key.append(requestPath); + if (request != null) { + String codingKey = getContentCodingKey(request); + if (ObjectUtils.hasText(codingKey)) { + key.append("+encoding=").append(codingKey); + } + } + return key.toString(); + } + + /** + * 根据请求获取内容code key + * @param request request + * @return key + */ + private String getContentCodingKey(HttpServletRequest request) { + String header = request.getHeader(HttpHeaders.ACCEPT_ENCODING); + if (!ObjectUtils.hasText(header)) { + return null; + } + return Arrays.stream(StringUtils.tokenizeToStringArray(header, ",")) + .map(token -> { + int index = token.indexOf(';'); + return (index >= 0 ? token.substring(0, index) : token).trim().toLowerCase(); + }) + .sorted() + .collect(Collectors.joining(",")); + } + + + + /** + * 每新增一个插件, 都需要调用该方法,来解析该插件的 StaticResourceConfig 配置。并将其保存到 StaticResourceConfig bean 中。 + * @param pluginDescriptor 插件信息 + * @param webConfig web配置 + */ + public static synchronized void parse(PluginDescriptor pluginDescriptor, + ClassLoader pluginClassLoader, + WebConfig webConfig){ + if(!webConfig.isEnable()){ + return; + } + final Set locations = webConfig.getResourceLocations(); + if(ObjectUtils.isEmpty(locations)){ + return; + } + + Set classPaths = new HashSet<>(); + Set filePaths = new HashSet<>(); + + String pluginId = pluginDescriptor.getPluginId(); + + for (String location : locations) { + if(ObjectUtils.isEmpty(location)){ + continue; + } + final int first = location.indexOf(":"); + if(first == -1){ + logger.warn("插件[{}]配置的静态资源格式错误: {}", + MsgUtils.getPluginUnique(pluginDescriptor), location); + continue; + } + String type = location.substring(0, first); + String path = location.substring(first+1); + + if("classpath".equalsIgnoreCase(type)){ + if(path.startsWith("/")){ + path = path.substring(1); + } + if(!path.endsWith("/")){ + path = path + "/"; + } + classPaths.add(path); + } else if("file".equalsIgnoreCase(type)){ + if(!path.endsWith(File.separator)){ + path = path + File.separator; + } + filePaths.add(path); + } else { + logger.warn("插件[{}]配置的静态资源类型不能识别: {}", MsgUtils.getPluginUnique(pluginDescriptor), type); + } + } + + PluginStaticResource pluginResource = new PluginStaticResource(); + pluginResource.setClassPaths(classPaths); + pluginResource.setFilePaths(filePaths); + pluginResource.setPluginDescriptor(pluginDescriptor); + pluginResource.setPluginClassLoader(pluginClassLoader); + + logger.info("插件[{}]配置的静态资源: classpath[{}], file[{}]", MsgUtils.getPluginUnique(pluginDescriptor), + classPaths, filePaths); + + if(PLUGIN_RESOURCE_MAP.containsKey(pluginId)){ + // 如果存在该插件id的插件资源信息, 则先移除它 + remove(pluginId); + } + PLUGIN_RESOURCE_MAP.put(pluginId, pluginResource); + } + + + + /** + * 卸载插件时。调用该方法移除插件的资源信息 + * @param pluginId 插件id + */ + public static synchronized void remove(String pluginId){ + PluginStaticResource pluginResource = PLUGIN_RESOURCE_MAP.get(pluginId); + if(pluginResource == null){ + return; + } + PLUGIN_RESOURCE_MAP.remove(pluginId); + } + + + + /** + * 插件资源解析后的信息 + */ + private static class PluginStaticResource { + + /** + * basePlugin bean + */ + private PluginDescriptor pluginDescriptor; + + /** + * 插件classloader + */ + private ClassLoader pluginClassLoader; + + /** + * 定义的classpath集合 + */ + private Set classPaths; + + /** + * 定义的文件路径集合 + */ + private Set filePaths; + + /** + * 缓存的资源。key 为资源的可以。值为资源 + */ + private final Map cacheResourceMaps = new ConcurrentHashMap<>(); + + PluginDescriptor getPluginDescriptor() { + return pluginDescriptor; + } + + void setPluginDescriptor(PluginDescriptor pluginDescriptor) { + this.pluginDescriptor = pluginDescriptor; + } + + ClassLoader getPluginClassLoader() { + return pluginClassLoader; + } + + void setPluginClassLoader(ClassLoader pluginClassLoader) { + this.pluginClassLoader = pluginClassLoader; + } + + Set getClassPaths() { + return classPaths; + } + + void setClassPaths(Set classPaths) { + this.classPaths = classPaths; + } + + Set getFilePaths() { + return filePaths; + } + + void setFilePaths(Set filePaths) { + this.filePaths = filePaths; + } + + + Resource getCacheResource(String key){ + return cacheResourceMaps.get(key); + } + + void putCacheResource(String key, Resource resource){ + if(StringUtils.isEmpty(key) || resource == null){ + return; + } + cacheResourceMaps.put(key, resource); + } + } + +} + + + diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java new file mode 100644 index 0000000..9c797b8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java @@ -0,0 +1,38 @@ +package com.gitee.starblues.spring.web; + +import com.gitee.starblues.integration.IntegrationConfiguration; +import org.springframework.http.CacheControl; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * 插件静态资源webMvc配置 + * @author starBlues + * @version 3.0.0 + */ +public class PluginStaticResourceWebMvcConfigurer implements WebMvcConfigurer { + + private final PluginStaticResourceConfig resourceConfig; + + public PluginStaticResourceWebMvcConfigurer(PluginStaticResourceConfig resourceConfig) { + this.resourceConfig = resourceConfig; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + String pathPattern = "/" + resourceConfig.getPathPrefix() + "/**"; + ResourceHandlerRegistration resourceHandlerRegistration = registry.addResourceHandler(pathPattern); + CacheControl cacheControl = resourceConfig.getCacheControl(); + if(cacheControl != null){ + resourceHandlerRegistration.setCacheControl(cacheControl); + } else { + resourceHandlerRegistration.setCacheControl(CacheControl.noStore()); + } + resourceHandlerRegistration + .resourceChain(false) + .addResolver(new PluginStaticResourceResolver()); + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java new file mode 100644 index 0000000..f5adbc7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java @@ -0,0 +1,120 @@ +package com.gitee.starblues.spring.web.thymeleaf; + +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.spring.SpringPluginHook; +import com.gitee.starblues.utils.ClassUtils; +import com.gitee.starblues.utils.ObjectUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.GenericApplicationContext; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 插件 Thymeleaf 注册 + * @author starBlues + * @version 3.0.0 + */ +public class PluginThymeleafInvolved implements PluginLaunchInvolved { + + private static final Logger logger = LoggerFactory.getLogger(PluginThymeleafInvolved.class); + + private Set templateResolvers; + + private final Map pluginTemplateResolver = new ConcurrentHashMap<>(); + + @Override + public void initialize(GenericApplicationContext applicationContext, IntegrationConfiguration configuration) { + this.templateResolvers = getTemplateResolvers(getSpringTemplateEngine(applicationContext)); + } + + @Override + public void after(InsidePluginDescriptor descriptor, ClassLoader classLoader, SpringPluginHook pluginHook) throws Exception { + if(templateResolvers == null){ + return; + } + + ThymeleafConfig thymeleafConfig = pluginHook.getThymeleafConfig(); + if(thymeleafConfig == null || !thymeleafConfig.isEnabled()){ + return; + } + + String prefix = thymeleafConfig.getPrefix(); + if(ObjectUtils.isEmpty(prefix)){ + throw new IllegalArgumentException("prefix can't be empty"); + } else { + if(!prefix.endsWith("/")){ + thymeleafConfig.setPrefix(prefix + "/"); + } + } + if(ObjectUtils.isEmpty(thymeleafConfig.getSuffix())){ + throw new IllegalArgumentException("suffix can't be empty"); + } + + if(thymeleafConfig.getMode() == null){ + throw new IllegalArgumentException("mode can't be null"); + } + + ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(classLoader); + resolver.setPrefix(thymeleafConfig.getPrefix() + "/"); + resolver.setSuffix(thymeleafConfig.getSuffix()); + resolver.setTemplateMode(thymeleafConfig.getMode()); + + resolver.setCacheable(thymeleafConfig.getCache()); + if(thymeleafConfig.getEncoding() != null){ + resolver.setCharacterEncoding(thymeleafConfig.getEncoding().name()); + } + Integer order = thymeleafConfig.getTemplateResolverOrder(); + if(order != null){ + resolver.setOrder(order); + } + resolver.setCheckExistence(true); + templateResolvers.add(resolver); + if(!pluginTemplateResolver.containsKey(descriptor.getPluginId())){ + pluginTemplateResolver.put(descriptor.getPluginId(), resolver); + } + } + + @Override + public void close(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { + pluginTemplateResolver.remove(descriptor.getPluginId()); + } + + private SpringTemplateEngine getSpringTemplateEngine(GenericApplicationContext context){ + String[] beanNamesForType = context.getBeanNamesForType(SpringTemplateEngine.class, + false, false); + if(beanNamesForType.length == 0){ + return null; + } + try { + return context.getBean(SpringTemplateEngine.class); + } catch (Exception e){ + return null; + } + } + + private Set getTemplateResolvers(SpringTemplateEngine springTemplateEngine) { + String errorMsg = "当前插件不能使用Thymeleaf, 主程序未发现Thymeleaf注册入口"; + if(springTemplateEngine == null){ + logger.error(errorMsg); + } + try { + Set templateResolvers = ClassUtils.getReflectionField(springTemplateEngine, "templateResolvers"); + if(templateResolvers == null) { + logger.error(errorMsg); + } + return templateResolvers; + } catch (Exception e){ + logger.error("当前插件不能使用Thymeleaf, 获取主程序注册入口失败. {}", e.getMessage()); + return null; + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java new file mode 100644 index 0000000..3b2793f --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java @@ -0,0 +1,108 @@ +package com.gitee.starblues.spring.web.thymeleaf; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * 插件 Thymeleaf 配置 + * @author starBlues + * @version 3.0.0 + */ +public class ThymeleafConfig { + + public static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; + + public static final String DEFAULT_PREFIX = "templates/"; + + public static final String DEFAULT_SUFFIX = ".html"; + + private boolean enabled = true; + + /** + * 存放模板引擎的前缀 + */ + private String prefix = DEFAULT_PREFIX; + + /** + * 模板引擎文件的后缀 + */ + private String suffix = DEFAULT_SUFFIX; + + /** + * 模型引入的模型 + * HTML、XML、TEXT、JAVASCRIPT、CSS、RAW + */ + private String mode = "HTML"; + + /** + * 模板引擎的编码 + */ + private Charset encoding = DEFAULT_ENCODING; + + /** + * 是否启用模板引擎的缓存 + */ + private Boolean cache = true; + + /** + * 模板解析器的执行顺序, 数字越小越先执行 + */ + private Integer templateResolverOrder; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + public String getSuffix() { + return suffix; + } + + public void setSuffix(String suffix) { + this.suffix = suffix; + } + + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + + public Charset getEncoding() { + return encoding; + } + + public void setEncoding(String encoding) { + this.encoding = Charset.forName(encoding); + } + + public Boolean getCache() { + return cache; + } + + public void setCache(Boolean cache) { + this.cache = cache; + } + + public Integer getTemplateResolverOrder() { + return templateResolverOrder; + } + + public void setTemplateResolverOrder(Integer templateResolverOrder) { + this.templateResolverOrder = templateResolverOrder; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 11f09da..a50ce45 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -3,7 +3,9 @@ package com.gitee.starblues.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Closeable; import java.io.File; +import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; @@ -231,4 +233,22 @@ public class ResourceUtils { } } + public static void closeQuietly(Object closeable){ + closeQuietly(closeable, null); + } + + public static void closeQuietly(Object closeable, Consumer consumer){ + if (closeable != null) { + try { + if(closeable instanceof AutoCloseable){ + ((AutoCloseable) closeable).close(); + } + } catch (final Exception e) { + if (consumer != null) { + consumer.accept(e); + } + } + } + } + } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java index 675a976..293bcf9 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java +++ b/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -15,6 +15,7 @@ import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterExceptio import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import org.apache.maven.shared.artifact.filter.collection.FilterArtifacts; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -55,10 +56,20 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { if (!CommonUtils.isEmpty(includes)) { filters.addFilter(new IncludeFilter(this.includes)); } - if (!CommonUtils.isEmpty(excludes)) { - filters.addFilter(new ExcludeFilter(this.excludes)); + if(CommonUtils.isEmpty(excludes)){ + excludes = new ArrayList<>(); } + // 添加主框架排除 + addPluginFrameworkExclude(); + filters.addFilter(new ExcludeFilter(this.excludes)); return filters; } + private void addPluginFrameworkExclude(){ + final Exclude pluginFrameworkExclude = new Exclude(); + pluginFrameworkExclude.setGroupId("com.gitee.starblues"); + pluginFrameworkExclude.setArtifactId("springboot-plugin-framework"); + excludes.add(pluginFrameworkExclude); + } + } -- Gitee From 2233fec4130be78cf651daba06accc0d4d186f7d Mon Sep 17 00:00:00 2001 From: StarBlues Date: Tue, 25 Jan 2022 15:16:25 +0800 Subject: [PATCH 24/37] clear config --- pom.xml | 2 +- .../common/AbstractDependencyPlugin.java | 84 +++++ .../com/gitee/starblues/common/Constants.java | 23 ++ .../starblues/common/DependencyPlugin.java | 18 +- .../starblues/common/PackageStructure.java | 30 +- springboot-plugin-bootstrap/pom.xml | 37 ++- .../bootstrap/ConfigurePluginEnvironment.java | 3 +- .../bootstrap/DefaultSpringPluginHook.java | 30 +- .../EmptyMainApplicationContext.java | 3 +- .../bootstrap/EmptySpringBeanFactory.java | 3 +- .../bootstrap/PluginApplicationContext.java | 3 +- .../bootstrap/PluginListableBeanFactory.java | 3 +- .../bootstrap/PluginOneselfInteractive.java | 2 - .../bootstrap/PluginSpringApplication.java | 3 +- .../annotation/DisablePluginWeb.java | 5 +- .../ComposeSpringPluginProcessor.java | 4 +- .../processor/DefaultProcessorContext.java | 3 +- .../processor/FrameDefineBeanProcessor.java | 8 +- .../processor/InvokeOtherPluginProcessor.java | 3 +- .../bootstrap/processor/ProcessorContext.java | 2 - .../processor/ProcessorException.java | 3 +- .../PluginInterceptorRegister.java | 2 +- .../PluginInterceptorRegistration.java | 2 +- .../PluginInterceptorRegistry.java | 2 +- .../processor/invoke/InvokeBeanFactory.java | 3 +- .../processor/invoke/InvokeProxyHandler.java | 3 +- .../PluginClassPathBeanDefinitionScanner.java | 3 +- ...or.java => PluginControllerProcessor.java} | 5 +- .../web/PluginInterceptorsProcessor.java | 3 +- .../bootstrap/realize/StopValidator.java | 15 +- .../bootstrap/utils/AnnotationUtils.java | 1 + springboot-plugin-framework/pom.xml | 52 ++- .../gitee/starblues/annotation/Caller.java | 6 +- .../starblues/core/DefaultPluginChecker.java | 43 --- .../core/DefaultPluginInsideInfo.java | 11 + .../starblues/core/DefaultPluginManager.java | 159 +++++---- .../core/DefaultRealizeProvider.java | 27 +- .../gitee/starblues/core/PluginChecker.java | 28 +- .../com/gitee/starblues/core/PluginInfo.java | 6 + .../gitee/starblues/core/PluginInfoFace.java | 18 +- .../starblues/core/PluginInsideInfo.java | 7 +- .../starblues/core/PluginLauncherManager.java | 30 +- .../gitee/starblues/core/PluginManager.java | 18 +- .../gitee/starblues/core/RealizeProvider.java | 7 - .../core/checker/ComposePluginChecker.java | 64 ++++ .../core/checker/DefaultPluginChecker.java | 131 ++++++++ .../core/checker/DependencyPluginChecker.java | 104 ++++++ .../DefaultMainResourcePatternDefiner.java | 84 ----- .../classloader/NestedJarResourceLoader.java | 5 +- .../RepeatResourceLoaderFactory.java | 11 - .../AbstractPluginDescriptorLoader.java | 10 +- .../descriptor/DefaultDependencyPlugin.java | 50 +++ .../descriptor/DefaultPluginDescriptor.java | 28 +- .../descriptor/EmptyPluginDescriptor.java | 4 +- .../descriptor/InsidePluginDescriptor.java | 3 +- .../core/descriptor/PluginDescriptor.java | 6 +- .../descriptor/PluginDescriptorLoader.java | 2 +- .../ProdPluginDescriptorLoader.java | 2 +- .../exception/PluginDisabledException.java | 16 +- .../core/{ => exception}/PluginException.java | 2 +- .../PluginProhibitStopException.java | 16 + .../BasicMainResourcePatternDefiner.java | 33 ++ .../core/launcher/plugin/PluginLauncher.java | 2 +- .../PluginMainResourcePatternDefiner.java | 61 +++- .../plugin/SpringPluginHookWrapper.java | 6 + .../gitee/starblues/core/package-info.java | 5 - .../extension/AbstractExtension.java | 103 ------ .../starblues/extension/ExtensionFactory.java | 61 ---- .../extension/ExtensionInitializer.java | 161 --------- .../PluginControllerProcessorExtend.java | 36 -- .../AutoIntegrationConfiguration.java | 145 ++------- .../integration/ConfigurationBuilder.java | 307 ------------------ .../DefaultIntegrationConfiguration.java | 24 +- ...int.java => ExtendPointConfiguration.java} | 54 +-- .../ExtendPointWebConfiguration.java | 61 ++++ .../integration/IntegrationConfiguration.java | 62 ++-- .../AbstractPluginApplication.java | 22 -- .../application/AutoPluginApplication.java | 5 +- .../application/DefaultPluginApplication.java | 4 +- .../application/EmptyPluginApplication.java | 49 --- .../application/PluginApplication.java | 2 +- .../integration/application/package-info.java | 7 - .../listener/DefaultInitializerListener.java | 11 +- .../DefaultPluginListenerFactory.java | 119 +++++++ .../integration/listener/PluginListener.java | 58 +++- .../listener/PluginListenerFactory.java | 129 +------- ...ningListener.java => SwaggerListener.java} | 29 +- .../manager/DefaultPluginManagerFactory.java | 34 -- .../manager/PluginManagerFactory.java | 19 -- .../operator/DefaultPluginOperator.java | 5 + .../operator/EmptyPluginOperator.java | 4 +- .../integration/operator/PluginOperator.java | 15 +- .../operator/PluginOperatorWrapper.java | 41 +-- .../AbstractPluginSpringBeanRefresh.java | 32 -- .../refresh/AbstractSpringBeanRefresh.java | 78 ----- .../gitee/starblues/realize/ConfigBean.java | 26 -- .../realize/ConfigDefinitionTip.java | 137 -------- .../gitee/starblues/realize/PluginUtils.java | 97 ------ .../starblues/spring/SpringPluginHook.java | 7 + .../com/gitee/starblues/utils/MsgUtils.java | 7 + .../gitee/starblues/utils/ResourceUtils.java | 10 +- .../spring-configuration-metadata.json | 71 +--- .../pom.xml | 2 +- .../pack/AbstractDependencyFilterMojo.java | 17 +- .../plugin/pack/AbstractPackagerMojo.java | 15 +- .../plugin/pack/BasicRepackager.java | 17 +- .../gitee/starblues/plugin/pack/Constant.java | 9 +- .../plugin/pack/DependencyPlugin.java | 55 ++++ .../plugin/pack/LoadMainResourcePattern.java | 0 .../starblues/plugin/pack/PluginInfo.java | 24 +- .../starblues/plugin/pack/RepackageMojo.java | 1 - .../starblues/plugin/pack/Repackager.java | 0 .../starblues/plugin/pack/dev/Dependency.java | 0 .../starblues/plugin/pack/dev/DevConfig.java | 0 .../plugin/pack/dev/DevRepackager.java | 0 .../plugin/pack/filter/DependencyFilter.java | 0 .../starblues/plugin/pack/filter/Exclude.java | 12 +- .../plugin/pack/filter/ExcludeFilter.java | 0 .../pack/filter/FilterableDependency.java | 0 .../starblues/plugin/pack/filter/Include.java | 0 .../plugin/pack/filter/IncludeFilter.java | 0 .../plugin/pack/prod/DirPackageGenerator.java | 0 .../plugin/pack/prod/JarPackageGenerator.java | 0 .../starblues/plugin/pack/prod/JarWriter.java | 0 .../plugin/pack/prod/PackageGenerator.java | 0 .../plugin/pack/prod/ProdConfig.java | 0 .../plugin/pack/prod/ProdRepackager.java | 0 .../plugin/pack/prod/ZipProdRepackager.java | 3 +- .../plugin/pack/utils/CommonUtils.java | 0 .../main/resources/META-INF/maven/plugin.xml | 4 +- 130 files changed, 1503 insertions(+), 2056 deletions(-) create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java => spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java (39%) rename springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/{PluginControllerRegistryProcessor.java => PluginControllerProcessor.java} (98%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/UnRegistryValidator.java => springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java (67%) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{ => exception}/PluginException.java (97%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/{IntegrationExtendPoint.java => ExtendPointConfiguration.java} (55%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/package-info.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/{SwaggerListeningListener.java => SwaggerListener.java} (69%) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractPluginSpringBeanRefresh.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractSpringBeanRefresh.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigBean.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/pom.xml (98%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java (78%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java (80%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java (94%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/Constant.java (67%) create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java (67%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java (99%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java (33%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java (99%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java (100%) rename {springboot-plugin-maven-pack => springboot-plugin-maven-packager}/src/main/resources/META-INF/maven/plugin.xml (98%) diff --git a/pom.xml b/pom.xml index 2141dd2..94ab37e 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ springboot-plugin-bootstrap springboot-plugin-framework-example - springboot-plugin-maven-pack + springboot-plugin-maven-packager diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java new file mode 100644 index 0000000..1c65089 --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java @@ -0,0 +1,84 @@ +package com.gitee.starblues.common; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +/** + * 依赖的插件 + * @author starBlues + * @version 3.0.0 + */ +public abstract class AbstractDependencyPlugin implements DependencyPlugin{ + + public static final String SPLIT_ALL = ","; + public static final String SPLIT_ONE = "@"; + + + /** + * set依赖插件id + * @param id 插件id + */ + public abstract void setId(String id); + + /** + * set依赖插件版本 + * @param version 插件版本 + */ + public abstract void setVersion(String version); + + /** + * set optional + * @param optional 是否可选 + */ + public abstract void setOptional(Boolean optional); + + + public static String toStr(List dependencyPlugins){ + if(dependencyPlugins == null || dependencyPlugins.isEmpty()){ + return null; + } + StringBuilder stringBuilder = new StringBuilder(); + final int size = dependencyPlugins.size(); + for (int i = 0; i < size; i++) { + AbstractDependencyPlugin dependencyPlugin = dependencyPlugins.get(i); + Boolean optional = dependencyPlugin.getOptional(); + if(optional == null){ + optional = false; + } + stringBuilder.append(dependencyPlugin.getId()) + .append(SPLIT_ONE).append(dependencyPlugin.getVersion()) + .append(SPLIT_ONE).append(optional); + if(i <= size - 2){ + stringBuilder.append(SPLIT_ALL); + } + } + return stringBuilder.toString(); + } + + + public static List toList(String str, Supplier supplier){ + String[] all = str.split(SPLIT_ALL); + if(all.length == 0){ + return Collections.emptyList(); + } + List list = new ArrayList<>(all.length); + for (String s : all) { + String[] one = s.split(SPLIT_ONE); + if(one.length == 0){ + continue; + } + if(one.length != 3){ + continue; + } + AbstractDependencyPlugin dependencyPlugin = supplier.get(); + dependencyPlugin.setId(one[0]); + dependencyPlugin.setVersion(one[1]); + dependencyPlugin.setOptional("true".equalsIgnoreCase(one[2])); + list.add(dependencyPlugin); + } + return list; + } + +} diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java new file mode 100644 index 0000000..dc4dc7a --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java @@ -0,0 +1,23 @@ +package com.gitee.starblues.common; + +/** + * 静态常量 + * @author starBlues + * @version 3.0.0 + */ +public abstract class Constants { + + private Constants(){} + + + /** + * 禁用所有插件标志 + */ + public final static String DISABLED_ALL_PLUGIN = "*"; + + /** + * 允许所有版本的标志 + */ + public final static String ALLOW_VERSION = "0.0.0"; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java similarity index 39% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java index 2860cc8..e269863 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDependency.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java @@ -1,30 +1,28 @@ -package com.gitee.starblues.core.descriptor; +package com.gitee.starblues.common; /** - * 插件依赖信息 + * 依赖的插件 * @author starBlues * @version 3.0.0 */ -public interface PluginDependency { - +public interface DependencyPlugin { /** * 依赖插件id * @return String */ - String getDependencyId(); + String getId(); /** - * 依赖插件版本 + * 依赖插件版本. 如果设置为: 0.0.0 表示支持任意版本依赖 * @return String */ - String getDependencyVersion(); + String getVersion(); /** - * 是否必须的 + * 是否为必须依赖. 默认: false * @return boolean */ - boolean optional(); - + Boolean getOptional(); } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java index 62b4cd1..34365ba 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java @@ -2,6 +2,8 @@ package com.gitee.starblues.common; import java.io.File; +import java.util.HashSet; +import java.util.Set; import java.util.regex.Matcher; /** @@ -13,6 +15,11 @@ public abstract class PackageStructure { private PackageStructure(){} + public static final String[] ILLEGAL_FORMAT = new String[]{ + AbstractDependencyPlugin.SPLIT_ALL, AbstractDependencyPlugin.SPLIT_ONE + }; + + public static final String CHARSET_NAME = "utf-8"; public static final String SEPARATOR = "/"; @@ -49,20 +56,13 @@ public abstract class PackageStructure { return path; } - -// public final static String PROD_LIB_DIR = LIB_NAME + SEPARATOR; -// -// public final static String PROD_CLASSES_DIR = CLASSES_NAME + SEPARATOR; - - -// public static final String PROD_META_INF_PATH = META_INF_NAME + SEPARATOR; -// -// public static final String DEV_MANIFEST_PATH = META_INF_NAME + SEPARATOR + MANIFEST; -// -// public static final String PROD_MANIFEST_PATH = PROD_META_INF_PATH + MANIFEST; - - - -// public static final String PROD_LIB_INDEX_PATH = PROD_META_INF_PATH + LIB_INDEX_NAME; + public static String getIllegal(String str){ + for (String s : ILLEGAL_FORMAT) { + if(str.contains(s)){ + return s; + } + } + return null; + } } diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index c3b3096..c547097 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -19,8 +19,9 @@ 3.0.0-RELEASE + 1.9.6 1.7.7 - 2.5.0 + 2.5.6 5.3.2 4.0.1 2.11.3 @@ -28,11 +29,30 @@ + + org.aspectj + aspectjweaver + ${aspectj.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + com.gitee.starblues springboot-plugin-framework - 3.0.0-RELEASE + ${springboot-plugin-framework} provided + true @@ -40,6 +60,7 @@ spring-boot ${spring-boot.version} provided + true @@ -47,6 +68,7 @@ spring-webmvc ${spring.version} provided + true @@ -57,17 +79,6 @@ true - - org.slf4j - slf4j-api - ${slf4j.version} - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 89a15a7..90ec086 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -11,8 +11,9 @@ import java.util.HashMap; import java.util.Map; /** + * 插件环境配置 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ class ConfigurePluginEnvironment { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java index 8f5ec6e..1b5e534 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -3,7 +3,10 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; +import com.gitee.starblues.bootstrap.realize.StopValidator; import com.gitee.starblues.bootstrap.utils.DestroyUtils; +import com.gitee.starblues.bootstrap.utils.SpringBeanUtils; +import com.gitee.starblues.core.exception.PluginProhibitStopException; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.ApplicationContextProxy; import com.gitee.starblues.spring.SpringPluginHook; @@ -15,20 +18,45 @@ import org.springframework.core.io.support.SpringFactoriesLoader; import java.util.Map; /** + * 默认的插件钩子器 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DefaultSpringPluginHook implements SpringPluginHook { private final SpringPluginProcessor pluginProcessor; private final ProcessorContext processorContext; + private final StopValidator stopValidator; public DefaultSpringPluginHook(SpringPluginProcessor pluginProcessor, ProcessorContext processorContext) { this.pluginProcessor = pluginProcessor; this.processorContext = processorContext; + this.stopValidator = SpringBeanUtils.getExistBean(processorContext.getApplicationContext(), + StopValidator.class); } + /** + * 先校验是否可卸载 + */ + @Override + public void stopVerify() { + if(stopValidator == null){ + return; + } + try { + StopValidator.Result result = stopValidator.verify(); + if(result != null && !result.isVerify()){ + throw new PluginProhibitStopException(processorContext.getPluginDescriptor(), + result.getMessage()); + } + } catch (Exception e){ + throw new PluginProhibitStopException(processorContext.getPluginDescriptor(), + e.getMessage()); + } + } + + @Override public void close() throws Exception{ try { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java index 00cbb67..3ce3828 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java @@ -12,8 +12,9 @@ import java.util.Map; import java.util.Set; /** + * 空的MainApplicationContext实现 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class EmptyMainApplicationContext implements MainApplicationContext { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java index 401adf3..e79ec6d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java @@ -10,8 +10,9 @@ import java.lang.annotation.Annotation; import java.util.Map; /** + * 空的 SpringBeanFactory 实现 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class EmptySpringBeanFactory implements SpringBeanFactory { @Override diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java index 08c76c6..bb6de9a 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java @@ -8,8 +8,9 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.core.io.ResourceLoader; /** + * 插件ApplicationContext实现 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginApplicationContext extends AnnotationConfigApplicationContext { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java index 9ec2c5e..a90d85c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -17,8 +17,9 @@ import org.springframework.lang.Nullable; import java.util.Set; /** + * 插件BeanFactory实现 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginListableBeanFactory extends DefaultListableBeanFactory { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index d856382..a53dd53 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -59,8 +59,6 @@ public class PluginOneselfInteractive implements PluginInteractive { return opExtractFactory; } - - private InsidePluginDescriptor createPluginDescriptor(){ InsidePluginDescriptor pluginDescriptor; try (PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader()){ diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java index 2f7c5a8..3830f19 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -15,8 +15,9 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ResourceLoader; /** + * 插件SpringApplication实现 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginSpringApplication extends SpringApplication { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java index b923eeb..72e8143 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java @@ -3,9 +3,10 @@ package com.gitee.starblues.bootstrap.annotation; import java.lang.annotation.*; /** - * 禁用web环境. 如果该注解加入到入口类上, 表示 + * 禁用web环境. 如果该注解加入到入口类上, 表示当前插件禁用web的功能。 + * 包括:controller注册、拦截器注册、web静态资源访问、thymeleaf模板引擎 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index d3daeeb..456a369 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -2,7 +2,7 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; import com.gitee.starblues.bootstrap.annotation.DisablePluginWeb; -import com.gitee.starblues.bootstrap.processor.web.PluginControllerRegistryProcessor; +import com.gitee.starblues.bootstrap.processor.web.PluginControllerProcessor; import com.gitee.starblues.bootstrap.processor.web.PluginInterceptorsProcessor; import com.gitee.starblues.bootstrap.processor.web.PluginStaticResourceProcessor; import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; @@ -149,7 +149,7 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { return; } context.getWebConfig().setEnable(true); - processors.add(new PluginControllerRegistryProcessor()); + processors.add(new PluginControllerProcessor()); processors.add(new PluginInterceptorsProcessor()); processors.add(new PluginStaticResourceProcessor()); processors.add(new PluginThymeleafProcessor()); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 5f0db4c..4963f24 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -15,8 +15,9 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.util.ClassUtils; /** + * 默认的处理者上下文 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DefaultProcessorContext extends CacheRegistryInfo implements ProcessorContext{ diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java index 9541deb..7f4afbf 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java @@ -1,22 +1,24 @@ package com.gitee.starblues.bootstrap.processor; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; /** + * 框架内置bean注册 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class FrameDefineBeanProcessor implements SpringPluginProcessor { @Override public void refreshBefore(ProcessorContext context) throws ProcessorException { ConfigurableApplicationContext applicationContext = context.getApplicationContext(); - PluginDescriptor pluginDescriptor = context.getPluginDescriptor(); + InsidePluginDescriptor pluginDescriptor = context.getPluginDescriptor(); ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - beanFactory.registerSingleton("pluginDescriptor", pluginDescriptor); + beanFactory.registerSingleton("pluginDescriptor", pluginDescriptor.toPluginDescriptor()); } @Override diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java index fe64bac..91a77dc 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java @@ -22,8 +22,9 @@ import java.util.Map; import java.util.Set; /** + * 反射调用其他插件的处理者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class InvokeOtherPluginProcessor implements SpringPluginProcessor { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index ccb2966..527ec33 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -3,14 +3,12 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.core.launcher.plugin.RegistryInfo; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringBeanFactory; import com.gitee.starblues.spring.WebConfig; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ResourceLoader; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java index 7ccb83f..a2a78a6 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java @@ -1,8 +1,9 @@ package com.gitee.starblues.bootstrap.processor; /** + * 处理者异常 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ProcessorException extends RuntimeException{ diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java index b997b9d..dc0304b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java @@ -3,7 +3,7 @@ package com.gitee.starblues.bootstrap.processor.interceptor; /** * 插件拦截器注册者 * @author starBlues - * @version 2.4.1 + * @version 3.0.0 */ public interface PluginInterceptorRegister { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java index 4610c2f..7f706ba 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java @@ -15,7 +15,7 @@ import java.util.List; /** * 插件拦截器注册的信息 * @author starBlues - * @version 2.4.1 + * @version 3.0.0 */ public class PluginInterceptorRegistration { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java index c33e081..9a5f45b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java @@ -15,7 +15,7 @@ import java.util.stream.Collectors; /** * 插件拦截器添加者 * @author starBlues - * @version 2.4.1 + * @version 3.0.0 */ public class PluginInterceptorRegistry { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java index 3c61711..0e092eb 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java @@ -7,8 +7,9 @@ import org.springframework.beans.factory.FactoryBean; import java.lang.reflect.Proxy; /** + * 反射调用其他插件定义的接口bean工厂 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class InvokeBeanFactory implements FactoryBean { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java index 7dcd0bf..acfa514 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java @@ -11,8 +11,9 @@ import java.lang.reflect.Method; import java.util.Objects; /** + * 反射调用处理模块 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class InvokeProxyHandler implements InvocationHandler { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java index cb5fd0c..050b4ce 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java @@ -5,8 +5,9 @@ import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; /** + * 插件自定义 classpath bean 扫描 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerRegistryProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java similarity index 98% rename from springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerRegistryProcessor.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java index 9c1de3e..35bcaf9 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerRegistryProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java @@ -25,12 +25,13 @@ import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; /** + * 插件Controller处理者 * @author starBlues * @version 3.0.0 */ -public class PluginControllerRegistryProcessor implements SpringPluginProcessor { +public class PluginControllerProcessor implements SpringPluginProcessor { - private final static Logger LOG = LoggerFactory.getLogger(PluginControllerRegistryProcessor.class); + private final static Logger LOG = LoggerFactory.getLogger(PluginControllerProcessor.class); private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java index 26b4cab..6113e92 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java @@ -22,8 +22,9 @@ import java.util.ArrayList; import java.util.List; /** + * 插件拦截器处理者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginInterceptorsProcessor implements SpringPluginProcessor { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/UnRegistryValidator.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java similarity index 67% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/UnRegistryValidator.java rename to springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java index af17b2c..8ca4499 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/UnRegistryValidator.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java @@ -1,26 +1,25 @@ -package com.gitee.starblues.realize; +package com.gitee.starblues.bootstrap.realize; /** - * 卸载校验器 + * 插件停止校验器. 自主实现判断是否可卸载 * @author starBlues - * @version 2.4.0 + * @version 3.0.0 */ -public interface UnRegistryValidator { +public interface StopValidator { /** - * 校验是否可卸载 + * 校验是否可卸载。如果校验器抛出异常. 默认插件不可停止 * @return 校验结果 - * @throws Exception 校验异常. 校验异常后, 该插件默认不可卸载 */ - Result verify() throws Exception; + Result verify(); class Result{ /** * 是否可卸载 */ - private boolean verify; + private final boolean verify; /** * 不可卸载时的提示内容 diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java index 03a89bb..dbf5588 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java @@ -5,6 +5,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** + * 注解工具类 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index 9d4f4d8..f00201f 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -68,8 +68,8 @@ 1.7.7 2.11.0 - 5.0.7.RELEASE - 2.4.1 + 5.3.12 + 2.5.6 2.10.5 1.5.2 4.0.1 @@ -78,11 +78,6 @@ - - com.gitee.starblues - spring-plugin-framework-common - ${project.version} - org.slf4j @@ -96,11 +91,24 @@ ${commons-io.version} + + com.github.zafarkhaja + java-semver + ${java-semver.version} + + + + com.gitee.starblues + spring-plugin-framework-common + ${project.version} + + org.springframework.boot spring-boot ${spring-boot.version} provided + true @@ -108,6 +116,7 @@ spring-webmvc ${spring.version} provided + true @@ -115,6 +124,7 @@ thymeleaf-spring5 3.0.12.RELEASE provided + true @@ -130,6 +140,7 @@ springfox-spring-web ${swagger-spring-web.version} provided + true @@ -137,12 +148,7 @@ springdoc-openapi-ui ${springdoc.version} provided - - - - com.github.zafarkhaja - java-semver - ${java-semver.version} + true @@ -167,6 +173,26 @@ + + org.apache.maven.plugins + maven-shade-plugin + + + + com.gitee.starblues:spring-plugin-framework-common + + + + + + package + + shade + + + + + org.apache.maven.plugins maven-assembly-plugin diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java index 6fed31b..73bb1f7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java @@ -1,14 +1,14 @@ package com.gitee.starblues.annotation; + +import java.lang.annotation.*; + /** * 调用者的注解。配合 @Supplier 注解使用, 两者结合实现插件中的方法调用。 * * @author starBlues * @version 2.4.0 */ - -import java.lang.annotation.*; - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java deleted file mode 100644 index 637d630..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginChecker.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gitee.starblues.core; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.utils.Assert; - -import java.io.FileNotFoundException; -import java.nio.file.Files; -import java.nio.file.Path; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class DefaultPluginChecker implements PluginChecker{ - - - @Override - public void check(Path path) throws Exception { - if(path == null){ - throw new FileNotFoundException("path 文件路径不能为空"); - } - if(Files.notExists(path)){ - throw new FileNotFoundException("不存在文件: " + path.toString()); - } - } - - @Override - public void check(PluginDescriptor descriptor) throws Exception { - Assert.isNotNull(descriptor, "PluginDescriptor 不能为空"); - - Assert.isNotEmpty(descriptor.getPluginPath(), - "插件路径[pluginDescriptor->getPluginPath] 不能为空"); - - Assert.isNotNull(descriptor.getPluginId(), - "插件id[pluginDescriptor->getPluginId] 不能为空"); - - Assert.isNotNull(descriptor.getPluginBootstrapClass(), - "插件id[pluginDescriptor->getPluginBootstrapClass] 不能为空"); - - Assert.isNotNull(descriptor.getPluginVersion(), - "插件id[pluginDescriptor->getPluginVersion] 不能为空"); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java index df0a622..0a00166 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java @@ -12,6 +12,7 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { private final String pluginId; private final InsidePluginDescriptor pluginDescriptor; private PluginState pluginState; + private boolean isFollowInitial = false; public DefaultPluginInsideInfo(InsidePluginDescriptor pluginDescriptor) { this.pluginId = pluginDescriptor.getPluginId(); @@ -23,6 +24,11 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { this.pluginState = pluginState; } + @Override + public void setFollowSystem() { + isFollowInitial = true; + } + @Override public String getPluginId() { return pluginId; @@ -48,5 +54,10 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { return pluginState; } + @Override + public boolean isFollowSystem() { + return isFollowInitial; + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 9e50dda..c9bb6d4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -1,21 +1,26 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.checker.ComposePluginChecker; +import com.gitee.starblues.core.checker.DefaultPluginChecker; +import com.gitee.starblues.core.checker.DependencyPluginChecker; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.exception.PluginDisabledException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.scanner.ComposePathResolve; import com.gitee.starblues.core.scanner.DevPathResolve; import com.gitee.starblues.core.scanner.PathResolve; import com.gitee.starblues.core.scanner.ProdPathResolve; -import com.gitee.starblues.integration.operator.PluginOperator; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.integration.listener.DefaultPluginListenerFactory; +import com.gitee.starblues.integration.listener.PluginListenerFactory; import com.gitee.starblues.utils.*; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @@ -33,36 +38,36 @@ public class DefaultPluginManager implements PluginManager{ private final Logger log = LoggerFactory.getLogger(this.getClass()); private final RealizeProvider provider; + private final IntegrationConfiguration configuration; private final List pluginRootDirs; private final PathResolve pathResolve; + protected final ComposePluginChecker pluginChecker; private final AtomicBoolean loaded = new AtomicBoolean(false); private final Map startedPlugins = new ConcurrentHashMap<>(); private final Map resolvedPlugins = new ConcurrentHashMap<>(); - private Set disabledPluginIds; - private List sortedPluginIds; + protected PluginListenerFactory pluginListenerFactory; - public DefaultPluginManager(RealizeProvider realizeProvider, String ...pluginRootDirs) { - this(realizeProvider, pluginRootDirs == null ? null : Arrays.asList(pluginRootDirs)); - } + private List sortedPluginIds; - public DefaultPluginManager(RealizeProvider realizeProvider, List pluginRootDirs) { - this.provider = Assert.isNotNull(realizeProvider, - "参数 realizeProvider 不能为空"); - if(pluginRootDirs == null){ - this.pluginRootDirs = Collections.emptyList(); - } else { - this.pluginRootDirs = pluginRootDirs; - } + public DefaultPluginManager(RealizeProvider realizeProvider, IntegrationConfiguration configuration) { + this.provider = Assert.isNotNull(realizeProvider, "参数 realizeProvider 不能为空"); + this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); + this.pluginRootDirs = configuration.pluginPath(); this.pathResolve = new ComposePathResolve(new DevPathResolve(), new ProdPathResolve()); + this.pluginChecker = getComposePluginChecker(realizeProvider); + setSortedPluginIds(configuration.sortInitPluginIds()); } - public void setDisabledPluginIds(Set disabledPluginIds) { - this.disabledPluginIds = disabledPluginIds; + protected ComposePluginChecker getComposePluginChecker(RealizeProvider realizeProvider){ + ComposePluginChecker checker = new ComposePluginChecker(); + checker.add(new DefaultPluginChecker(realizeProvider, configuration)); + checker.add(new DependencyPluginChecker(this)); + return checker; } public void setSortedPluginIds(List sortedPluginIds) { @@ -101,14 +106,19 @@ public class DefaultPluginManager implements PluginManager{ log.warn(warn.toString(), pluginRootDirs); return Collections.emptyList(); } + pluginListenerFactory = createPluginListenerFactory(); Map pluginInfoMap = new LinkedHashMap<>(scanPluginPaths.size()); for (Path path : scanPluginPaths) { try { PluginInsideInfo pluginInfo = loadPlugin(path, false); if(pluginInfo != null){ - pluginInfoMap.put(pluginInfo.getPluginId(), pluginInfo.toPluginInfo()); + pluginInfo.setFollowSystem(); + PluginInfo pluginInfoFace = pluginInfo.toPluginInfo(); + pluginListenerFactory.loadSuccess(pluginInfoFace); + pluginInfoMap.put(pluginInfo.getPluginId(), pluginInfoFace); } } catch (PluginException e) { + pluginListenerFactory.loadFailure(path, e); log.error("加载插件包失败: {}. {}", path, e.getMessage(), e); } } @@ -118,16 +128,20 @@ public class DefaultPluginManager implements PluginManager{ } } + protected PluginListenerFactory createPluginListenerFactory(){ + return new DefaultPluginListenerFactory(); + } + @Override public boolean verify(Path pluginPath) { Assert.isNotNull(pluginPath, "参数pluginPath不能为空"); try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ - provider.getPluginChecker().check(pluginPath); + pluginChecker.check(pluginPath); PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); if(pluginDescriptor == null){ return false; } - provider.getPluginChecker().check(pluginDescriptor); + pluginChecker.checkDescriptor(pluginDescriptor); return true; } catch (Exception e) { log.error("插件jar包校验失败: {}" , pluginPath, e); @@ -163,21 +177,27 @@ public class DefaultPluginManager implements PluginManager{ // 加载插件 PluginInsideInfo pluginInsideInfo = loadPlugin(pluginPath, true); if(pluginInsideInfo != null){ - return pluginInsideInfo.toPluginInfo(); + PluginInfo pluginInfoFace = pluginInsideInfo.toPluginInfo(); + pluginListenerFactory.loadSuccess(pluginInfoFace); + return pluginInfoFace; } else { + pluginListenerFactory.loadFailure(pluginPath, new PluginException("Not found PluginInsideInfo")); return null; } } catch (Exception e) { - throw PluginException.getPluginException(e, ()-> { + PluginException pluginException = PluginException.getPluginException(e, () -> { throw new PluginException("插件包加载失败: " + sourcePluginPath, e); }); + pluginListenerFactory.loadFailure(pluginPath, pluginException); + throw pluginException; } } @Override public synchronized void unLoad(String pluginId) { Assert.isNotNull(pluginId, "参数pluginId不能为空"); - resolvedPlugins.remove(pluginId); + PluginInsideInfo pluginInsideInfo = resolvedPlugins.remove(pluginId); + pluginListenerFactory.unLoadSuccess(pluginInsideInfo.toPluginInfo()); } @Override @@ -187,19 +207,23 @@ public class DefaultPluginManager implements PluginManager{ if(loadPluginInfo == null){ throw new PluginException("插件包安装失败: " + pluginPath); } + PluginInsideInfo pluginInsideInfo = resolvedPlugins.get(loadPluginInfo.getPluginId()); + PluginInfo pluginInfo = pluginInsideInfo.toPluginInfo(); try { - PluginInsideInfo pluginInsideInfo = resolvedPlugins.get(loadPluginInfo.getPluginId()); start(pluginInsideInfo); - log.info("安装插件[{}]成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); + pluginListenerFactory.startSuccess(pluginInfo); + log.info("插件[{}]安装成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); return pluginInsideInfo.toPluginInfo(); } catch (Exception e){ if(e instanceof PluginDisabledException){ throw (PluginDisabledException)e; } - throw PluginException.getPluginException(e, ()-> { + PluginException pluginException = PluginException.getPluginException(e, ()-> { unLoad(loadPluginInfo.getPluginId()); throw new PluginException("插件包安装失败: " + pluginPath); }); + pluginListenerFactory.startFailure(pluginInfo, pluginException); + throw pluginException; } } @@ -210,15 +234,20 @@ public class DefaultPluginManager implements PluginManager{ if(wrapperInside == null){ throw new PluginException("没有发现插件: " + pluginId); } + PluginInfo pluginInfo = wrapperInside.toPluginInfo(); if(wrapperInside.getPluginState() == PluginState.STARTED){ try { stop(wrapperInside); + pluginListenerFactory.stopSuccess(pluginInfo); } catch (Exception e) { - throw PluginException.getPluginException(e, ()-> new PluginException("停止", pluginId, e)); + PluginException pluginException = PluginException.getPluginException(e, + ()-> new PluginException("停止", pluginId, e)); + pluginListenerFactory.stopFailure(pluginInfo, pluginException); + throw pluginException; } } startedPlugins.remove(pluginId); - resolvedPlugins.remove(pluginId); + unLoad(pluginId); MsgUtils.info(log, wrapperInside.getPluginDescriptor(), "卸载成功"); } @@ -231,7 +260,7 @@ public class DefaultPluginManager implements PluginManager{ throw new PluginException("非法插件包: " + pluginPath); } // 检查插件是否被禁用 - checkDisabled(upgradePlugin, "更新"); + PluginDisabledException.checkDisabled(upgradePlugin, configuration, "更新"); String pluginId = upgradePlugin.getPluginId(); // 得到旧插件 PluginInsideInfo oldPlugin = getPlugin(pluginId); @@ -268,12 +297,17 @@ public class DefaultPluginManager implements PluginManager{ if(pluginInsideInfo == null){ throw new PluginException("没有发现插件: " + pluginId); } + PluginInfo pluginInfo = pluginInsideInfo.toPluginInfo(); try { start(pluginInsideInfo); - log.info("启动插件[{}]成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); - return pluginInsideInfo.toPluginInfo(); + log.info("插件[{}]启动成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); + pluginListenerFactory.startSuccess(pluginInfo); + return pluginInfo; } catch (Exception e){ - throw PluginException.getPluginException(e, ()-> new PluginException(pluginInsideInfo.getPluginDescriptor(), "启动失败", e)); + PluginException pluginException = PluginException.getPluginException(e, + ()-> new PluginException(pluginInsideInfo.getPluginDescriptor(), "启动失败", e)); + pluginListenerFactory.startFailure(pluginInfo, pluginException); + throw pluginException; } } @@ -286,12 +320,17 @@ public class DefaultPluginManager implements PluginManager{ if(pluginInsideInfo == null){ throw new PluginException("没有发现插件: " + pluginId); } + PluginInfo pluginInfo = pluginInsideInfo.toPluginInfo(); try { stop(pluginInsideInfo); log.info("停止插件[{}]成功", MsgUtils.getPluginUnique(pluginInsideInfo.getPluginDescriptor())); - return pluginInsideInfo.toPluginInfo(); + pluginListenerFactory.stopSuccess(pluginInfo); + return pluginInfo; } catch (Exception e) { - throw PluginException.getPluginException(e, ()-> new PluginException(pluginInsideInfo.getPluginDescriptor(), "停止失败", e)); + PluginException pluginException = PluginException.getPluginException(e, + () -> new PluginException(pluginInsideInfo.getPluginDescriptor(), "停止失败", e)); + pluginListenerFactory.stopFailure(pluginInfo, pluginException); + throw pluginException; } } @@ -347,7 +386,7 @@ public class DefaultPluginManager implements PluginManager{ protected PluginInsideInfo loadFromPath(Path pluginPath) { try { - provider.getPluginChecker().check(pluginPath); + pluginChecker.check(pluginPath); } catch (Exception e) { throw PluginException.getPluginException(e, ()-> { return new PluginException("非法插件包. " + e.getMessage(), e); @@ -361,7 +400,7 @@ public class DefaultPluginManager implements PluginManager{ } String pluginId = pluginDescriptor.getPluginId(); PluginInsideInfo pluginInsideInfo = new DefaultPluginInsideInfo(pluginDescriptor); - if(isDisabled(pluginId)){ + if(configuration.isDisabled(pluginId)){ pluginInsideInfo.setPluginState(PluginState.DISABLED); } else { pluginInsideInfo.setPluginState(PluginState.LOADED); @@ -445,9 +484,7 @@ public class DefaultPluginManager implements PluginManager{ protected void start(PluginInsideInfo pluginInsideInfo) throws Exception{ Assert.isNotNull(pluginInsideInfo, "pluginInsideInfo 参数不能为空"); String pluginId = pluginInsideInfo.getPluginId(); - InsidePluginDescriptor pluginDescriptor = pluginInsideInfo.getPluginDescriptor(); - checkCanStarted(pluginInsideInfo); - provider.getPluginChecker().check(pluginDescriptor); + pluginChecker.checkCanStart(pluginInsideInfo); pluginInsideInfo.setPluginState(PluginState.STARTED); startedPlugins.put(pluginId, pluginInsideInfo); resolvedPlugins.remove(pluginId); @@ -459,7 +496,7 @@ public class DefaultPluginManager implements PluginManager{ * @throws Exception 启动异常 */ protected void stop(PluginInsideInfo pluginInsideInfo) throws Exception{ - checkCanStopped(pluginInsideInfo); + pluginChecker.checkCanStop(pluginInsideInfo); String pluginId = pluginInsideInfo.getPluginId(); pluginInsideInfo.setPluginState(PluginState.STOPPED); resolvedPlugins.put(pluginId, pluginInsideInfo); @@ -533,47 +570,5 @@ public class DefaultPluginManager implements PluginManager{ } } - /** - * 检查插件是否可启动 - * @param pluginInsideInfo PluginInfo - */ - private void checkCanStarted(PluginInfo pluginInsideInfo){ - checkDisabled(pluginInsideInfo, "启动"); - PluginState pluginState = pluginInsideInfo.getPluginState(); - if(pluginState == PluginState.STARTED){ - throw new PluginException(pluginInsideInfo.getPluginDescriptor(), "已经启动, 不能再启动"); - } - } - - /** - * 检查插件是否能停止 - * @param pluginInsideInfo PluginInfo - */ - private void checkCanStopped(PluginInfo pluginInsideInfo){ - checkDisabled(pluginInsideInfo, "停止"); - PluginState pluginState = pluginInsideInfo.getPluginState(); - if(pluginState != PluginState.STARTED){ - throw new PluginException(pluginInsideInfo.getPluginDescriptor(), "没有启动, 不能停止"); - } - } - - /** - * 检查插件是否被禁用 - * @param pluginInsideInfo PluginInfo - */ - private void checkDisabled(PluginInfo pluginInsideInfo, String opType){ - if(pluginInsideInfo.getPluginState() == PluginState.DISABLED || isDisabled(pluginInsideInfo.getPluginId())){ - throw new PluginDisabledException(pluginInsideInfo.getPluginDescriptor(), opType); - } - } - - /** - * 插件是否被禁用 - * @param pluginId 插件id - * @return boolean - */ - private boolean isDisabled(String pluginId){ - return disabledPluginIds != null && disabledPluginIds.contains(pluginId); - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java index f45e97a..2fc1fe2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -2,7 +2,6 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; -import com.gitee.starblues.core.descriptor.ProdPackagePluginDescriptorLoader; import com.gitee.starblues.core.descriptor.ProdPluginDescriptorLoader; import com.gitee.starblues.core.scanner.BasePluginScanner; import com.gitee.starblues.core.scanner.DevPathResolve; @@ -10,7 +9,9 @@ import com.gitee.starblues.core.scanner.PluginScanner; import com.gitee.starblues.core.scanner.ProdPathResolve; import com.gitee.starblues.core.version.SemverVersionInspector; import com.gitee.starblues.core.version.VersionInspector; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.utils.Assert; +import org.springframework.context.ApplicationContext; /** * @author starBlues @@ -20,20 +21,22 @@ public class DefaultRealizeProvider implements RealizeProvider { private PluginScanner pluginScanner; private PluginDescriptorLoader pluginDescriptorLoader; - private PluginChecker pluginChecker; private VersionInspector versionInspector; - protected final RuntimeMode runtimeMode; + protected final IntegrationConfiguration configuration; + protected final ApplicationContext applicationContext; - public DefaultRealizeProvider(RuntimeMode runtimeMode){ - this.runtimeMode = Assert.isNotNull(runtimeMode, "参数 runtimeMode 不能为空"); + public DefaultRealizeProvider(IntegrationConfiguration configuration, + ApplicationContext applicationContext){ + this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); + this.applicationContext = Assert.isNotNull(applicationContext, "参数 configuration 不能为空"); } @Override public void init() { BasePluginScanner basePluginScanner = new BasePluginScanner(); PluginDescriptorLoader pluginDescriptorLoader = null; - if(runtimeMode == RuntimeMode.DEV){ + if(configuration.environment() == RuntimeMode.DEV){ basePluginScanner.setPathResolve(new DevPathResolve()); pluginDescriptorLoader = new DevPluginDescriptorLoader(); } else { @@ -43,7 +46,6 @@ public class DefaultRealizeProvider implements RealizeProvider { setPluginScanner(basePluginScanner); setPluginDescriptorLoader(pluginDescriptorLoader); - setPluginChecker(new DefaultPluginChecker()); setVersionInspector(new SemverVersionInspector()); } @@ -56,17 +58,13 @@ public class DefaultRealizeProvider implements RealizeProvider { "pluginDescriptorLoader 不能为空"); } - public void setPluginChecker(PluginChecker pluginChecker) { - this.pluginChecker = Assert.isNotNull(pluginChecker, "pluginChecker 不能为空"); - } - public void setVersionInspector(VersionInspector versionInspector) { this.versionInspector = Assert.isNotNull(versionInspector, "versionInspector 不能为空"); } @Override public RuntimeMode getRuntimeMode() { - return runtimeMode; + return configuration.environment(); } @Override @@ -79,11 +77,6 @@ public class DefaultRealizeProvider implements RealizeProvider { return Assert.isNotNull(pluginDescriptorLoader, "PluginDescriptorLoader 实现不能为空"); } - @Override - public PluginChecker getPluginChecker() { - return Assert.isNotNull(pluginChecker, "PluginChecker 实现不能为空"); - } - @Override public VersionInspector getVersionInspector() { return Assert.isNotNull(versionInspector, "VersionInspector 实现不能为空"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java index 72b16ef..b839fa2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java @@ -1,11 +1,14 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginException; + import java.nio.file.Path; /** - * 检查插件是否合法 + * 插件检查者 * @author starBlues + * @version 3.0.0 */ public interface PluginChecker { @@ -14,13 +17,28 @@ public interface PluginChecker { * @param path path * @throws Exception 检查异常 */ - void check(Path path) throws Exception; + default void check(Path path) throws Exception{} /** - * 检查 + * 检查插件描述是否合法 * @param descriptor 插件信息 - * @throws Exception 检查异常 + * @throws PluginException 检查异常 + */ + default void checkDescriptor(PluginDescriptor descriptor) throws PluginException{} + + /** + * 检查是否能启动 + * @param pluginInfo 插件信息 + * @throws PluginException 不能启动, 抛出PluginException异常即可 */ - void check(PluginDescriptor descriptor) throws Exception; + default void checkCanStart(PluginInfo pluginInfo) throws PluginException{} + + /** + * 检查是否能停止 + * @param pluginInfo 插件信息 + * @throws PluginException 不能停止, 抛出PluginException异常即可 + */ + default void checkCanStop(PluginInfo pluginInfo) throws PluginException{} + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java index 6b7537a..48afaf3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java @@ -33,4 +33,10 @@ public interface PluginInfo { */ PluginState getPluginState(); + /** + * 是否跟随系统启动而加载的插件 + * @return true: 是, false: 否 + */ + boolean isFollowSystem(); + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java index 32ad7d6..e21e9f4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java @@ -13,22 +13,13 @@ public class PluginInfoFace implements PluginInfo { private final PluginDescriptor pluginDescriptor; private final PluginState pluginState; + private final boolean followSystem; public PluginInfoFace(PluginInsideInfo pluginInsideInfo) { Assert.isNotNull(pluginInsideInfo, "参数 pluginWrapperInside 不能为空"); this.pluginDescriptor = pluginInsideInfo.getPluginDescriptor().toPluginDescriptor(); this.pluginState = pluginInsideInfo.getPluginState(); - } - - public PluginInfoFace(PluginDescriptor pluginDescriptor, PluginState pluginState) { - Assert.isNotNull(pluginDescriptor, "参数 pluginDescriptor 不能为空"); - Assert.isNotNull(pluginState, "参数 pluginState 不能为空"); - if(pluginDescriptor instanceof InsidePluginDescriptor){ - this.pluginDescriptor = ((InsidePluginDescriptor)pluginDescriptor).toPluginDescriptor(); - } else { - this.pluginDescriptor = pluginDescriptor; - } - this.pluginState = pluginState; + this.followSystem = pluginInsideInfo.isFollowSystem(); } @Override @@ -50,4 +41,9 @@ public class PluginInfoFace implements PluginInfo { public PluginState getPluginState() { return pluginState; } + + @Override + public boolean isFollowSystem() { + return followSystem; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java index 28d92f9..cee4cd9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java @@ -15,6 +15,11 @@ public interface PluginInsideInfo extends PluginInfo { */ void setPluginState(PluginState pluginState); + /** + * 设置是跟随系统启动而启动的插件 + */ + void setFollowSystem(); + /** * 得到插件描述 * @return PluginDescriptor @@ -23,7 +28,7 @@ public interface PluginInsideInfo extends PluginInfo { InsidePluginDescriptor getPluginDescriptor(); /** - * 转换为插件信息 + * 转换为外部插件信息 * @return PluginInfo */ PluginInfo toPluginInfo(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index a6e33c3..dd69439 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -2,17 +2,22 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginException; +import com.gitee.starblues.core.exception.PluginProhibitStopException; import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginLauncher; import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolvedFactory; import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.integration.listener.DefaultPluginListenerFactory; +import com.gitee.starblues.integration.listener.PluginListenerFactory; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.MainApplicationContextProxy; import com.gitee.starblues.spring.SpringPluginHook; import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; import com.gitee.starblues.spring.invoke.InvokeSupperCache; +import com.gitee.starblues.utils.SpringBeanUtils; import org.springframework.context.support.GenericApplicationContext; import java.util.List; @@ -20,13 +25,15 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * 可引导启动的插件管理者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginLauncherManager extends DefaultPluginManager{ private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); + private final MainApplicationContext mainApplicationContext; private final GenericApplicationContext mainGenericApplicationContext; private final IntegrationConfiguration configuration; @@ -36,7 +43,7 @@ public class PluginLauncherManager extends DefaultPluginManager{ public PluginLauncherManager(RealizeProvider realizeProvider, GenericApplicationContext applicationContext, IntegrationConfiguration configuration) { - super(realizeProvider, configuration.pluginPath()); + super(realizeProvider, configuration); this.mainApplicationContext = new MainApplicationContextProxy( applicationContext.getBeanFactory(), applicationContext); @@ -44,9 +51,20 @@ public class PluginLauncherManager extends DefaultPluginManager{ this.configuration = configuration; this.invokeSupperCache = new DefaultInvokeSupperCache(); this.pluginLaunchInvolved = new PluginLaunchInvolvedFactory(); + addCustomPluginChecker(); + } + + private void addCustomPluginChecker(){ + List pluginCheckers = SpringBeanUtils.getBeans(mainGenericApplicationContext, + PluginChecker.class); + for (PluginChecker pluginChecker : pluginCheckers) { + super.pluginChecker.add(pluginChecker); + } + } - setDisabledPluginIds(configuration.disablePluginIds()); - setSortedPluginIds(configuration.sortInitPluginIds()); + @Override + protected PluginListenerFactory createPluginListenerFactory() { + return new DefaultPluginListenerFactory(mainGenericApplicationContext); } @Override @@ -81,7 +99,9 @@ public class PluginLauncherManager extends DefaultPluginManager{ if(registryPluginInfo == null){ throw new PluginException("没有发现插件 '" + pluginId + "' 信息"); } - registryPluginInfo.getSpringPluginHook().close(); + SpringPluginHook springPluginHook = registryPluginInfo.getSpringPluginHook(); + springPluginHook.stopVerify(); + springPluginHook.close(); invokeSupperCache.remove(pluginId); pluginRegistryInfoMap.remove(pluginId); super.stop(pluginInsideInfo); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java index 3561e47..5d0c20f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -1,5 +1,7 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.exception.PluginException; + import java.nio.file.Path; import java.util.List; @@ -28,9 +30,10 @@ public interface PluginManager { List loadPlugins(); /** - * 校验插件包 - * @param pluginPath 插件包路径 - * @return 校验结果. true 成功, false 失败 + * 校验插件jar包 + * @param pluginPath 插件包的路径 + * @return 成功: 返回true; 失败: 抛出异常或者返回false + * @throws PluginException 校验异常 */ boolean verify(Path pluginPath); @@ -58,11 +61,12 @@ public interface PluginManager { void unLoad(String pluginId); /** - * 安装路径直接安装插件, 并启动 + * 通过路径安装插件(会启用), 该插件文件必须存在于服务器 [适用于生产环境] + * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar * @param pluginPath 插件路径 - * @param unpackPlugin 是否解压插件文件 - * @return 安装的插件信息 - * @throws PluginException 插件异常 + * @param unpackPlugin 是否解压插件包. (如果插件包为压缩包时生效) + * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null + * @throws PluginException 异常信息 */ PluginInfo install(Path pluginPath, boolean unpackPlugin) throws PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java index 75fdf15..577fa69 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -1,6 +1,5 @@ package com.gitee.starblues.core; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.scanner.PluginScanner; import com.gitee.starblues.core.version.VersionInspector; @@ -34,12 +33,6 @@ public interface RealizeProvider { */ PluginDescriptorLoader getPluginDescriptorLoader(); - /** - * 得到 PluginChecker 实现 - * @return PluginChecker - */ - PluginChecker getPluginChecker(); - /** * 得到 VersionInspector 实现 * @return VersionInspector diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java new file mode 100644 index 0000000..15394d9 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java @@ -0,0 +1,64 @@ +package com.gitee.starblues.core.checker; + +import com.gitee.starblues.core.PluginChecker; +import com.gitee.starblues.core.PluginInfo; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginException; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * 组合插件检查者 + * @author starBlues + * @version 3.0.0 + */ +public class ComposePluginChecker implements PluginChecker { + + private final List pluginCheckers; + + public ComposePluginChecker() { + this(new ArrayList<>()); + } + + public ComposePluginChecker(List pluginCheckers) { + this.pluginCheckers = pluginCheckers; + } + + public void add(PluginChecker pluginChecker){ + if(pluginChecker != null){ + this.pluginCheckers.add(pluginChecker); + } + } + + + @Override + public void check(Path path) throws Exception { + for (PluginChecker pluginChecker : pluginCheckers) { + pluginChecker.check(path); + } + } + + @Override + public void checkDescriptor(PluginDescriptor descriptor) throws PluginException { + for (PluginChecker pluginChecker : pluginCheckers) { + pluginChecker.checkDescriptor(descriptor); + } + } + + @Override + public void checkCanStart(PluginInfo pluginInfo) throws PluginException { + for (PluginChecker pluginChecker : pluginCheckers) { + pluginChecker.checkCanStart(pluginInfo); + } + } + + @Override + public void checkCanStop(PluginInfo pluginInfo) throws PluginException { + for (PluginChecker pluginChecker : pluginCheckers) { + pluginChecker.checkCanStart(pluginInfo); + } + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java new file mode 100644 index 0000000..687d628 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java @@ -0,0 +1,131 @@ +package com.gitee.starblues.core.checker; + +import com.gitee.starblues.common.Constants; +import com.gitee.starblues.common.DependencyPlugin; +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.core.PluginChecker; +import com.gitee.starblues.core.PluginInfo; +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.RealizeProvider; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginDisabledException; +import com.gitee.starblues.core.exception.PluginException; +import com.gitee.starblues.integration.IntegrationConfiguration; +import com.gitee.starblues.integration.operator.DefaultPluginOperator; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.MsgUtils; +import com.gitee.starblues.utils.ObjectUtils; + +import java.io.FileNotFoundException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginChecker implements PluginChecker { + + + protected final RealizeProvider realizeProvider; + protected final IntegrationConfiguration configuration; + + private final Set enablePluginIds; + private final Set disabledPluginIds; + + public DefaultPluginChecker(RealizeProvider realizeProvider, + IntegrationConfiguration configuration) { + this.realizeProvider = realizeProvider; + this.configuration = configuration; + this.enablePluginIds = configuration.enablePluginIds(); + this.disabledPluginIds = configuration.disablePluginIds(); + } + + @Override + public void check(Path path) throws Exception { + if(path == null){ + throw new FileNotFoundException("path 文件路径不能为空"); + } + if(Files.notExists(path)){ + throw new FileNotFoundException("不存在文件: " + path.toString()); + } + } + + @Override + public void checkDescriptor(PluginDescriptor descriptor) throws PluginException { + Assert.isNotNull(descriptor, "PluginDescriptor 不能为空"); + + Assert.isNotEmpty(descriptor.getPluginPath(), "pluginPath 不能为空"); + + Assert.isNotNull(descriptor.getPluginId(), + PluginDescriptorKey.PLUGIN_ID + "不能为空"); + + Assert.isNotNull(descriptor.getPluginBootstrapClass(), + PluginDescriptorKey.PLUGIN_BOOTSTRAP_CLASS + "不能为空"); + + Assert.isNotNull(descriptor.getPluginVersion(), + PluginDescriptorKey.PLUGIN_VERSION + "不能为空"); + + String illegal = PackageStructure.getIllegal(descriptor.getPluginId()); + if(illegal != null){ + throw new PluginException(descriptor, "插件id不能包含:" + illegal); + } + illegal = PackageStructure.getIllegal(descriptor.getPluginVersion()); + if(illegal != null){ + throw new PluginException(descriptor, "插件版本号不能包含:" + illegal); + } + } + + + @Override + public void checkCanStart(PluginInfo pluginInfo) throws PluginException { + checkDescriptor(pluginInfo.getPluginDescriptor()); + PluginDisabledException.checkDisabled(pluginInfo, configuration, "启动"); + PluginState pluginState = pluginInfo.getPluginState(); + if(pluginState == PluginState.STARTED){ + throw new PluginException(pluginInfo.getPluginDescriptor(), "已经启动, 不能再启动"); + } + checkRequiresVersion(pluginInfo); + } + + + @Override + public void checkCanStop(PluginInfo pluginInfo) throws PluginException { + PluginDisabledException.checkDisabled(pluginInfo, configuration, "停止"); + PluginState pluginState = pluginInfo.getPluginState(); + if(pluginState != PluginState.STARTED){ + throw new PluginException(pluginInfo.getPluginDescriptor(), "没有启动, 不能停止"); + } + } + + /** + * 检查可安装到主程序的版本 + * @param pluginInfo pluginInfo + */ + private void checkRequiresVersion(PluginInfo pluginInfo){ + String version = configuration.version(); + if(ObjectUtils.isEmpty(version) || Constants.ALLOW_VERSION.equals(version)){ + return; + } + String requires = pluginInfo.getPluginDescriptor().getRequires(); + boolean exactVersion = configuration.exactVersion(); + int compareVersion = realizeProvider.getVersionInspector().compareTo(requires, version); + if(exactVersion && compareVersion != 0){ + String error = "需要安装到[" + requires + "]版本的主程序, 但当前主程序版本为[" + version + "]"; + throw new PluginException(pluginInfo.getPluginDescriptor(), error); + } + if(compareVersion > 0){ + String error = "需要安装到小于等于[" + requires + "]版本的主程序, 但当前主程序版本为[" + version + "]"; + throw new PluginException(pluginInfo.getPluginDescriptor(), error); + } + } + + + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java new file mode 100644 index 0000000..ba327fe --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java @@ -0,0 +1,104 @@ +package com.gitee.starblues.core.checker; + +import com.gitee.starblues.common.Constants; +import com.gitee.starblues.common.DependencyPlugin; +import com.gitee.starblues.core.PluginChecker; +import com.gitee.starblues.core.PluginInfo; +import com.gitee.starblues.core.PluginManager; +import com.gitee.starblues.core.PluginState; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginDisabledException; +import com.gitee.starblues.core.exception.PluginException; +import com.gitee.starblues.utils.MsgUtils; +import com.gitee.starblues.utils.ObjectUtils; + +import java.util.List; +import java.util.Objects; + +/** + * 插件依赖的插件检查者 + * @author starBlues + * @version 3.0.0 + */ +public class DependencyPluginChecker implements PluginChecker { + + private final PluginManager pluginManager; + + public DependencyPluginChecker(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + /** + * 检查插件依赖。如果依赖没有启动, 则自动启动 + * @param pluginInfo 插件信息 + * @throws PluginException PluginException + */ + @Override + public void checkCanStart(PluginInfo pluginInfo) throws PluginException { + List dependencyPlugins = pluginInfo.getPluginDescriptor().getDependencyPlugin(); + if(ObjectUtils.isEmpty(dependencyPlugins)){ + return; + } + PluginDescriptor descriptor = pluginInfo.getPluginDescriptor(); + resolveDependencyPlugin(pluginInfo, (dependencyPlugin, dependencyPluginInfo)->{ + String id = dependencyPlugin.getId(); + String version = dependencyPlugin.getVersion(); + boolean allowAllVersion = Constants.ALLOW_VERSION.equals(version); + + boolean findDependency = false; + if(dependencyPluginInfo != null){ + if(allowAllVersion){ + findDependency = true; + } else { + findDependency = Objects.equals(dependencyPluginInfo.getPluginDescriptor().getPluginVersion(), + descriptor.getPluginVersion()); + } + } + String dependencyPluginUnique = MsgUtils.getPluginUnique(id, allowAllVersion ? null : version); + if(!findDependency){ + throw new PluginException(descriptor, "需要依赖插件[" + dependencyPluginUnique + "]启动"); + } + if(dependencyPluginInfo.getPluginState() != PluginState.STARTED){ + // 没有启动的话, 手动启动 + try { + pluginManager.start(dependencyPluginInfo.getPluginId()); + } catch (Exception e){ + if(e instanceof PluginDisabledException){ + // 依赖被禁用, 不能启动 + throw new PluginDisabledException(descriptor, + "依赖插件[" + dependencyPluginUnique + "]被禁用, 无法启动当前插件"); + } + throw new PluginException(descriptor, + "依赖插件[" + dependencyPluginUnique + "]启动失败. 无法启动当前插件", e); + } + } + }); + } + + private void resolveDependencyPlugin(PluginInfo pluginInfo, ResolveDependencyPlugin resolveDependencyPlugin) + throws PluginException { + List dependencyPlugins = pluginInfo.getPluginDescriptor().getDependencyPlugin(); + if(ObjectUtils.isEmpty(dependencyPlugins)){ + return; + } + for (DependencyPlugin dependencyPlugin : dependencyPlugins) { + if (dependencyPlugin.getOptional()) { + continue; + } + PluginInfo plugin = pluginManager.getPluginInfo(dependencyPlugin.getId()); + resolveDependencyPlugin.process(dependencyPlugin, plugin); + } + } + + @FunctionalInterface + protected interface ResolveDependencyPlugin{ + /** + * 处理依赖的插件 + * @param dependencyPlugin 当前依赖的插件 + * @param dependencyPluginInfo 查询出当前系统安装的依赖的插件信息。可能为空 + * @throws PluginException 处理异常 + */ + void process(DependencyPlugin dependencyPlugin, PluginInfo dependencyPluginInfo) throws PluginException; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java deleted file mode 100644 index cca5db5..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourcePatternDefiner.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.gitee.starblues.core.classloader; - -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ObjectUtils; -import org.springframework.context.ApplicationContext; - -import java.util.*; - -/** - * 默认主程序资源定义者 - * @author starBlues - * @version 3.0.0 - */ -public class DefaultMainResourcePatternDefiner implements MainResourcePatternDefiner { - - private final Set resourcePatterns = new HashSet<>(); - - private final String mainPackageName; - - public DefaultMainResourcePatternDefiner(String mainPackageName){ - this.mainPackageName = Assert.isNotEmpty(mainPackageName, - "参数 mainPackageName 不能为空"); - initDefaultResources(); - } - - - @Override - public Set getIncludePatterns() { - return resourcePatterns; - } - - @Override - public Set getExcludePatterns() { - return null; - } - - - private void initDefaultResources() { - // == java == - resourcePatterns.add("java/**"); - resourcePatterns.add("javax/**"); - resourcePatterns.add("sun/**"); - - // == main == - resourcePatterns.add(mainPackageName.replace(".", "/")); - - // == springboot-plugin-framework == - resourcePatterns.add("com/gitee/starblues/**"); - - // aop - resourcePatterns.add("org/aspectj/**"); - - // === spring-boot-starter === - // logback-classic - resourcePatterns.add("ch/qos/logback/classic/**"); - resourcePatterns.add("org/slf4j/impl/**"); - // logback-core - resourcePatterns.add("ch/qos/logback/core/**"); - // log4j-api - resourcePatterns.add("org/apache/logging/log4j/**"); - // log4j-to-slf4j - resourcePatterns.add("org/apache/logging/slf4j/**"); - // slf4j-api jul-to-slf4j(org/slf4j/bridge/**) - resourcePatterns.add("org/slf4j/**"); - - resourcePatterns.add("META-INF/spring.factories"); - - // spring-boot - resourcePatterns.add("org/springframework/boot/**"); - // spring-boot-autoconfigure - resourcePatterns.add("org/springframework/boot/autoconfigure/**"); - // spring-core spring-context spring-aop spring-beans - resourcePatterns.add("org/aopalliance/**"); - resourcePatterns.add("org/springframework/aop/**"); - // spring-beans spring-context spring-core spring-expression - resourcePatterns.add("org/springframework/**"); - // spring-jcl - resourcePatterns.add("org/apache.commons/logging/**"); - // snakeyaml - resourcePatterns.add("org/yaml/snakeyaml/**"); - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java index 6d34c50..6417f26 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java @@ -1,6 +1,6 @@ package com.gitee.starblues.core.classloader; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import java.io.InputStream; @@ -13,8 +13,9 @@ import java.util.jar.JarInputStream; import java.util.zip.ZipEntry; /** + * 嵌套jar加载者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class NestedJarResourceLoader extends AbstractResourceLoader{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java deleted file mode 100644 index dca7448..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/RepeatResourceLoaderFactory.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.gitee.starblues.core.classloader; - -import java.nio.file.Path; - -/** - * @author starBlues - * @version 1.0 - */ -public class RepeatResourceLoaderFactory extends ResourceLoaderFactory{ - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index 47b2133..a9df159 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -1,7 +1,9 @@ package com.gitee.starblues.core.descriptor; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.common.AbstractDependencyPlugin; +import com.gitee.starblues.common.DependencyPlugin; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; @@ -80,9 +82,15 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor descriptor.setProvider(getValue(attributes, PLUGIN_PROVIDER, false)); descriptor.setLicense(getValue(attributes, PLUGIN_LICENSE, false)); descriptor.setConfigFileName(getValue(attributes, PLUGIN_CONFIG_FILE_NAME, false)); + + descriptor.setDependencyPlugins(getPluginDependency(attributes)); return descriptor; } + protected List getPluginDependency(Attributes attributes){ + return AbstractDependencyPlugin.toList(getValue(attributes, PLUGIN_DEPENDENCIES), DefaultDependencyPlugin::new); + } + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception{ String libIndex = getValue(attributes, PLUGIN_RESOURCES_CONFIG); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java new file mode 100644 index 0000000..ce831b5 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java @@ -0,0 +1,50 @@ +package com.gitee.starblues.core.descriptor; + +import com.gitee.starblues.common.AbstractDependencyPlugin; + +/** + * 依赖的插件信息 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultDependencyPlugin extends AbstractDependencyPlugin { + + private String id; + private String version; + private Boolean optional = false; + + @Override + public String getId() { + return id; + } + + @Override + public String getVersion() { + return version; + } + + @Override + public Boolean getOptional() { + if(optional == null){ + return false; + } + return optional; + } + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public void setVersion(String version) { + this.version = version; + } + + @Override + public void setOptional(Boolean optional) { + if(optional == null){ + optional = false; + } + this.optional = optional; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java index 100e6c1..d187353 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java @@ -1,11 +1,11 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.DependencyPlugin; +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.utils.Assert; -import java.nio.file.Path; import java.util.List; -import java.util.Set; -import java.util.jar.Manifest; import static com.gitee.starblues.common.PluginDescriptorKey.*; @@ -29,6 +29,7 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ private String provider; private String license; + private List dependencyPlugins; public DefaultPluginDescriptor(String pluginId, String pluginVersion, String pluginClass, String pluginPath) { @@ -36,6 +37,7 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ this.pluginVersion = Assert.isNotEmpty(pluginVersion, PLUGIN_VERSION + "不能为空"); this.pluginBootstrapClass = Assert.isNotEmpty(pluginClass, PLUGIN_BOOTSTRAP_CLASS + "不能为空"); this.pluginPath = Assert.isNotNull(pluginPath, "插件路径[pluginPath]不能为空"); + check(); } void setDescription(String description) { @@ -58,6 +60,10 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ this.type = type; } + void setDependencyPlugins(List dependencyPlugins) { + this.dependencyPlugins = dependencyPlugins; + } + @Override public String getPluginId() { return pluginId; @@ -99,13 +105,25 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ } @Override - public List getPluginDependency() { - return null; + public List getDependencyPlugin() { + return dependencyPlugins; } + @Override public Type getType() { return type; } + private void check(){ + String illegal = PackageStructure.getIllegal(pluginId); + if(illegal != null){ + throw new PluginException(this, "插件id不能包含:" + illegal); + } + illegal = PackageStructure.getIllegal(pluginVersion); + if(illegal != null){ + throw new PluginException(this, "插件版本号不能包含:" + illegal); + } + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java index 58c943c..fb9aa42 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java @@ -1,5 +1,7 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.DependencyPlugin; + import java.nio.file.Path; import java.util.List; import java.util.Set; @@ -51,7 +53,7 @@ public class EmptyPluginDescriptor implements InsidePluginDescriptor{ } @Override - public List getPluginDependency() { + public List getDependencyPlugin() { return null; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java index 0b207b0..6cfc67a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java @@ -5,8 +5,9 @@ import java.util.Set; import java.util.jar.Manifest; /** + * 内部的PluginDescriptor * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface InsidePluginDescriptor extends PluginDescriptor{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java index 5166f27..017592d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -1,5 +1,7 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.DependencyPlugin; + import java.util.List; /** @@ -40,7 +42,7 @@ public interface PluginDescriptor { String getDescription(); /** - * 获取插件所需主程序版本 + * 获取插件所能安装到主程序的版本 * @return String */ String getRequires(); @@ -61,7 +63,7 @@ public interface PluginDescriptor { * 获取当前插件依赖 * @return List */ - List getPluginDependency(); + List getDependencyPlugin(); /** * 得到插件类型 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java index 4b56072..77bcb08 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java @@ -1,6 +1,6 @@ package com.gitee.starblues.core.descriptor; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.exception.PluginException; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index a82412b..be6b4a8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -1,6 +1,6 @@ package com.gitee.starblues.core.descriptor; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.utils.ResourceUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java index e252786..4d6b2e6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java @@ -1,7 +1,9 @@ package com.gitee.starblues.core.exception; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.PluginInfo; +import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.utils.MsgUtils; import com.gitee.starblues.utils.ObjectUtils; @@ -20,4 +22,16 @@ public class PluginDisabledException extends PluginException { super("插件[" + MsgUtils.getPluginUnique(pluginDescriptor) + "]已被禁用, 不能" + (!ObjectUtils.isEmpty(opType) ? opType : "操作")); } + + /** + * 检查插件是否被禁用 + * @param pluginInsideInfo PluginInfo + */ + public static void checkDisabled(PluginInfo pluginInsideInfo, IntegrationConfiguration configuration, String opType){ + if(pluginInsideInfo.getPluginState() == PluginState.DISABLED + || configuration.isDisabled(pluginInsideInfo.getPluginId()) + || !configuration.isEnable(pluginInsideInfo.getPluginId())){ + throw new PluginDisabledException(pluginInsideInfo.getPluginDescriptor(), opType); + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java similarity index 97% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java index a450b0f..3280be3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core; +package com.gitee.starblues.core.exception; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.MsgUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java new file mode 100644 index 0000000..07327a8 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java @@ -0,0 +1,16 @@ +package com.gitee.starblues.core.exception; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.utils.MsgUtils; + +/** + * 插件禁止停止异常 + * @author starBlues + * @version 3.0.0 + */ +public class PluginProhibitStopException extends PluginException{ + + public PluginProhibitStopException(PluginDescriptor pluginDescriptor, String message) { + super(pluginDescriptor, "被禁止卸载. " + MsgUtils.getThrowableMsg(message)); + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java new file mode 100644 index 0000000..aa14b82 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java @@ -0,0 +1,33 @@ +package com.gitee.starblues.core.launcher.plugin; + +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; +import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; + +import java.util.HashSet; +import java.util.Set; + +/** + * 基本的主程序资源匹配定义 + * @author starBlues + * @version 3.0.0 + */ +public class BasicMainResourcePatternDefiner implements MainResourcePatternDefiner { + + private final String mainPackageName; + + public BasicMainResourcePatternDefiner(String mainPackageName) { + this.mainPackageName = mainPackageName; + } + + @Override + public Set getIncludePatterns() { + Set includePatterns = new HashSet<>(); + includePatterns.add(mainPackageName); + return includePatterns; + } + + @Override + public Set getExcludePatterns() { + return null; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 6fd8ca0..51e7914 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -32,7 +32,7 @@ public class PluginLauncher extends AbstractLauncher { PluginLaunchInvolved pluginLaunchInvolved) { this.pluginInteractive = pluginInteractive; this.pluginDescriptor = pluginInteractive.getPluginDescriptor(); - this.mainResourcePatternDefiner = new PluginMainResourcePatternDefiner(pluginDescriptor); + this.mainResourcePatternDefiner = new PluginMainResourcePatternDefiner(pluginInteractive); this.pluginLaunchInvolved = pluginLaunchInvolved; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index 6e88efe..a19951d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -1,8 +1,11 @@ package com.gitee.starblues.core.launcher.plugin; +import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; +import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.SpringBeanUtilsV3; import java.util.HashSet; import java.util.Set; @@ -15,22 +18,31 @@ import java.util.Set; public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDefiner { private static final String FRAMEWORK = "com/gitee/starblues/**"; - private static final String SPRING_WEB = "org/springframework/web/**"; public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; + private final String mainPackage; private final InsidePluginDescriptor descriptor; + private final BasicMainResourcePatternDefiner basicPatternDefiner; - public PluginMainResourcePatternDefiner(InsidePluginDescriptor descriptor) { - this.descriptor = descriptor; + public PluginMainResourcePatternDefiner(PluginInteractive pluginInteractive) { + mainPackage = pluginInteractive.getConfiguration().mainPackage(); + this.descriptor = pluginInteractive.getPluginDescriptor(); + basicPatternDefiner = getPatternDefiner(pluginInteractive); } @Override public Set getIncludePatterns() { Set includeResourcePatterns = super.getIncludePatterns(); + Set includePatterns = basicPatternDefiner.getIncludePatterns(); + if(!ObjectUtils.isEmpty(includePatterns)){ + includeResourcePatterns.addAll(includePatterns); + } else { + includeResourcePatterns.add(mainPackage); + } includeResourcePatterns.add(FRAMEWORK); - includeResourcePatterns.add(SPRING_WEB); - includeResourcePatterns.add("org/springframework/ui/**"); + addWebIncludeResourcePatterns(includeResourcePatterns); + addSwagger(includeResourcePatterns); // 配置插件自定义从主程序加载的资源匹配 Set includeMainResourcePatterns = descriptor.getIncludeMainResourcePatterns(); @@ -47,9 +59,15 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef return includeResourcePatterns; } + + @Override public Set getExcludePatterns() { Set excludeResourcePatterns = new HashSet<>(); + Set excludePatterns = basicPatternDefiner.getExcludePatterns(); + if(!ObjectUtils.isEmpty(excludePatterns)){ + excludeResourcePatterns.addAll(excludePatterns); + } Set excludeMainResourcePatterns = descriptor.getExcludeMainResourcePatterns(); if(!ObjectUtils.isEmpty(excludeMainResourcePatterns)){ excludeResourcePatterns.addAll(excludeMainResourcePatterns); @@ -57,4 +75,37 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef excludeResourcePatterns.add(FACTORIES_RESOURCE_LOCATION); return excludeResourcePatterns; } + + + + protected void addWebIncludeResourcePatterns(Set patterns){ + patterns.add("org/springframework/web/**"); + patterns.add("org/springframework/http/**"); + patterns.add("org/springframework/remoting/**"); + patterns.add("org/springframework/ui/**"); + + patterns.add("com/fasterxml/jackson/**"); + } + + protected void addSwagger(Set patterns){ + patterns.add("springfox/documentation/**"); + patterns.add("io/swagger/**"); + } + + /** + * 获取基本的 MainResourcePatternDefiner + * @param pluginInteractive PluginInteractive + * @return BasicMainResourcePatternDefiner + */ + private BasicMainResourcePatternDefiner getPatternDefiner(PluginInteractive pluginInteractive){ + final MainApplicationContext mainApplicationContext = pluginInteractive.getMainApplicationContext(); + BasicMainResourcePatternDefiner definer = SpringBeanUtilsV3.getExistBean( + mainApplicationContext, BasicMainResourcePatternDefiner.class); + if(definer == null){ + return new BasicMainResourcePatternDefiner(mainPackage); + } else { + return definer; + } + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java index 7e6cf83..85f1cfc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java @@ -1,6 +1,7 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.exception.PluginProhibitStopException; import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; @@ -29,6 +30,11 @@ public class SpringPluginHookWrapper implements SpringPluginHook { this.classLoader = classLoader; } + @Override + public void stopVerify() throws PluginProhibitStopException { + target.stopVerify(); + } + @Override public ApplicationContext getApplicationContext() { return target.getApplicationContext(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java deleted file mode 100644 index c4e2fbd..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * @author starBlues - * @version 3.0.0 - */ -package com.gitee.starblues.core; \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java deleted file mode 100644 index 4ca2836..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/AbstractExtension.java +++ /dev/null @@ -1,103 +0,0 @@ -//package com.gitee.starblues.extension; -// -//import com.gitee.starblues.factory.process.pipe.PluginPreProcessorExtend; -//import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -//import com.gitee.starblues.integration.application.PluginApplication; -//import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -//import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -//import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -//import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; -//import org.springframework.context.ApplicationContext; -// -//import java.util.List; -// -///** -// * 抽象的扩展工厂 -// * -// * @author starBlues -// * @version 2.4.0 -// */ -//public abstract class AbstractExtension { -// -// protected PluginApplication pluginApplication; -// -// public void setPluginApplication(PluginApplication pluginApplication) { -// this.pluginApplication = pluginApplication; -// } -// -// /** -// * 扩展唯一的key -// * @return String -// */ -// public abstract String key(); -// -// /** -// * 该扩展初始化的操作 -// * 主要是在插件初始化阶段被调用 -// * @param mainApplicationContext 主程序ApplicationContext -// * @throws Exception 初始化异常 -// */ -// public void initialize(ApplicationContext mainApplicationContext) throws Exception{ -// } -// -// /** -// * 返回插件的资源加载者。 -// * 主要是加载插件中的某些资源,比如文件、图片等。 -// * @return List PluginResourceLoader -// */ -// public List getPluginResourceLoader(){ -// return null; -// } -// -// /** -// * 返回扩展的插件中的类分组器。 -// * 该扩展主要是对插件中的Class文件分组,然后供 PluginPipeProcessor、PluginPostProcessor 阶段使用。 -// * @param mainApplicationContext 主程序ApplicationContext -// * @return List PluginPipeProcessorExtend -// */ -// public List getPluginClassGroup(ApplicationContext mainApplicationContext){ -// return null; -// } -// -// /** -// * 返回扩展的插件前置处理者。 -// * 该扩展主要是对每一个插件进行处理 -// * @param mainApplicationContext 主程序ApplicationContext -// * @return List PluginPipeProcessorExtend -// */ -// public List getPluginPreProcessor(ApplicationContext mainApplicationContext){ -// return null; -// } -// -// /** -// * 返回扩展的bean定义注册者扩展 -// * 该扩展主要是对每一个插件进行处理 -// * @param mainApplicationContext 主程序ApplicationContext -// * @return List PluginPipeProcessorExtend -// */ -// public List getPluginBeanRegistrar(ApplicationContext mainApplicationContext){ -// return null; -// } -// -// /** -// * 返回扩展的流插件处理者。 -// * 该扩展主要是对每一个插件进行处理 -// * @param mainApplicationContext 主程序ApplicationContext -// * @return List PluginPipeProcessorExtend -// */ -// public List getPluginPipeProcessor(ApplicationContext mainApplicationContext){ -// return null; -// } -// -// /** -// * 返回扩展的插件后置处理者。 -// * 该扩展主要是对全部插件进行处理。 -// * @param mainApplicationContext 主程序ApplicationContext -// * @return List PluginPostProcessorExtend -// */ -// public List getPluginPostProcessor(ApplicationContext mainApplicationContext){ -// return null; -// } -// -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java deleted file mode 100644 index 538aba0..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -//package com.gitee.starblues.extension; -// -//import com.gitee.starblues.utils.SpringBeanUtils; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.context.ApplicationContext; -//import org.springframework.util.StringUtils; -// -//import java.util.*; -//import java.util.concurrent.ConcurrentHashMap; -// -///** -// * 静态的扩展工厂 -// * -// * @author starBlues -// * @version 2.4.0 -// */ -//public class ExtensionFactory { -// -// private static final Logger LOG = LoggerFactory.getLogger(ExtensionFactory.class); -// -// /** -// * 扩展工厂。key 扩展的key. 值为扩展的实现 -// */ -// private final static Map PLUGIN_EXTENSION_MAP = new ConcurrentHashMap<>(); -// -// private ExtensionFactory(){} -// -// -// -// public static void addExtension(AbstractExtension abstractExtension){ -// if(abstractExtension == null){ -// LOG.warn("add failure, abstractExtension is null"); -// return; -// } -// String key = abstractExtension.key(); -// if(StringUtils.isEmpty(key)){ -// LOG.error("add failure, key is empty"); -// } -// PLUGIN_EXTENSION_MAP.put(key, abstractExtension); -// } -// -// /** -// * 得到PluginControllerProcessorExtend的实现 -// * @param mainApplicationContext 主程序的 ApplicationContext -// * @return PluginControllerProcessorExtend 的实现对象集合 -// */ -// public static List getPluginControllerProcessorExtend(ApplicationContext mainApplicationContext){ -// return SpringBeanUtils.getBeans(mainApplicationContext, -// PluginControllerProcessorExtend.class); -// } -// -// -// static Map getPluginExtension() { -// return Collections.unmodifiableMap(PLUGIN_EXTENSION_MAP); -// } -// -// -// -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java deleted file mode 100644 index 5c9c3a5..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/ExtensionInitializer.java +++ /dev/null @@ -1,161 +0,0 @@ -//package com.gitee.starblues.extension; -// -//import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -//import com.gitee.starblues.factory.process.pipe.PluginPreProcessorExtend; -//import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -//import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -//import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; -//import com.gitee.starblues.factory.process.pipe.loader.PluginResourceLoader; -//import com.gitee.starblues.utils.CommonUtils; -//import com.gitee.starblues.utils.OrderPriority; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.context.ApplicationContext; -// -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.atomic.AtomicBoolean; -//import java.util.function.Consumer; -//import java.util.function.Function; -// -///** -// * 静态的扩展初始化器 -// * -// * @author starBlues -// * @version 2.4.0 -// */ -//public class ExtensionInitializer { -// -// -// private static final Logger LOG = LoggerFactory.getLogger(ExtensionInitializer.class); -// -// private static final AtomicBoolean IS_INIT = new AtomicBoolean(false); -// -// private static final List RESOURCE_LOADERS_EXTENDS = new ArrayList<>(); -// private static final List PIPE_PROCESSOR_EXTENDS = new ArrayList<>(); -// private static final List BEAN_REGISTRAR_EXTEND = new ArrayList<>(); -// private static final List CLASS_GROUP_EXTENDS = new ArrayList<>(); -// private static final List PRE_PROCESSOR_EXTENDS = new ArrayList<>(); -// private static final List POST_PROCESSOR_EXTENDS = new ArrayList<>(); -// -// private ExtensionInitializer(){ -// -// } -// -// -// public static synchronized void initialize(ApplicationContext applicationContext){ -// if(applicationContext == null){ -// LOG.error("ApplicationContext is null, cannot initialize"); -// return; -// } -// if(IS_INIT.get()){ -// throw new RuntimeException("The extension has been initialized"); -// } -// Map pluginExtension = ExtensionFactory.getPluginExtension(); -// for (Map.Entry entry : pluginExtension.entrySet()){ -// AbstractExtension abstractExtension = entry.getValue(); -// if(abstractExtension == null){ -// continue; -// } -// try { -// abstractExtension.initialize(applicationContext); -// initialize(abstractExtension, applicationContext); -// } catch (Exception e) { -// LOG.error("Plugin extension '{}' initialize exception. {}", abstractExtension.key(), e.getMessage(), e); -// } -// } -// IS_INIT.set(true); -// } -// -// private static void initialize(AbstractExtension abstractExtension, ApplicationContext applicationContext){ -// StringBuilder debug = new StringBuilder(); -// debug.append("Plugin extension '").append(abstractExtension.key()).append("'") -// .append(" are ["); -// iteration(abstractExtension.getPluginResourceLoader(), extend->{ -// RESOURCE_LOADERS_EXTENDS.add(extend); -// debug.append(extend.key()).append("、"); -// }, bean -> bean.order()); -// -// iteration(abstractExtension.getPluginPreProcessor(applicationContext), extend->{ -// PRE_PROCESSOR_EXTENDS.add(extend); -// debug.append(extend.key()).append("、"); -// }, bean -> bean.order()); -// -// iteration(abstractExtension.getPluginBeanRegistrar(applicationContext), extend->{ -// BEAN_REGISTRAR_EXTEND.add(extend); -// debug.append(extend.key()).append("、"); -// }, null); -// -// iteration(abstractExtension.getPluginPipeProcessor(applicationContext), extend->{ -// PIPE_PROCESSOR_EXTENDS.add(extend); -// debug.append(extend.key()).append("、"); -// }, bean -> bean.order()); -// -// iteration(abstractExtension.getPluginClassGroup(applicationContext), extend->{ -// CLASS_GROUP_EXTENDS.add(extend); -// debug.append(extend.key()).append("、"); -// }, null); -// -// iteration(abstractExtension.getPluginPostProcessor(applicationContext), extend->{ -// POST_PROCESSOR_EXTENDS.add(extend); -// debug.append(extend.key()); -// }, bean -> bean.order()); -// -// debug.append("] is registered"); -// LOG.info("Plugin extension '{}' is registered", abstractExtension.key()); -// LOG.debug(debug.toString()); -// } -// -// -// public static List getResourceLoadersExtends() { -// return RESOURCE_LOADERS_EXTENDS; -// } -// -// public static List getPreProcessorExtends() { -// return PRE_PROCESSOR_EXTENDS; -// } -// -// public static List getPipeProcessorExtends() { -// return PIPE_PROCESSOR_EXTENDS; -// } -// -// public static List getPluginBeanRegistrarExtends() { -// return BEAN_REGISTRAR_EXTEND; -// } -// -// public static List getClassGroupExtends() { -// return CLASS_GROUP_EXTENDS; -// } -// -// public static List getPostProcessorExtends() { -// return POST_PROCESSOR_EXTENDS; -// } -// -// /** -// * 迭代器 -// * @param list 当前处理的集合 -// * @param consumer 消费集合中的数据项 -// * @param order 排序集合。传入 null 表示不需要排序 -// */ -// private static void iteration(List list, Consumer consumer, final Function order){ -// if(list == null || list.isEmpty()){ -// return; -// } -// if(order != null){ -// list.stream() -// .filter(t -> t != null) -// .sorted(CommonUtils.orderPriority(order)) -// .forEach(consumer); -// ; -// } else { -// for (T t : list) { -// if(t != null){ -// consumer.accept(t); -// } -// } -// } -// } -// -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java deleted file mode 100644 index 71e6b69..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/PluginControllerProcessorExtend.java +++ /dev/null @@ -1,36 +0,0 @@ -//package com.gitee.starblues.extension; -// -// -//import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; -// -//import java.util.List; -// -///** -// * 可扩展的 controller 处理者 -// * -// * @author starBlues -// * @version 2.4.0 -// */ -//public interface PluginControllerProcessorExtend { -// -// /** -// * 初始化 -// */ -// void initialize(); -// -// /** -// * 注册 -// * @param pluginId 插件id -// * @param controllerWrappers controller 类集合 -// * @throws Exception 异常 -// */ -// void registry(String pluginId, List controllerWrappers) throws Exception; -// -// /** -// * 注册 -// * @param pluginId 插件id -// * @param controllerWrappers controller 类集合 -// * @throws Exception 异常 -// */ -// void unRegistry(String pluginId, List controllerWrappers) throws Exception; -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index 9c7c137..6ef8ad5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.utils.ResourceUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -19,7 +20,7 @@ import java.util.Set; public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguration{ public static final String ENABLE_KEY = "plugin.enable"; - public static final String ENABLE_STARTER_KEY = "plugin.enable-starter"; + public static final String ENABLE_STARTER_KEY = "plugin.enableStarter"; /** * 是否启用插件功能 @@ -47,10 +48,16 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio private List pluginPath; /** - * 插件文件的路径 + * 上传的插件所存储的临时目录 + */ + @Value("${uploadTempPath:temp}") + private String uploadTempPath; + + /** + * 在卸载插件后, 备份插件的目录 */ - @Value("${pluginConfigFilePath:plugin-configs}") - private String pluginConfigFilePath; + @Value("${backupPath:backupPlugin}") + private String backupPath; /** * 插件rest接口前缀. 默认: /plugins @@ -74,22 +81,20 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio private Boolean enablePluginIdRestPathPrefix; /** - * 是否启用Swagger刷新机制. 默认启用 + * 启用的插件id */ - @Value("${enableSwaggerRefresh:true}") - private Boolean enableSwaggerRefresh; + private Set enablePluginIds; /** - * 在卸载插件后, 备份插件的目录 + * 禁用的插件id, 禁用后系统不会启动该插件 + * 如果禁用所有插件, 则Set集合中返回一个字符: * */ - @Value("${backupPath:}") - private String backupPath; + private Set disablePluginIds; /** - * 上传的插件所存储的临时目录 + * 设置初始化时插件启动的顺序 */ - @Value("${uploadTempPath:}") - private String uploadTempPath; + private List sortInitPluginIds; /** * 当前主程序的版本号, 用于校验插件是否可安装. @@ -104,37 +109,8 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio * 设置为false表示插件设置的requires的版本号小于等于version值, 插件就可安装, 即requires<=x.y.z * 默认为false */ - @Value("${exactVersionAllowed:false}") - private Boolean exactVersionAllowed; - - /** - * 停止插件时, 是否停止当前插件依赖的插件 - * 默认不停止 - **/ - @Value("${exactVersionAllowed:false}") - private Boolean stopDependents; - - /** - * 启用的插件id - */ - private Set enablePluginIds; - - /** - * 禁用的插件id, 禁用后系统不会启动该插件 - * 如果禁用所有插件, 则Set集合中返回一个字符: * - */ - private Set disablePluginIds; - - /** - * 设置初始化时插件启动的顺序 - */ - private List sortInitPluginIds; - - /** - * 是否启用webSocket的功能. 如需启用, 则需要引入springboot支持的WebSocket依赖 - */ - @Value("${enableWebSocket:false}") - private Boolean enableWebSocket; + @Value("${exactVersion:false}") + private Boolean exactVersion; @Override public boolean enable() { @@ -151,7 +127,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String mainPackage() { - return mainPackage; + return ResourceUtils.replacePackage(mainPackage); } @Override @@ -159,11 +135,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio return pluginPath; } - @Override - public String pluginConfigFilePath() { - return pluginConfigFilePath; - } - @Override public String uploadTempPath() { if(ObjectUtils.isEmpty(uploadTempPath)){ @@ -180,14 +151,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio return backupPath; } - @Override - public boolean enablePluginRestController() { - if(enablePluginRestController == null){ - return super.enablePluginRestController(); - } - return enablePluginRestController; - } - @Override public String pluginRestPathPrefix() { if(ObjectUtils.isEmpty(pluginRestPathPrefix)){ @@ -216,11 +179,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio return disablePluginIds; } - @Override - public boolean enableSwaggerRefresh() { - return enableSwaggerRefresh; - } - @Override public List sortInitPluginIds() { return sortInitPluginIds; @@ -232,27 +190,11 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio } @Override - public boolean exactVersionAllowed() { - if(exactVersionAllowed == null){ + public boolean exactVersion() { + if(exactVersion == null){ return false; } - return exactVersionAllowed; - } - - @Override - public boolean enableWebSocket() { - if(enableWebSocket == null){ - return false; - } - return enableWebSocket; - } - - @Override - public boolean stopDependents() { - if(stopDependents == null){ - return super.stopDependents(); - } - return stopDependents; + return exactVersion; } public Boolean getEnable() { @@ -287,14 +229,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.pluginPath = pluginPath; } - public String getPluginConfigFilePath() { - return pluginConfigFilePath; - } - - public void setPluginConfigFilePath(String pluginConfigFilePath) { - this.pluginConfigFilePath = pluginConfigFilePath; - } - public String getPluginRestPathPrefix() { return pluginRestPathPrefix; } @@ -319,14 +253,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.enablePluginIdRestPathPrefix = enablePluginIdRestPathPrefix; } - public Boolean getEnableSwaggerRefresh() { - return enableSwaggerRefresh; - } - - public void setEnableSwaggerRefresh(Boolean enableSwaggerRefresh) { - this.enableSwaggerRefresh = enableSwaggerRefresh; - } - public String getBackupPath() { return backupPath; } @@ -351,20 +277,12 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.version = version; } - public Boolean getExactVersionAllowed() { - return exactVersionAllowed; + public Boolean getExactVersion() { + return exactVersion; } - public void setExactVersionAllowed(Boolean exactVersionAllowed) { - this.exactVersionAllowed = exactVersionAllowed; - } - - public Boolean getStopDependents() { - return stopDependents; - } - - public void setStopDependents(Boolean stopDependents) { - this.stopDependents = stopDependents; + public void setExactVersion(Boolean exactVersion) { + this.exactVersion = exactVersion; } public Set getEnablePluginIds() { @@ -391,11 +309,4 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio this.sortInitPluginIds = sortInitPluginIds; } - public Boolean getEnableWebSocket() { - return enableWebSocket; - } - - public void setEnableWebSocket(Boolean enableWebSocket) { - this.enableWebSocket = enableWebSocket; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java deleted file mode 100644 index 3caf8d6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ConfigurationBuilder.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.gitee.starblues.integration; - -import com.gitee.starblues.core.RuntimeMode; -import org.springframework.util.ObjectUtils; - -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * 通过构造者进行配置插件初始化配置 - * - * @author starBlues - * @version 2.4.4 - */ -@Deprecated -public class ConfigurationBuilder extends DefaultIntegrationConfiguration{ - - private final boolean enable; - - private final RuntimeMode runtimeMode; - private final List pluginPath; - private final String pluginConfigFilePath; - - private final String uploadTempPath; - private final String backupPath; - private final String pluginRestPathPrefix; - - private final Boolean enablePluginIdRestPathPrefix; - - private final Set enablePluginIds; - private final Set disablePluginIds; - private final List sortInitPluginIds; - private final Boolean enableSwaggerRefresh; - - private final String version; - private final Boolean exactVersionAllowed; - - private final Boolean enableWebSocket; - - private final Boolean stopDependents; - - public ConfigurationBuilder(Builder builder) { - this.runtimeMode = Objects.requireNonNull(builder.runtimeMode, "runtimeMode can't be empty"); - if(ObjectUtils.isEmpty(builder.pluginPath)){ - throw new IllegalArgumentException("pluginPath can't be empty"); - } - this.pluginPath = builder.pluginPath; - this.pluginConfigFilePath = Objects.requireNonNull(builder.pluginConfigFilePath, - "pluginConfigFilePath can't be empty"); - this.uploadTempPath = builder.uploadTempPath; - this.backupPath = builder.backupPath; - this.pluginRestPathPrefix = builder.pluginRestPathPrefix; - this.enablePluginIdRestPathPrefix = builder.enablePluginIdRestPathPrefix; - this.enablePluginIds = builder.enablePluginIds; - this.disablePluginIds = builder.disablePluginIds; - this.sortInitPluginIds = builder.sortInitPluginIds; - this.version = builder.version; - this.exactVersionAllowed = builder.exactVersionAllowed; - if(builder.enable == null){ - this.enable = true; - } else { - this.enable = builder.enable; - } - if(builder.enableSwaggerRefresh == null){ - this.enableSwaggerRefresh = true; - } else { - this.enableSwaggerRefresh = builder.enableSwaggerRefresh; - } - if(builder.enableWebSocket == null){ - this.enableWebSocket = false; - } else { - this.enableWebSocket = builder.enableWebSocket; - } - if(builder.stopDependents == null){ - this.stopDependents = false; - } else { - this.stopDependents = builder.stopDependents; - } - } - - public static Builder toBuilder(){ - return new Builder(); - } - - public static class Builder{ - - private Boolean enable; - - private RuntimeMode runtimeMode = RuntimeMode.DEV; - private List pluginPath; - private String pluginConfigFilePath = ""; - - private String uploadTempPath; - private String backupPath; - private String pluginRestPathPrefix; - private Boolean enablePluginIdRestPathPrefix; - - private Set enablePluginIds; - private Set disablePluginIds; - private List sortInitPluginIds; - private Boolean enableSwaggerRefresh; - - private String version; - private Boolean exactVersionAllowed; - - private Boolean enableWebSocket; - - private Boolean stopDependents; - - public Builder runtimeMode(RuntimeMode runtimeMode){ - this.runtimeMode = runtimeMode; - return this; - } - - public Builder enable(Boolean enable){ - this.enable = enable; - return this; - } - - public Builder pluginPath(List pluginPath){ - this.pluginPath = pluginPath; - return this; - } - - public Builder pluginConfigFilePath(String pluginConfigFilePath){ - this.pluginConfigFilePath = pluginConfigFilePath; - return this; - } - - public Builder uploadTempPath(String uploadTempPath){ - this.uploadTempPath = uploadTempPath; - return this; - } - - public Builder backupPath(String backupPath){ - this.backupPath = backupPath; - return this; - } - - public Builder pluginRestPathPrefix(String pluginRestPathPrefix){ - this.pluginRestPathPrefix = pluginRestPathPrefix; - return this; - } - - public Builder enablePluginIdRestPathPrefix(Boolean enablePluginIdRestPathPrefix){ - this.enablePluginIdRestPathPrefix = enablePluginIdRestPathPrefix; - return this; - } - - public Builder enablePluginIds(Set enablePluginIds){ - this.enablePluginIds = enablePluginIds; - return this; - } - - public Builder disablePluginIds(Set disablePluginIds){ - this.disablePluginIds = disablePluginIds; - return this; - } - - public Builder sortInitPluginIds(List sortInitPluginIds){ - this.sortInitPluginIds = sortInitPluginIds; - return this; - } - - public Builder enableSwaggerRefresh(Boolean enableSwaggerRefresh){ - this.enableSwaggerRefresh = enableSwaggerRefresh; - return this; - } - - public Builder version(String version){ - this.version = version; - return this; - } - - public Builder exactVersionAllowed(Boolean exactVersionAllowed){ - this.exactVersionAllowed = exactVersionAllowed; - return this; - } - - public Builder enableWebSocket(Boolean enableWebSocket){ - this.enableWebSocket = enableWebSocket; - return this; - } - - public Builder stopDependents(Boolean stopDependents){ - this.stopDependents = stopDependents; - return this; - } - - public ConfigurationBuilder build(){ - return new ConfigurationBuilder(this); - } - - } - - - @Override - public RuntimeMode environment() { - return runtimeMode; - } - - @Override - public String mainPackage() { - return null; - } - @Override - public List pluginPath() { - if(ObjectUtils.isEmpty(pluginPath)){ - return super.pluginPath(); - } - return pluginPath; - } - - @Override - public String pluginConfigFilePath() { - return pluginConfigFilePath; - } - - - @Override - public String uploadTempPath() { - if(!ObjectUtils.isEmpty(uploadTempPath)){ - return super.uploadTempPath(); - } else { - return uploadTempPath; - } - } - - @Override - public String backupPath() { - if(!ObjectUtils.isEmpty(backupPath)){ - return super.backupPath(); - } else { - return backupPath; - } - } - - @Override - public String pluginRestPathPrefix() { - if(!ObjectUtils.isEmpty(pluginRestPathPrefix)){ - return super.pluginRestPathPrefix(); - } else { - return pluginRestPathPrefix; - } - } - - @Override - public boolean enablePluginIdRestPathPrefix() { - if(enablePluginIdRestPathPrefix == null){ - return super.enablePluginIdRestPathPrefix(); - } else { - return enablePluginIdRestPathPrefix; - } - } - - @Override - public boolean enable() { - return enable; - } - - @Override - public Set enablePluginIds() { - return enablePluginIds; - } - - @Override - public Set disablePluginIds() { - return disablePluginIds; - } - - @Override - public List sortInitPluginIds() { - return sortInitPluginIds; - } - - @Override - public boolean enableSwaggerRefresh() { - return enableSwaggerRefresh; - } - - @Override - public String version() { - if(!ObjectUtils.isEmpty(version)){ - return super.version(); - } - return version; - } - - @Override - public boolean exactVersionAllowed() { - if(exactVersionAllowed == null){ - return super.exactVersionAllowed(); - } - return exactVersionAllowed; - } - - @Override - public boolean enableWebSocket() { - return enableWebSocket; - } - - @Override - public boolean stopDependents() { - return stopDependents; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index 7643b23..4ccb689 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.utils.Assert; import org.springframework.http.CacheControl; import java.util.ArrayList; @@ -44,11 +45,6 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf return "backupPlugin"; } - @Override - public boolean enablePluginRestController() { - return true; - } - @Override public String pluginRestPathPrefix(){ return DEFAULT_PLUGIN_REST_PATH_PREFIX; @@ -69,11 +65,6 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf return null; } - @Override - public boolean enableSwaggerRefresh() { - return true; - } - @Override public List sortInitPluginIds() { return null; @@ -85,17 +76,16 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf } @Override - public boolean exactVersionAllowed() { + public boolean exactVersion() { return false; } + /** + * 检查配置 + */ @Override - public boolean enableWebSocket() { - return false; + public void checkConfig(){ + Assert.isNotEmpty(mainPackage(), "插件配置: mainPackage 不能为空"); } - @Override - public boolean stopDependents() { - return false; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java similarity index 55% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java index ee932c3..889e7b0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationExtendPoint.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java @@ -1,9 +1,9 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.DefaultRealizeProvider; -import com.gitee.starblues.core.RealizeProvider; -import com.gitee.starblues.core.classloader.DefaultMainResourcePatternDefiner; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; +import com.gitee.starblues.core.RealizeProvider;; +import com.gitee.starblues.core.launcher.plugin.BasicMainResourcePatternDefiner; +import com.gitee.starblues.integration.listener.SwaggerListener; import com.gitee.starblues.integration.operator.DefaultPluginOperator; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; @@ -11,31 +11,28 @@ import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; import com.gitee.starblues.spring.extract.ExtractFactory; import com.gitee.starblues.spring.web.PluginStaticResourceConfig; -import com.gitee.starblues.spring.web.PluginStaticResourceResolver; import com.gitee.starblues.spring.web.PluginStaticResourceWebMvcConfigurer; import com.gitee.starblues.spring.web.thymeleaf.PluginThymeleafInvolved; import org.springframework.boot.autoconfigure.condition.*; -import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.servlet.resource.ResourceResolver; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.templatemode.TemplateMode; -import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; -import org.thymeleaf.templateresolver.ITemplateResolver; +import springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper; /** - * 集成扩展点 + * 系统Bean配置 * @author starBlues * @version 3.0.0 */ -public class IntegrationExtendPoint { +public class ExtendPointConfiguration { private final GenericApplicationContext applicationContext; private final IntegrationConfiguration configuration; - public IntegrationExtendPoint(GenericApplicationContext applicationContext, - IntegrationConfiguration configuration) { + public ExtendPointConfiguration(GenericApplicationContext applicationContext, + IntegrationConfiguration configuration) { this.applicationContext = applicationContext; this.configuration = configuration; } @@ -60,45 +57,20 @@ public class IntegrationExtendPoint { @Bean @ConditionalOnMissingBean public RealizeProvider realizeProvider() { - DefaultRealizeProvider defaultRealizeProvider = new DefaultRealizeProvider(configuration.environment()); + DefaultRealizeProvider defaultRealizeProvider = new DefaultRealizeProvider(configuration, applicationContext); defaultRealizeProvider.init(); return defaultRealizeProvider; } @Bean - @ConditionalOnMissingBean - public MainResourcePatternDefiner mainResourcePatternDefiner(){ - return new DefaultMainResourcePatternDefiner(configuration.mainPackage()); - } - - @Bean - @ConditionalOnClass(ResourceResolver.class) - @ConditionalOnWebApplication - @ConditionalOnMissingBean - public PluginStaticResourceWebMvcConfigurer pluginWebResourceResolver(PluginStaticResourceConfig resourceConfig){ - return new PluginStaticResourceWebMvcConfigurer(resourceConfig); - } - - @Bean - @ConditionalOnClass(ResourceResolver.class) - @ConditionalOnWebApplication - @ConditionalOnMissingBean - public PluginStaticResourceConfig pluginStaticResourceConfig(){ - return new PluginStaticResourceConfig(); + public ExtractFactory extractFactory(){ + return ExtractFactory.getInstant(); } @Bean - @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class }) - @ConditionalOnWebApplication - @ConditionalOnProperty(name = "spring.thymeleaf.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnMissingBean - public PluginThymeleafInvolved pluginThymeleafInvolved(){ - return new PluginThymeleafInvolved(); - } - - @Bean - public ExtractFactory extractFactory(){ - return ExtractFactory.getInstant(); + public BasicMainResourcePatternDefiner mainResourcePatternDefiner(){ + return new BasicMainResourcePatternDefiner(configuration.mainPackage()); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java new file mode 100644 index 0000000..2df20b7 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java @@ -0,0 +1,61 @@ +package com.gitee.starblues.integration; + +import com.gitee.starblues.integration.listener.SwaggerListener; +import com.gitee.starblues.spring.web.PluginStaticResourceConfig; +import com.gitee.starblues.spring.web.PluginStaticResourceWebMvcConfigurer; +import com.gitee.starblues.spring.web.thymeleaf.PluginThymeleafInvolved; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.web.servlet.resource.ResourceResolver; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.templatemode.TemplateMode; +import springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper; + +/** + * 系统web环境配置点 + * @author starBlues + * @version 3.0.0 + */ +@ConditionalOnWebApplication +public class ExtendPointWebConfiguration { + + private final GenericApplicationContext applicationContext; + + public ExtendPointWebConfiguration(GenericApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Bean + @ConditionalOnClass(ResourceResolver.class) + @ConditionalOnMissingBean + public PluginStaticResourceWebMvcConfigurer pluginWebResourceResolver(PluginStaticResourceConfig resourceConfig){ + return new PluginStaticResourceWebMvcConfigurer(resourceConfig); + } + + @Bean + @ConditionalOnClass(ResourceResolver.class) + @ConditionalOnMissingBean + public PluginStaticResourceConfig pluginStaticResourceConfig(){ + return new PluginStaticResourceConfig(); + } + + @Bean + @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class }) + @ConditionalOnProperty(name = "spring.thymeleaf.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnMissingBean + public PluginThymeleafInvolved pluginThymeleafInvolved(){ + return new PluginThymeleafInvolved(); + } + + @Bean + @ConditionalOnClass({ DocumentationPluginsBootstrapper.class }) + @ConditionalOnMissingBean + public SwaggerListener swaggerListener(){ + return new SwaggerListener(applicationContext); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index 66efc34..d2b835b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -1,7 +1,9 @@ package com.gitee.starblues.integration; +import com.gitee.starblues.common.Constants; import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.utils.ObjectUtils; import org.springframework.http.CacheControl; import java.util.List; @@ -40,14 +42,6 @@ public interface IntegrationConfiguration { */ List pluginPath(); - /** - * 插件文件的配置路径。在生产环境下, 插件的配置文件路径。 - * 在生产环境下, 请将所有插件使用到的配置文件统一放到该路径下管理。 - * 在开发环境下,配置为空串。程序会自动从 resources 获取配置文件, 所以请确保编译后的target 下存在该配置文件 - * @return 插件文件的配置路径 - */ - String pluginConfigFilePath(); - /** * 上传插件包存储的临时路径。默认 temp(相对于主程序jar路径)。 * @return 上传插件的临时保存路径。 @@ -60,12 +54,6 @@ public interface IntegrationConfiguration { */ String backupPath(); - /** - * 是否启用插件的 rest controller 接口注册. 默认启用 - * @return true 启用, false 禁用 - */ - boolean enablePluginRestController(); - /** * 插件 RestController 统一请求的路径前缀 * @return path @@ -93,12 +81,6 @@ public interface IntegrationConfiguration { */ Set disablePluginIds(); - /** - * 是否启用Swagger刷新机制 - * @return 启用返回true, 不启用返回 false - */ - boolean enableSwaggerRefresh(); - /** * 设置初始化时插件启动的顺序. * @return 有顺序的插件id @@ -108,7 +90,7 @@ public interface IntegrationConfiguration { /** * 当前主程序的版本号, 用于校验插件是否可安装. * 插件中可通过插件配置信息 requires 来指定可安装的主程序版本 - * @return 系统版本号, 如果为: 0.0.0 的话, 表示不校验 + * @return 系统版本号, 如果为为空或者 0.0.0 表示不校验 */ String version(); @@ -118,19 +100,43 @@ public interface IntegrationConfiguration { * 默认为false * @return true or false */ - boolean exactVersionAllowed(); + boolean exactVersion(); + + + /** + * 检查配置 + */ + default void checkConfig(){}; /** - * 是否启用webSocket功能. 如需启用, 则需要引入springboot支持的WebSocket依赖 - * @return 启用返回true,不启用返回false + * 是否被启动 + * @param pluginId 插件id + * @return true: 启用, false: 未启用 */ - boolean enableWebSocket(); + default boolean isEnable(String pluginId){ + if(ObjectUtils.isEmpty(enablePluginIds())){ + return true; + } + if(isDisabled(pluginId)){ + return false; + } + return enablePluginIds().contains(pluginId); + } /** - * 停止插件时, 是否停止依赖的插件 - * @return 停止返回true,不停止返回false + * 是否被禁用 + * @param pluginId 插件id + * @return true: 禁用, false: 未禁用 */ - boolean stopDependents(); + default boolean isDisabled(String pluginId){ + if(ObjectUtils.isEmpty(disablePluginIds())){ + return false; + } + if(disablePluginIds().contains(Constants.DISABLED_ALL_PLUGIN)){ + return true; + } + return disablePluginIds().contains(pluginId); + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java index 8387a1a..f2fd9cc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java @@ -16,28 +16,6 @@ import java.util.List; */ public abstract class AbstractPluginApplication implements PluginApplication { - protected final PluginListenerFactory listenerFactory = new PluginListenerFactory(); - - @Override - public void addListener(PluginListener pluginListener) { - this.listenerFactory.addPluginListener(pluginListener); - } - - @Override - public void addListener(Class pluginListenerClass) { - listenerFactory.addPluginListener(pluginListenerClass); - } - - @Override - public void addListener(List pluginListeners) { - if(pluginListeners == null || pluginListeners.isEmpty()){ - return; - } - for (PluginListener pluginListener : pluginListeners) { - this.listenerFactory.addPluginListener(pluginListener); - } - } - /** * 子类可通过Application 获取插件定义的配置 * @param applicationContext applicationContext diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java index aedf7b7..46f7c5a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java @@ -1,6 +1,7 @@ package com.gitee.starblues.integration.application; -import com.gitee.starblues.integration.IntegrationExtendPoint; +import com.gitee.starblues.integration.ExtendPointConfiguration; +import com.gitee.starblues.integration.ExtendPointWebConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.PluginUser; @@ -16,7 +17,7 @@ import org.springframework.context.annotation.Import; * @author starBlues * @version 2.2.0 */ -@Import(IntegrationExtendPoint.class) +@Import({ExtendPointConfiguration.class, ExtendPointWebConfiguration.class}) public class AutoPluginApplication extends DefaultPluginApplication implements PluginApplication, ApplicationContextAware, ApplicationListener { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index ec7b847..7b4d676 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -48,8 +48,10 @@ public class DefaultPluginApplication extends AbstractPluginApplication { if(beInitialized.get()){ throw new RuntimeException("Plugin has been initialized"); } - // 检查Configuration + // 获取Configuration IntegrationConfiguration configuration = getConfiguration(applicationContext); + // 检查配置 + configuration.checkConfig(); createPluginUser(applicationContext); createPluginOperator(applicationContext); try { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java deleted file mode 100644 index 77f0f8a..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/EmptyPluginApplication.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.gitee.starblues.integration.application; - -import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.listener.PluginListener; -import com.gitee.starblues.integration.operator.EmptyPluginOperator; -import com.gitee.starblues.integration.operator.PluginOperator; -import com.gitee.starblues.integration.user.EmptyPluginUser; -import com.gitee.starblues.integration.user.PluginUser; -import org.springframework.context.ApplicationContext; - -import java.util.List; - -/** - * @author starBlues - * @version 1.0 - */ -public class EmptyPluginApplication implements PluginApplication{ - - - @Override - public void initialize(ApplicationContext applicationContext, PluginInitializerListener listener) { - - } - - @Override - public PluginOperator getPluginOperator() { - return new EmptyPluginOperator(); - } - - @Override - public PluginUser getPluginUser() { - return new EmptyPluginUser(); - } - - @Override - public void addListener(PluginListener pluginListener) { - - } - - @Override - public void addListener(Class pluginListenerClass) { - - } - - @Override - public void addListener(List pluginListeners) { - - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java index bd0b0a6..f8f377e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java @@ -11,7 +11,7 @@ import org.springframework.context.ApplicationContext; * @author starBlues * @version 2.4.3 */ -public interface PluginApplication extends PluginListenerContext { +public interface PluginApplication{ /** * 初始化 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/package-info.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/package-info.java deleted file mode 100644 index 262e0b3..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * 插件 PluginApplication 的实现包 - * - * @author starBlues - * @version 1.0 - */ -package com.gitee.starblues.integration.application; \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java index 71a936a..c5f7e6a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java @@ -1,19 +1,20 @@ package com.gitee.starblues.integration.listener; +import com.gitee.starblues.utils.SpringBeanUtils; import org.springframework.context.ApplicationContext; /** * 默认的初始化监听者。内置注册 * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DefaultInitializerListener implements PluginInitializerListener{ - public final ApplicationContext applicationContext; + private final SwaggerListener swaggerListener; public DefaultInitializerListener(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; + this.swaggerListener = SpringBeanUtils.getExistBean(applicationContext, SwaggerListener.class); } @@ -24,7 +25,9 @@ public class DefaultInitializerListener implements PluginInitializerListener{ @Override public void complete() { - + if(swaggerListener != null){ + swaggerListener.refresh(); + } } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java new file mode 100644 index 0000000..5fb9465 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java @@ -0,0 +1,119 @@ +package com.gitee.starblues.integration.listener; + +import com.gitee.starblues.core.PluginInfo; +import com.gitee.starblues.utils.SpringBeanUtils; +import org.springframework.context.ApplicationContext; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * 默认的插件工厂 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginListenerFactory implements PluginListenerFactory{ + + private final List listeners; + + public DefaultPluginListenerFactory(ApplicationContext applicationContext){ + listeners = SpringBeanUtils.getBeans(applicationContext, PluginListener.class); + addPluginListener(new SwaggerListener(applicationContext)); + } + + public DefaultPluginListenerFactory(){ + listeners = new ArrayList<>(); + } + + @Override + public synchronized void addPluginListener(PluginListener pluginListener) { + if(pluginListener != null){ + listeners.add(pluginListener); + } + } + + @Override + public List getListeners() { + return listeners; + } + + @Override + public void loadSuccess(PluginInfo pluginInfo) { + for (PluginListener listener : listeners) { + try { + listener.loadSuccess(pluginInfo); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void loadFailure(Path path, Throwable throwable) { + for (PluginListener listener : listeners) { + try { + listener.loadFailure(path, throwable); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void unLoadSuccess(PluginInfo pluginInfo) { + for (PluginListener listener : listeners) { + try { + listener.unLoadSuccess(pluginInfo); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void startSuccess(PluginInfo pluginInfo) { + for (PluginListener listener : listeners) { + try { + listener.startSuccess(pluginInfo); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void startFailure(PluginInfo pluginInfo, Throwable throwable) { + for (PluginListener listener : listeners) { + try { + listener.startFailure(pluginInfo, throwable); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void stopSuccess(PluginInfo pluginInfo) { + for (PluginListener listener : listeners) { + try { + listener.stopSuccess(pluginInfo); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void stopFailure(PluginInfo pluginInfo, Throwable throwable) { + for (PluginListener listener : listeners) { + try { + listener.stopFailure(pluginInfo, throwable); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java index c22c76c..9286882 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java @@ -1,40 +1,70 @@ package com.gitee.starblues.integration.listener; +import com.gitee.starblues.core.PluginInfo; + +import java.nio.file.Path; + /** - * 插件bean监听者 + * 插件监听者 * * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public interface PluginListener { + /** + * 加载插件成功 + * @param pluginInfo 插件信息 + */ + default void loadSuccess(PluginInfo pluginInfo){} /** - * 注册插件成功 - * @param pluginId 插件id - * @param isStartInitial 是否随着系统启动时而进行的插件注册 + * 加载失败 + * @param path 要加载的插件路径 + * @param throwable 异常信息 */ - void registry(String pluginId, boolean isStartInitial); + default void loadFailure(Path path, Throwable throwable){} /** * 卸载插件成功 - * @param pluginId 插件id + * @param pluginInfo 插件信息 + */ + default void unLoadSuccess(PluginInfo pluginInfo){} + + /** + * 卸载失败 + * @param pluginInfo 插件信息 + * @param throwable 异常信息 */ - void unRegistry(String pluginId); + default void unLoadFailure(PluginInfo pluginInfo, Throwable throwable){} /** - * 注册错误 - * @param pluginId 插件id + * 注册插件成功 + * @param pluginInfo 插件信息 + */ + default void startSuccess(PluginInfo pluginInfo){} + + + /** + * 启动失败 + * @param pluginInfo 插件信息 * @param throwable 异常信息 */ - void registryFailure(String pluginId, Throwable throwable); + default void startFailure(PluginInfo pluginInfo, Throwable throwable){} + + /** + * 卸载插件成功 + * @param pluginInfo 插件信息 + */ + default void stopSuccess(PluginInfo pluginInfo){} + /** - * 注册错误 - * @param pluginId 插件id + * 停止失败 + * @param pluginInfo 插件信息 * @param throwable 异常信息 */ - void unRegistryFailure(String pluginId, Throwable throwable); + default void stopFailure(PluginInfo pluginInfo, Throwable throwable){} } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java index 3be2863..b707735 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java @@ -1,148 +1,27 @@ package com.gitee.starblues.integration.listener; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.ArrayList; import java.util.List; -import java.util.Objects; /** * 插件监听工厂 * * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ -public class PluginListenerFactory implements PluginListener { - - private final List listeners = new ArrayList<>(); - private final List listenerClasses = new ArrayList<>(); - private boolean isBuildListenerClass = false; - - @Override - public void registry(String pluginId, boolean isInitialize) { - for (PluginListener listener : listeners) { - try { - listener.registry(pluginId, isInitialize); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - @Override - public void unRegistry(String pluginId) { - for (PluginListener listener : listeners) { - try { - listener.unRegistry(pluginId); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - @Override - public void registryFailure(String pluginId, Throwable throwable) { - for (PluginListener listener : listeners) { - try { - listener.registryFailure(pluginId, throwable); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - @Override - public void unRegistryFailure(String pluginId, Throwable throwable) { - for (PluginListener listener : listeners) { - try { - listener.unRegistryFailure(pluginId, throwable); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - +public interface PluginListenerFactory extends PluginListener { /** * 添加监听者 * * @param pluginListener 插件监听者 */ - public void addPluginListener(PluginListener pluginListener) { - if (pluginListener != null) { - listeners.add(pluginListener); - } - } - - /** - * 添加监听者 - * - * @param pluginListenerClass 插件监听者Class类 - * @param 插件监听者类。继承 PluginListener - */ - public void addPluginListener(Class pluginListenerClass) { - if (pluginListenerClass != null) { - synchronized (listenerClasses) { - listenerClasses.add(pluginListenerClass); - } - } - } - - public void buildListenerClass(GenericApplicationContext applicationContext) { - if (applicationContext == null) { - return; - } - synchronized (listenerClasses) { - if(isBuildListenerClass){ - return; - } - // 搜索Spring容器中的监听器 - List pluginListeners = SpringBeanUtils.getBeans(applicationContext, PluginListener.class); - if(pluginListeners.isEmpty()){ - pluginListeners = new ArrayList<>(); - } - for (Class listenerClass : listenerClasses) { - // 兼容 spring 4.x - applicationContext.registerBeanDefinition(listenerClass.getName(), - BeanDefinitionBuilder.genericBeanDefinition(listenerClass).getBeanDefinition()); - T bean = applicationContext.getBean(listenerClass); - pluginListeners.add(bean); - } - for (PluginListener pluginListener : pluginListeners) { - boolean find = false; - for (PluginListener listener : listeners) { - if(Objects.equals(listener, pluginListener)){ - find = true; - break; - } - } - // 防止监听器重复注册 - if(!find){ - listeners.add(pluginListener); - } - } - listenerClasses.clear(); - isBuildListenerClass = true; - } - } + void addPluginListener(PluginListener pluginListener); /** * 得到监听者 * * @return 监听者集合 */ - public List getListeners() { - return listeners; - } + List getListeners(); - /** - * 得到监听者class - * - * @return 监听者class集合 - */ - public List getListenerClasses() { - return listenerClasses; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListeningListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java similarity index 69% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListeningListener.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java index 41ebd26..daa7eb1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListeningListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java @@ -1,5 +1,6 @@ package com.gitee.starblues.integration.listener; +import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.utils.SpringBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,41 +10,26 @@ import springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapp /** * Swagger 监听事件 * @author starBlues - * @version 2.4.0 + * @version 3.0.0 */ -public class SwaggerListeningListener implements PluginListener{ +public class SwaggerListener implements PluginListener{ private final Logger log = LoggerFactory.getLogger(this.getClass()); private final ApplicationContext mainApplicationContext; - public SwaggerListeningListener(ApplicationContext mainApplicationContext) { + public SwaggerListener(ApplicationContext mainApplicationContext) { this.mainApplicationContext = mainApplicationContext; } @Override - public void registry(String pluginId, boolean isInitialize) { - if(isInitialize){ + public void startSuccess(PluginInfo pluginInfo) { + if(pluginInfo.isFollowSystem()){ return; } refresh(); } - @Override - public void unRegistry(String pluginId) { - refresh(); - } - - @Override - public void registryFailure(String pluginId, Throwable throwable) { - - } - - @Override - public void unRegistryFailure(String pluginId, Throwable throwable) { - - } - - private void refresh(){ + void refresh(){ try { DocumentationPluginsBootstrapper documentationPluginsBootstrapper = SpringBeanUtils.getExistBean(mainApplicationContext, DocumentationPluginsBootstrapper.class); @@ -59,5 +45,4 @@ public class SwaggerListeningListener implements PluginListener{ } } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java deleted file mode 100644 index c150b8c..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/DefaultPluginManagerFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.gitee.starblues.integration.manager; - -import com.gitee.starblues.core.*; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.utils.Assert; - -import java.util.List; - -/** - * 默认的 PluginManagerFactory - * @author starBlues - * @version 3.0.0 - */ -@Deprecated -public class DefaultPluginManagerFactory implements PluginManagerFactory{ - - private final IntegrationConfiguration configuration; - - public DefaultPluginManagerFactory(IntegrationConfiguration configuration) { - this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); - } - - @Override - public PluginManager getPluginManager() { - RuntimeMode runtimeMode = Assert.isNotEmpty(configuration.environment(), - "配置[environment]不能为空"); - String mainPackageName = Assert.isNotEmpty(configuration.mainPackage(), - "配置[mainPackage]不能为空"); - List pluginPaths = Assert.isNotEmpty(configuration.pluginPath(), - "配置[pluginPath]不能为空"); - RealizeProvider realizeProvider = new DefaultRealizeProvider(runtimeMode); - return new DefaultPluginManager(realizeProvider, pluginPaths); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java deleted file mode 100644 index 1d62aeb..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/manager/PluginManagerFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.gitee.starblues.integration.manager; - -import com.gitee.starblues.core.PluginManager; - -/** - * PluginManager 工厂 - * @author starBlues - * @version 3.0.0 - */ -public interface PluginManagerFactory { - - /** - * 得到 PluginManager - * @return PluginManager - */ - PluginManager getPluginManager(); - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 337d3b9..2bfe953 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -2,6 +2,7 @@ package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.*; import com.gitee.starblues.core.exception.PluginDisabledException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.listener.PluginInitializerListenerFactory; @@ -162,6 +163,10 @@ public class DefaultPluginOperator implements PluginOperator { @Override public boolean stop(String pluginId) throws PluginException { + PluginInfo pluginInfo = pluginManager.getPluginInfo(pluginId); + if(pluginInfo == null){ + throw new PluginException("没有发现插件: " + pluginId); + } return pluginManager.stop(pluginId) != null; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java index e7f9abc..dac4fdf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java @@ -1,14 +1,12 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.upload.UploadParam; -import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; import java.util.List; -import java.util.Set; /** * @author starBlues diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java index 44d5f8b..733eb55 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java @@ -1,22 +1,19 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.upload.UploadByInputStreamParam; import com.gitee.starblues.integration.operator.upload.UploadByMultipartFileParam; import com.gitee.starblues.integration.operator.upload.UploadParam; -import org.springframework.web.multipart.MultipartFile; -import java.io.InputStream; import java.nio.file.Path; import java.util.List; -import java.util.Set; /** * 操作插件的接口 * @author starBlues - * @version 2.4.4 + * @version 3.0.0 * @see DefaultPluginOperator */ public interface PluginOperator { @@ -31,11 +28,11 @@ public interface PluginOperator { /** * 校验插件jar包 - * @param jarPath 插件包的路径 + * @param pluginPath 插件包的路径 * @return 成功: 返回true; 失败: 抛出异常或者返回false * @throws PluginException 校验异常 */ - boolean verify(Path jarPath) throws PluginException; + boolean verify(Path pluginPath) throws PluginException; /** * 解析插件包 @@ -48,12 +45,12 @@ public interface PluginOperator { /** * 通过路径安装插件(会启用), 该插件文件必须存在于服务器 [适用于生产环境] * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar - * @param jarPath 插件路径 + * @param pluginPath 插件路径 * @param unpackPlugin 是否解压插件包. (如果插件包为压缩包时生效) * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null * @throws PluginException 异常信息 */ - PluginInfo install(Path jarPath, boolean unpackPlugin) throws PluginException; + PluginInfo install(Path pluginPath, boolean unpackPlugin) throws PluginException; /** * 卸载插件 [适用于生产环境] diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index 3de3890..ac7e068 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -1,18 +1,16 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.PluginException; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.upload.UploadParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; import java.util.Collections; import java.util.List; -import java.util.Set; /** * 插件操作包装者 @@ -24,12 +22,12 @@ public class PluginOperatorWrapper implements PluginOperator{ protected final Logger log = LoggerFactory.getLogger(this.getClass()); private final PluginOperator pluginOperator; - private final IntegrationConfiguration integrationConfiguration; + private final IntegrationConfiguration configuration; public PluginOperatorWrapper(PluginOperator pluginOperator, - IntegrationConfiguration integrationConfiguration) { + IntegrationConfiguration configuration) { this.pluginOperator = pluginOperator; - this.integrationConfiguration = integrationConfiguration; + this.configuration = configuration; } @Override @@ -77,7 +75,6 @@ public class PluginOperatorWrapper implements PluginOperator{ if(isDisable()){ return; } - checkIsUnRegistry(pluginId); pluginOperator.uninstall(pluginId, isDelete, isBackup); } @@ -102,7 +99,6 @@ public class PluginOperatorWrapper implements PluginOperator{ if(isDisable()){ return false; } - checkIsUnRegistry(pluginId); return pluginOperator.stop(pluginId); } @@ -151,7 +147,7 @@ public class PluginOperatorWrapper implements PluginOperator{ * @return true 禁用 */ private boolean isDisable(){ - if(integrationConfiguration.enable()){ + if(configuration.enable()){ return false; } // 如果禁用的话, 直接返回 @@ -159,31 +155,4 @@ public class PluginOperatorWrapper implements PluginOperator{ return true; } - /** - * 检查是否可卸载 - * @param pluginId 插件id - * @throws Exception 检查异常 - */ - private void checkIsUnRegistry(String pluginId) throws PluginException{ -// ConfigurableApplicationContext pluginApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); -// if(pluginApplicationContext == null){ -// log.error("Plugin '{}' Not found ApplicationContext. So cannot found and execute unRegistryValidator", -// pluginId); -// return; -// } -// List unRegistryValidators = SpringBeanUtils.getBeans(pluginApplicationContext, UnRegistryValidator.class); -// for (UnRegistryValidator unRegistryValidator : unRegistryValidators) { -// UnRegistryValidator.Result result = unRegistryValidator.verify(); -// if(result.isVerify()){ -// return; -// } -// String message = result.getMessage(); -// if(StringUtils.isNullOrEmpty(message)){ -// message = "Plugin [" + pluginId + "] Stop or Uninstall be banned"; -// } -// throw new Exception(message); -// } - } - - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractPluginSpringBeanRefresh.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractPluginSpringBeanRefresh.java deleted file mode 100644 index 6b625a4..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractPluginSpringBeanRefresh.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.gitee.starblues.integration.refresh; - -import com.gitee.starblues.integration.application.PluginApplication; - -import java.util.List; - -/** - * 抽象的插件SpringBean刷新类监听类. - * 继承该类。在插件动态的注册卸载时, refresh方法被触发, 可以获取到当前环境所有T实现的所有beans(不包括主程序中的beans) - * - * @author starBlues - * @version 2.0.2 - */ -public abstract class AbstractPluginSpringBeanRefresh extends AbstractSpringBeanRefresh { - - - public AbstractPluginSpringBeanRefresh(PluginApplication pluginApplication) { - super(pluginApplication); - } - - - /** - * 刷新bean - */ - @Override - protected List refresh(){ - return pluginApplication - .getPluginUser() - .getPluginBeans(typeClass); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractSpringBeanRefresh.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractSpringBeanRefresh.java deleted file mode 100644 index d553a3a..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/refresh/AbstractSpringBeanRefresh.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.gitee.starblues.integration.refresh; - -import com.gitee.starblues.integration.application.PluginApplication; -import com.gitee.starblues.integration.listener.PluginListener; - -import java.lang.reflect.ParameterizedType; -import java.util.List; - -/** - * 抽象的SpringBean刷新类监听类. - * 继承该类。在插件动态的注册卸载时, refresh方法被触发, 可以获取到当前环境所有T实现的所有beans(包括主程序中的beans) - * - * @author starBlues - * @version 2.4.0 - */ -public abstract class AbstractSpringBeanRefresh implements PluginListener { - - private List beans; - - protected final Class typeClass; - protected final PluginApplication pluginApplication; - - - public AbstractSpringBeanRefresh(PluginApplication pluginApplication) { - this.pluginApplication = pluginApplication; - pluginApplication.addListener(this); - this.typeClass = (Class)((ParameterizedType)getClass() - .getGenericSuperclass()) - .getActualTypeArguments()[0]; - } - - @Override - public void registry(String pluginId, boolean isInitialize) { - this.beans = refresh(); - registryEvent(beans); - } - - @Override - public void unRegistry(String pluginId) { - this.beans = refresh(); - unRegistryEvent(beans); - } - - /** - * 注册事件 - * @param beans 当前所有实现的bean - */ - protected void registryEvent(List beans){ - - } - - /** - * 卸载事件 - * @param beans 当前卸载后所有的beans - */ - protected void unRegistryEvent(List beans){ - - } - - /** - * 刷新bean - * @return 返回刷新后的Bean集合 - */ - protected List refresh(){ - return pluginApplication - .getPluginUser() - .getBeans(typeClass); - } - - - /** - * 得到beans - * @return beansMap - */ - public List getBeans() { - return beans; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigBean.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigBean.java deleted file mode 100644 index 73f6f82..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigBean.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.realize; - -/** - * 插件可配置自定义bean的接口。 - * 注意:该实现类只能注入插件中的配置文件和主程序bean. 不能注入插件中其他的组件bean。 - * bean 指的是Spring 容器中管理的bean - * - * @author starBlues - * @version 2.4.0 - */ -public interface ConfigBean { - - - /** - * 初始化。所有bean的初始化工作在此处实现 - * @throws Exception 初始化异常 - */ - void initialize() throws Exception; - - /** - * 销毁实现 - * @throws Exception 销毁异常 - */ - void destroy() throws Exception; - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java deleted file mode 100644 index a3f600e..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/ConfigDefinitionTip.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.gitee.starblues.realize; - -import com.gitee.starblues.integration.operator.module.PluginInfo; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.context.ApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * 给系统中所有ConfigDefinition 提供一个小工具类。可通过它获取主程序的某些bean. 和当前插件一些信息 - * @author starBlues - * @version 2.4.2 - */ -public class ConfigDefinitionTip { - -// private final PluginRegistryInfo pluginRegistryInfo; -// -// public ConfigDefinitionTip(PluginRegistryInfo pluginRegistryInfo) { -// this.pluginRegistryInfo = pluginRegistryInfo; -// } -// -// /** -// * 得到当前插件信息 -// * @return 插件信息 -// */ -// public PluginInfo getCurrentPluginInfo(){ -// PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); -// PluginManager pluginManager = pluginWrapper.getPluginManager(); -//// return new PluginInfo(pluginWrapper.getDescriptor(), pluginWrapper.getPluginState(), -//// pluginWrapper.getPluginPath().toAbsolutePath().toString(), -//// pluginManager.getRuntimeMode().toString()); -// return null; -// } -// -// /** -// * 得到主程序的 ApplicationContext -// * @return ApplicationContext -// */ -// public ApplicationContext getMainApplication() { -// return pluginRegistryInfo.getMainApplicationContext(); -// } -// -// /** -// * 获取当前插件的其他的ConfigDefinition -// * @param configDefinitionClass ConfigDefinition的类类型 -// * @param 类类型 -// * @return T -// */ -// public T getOtherConfigDefinition(Class configDefinitionClass){ -// return SpringBeanUtils.getObjectClass( -// pluginRegistryInfo.getConfigSingletons(), -// configDefinitionClass); -// } -// -// /** -// * 将Springboot类型的配置文件中的值映射为bean -// * 注意: 只针对插件扩展的 springboot 配置文件生效 -// * @param prefix 配置文件中的前置, 比如: plugin.config -// * @param type 配置文件中结构对应的类类型, 比如: plugin.config 下定义的键值对和type类类型一致 -// * @param 类类型 -// * @return T -// */ -// public T getConfigOfBean(String prefix, Class type){ -// return pluginRegistryInfo.getPluginBinder() -// .bind(prefix, Bindable.of(type)) -// .orElseGet(() -> null); -// } -// -// /** -// * 将Springboot类型的配置文件中的值映射为 List -// * 注意: 只针对插件扩展的 springboot 配置文件生效 -// * @param prefix 配置文件中的前置, 比如: plugin.config -// * @param type List元素的类类型 -// * @param List中定义的类类型 -// * @return List -// */ -// public List getConfigOfList(String prefix, Class type){ -// return pluginRegistryInfo.getPluginBinder() -// .bind(prefix, Bindable.listOf(type)) -// .orElseGet(Collections::emptyList); -// } -// -// /** -// * 将Springboot类型的配置文件中的值映射为 Set -// * 注意: 只针对插件扩展的 springboot 配置文件生效 -// * @param prefix 配置文件中的前置, 比如: plugin.config -// * @param type Set元素的类类型 -// * @param 类类型 -// * @return Set -// */ -// public Set getConfigOfSet(String prefix, Class type){ -// return pluginRegistryInfo.getPluginBinder() -// .bind(prefix, Bindable.setOf(type)) -// .orElseGet(Collections::emptySet); -// } -// -// -// /** -// * 将Springboot类型的配置文件中的值映射为 Map -// * 注意: 只针对插件扩展的 springboot 配置文件生效 -// * @param prefix 配置文件中的前置, 比如: plugin.config -// * @param keyType map的key元素类型 -// * @param valueType map的值元素类型 -// * @param map key 元素的类类型 -// * @param map value 元素的类类型 -// * @return Map -// */ -// public Map getConfigOfSet(String prefix, Class keyType, Class valueType){ -// return pluginRegistryInfo.getPluginBinder() -// .bind(prefix, Bindable.mapOf(keyType, valueType)) -// .orElseGet(Collections::emptyMap); -// } -// -// -// /** -// * 返回当前插件的ConfigurableEnvironment -// * @return ConfigurableEnvironment -// */ -// public ConfigurableEnvironment getPluginEnvironment(){ -// return pluginRegistryInfo.getPluginApplicationContext().getEnvironment(); -// } -// -// /** -// * 返回当前插件的Binder -// * @return Binder -// */ -// public Binder getPluginBinder(){ -// return pluginRegistryInfo.getPluginBinder(); -// } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java deleted file mode 100644 index bfd80d6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/realize/PluginUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.gitee.starblues.realize; - -import com.gitee.starblues.core.descriptor.PluginDescriptor; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.springframework.context.ApplicationContext; - -import java.util.List; - -/** - * 插件工具类 - * @author starBlues - * @version 2.4.0 - */ -public class PluginUtils { - - protected final ApplicationContext mainApplicationContext; - protected ApplicationContext pluginApplicationContext; - protected PluginDescriptor pluginDescriptor; - - @Deprecated - public PluginUtils(ApplicationContext mainApplicationContext, - ApplicationContext pluginApplicationContext, - PluginDescriptor pluginDescriptor) { - this.mainApplicationContext = mainApplicationContext; - this.pluginApplicationContext = pluginApplicationContext; - this.pluginDescriptor = pluginDescriptor; - } - - public PluginUtils(ApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - this.pluginApplicationContext = null; - this.pluginDescriptor = null; - } - - - /** - * 获取主程序的 ApplicationContext - * @return ApplicationContext - */ - public ApplicationContext getMainApplicationContext() { - return mainApplicationContext; - } - - /** - * 获取当前插件的 ApplicationContext - * @return ApplicationContext - */ - @Deprecated - public ApplicationContext getPluginApplicationContext() { - return pluginApplicationContext; - } - - /** - * 获取当前插件的描述信息 - * @return PluginDescriptor - */ - @Deprecated - public PluginDescriptor getPluginDescriptor(){ - return pluginDescriptor; - } - - - /** - * 通过 bean名称得到主程序中的bean - * @param name bean 名称 - * @param bean 类型 - * @return bean - */ - public T getMainBean(String name){ - Object bean = mainApplicationContext.getBean(name); - if(bean == null){ - return null; - } - return (T) bean; - } - - /** - * 通过bean类型得到主程序中的bean - * @param aClass bean 类型 - * @param bean 类型 - * @return bean - */ - public T getMainBean(Class aClass) { - return mainApplicationContext.getBean(aClass); - } - - /** - * 通过接口或者抽象类类型得到主程序中的多个实现对象 - * @param aClass bean 类型 - * @param bean 类型 - * @return bean - */ - public List getMainBeans(Class aClass){ - return SpringBeanUtils.getBeans(mainApplicationContext, aClass); - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java index 1c05f51..dfb8502 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java @@ -1,6 +1,7 @@ package com.gitee.starblues.spring; +import com.gitee.starblues.core.exception.PluginProhibitStopException; import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; /** @@ -10,6 +11,12 @@ import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; */ public interface SpringPluginHook extends AutoCloseable{ + /** + * 停止前校验. 如果抛出 PluginProhibitStopException 异常, 表示当前插件不可停止 + * @throws PluginProhibitStopException 插件禁止停止 + */ + void stopVerify() throws PluginProhibitStopException; + /** * 返回插件 ApplicationContext * @return ApplicationContext diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java index 3a7c759..cb3d3d0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java @@ -15,6 +15,13 @@ public abstract class MsgUtils { return pluginDescriptor.getPluginId() + "@" + pluginDescriptor.getPluginVersion(); } + public static String getPluginUnique(String pluginId, String version){ + if(ObjectUtils.isEmpty(version)){ + return pluginId; + } + return pluginId + "@" + version; + } + public static String getThrowableMsg(Throwable throwable){ return ObjectUtils.isEmpty(throwable.getMessage()) ? "" : throwable.getMessage(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index a50ce45..862d900 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -37,6 +37,7 @@ public class ResourceUtils { public static final String FILE_URL_PREFIX = "file:"; public static final String PACKAGE_SPLIT = "/"; + public static final String PACKAGE_SPLIT_DOT = "."; public static final String JAR_FILE_EXTENSION = ".jar"; public static final String ZIP_FILE_EXTENSION = ".zip"; @@ -64,7 +65,7 @@ public class ResourceUtils { String packageType = TYPE_PACKAGE + TYPE_SPLIT; if(isPackage(locationMatch)){ String location = locationMatch.replaceFirst(packageType, ""); - return location.replace(".", "/"); + return replacePackage(location); } LOGGER.error("locationMatch {} illegal", locationMatch); return null; @@ -186,6 +187,13 @@ public class ResourceUtils { } } + public static String replacePackage(String packageName){ + if(packageName == null){ + return null; + } + return packageName.replace(PACKAGE_SPLIT_DOT, PACKAGE_SPLIT); + } + // /** // * 根据 ~ 标记获取, 得到绝对路径 diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json index 420f888..19f1b55 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json @@ -15,7 +15,7 @@ "defaultValue": true }, { - "name": "plugin.enable-starter", + "name": "plugin.enableStarter", "type": "java.lang.Boolean", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", "description": "是否启用starter自动装配功能", @@ -25,14 +25,14 @@ "name": "plugin.runMode", "type": "java.lang.String", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "运行模式. 开发环境: development、dev; 生产/部署 环境: deployment、prod", + "description": "运行模式. 开发环境: dev; 生产/部署 环境: prod", "defaultValue": "dev" }, { "name": "plugin.mainPackage", "type": "java.lang.String", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "主程序包名, 包名建议设置到范围最大级别, 主要用于插件依赖主程序时的类时, 进行包名匹配", + "description": "主程序包名, 包名建议设置到范围最大级别, 主要用于插件依赖主程序时的类时, 进行包名匹配", "defaultValue": true }, { @@ -43,18 +43,16 @@ "defaultValue": "/plugins" }, { - "name": "plugin.pluginConfigFilePath", + "name": "plugin.backupPath", "type": "java.lang.String", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "插件对应的配置文件存放目录, 只作用于生产环境下", - "defaultValue": "/plugin-config" + "description": "卸载插件后, 备份插件的目录" }, { - "name": "plugin.enablePluginRestController", - "type": "java.lang.Boolean", + "name": "plugin.uploadTempPath", + "type": "java.lang.String", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "是否启用插件的 rest controller 接口注册. 默认启用", - "defaultValue": true + "description": "上传的插件所存储的临时目录" }, { "name": "plugin.pluginRestPathPrefix", @@ -70,46 +68,6 @@ "description": "是否启用插件id作为rest接口前缀", "defaultValue": true }, - { - "name": "plugin.enableSwaggerRefresh", - "type": "java.lang.Boolean", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "是否启用Swagger刷新机制", - "defaultValue": true - }, - { - "name": "plugin.backupPath", - "type": "java.lang.String", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "卸载插件后, 备份插件的目录" - }, - { - "name": "plugin.uploadTempPath", - "type": "java.lang.String", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "上传的插件所存储的临时目录" - }, - { - "name": "plugin.version", - "type": "java.lang.String", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "当前主程序的版本号, 用于校验插件是否可安装。插件中可通过插件配置信息 requires 来指定可安装的主程序版本。如果为: 0.0.0 的话, 表示不校验", - "defaultValue": "0.0.0" - }, - { - "name": "plugin.exactVersionAllowed", - "type": "java.lang.String", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "是否完全匹配版本。设置为true表示插件设置的requires的版本号完全匹配version版本号才可允许插件安装, 即: requires=x.y.z; 设置为false表示插件设置的requires的版本号小于等于version值, 插件就可安装, 即requires<=x.y.z", - "defaultValue": false - }, - { - "name": "plugin.stopDependents", - "type": "java.lang.String", - "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "停止插件时, 是否停止当前插件依赖的插件", - "defaultValue": false - }, { "name": "plugin.enablePluginIds", "type": "java.util.Set", @@ -129,10 +87,17 @@ "description": "设置初始化时插件启动的顺序" }, { - "name": "plugin.enableWebSocket", - "type": "java.lang.Boolean", + "name": "plugin.version", + "type": "java.lang.String", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", - "description": "是否启用webSocket的功能. 默认禁用", + "description": "当前主程序的版本号, 用于校验插件是否可安装。插件中可通过插件配置信息 requires 来指定可安装的主程序版本。如果为: 0.0.0 的话, 表示不校验", + "defaultValue": "0.0.0" + }, + { + "name": "plugin.exactVersion", + "type": "java.lang.String", + "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", + "description": "是否完全匹配版本。设置为true表示插件设置的requires的版本号完全匹配version版本号才可允许插件安装, 即: requires=x.y.z; 设置为false表示插件设置的requires的版本号小于等于version值, 插件就可安装, 即requires<=x.y.z", "defaultValue": false } ] diff --git a/springboot-plugin-maven-pack/pom.xml b/springboot-plugin-maven-packager/pom.xml similarity index 98% rename from springboot-plugin-maven-pack/pom.xml rename to springboot-plugin-maven-packager/pom.xml index b22ff75..c01d790 100644 --- a/springboot-plugin-maven-pack/pom.xml +++ b/springboot-plugin-maven-packager/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.gitee.starblues - springboot-plugin-maven-pack + springboot-plugin-maven-packager 3.0.0-RELEASE diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java similarity index 78% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java index 293bcf9..e26ca41 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -22,7 +22,7 @@ import java.util.Set; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @EqualsAndHashCode(callSuper = true) @Data @@ -61,15 +61,22 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { } // 添加主框架排除 addPluginFrameworkExclude(); + // 添加spring web 环境排除 + addSpringWebEnvExclude(); filters.addFilter(new ExcludeFilter(this.excludes)); return filters; } private void addPluginFrameworkExclude(){ - final Exclude pluginFrameworkExclude = new Exclude(); - pluginFrameworkExclude.setGroupId("com.gitee.starblues"); - pluginFrameworkExclude.setArtifactId("springboot-plugin-framework"); - excludes.add(pluginFrameworkExclude); + excludes.add(Exclude.get("com.gitee.starblues", "springboot-plugin-framework")); + } + + private void addSpringWebEnvExclude(){ + excludes.add(Exclude.get("org.springframework.boot", "spring-boot-starter-web")); + excludes.add(Exclude.get("org.springframework.boot", "spring-boot-starter-tomcat")); + excludes.add(Exclude.get("org.springframework.boot", "spring-boot-starter-json")); + excludes.add(Exclude.get("org.springframework", "spring-webmvc")); + excludes.add(Exclude.get("org.springframework", "spring-web")); } } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java similarity index 80% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java index 2dbf1ee..16a0ed6 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java @@ -1,5 +1,6 @@ package com.gitee.starblues.plugin.pack; +import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.plugin.pack.utils.CommonUtils; import lombok.Data; import lombok.EqualsAndHashCode; @@ -14,7 +15,7 @@ import java.util.Set; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @EqualsAndHashCode(callSuper = true) @Data @@ -64,12 +65,24 @@ public abstract class AbstractPackagerMojo extends AbstractDependencyFilterMojo{ } if(CommonUtils.isEmpty(pluginInfo.getId())){ throw new MojoExecutionException("configuration.pluginInfo.id config cannot be empty"); + } else { + String id = pluginInfo.getId(); + String illegal = PackageStructure.getIllegal(id); + if(illegal != null){ + throw new MojoExecutionException("configuration.pluginInfo.id config can't contain: " + illegal); + } } if(CommonUtils.isEmpty(pluginInfo.getBootstrapClass())){ throw new MojoExecutionException("configuration.pluginInfo.bootstrapClass config cannot be empty"); } if(CommonUtils.isEmpty(pluginInfo.getVersion())){ throw new MojoExecutionException("configuration.pluginInfo.version config cannot be empty"); + } else { + String version = pluginInfo.getVersion(); + String illegal = PackageStructure.getIllegal(version); + if(illegal != null){ + throw new MojoExecutionException("configuration.pluginInfo.version config can't contain: " + illegal); + } } } } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java similarity index 94% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index 895a46c..754d496 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -1,5 +1,6 @@ package com.gitee.starblues.plugin.pack; +import com.gitee.starblues.common.AbstractDependencyPlugin; import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.plugin.pack.dev.DevConfig; import com.gitee.starblues.plugin.pack.utils.CommonUtils; @@ -14,13 +15,13 @@ import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import static com.gitee.starblues.common.PackageStructure.*; import static com.gitee.starblues.common.PluginDescriptorKey.*; -import static com.gitee.starblues.plugin.pack.Constant.SCOPE_PROVIDED; import static com.gitee.starblues.plugin.pack.utils.CommonUtils.isEmpty; import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; @@ -128,9 +129,9 @@ public class BasicRepackager implements Repackager{ if(!isEmpty(requires)){ attributes.putValue(PLUGIN_REQUIRES, requires); } - String dependencies = pluginInfo.getDependencies(); - if(!isEmpty(dependencies)){ - attributes.putValue(PLUGIN_DEPENDENCIES, dependencies); + String dependencyPlugins = getDependencyPlugin(pluginInfo); + if(!isEmpty(dependencyPlugins)){ + attributes.putValue(PLUGIN_DEPENDENCIES, dependencyPlugins); } String description = pluginInfo.getDescription(); if(!isEmpty(description)){ @@ -140,10 +141,14 @@ public class BasicRepackager implements Repackager{ if(!isEmpty(license)){ attributes.putValue(PLUGIN_LICENSE, license); } - // TODO 未添加全 return manifest; } + protected String getDependencyPlugin(PluginInfo pluginInfo){ + List dependencyPlugins = pluginInfo.getDependencyPlugins(); + return AbstractDependencyPlugin.toStr(dependencyPlugins); + } + protected String getPluginPath(){ DevConfig devConfig = repackageMojo.getDevConfig(); if(devConfig != null && !isEmpty(devConfig.getPluginPath())){ @@ -245,7 +250,7 @@ public class BasicRepackager implements Repackager{ * @return 返回true表示被过滤掉 */ protected boolean filterArtifact(Artifact artifact){ - return SCOPE_PROVIDED.equalsIgnoreCase(artifact.getScope()); + return Constant.scopeFilter(artifact.getScope()); } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java similarity index 67% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java index 5da716a..7e39cf9 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Constant.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -2,12 +2,14 @@ package com.gitee.starblues.plugin.pack; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class Constant { public static final String PACKAGING_POM = "pom"; public static final String SCOPE_PROVIDED = "provided"; + public static final String SCOPE_COMPILE = "compile"; + public static final String SCOPE_TEST = "test"; public static final String MODE_DEV = "dev"; public static final String MODE_PROD = "prod"; @@ -21,4 +23,9 @@ public class Constant { return PACKAGING_POM.equalsIgnoreCase(packageType); } + public static boolean scopeFilter(String scope){ + return SCOPE_PROVIDED.equalsIgnoreCase(scope) + || SCOPE_TEST.equalsIgnoreCase(scope); + } + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java new file mode 100644 index 0000000..420a28b --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java @@ -0,0 +1,55 @@ +package com.gitee.starblues.plugin.pack; + +import com.gitee.starblues.common.AbstractDependencyPlugin; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * 依赖的插件 + * @author starBlues + * @version 3.0.0 + */ +public class DependencyPlugin extends AbstractDependencyPlugin { + + @Parameter(required = true) + private String id; + + @Parameter(required = true) + private String version; + + @Parameter(required = false, defaultValue = "true") + private Boolean optional = false; + + @Override + public String getId() { + return id; + } + + @Override + public String getVersion() { + return version; + } + + @Override + public Boolean getOptional() { + if(optional == null){ + return false; + } + return optional; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public void setVersion(String version) { + this.version = version; + } + + @Override + public void setOptional(Boolean optional) { + this.optional = optional; + } + +} diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java similarity index 67% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java index 4cbfaaa..5520b86 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -1,8 +1,11 @@ package com.gitee.starblues.plugin.pack; +import com.gitee.starblues.common.AbstractDependencyPlugin; import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; +import java.util.List; + /** * 插件信息 * @author starBlues @@ -33,11 +36,30 @@ public class PluginInfo { * 插件配置文件名称 */ private String configFileName; + + /** + * 插件描述 + */ private String description; + + /** + * 插件提供者 + */ private String provider; + + /** + * 需要安装的主程序版本 + */ private String requires; - private String dependencies; + + /** + * 插件 license + */ private String license; + /** + * 依赖的插件 + */ + private List dependencyPlugins; } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java similarity index 99% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java index f1592e7..7099f24 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java @@ -43,5 +43,4 @@ public class RepackageMojo extends AbstractPackagerMojo { } } - } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java similarity index 33% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java index bc52362..000c35e 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java @@ -1,8 +1,18 @@ package com.gitee.starblues.plugin.pack.filter; /** + * 排除依赖定义 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class Exclude extends FilterableDependency{ + + public static Exclude get(String groupId, String artifactId){ + Exclude exclude = new Exclude(); + exclude.setGroupId(groupId); + exclude.setArtifactId(artifactId); + return exclude; + } + + } diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java similarity index 99% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java index d0366aa..481a059 100644 --- a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -1,6 +1,7 @@ package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.dev.Dependency; import com.gitee.starblues.plugin.pack.dev.DevConfig; @@ -138,7 +139,7 @@ public class ZipProdRepackager extends DevRepackager { @Override protected boolean filterArtifact(Artifact artifact) { - return SCOPE_PROVIDED.equalsIgnoreCase(artifact.getScope()); + return Constant.scopeFilter(artifact.getScope()); } protected void resolveClasses() throws Exception { diff --git a/springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java similarity index 100% rename from springboot-plugin-maven-pack/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java diff --git a/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml similarity index 98% rename from springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml rename to springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml index c3ae287..926c24b 100644 --- a/springboot-plugin-maven-pack/src/main/resources/META-INF/maven/plugin.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml @@ -3,9 +3,9 @@ - Spring Boot Plugin Maven Pack + Spring Boot Plugin Maven Packager com.gitee.starblues - springboot-plugin-maven-pack + springboot-plugin-maven-packager 3.0.0-RELEASE springboot-plugin false -- Gitee From 1a534cb07a3bb9e84bb18d559aa7d42bc7b6b1d8 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 27 Jan 2022 16:36:07 +0800 Subject: [PATCH 25/37] add plugin-user --- .../common/AbstractDependencyPlugin.java | 3 + .../web/PluginControllerProcessor.java | 2 +- .../web/PluginInterceptorsProcessor.java | 4 +- .../bootstrap/realize/StopValidator.java | 2 +- .../annotation/ConfigDefinition.java | 38 --- .../starblues/core/DefaultPluginManager.java | 58 ++-- .../core/DefaultRealizeProvider.java | 22 +- .../starblues/core/PluginLauncherManager.java | 20 +- .../gitee/starblues/core/RealizeProvider.java | 7 + .../com/gitee/starblues/core/RuntimeMode.java | 4 + .../checker/ComposePluginBasicChecker.java | 57 ++++ ...java => ComposePluginLauncherChecker.java} | 31 +-- .../checker/DefaultPluginBasicChecker.java | 57 ++++ ...java => DefaultPluginLauncherChecker.java} | 53 +--- ...a => DependencyPluginLauncherChecker.java} | 16 +- .../core/checker/PluginBasicChecker.java | 29 ++ .../PluginLauncherChecker.java} | 25 +- .../AbstractPluginDescriptorLoader.java | 7 +- .../descriptor/ComposeDescriptorLoader.java | 59 +++++ .../ProdPluginDescriptorLoader.java | 3 +- .../core/launcher/plugin/PluginLauncher.java | 11 +- .../PluginMainResourcePatternDefiner.java | 5 +- .../PluginApplicationContextGetter.java | 37 +++ .../involved/PluginLaunchInvolvedFactory.java | 1 + .../integration/IntegrationConfiguration.java | 18 ++ .../DefaultPluginListenerFactory.java | 9 +- .../PluginInitializerListenerFactory.java | 8 + .../operator/DefaultPluginOperator.java | 30 +-- .../operator/EmptyPluginOperator.java | 5 +- .../integration/operator/PluginOperator.java | 65 ++--- .../operator/PluginOperatorWrapper.java | 8 +- .../integration/user/BeanWrapper.java | 34 +++ .../integration/user/DefaultPluginUser.java | 247 +++++++----------- .../integration/user/EmptyPluginUser.java | 27 +- .../integration/user/PluginUser.java | 107 +++----- .../CacheJdkSameTypeParamProxyFactory.java | 9 +- .../web/PluginStaticResourceResolver.java | 2 - ...tilsV3.java => SpringBeanCustomUtils.java} | 70 ++--- .../starblues/utils/SpringBeanUtils.java | 69 ++--- .../plugin/pack/dev/DevRepackager.java | 7 +- 40 files changed, 683 insertions(+), 583 deletions(-) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/ConfigDefinition.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/{ComposePluginChecker.java => ComposePluginLauncherChecker.java} (47%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/{DefaultPluginChecker.java => DefaultPluginLauncherChecker.java} (58%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/{DependencyPluginChecker.java => DependencyPluginLauncherChecker.java} (87%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/{PluginChecker.java => checker/PluginLauncherChecker.java} (45%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/{SpringBeanUtilsV3.java => SpringBeanCustomUtils.java} (62%) diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java index 1c65089..465a41e 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java @@ -59,6 +59,9 @@ public abstract class AbstractDependencyPlugin implements DependencyPlugin{ public static List toList(String str, Supplier supplier){ + if(str == null || "".equals(str)){ + return Collections.emptyList(); + } String[] all = str.split(SPLIT_ALL); if(all.length == 0){ return Collections.emptyList(); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java index 35bcaf9..942f610 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java @@ -47,7 +47,7 @@ public class PluginControllerProcessor implements SpringPluginProcessor { public void initialize(ProcessorContext processorContext) throws ProcessorException { SpringBeanFactory mainBeanFactory = processorContext.getMainBeanFactory(); this.requestMappingHandlerMapping = mainBeanFactory.getBean(RequestMappingHandlerMapping.class); - this.handlerAdapter = SpringBeanUtilsV3.getExistBean(processorContext.getMainApplicationContext(), + this.handlerAdapter = SpringBeanCustomUtils.getExistBean(processorContext.getMainApplicationContext(), RequestMappingHandlerAdapter.class); this.getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class, "getMappingForMethod", Method.class, Class.class); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java index 6113e92..a1ac87b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java @@ -10,7 +10,7 @@ import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.utils.ClassUtils; import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.SpringBeanUtilsV3; +import com.gitee.starblues.utils.SpringBeanCustomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.WebRequestInterceptor; @@ -37,7 +37,7 @@ public class PluginInterceptorsProcessor implements SpringPluginProcessor { @Override public void initialize(ProcessorContext context) throws ProcessorException { MainApplicationContext applicationContext = context.getMainApplicationContext(); - handlerMapping = SpringBeanUtilsV3.getExistBean(applicationContext, + handlerMapping = SpringBeanCustomUtils.getExistBean(applicationContext, AbstractHandlerMapping.class); if(handlerMapping == null){ logger.warn("Not found AbstractHandlerMapping, Plugin interceptor can't use"); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java index 8ca4499..5699e0b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java @@ -9,7 +9,7 @@ public interface StopValidator { /** - * 校验是否可卸载。如果校验器抛出异常. 默认插件不可停止 + * 校验是否可停止/卸载。如果校验器抛出异常. 默认插件不可停止/卸载 * @return 校验结果 */ Result verify(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/ConfigDefinition.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/ConfigDefinition.java deleted file mode 100644 index 42109c7..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/ConfigDefinition.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.annotation; - -import java.lang.annotation.*; - -/** - * 插件配置对应的bean定义注解 - * 如果存在配置文件, 则进行属性自定义 - * 如果未依赖配置文件, 则直接定义注解即可 - * @author starBlues - * @version 2.4.0 - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface ConfigDefinition { - - - /** - * 插件中的配置文件的名称, 新版本替换 value 值 - * @return String - */ - String fileName() default ""; - - /** - * 开发环境下文件后缀 - * 如果文件名称为: xxx.yml, 根据当前配置(当前配置为-dev)在开发环境下文件后缀为: xxx-dev.yml - * @return 开发环境下文件名称后缀, 比如 dev - */ - String devSuffix() default ""; - - /** - * 生产环境下文件后缀 - * 如果文件名称为: xxx.yml, 根据当前配置(当前配置为-prod)在生产环境下文件后缀为: xxx-prod.yml - * @return 生产环境下文件名称后缀, 比如 -prod - */ - String prodSuffix() default ""; - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index c9bb6d4..79286c7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -1,8 +1,9 @@ package com.gitee.starblues.core; -import com.gitee.starblues.core.checker.ComposePluginChecker; -import com.gitee.starblues.core.checker.DefaultPluginChecker; -import com.gitee.starblues.core.checker.DependencyPluginChecker; +import com.gitee.starblues.core.checker.ComposePluginLauncherChecker; +import com.gitee.starblues.core.checker.DefaultPluginLauncherChecker; +import com.gitee.starblues.core.checker.DependencyPluginLauncherChecker; +import com.gitee.starblues.core.checker.PluginBasicChecker; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; @@ -42,7 +43,9 @@ public class DefaultPluginManager implements PluginManager{ private final List pluginRootDirs; private final PathResolve pathResolve; - protected final ComposePluginChecker pluginChecker; + private final PluginBasicChecker basicChecker; + + protected final ComposePluginLauncherChecker launcherChecker; private final AtomicBoolean loaded = new AtomicBoolean(false); @@ -58,18 +61,23 @@ public class DefaultPluginManager implements PluginManager{ this.provider = Assert.isNotNull(realizeProvider, "参数 realizeProvider 不能为空"); this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); this.pluginRootDirs = configuration.pluginPath(); - this.pathResolve = new ComposePathResolve(new DevPathResolve(), new ProdPathResolve()); - this.pluginChecker = getComposePluginChecker(realizeProvider); + this.pathResolve = getComposePathResolve(); + this.basicChecker = realizeProvider.getPluginBasicChecker(); + this.launcherChecker = getComposeLauncherChecker(realizeProvider); setSortedPluginIds(configuration.sortInitPluginIds()); } - protected ComposePluginChecker getComposePluginChecker(RealizeProvider realizeProvider){ - ComposePluginChecker checker = new ComposePluginChecker(); - checker.add(new DefaultPluginChecker(realizeProvider, configuration)); - checker.add(new DependencyPluginChecker(this)); + protected ComposePluginLauncherChecker getComposeLauncherChecker(RealizeProvider realizeProvider){ + ComposePluginLauncherChecker checker = new ComposePluginLauncherChecker(); + checker.add(new DefaultPluginLauncherChecker(realizeProvider, configuration)); + checker.add(new DependencyPluginLauncherChecker(this)); return checker; } + protected ComposePathResolve getComposePathResolve(){ + return new ComposePathResolve(new DevPathResolve(), new ProdPathResolve()); + } + public void setSortedPluginIds(List sortedPluginIds) { this.sortedPluginIds = sortedPluginIds; } @@ -136,13 +144,9 @@ public class DefaultPluginManager implements PluginManager{ public boolean verify(Path pluginPath) { Assert.isNotNull(pluginPath, "参数pluginPath不能为空"); try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ - pluginChecker.check(pluginPath); + basicChecker.checkPath(pluginPath); PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); - if(pluginDescriptor == null){ - return false; - } - pluginChecker.checkDescriptor(pluginDescriptor); - return true; + return pluginDescriptor != null; } catch (Exception e) { log.error("插件jar包校验失败: {}" , pluginPath, e); return false; @@ -172,8 +176,10 @@ public class DefaultPluginManager implements PluginManager{ throw new PluginException("加载插件包[" + pluginPath + "]失败. 已经存在该插件: " + MsgUtils.getPluginUnique(plugin.getPluginDescriptor())); } - // 拷贝插件 - pluginPath = copyPlugin(pluginPath, unpackPlugin); + if(configuration.isProd()){ + // 如果为生产环境, 则拷贝插件 + pluginPath = copyPlugin(pluginPath, unpackPlugin); + } // 加载插件 PluginInsideInfo pluginInsideInfo = loadPlugin(pluginPath, true); if(pluginInsideInfo != null){ @@ -386,7 +392,7 @@ public class DefaultPluginManager implements PluginManager{ protected PluginInsideInfo loadFromPath(Path pluginPath) { try { - pluginChecker.check(pluginPath); + basicChecker.checkPath(pluginPath); } catch (Exception e) { throw PluginException.getPluginException(e, ()-> { return new PluginException("非法插件包. " + e.getMessage(), e); @@ -419,7 +425,7 @@ public class DefaultPluginManager implements PluginManager{ * @throws IOException IO 异常 */ protected Path copyPlugin(Path pluginPath, boolean unpackPlugin) throws IOException { - if(isDev()){ + if(configuration.isDev()){ return pluginPath; } File targetFile = pluginPath.toFile(); @@ -484,7 +490,7 @@ public class DefaultPluginManager implements PluginManager{ protected void start(PluginInsideInfo pluginInsideInfo) throws Exception{ Assert.isNotNull(pluginInsideInfo, "pluginInsideInfo 参数不能为空"); String pluginId = pluginInsideInfo.getPluginId(); - pluginChecker.checkCanStart(pluginInsideInfo); + launcherChecker.checkCanStart(pluginInsideInfo); pluginInsideInfo.setPluginState(PluginState.STARTED); startedPlugins.put(pluginId, pluginInsideInfo); resolvedPlugins.remove(pluginId); @@ -496,7 +502,7 @@ public class DefaultPluginManager implements PluginManager{ * @throws Exception 启动异常 */ protected void stop(PluginInsideInfo pluginInsideInfo) throws Exception{ - pluginChecker.checkCanStop(pluginInsideInfo); + launcherChecker.checkCanStop(pluginInsideInfo); String pluginId = pluginInsideInfo.getPluginId(); pluginInsideInfo.setPluginState(PluginState.STOPPED); resolvedPlugins.put(pluginId, pluginInsideInfo); @@ -533,14 +539,6 @@ public class DefaultPluginManager implements PluginManager{ return wrapperInside; } - /** - * 是否是开发环境 - * @return boolean - */ - private boolean isDev(){ - return provider.getRuntimeMode() == RuntimeMode.DEV; - } - /** * 检查是否目录中是否存在同名插件 * @param dirFile 目录文件 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java index 2fc1fe2..229ad01 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -1,5 +1,9 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.checker.ComposePluginBasicChecker; +import com.gitee.starblues.core.checker.DefaultPluginBasicChecker; +import com.gitee.starblues.core.checker.PluginBasicChecker; +import com.gitee.starblues.core.descriptor.ComposeDescriptorLoader; import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.descriptor.ProdPluginDescriptorLoader; @@ -20,6 +24,7 @@ import org.springframework.context.ApplicationContext; public class DefaultRealizeProvider implements RealizeProvider { private PluginScanner pluginScanner; + private PluginBasicChecker pluginBasicChecker; private PluginDescriptorLoader pluginDescriptorLoader; private VersionInspector versionInspector; @@ -35,17 +40,14 @@ public class DefaultRealizeProvider implements RealizeProvider { @Override public void init() { BasePluginScanner basePluginScanner = new BasePluginScanner(); - PluginDescriptorLoader pluginDescriptorLoader = null; if(configuration.environment() == RuntimeMode.DEV){ basePluginScanner.setPathResolve(new DevPathResolve()); - pluginDescriptorLoader = new DevPluginDescriptorLoader(); } else { basePluginScanner.setPathResolve(new ProdPathResolve()); - pluginDescriptorLoader = new ProdPluginDescriptorLoader(); } - setPluginScanner(basePluginScanner); - setPluginDescriptorLoader(pluginDescriptorLoader); + setPluginBasicChecker(new ComposePluginBasicChecker(applicationContext)); + setPluginDescriptorLoader(new ComposeDescriptorLoader(pluginBasicChecker)); setVersionInspector(new SemverVersionInspector()); } @@ -53,6 +55,11 @@ public class DefaultRealizeProvider implements RealizeProvider { this.pluginScanner = Assert.isNotNull(pluginScanner, "pluginScanner 不能为空"); } + public void setPluginBasicChecker(PluginBasicChecker pluginBasicChecker) { + this.pluginBasicChecker = Assert.isNotNull(pluginBasicChecker, + "pluginBasicChecker 不能为空"); + } + public void setPluginDescriptorLoader(PluginDescriptorLoader pluginDescriptorLoader) { this.pluginDescriptorLoader = Assert.isNotNull(pluginDescriptorLoader, "pluginDescriptorLoader 不能为空"); @@ -72,6 +79,11 @@ public class DefaultRealizeProvider implements RealizeProvider { return Assert.isNotNull(pluginScanner, "PluginScanner 实现不能为空"); } + @Override + public PluginBasicChecker getPluginBasicChecker() { + return Assert.isNotNull(pluginBasicChecker, "pluginBasicChecker 实现不能为空"); + } + @Override public PluginDescriptorLoader getPluginDescriptorLoader() { return Assert.isNotNull(pluginDescriptorLoader, "PluginDescriptorLoader 实现不能为空"); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index dd69439..0f18ec6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -1,9 +1,9 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.checker.PluginLauncherChecker; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginException; -import com.gitee.starblues.core.exception.PluginProhibitStopException; import com.gitee.starblues.core.launcher.plugin.DefaultPluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.core.launcher.plugin.PluginLauncher; @@ -31,7 +31,7 @@ import java.util.concurrent.ConcurrentHashMap; */ public class PluginLauncherManager extends DefaultPluginManager{ - private final Map pluginRegistryInfoMap = new ConcurrentHashMap<>(); + private final Map registryInfo = new ConcurrentHashMap<>(); private final MainApplicationContext mainApplicationContext; @@ -55,10 +55,10 @@ public class PluginLauncherManager extends DefaultPluginManager{ } private void addCustomPluginChecker(){ - List pluginCheckers = SpringBeanUtils.getBeans(mainGenericApplicationContext, - PluginChecker.class); - for (PluginChecker pluginChecker : pluginCheckers) { - super.pluginChecker.add(pluginChecker); + List pluginCheckers = SpringBeanUtils.getBeans(mainGenericApplicationContext, + PluginLauncherChecker.class); + for (PluginLauncherChecker pluginChecker : pluginCheckers) { + super.launcherChecker.add(pluginChecker); } } @@ -83,7 +83,7 @@ public class PluginLauncherManager extends DefaultPluginManager{ PluginLauncher pluginLauncher = new PluginLauncher(pluginInteractive, pluginLaunchInvolved); SpringPluginHook springPluginHook = pluginLauncher.run(); RegistryPluginInfo registryPluginInfo = new RegistryPluginInfo(pluginDescriptor, springPluginHook); - pluginRegistryInfoMap.put(pluginDescriptor.getPluginId(), registryPluginInfo); + registryInfo.put(pluginDescriptor.getPluginId(), registryPluginInfo); } catch (Exception e){ // 启动失败, 进行停止 super.stop(pluginInsideInfo); @@ -95,7 +95,7 @@ public class PluginLauncherManager extends DefaultPluginManager{ @Override protected void stop(PluginInsideInfo pluginInsideInfo) throws Exception { String pluginId = pluginInsideInfo.getPluginId(); - RegistryPluginInfo registryPluginInfo = pluginRegistryInfoMap.get(pluginId); + RegistryPluginInfo registryPluginInfo = registryInfo.get(pluginId); if(registryPluginInfo == null){ throw new PluginException("没有发现插件 '" + pluginId + "' 信息"); } @@ -103,11 +103,11 @@ public class PluginLauncherManager extends DefaultPluginManager{ springPluginHook.stopVerify(); springPluginHook.close(); invokeSupperCache.remove(pluginId); - pluginRegistryInfoMap.remove(pluginId); + registryInfo.remove(pluginId); super.stop(pluginInsideInfo); } - private static class RegistryPluginInfo{ + static class RegistryPluginInfo{ private final PluginDescriptor descriptor; private final SpringPluginHook springPluginHook; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java index 577fa69..ee42ca3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -1,5 +1,6 @@ package com.gitee.starblues.core; +import com.gitee.starblues.core.checker.PluginBasicChecker; import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.scanner.PluginScanner; import com.gitee.starblues.core.version.VersionInspector; @@ -27,6 +28,12 @@ public interface RealizeProvider { */ PluginScanner getPluginScanner(); + /** + * 得到插件基本的检查者 + * @return PluginBasicChecker + */ + PluginBasicChecker getPluginBasicChecker(); + /** * 得到 PluginDescriptorLoader 实现 * @return PluginDescriptorLoader diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java index 75cd554..b306962 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java @@ -23,6 +23,10 @@ public enum RuntimeMode { this.mode = mode; } + public String getMode() { + return mode; + } + public static RuntimeMode byName(String model){ if(DEV.name().equalsIgnoreCase(model)){ return RuntimeMode.DEV; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java new file mode 100644 index 0000000..f0d2b9b --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java @@ -0,0 +1,57 @@ +package com.gitee.starblues.core.checker; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginException; +import com.gitee.starblues.utils.SpringBeanUtils; +import org.springframework.context.ApplicationContext; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * 组合插件检查者 + * @author starBlues + * @version 3.0.0 + */ +public class ComposePluginBasicChecker implements PluginBasicChecker { + + private final List pluginCheckers; + + public ComposePluginBasicChecker(ApplicationContext applicationContext) { + this.pluginCheckers = new ArrayList<>(); + addDefaultChecker(); + addCustomChecker(applicationContext); + } + + protected void addDefaultChecker(){ + pluginCheckers.add(new DefaultPluginBasicChecker()); + } + + protected void addCustomChecker(ApplicationContext applicationContext){ + List pluginCheckers = SpringBeanUtils.getBeans(applicationContext, + PluginBasicChecker.class); + this.pluginCheckers.addAll(pluginCheckers); + } + + public void add(PluginBasicChecker pluginChecker){ + if(pluginChecker != null){ + this.pluginCheckers.add(pluginChecker); + } + } + + + @Override + public void checkPath(Path path) throws Exception { + for (PluginBasicChecker pluginChecker : pluginCheckers) { + pluginChecker.checkPath(path); + } + } + + @Override + public void checkDescriptor(PluginDescriptor descriptor) throws PluginException { + for (PluginBasicChecker pluginChecker : pluginCheckers) { + pluginChecker.checkDescriptor(descriptor); + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java similarity index 47% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java index 15394d9..a451994 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java @@ -1,6 +1,5 @@ package com.gitee.starblues.core.checker; -import com.gitee.starblues.core.PluginChecker; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginException; @@ -14,50 +13,36 @@ import java.util.List; * @author starBlues * @version 3.0.0 */ -public class ComposePluginChecker implements PluginChecker { +public class ComposePluginLauncherChecker implements PluginLauncherChecker { - private final List pluginCheckers; + private final List pluginCheckers; - public ComposePluginChecker() { + public ComposePluginLauncherChecker() { this(new ArrayList<>()); } - public ComposePluginChecker(List pluginCheckers) { + public ComposePluginLauncherChecker(List pluginCheckers) { this.pluginCheckers = pluginCheckers; } - public void add(PluginChecker pluginChecker){ + public void add(PluginLauncherChecker pluginChecker){ if(pluginChecker != null){ this.pluginCheckers.add(pluginChecker); } } - @Override - public void check(Path path) throws Exception { - for (PluginChecker pluginChecker : pluginCheckers) { - pluginChecker.check(path); - } - } - - @Override - public void checkDescriptor(PluginDescriptor descriptor) throws PluginException { - for (PluginChecker pluginChecker : pluginCheckers) { - pluginChecker.checkDescriptor(descriptor); - } - } - @Override public void checkCanStart(PluginInfo pluginInfo) throws PluginException { - for (PluginChecker pluginChecker : pluginCheckers) { + for (PluginLauncherChecker pluginChecker : pluginCheckers) { pluginChecker.checkCanStart(pluginInfo); } } @Override public void checkCanStop(PluginInfo pluginInfo) throws PluginException { - for (PluginChecker pluginChecker : pluginCheckers) { - pluginChecker.checkCanStart(pluginInfo); + for (PluginLauncherChecker pluginChecker : pluginCheckers) { + pluginChecker.checkCanStop(pluginInfo); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java new file mode 100644 index 0000000..71148e4 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java @@ -0,0 +1,57 @@ +package com.gitee.starblues.core.checker; + +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginException; +import com.gitee.starblues.utils.Assert; + +import java.io.FileNotFoundException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * 默认的基本检查者 + * @author starBlues + * @version 3.0.0 + */ +public class DefaultPluginBasicChecker implements PluginBasicChecker { + + + @Override + public void checkPath(Path path) throws Exception { + if(path == null){ + throw new FileNotFoundException("path 文件路径不能为空"); + } + if(Files.notExists(path)){ + throw new FileNotFoundException("不存在文件: " + path.toString()); + } + } + + @Override + public void checkDescriptor(PluginDescriptor descriptor) throws PluginException { + Assert.isNotNull(descriptor, "PluginDescriptor 不能为空"); + + Assert.isNotEmpty(descriptor.getPluginPath(), "pluginPath 不能为空"); + + Assert.isNotNull(descriptor.getPluginId(), + PluginDescriptorKey.PLUGIN_ID + "不能为空"); + + Assert.isNotNull(descriptor.getPluginBootstrapClass(), + PluginDescriptorKey.PLUGIN_BOOTSTRAP_CLASS + "不能为空"); + + Assert.isNotNull(descriptor.getPluginVersion(), + PluginDescriptorKey.PLUGIN_VERSION + "不能为空"); + + String illegal = PackageStructure.getIllegal(descriptor.getPluginId()); + if(illegal != null){ + throw new PluginException(descriptor, "插件id不能包含:" + illegal); + } + illegal = PackageStructure.getIllegal(descriptor.getPluginVersion()); + if(illegal != null){ + throw new PluginException(descriptor, "插件版本号不能包含:" + illegal); + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java similarity index 58% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java index 687d628..6fce534 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java @@ -1,10 +1,8 @@ package com.gitee.starblues.core.checker; import com.gitee.starblues.common.Constants; -import com.gitee.starblues.common.DependencyPlugin; import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.common.PluginDescriptorKey; -import com.gitee.starblues.core.PluginChecker; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.RealizeProvider; @@ -12,78 +10,33 @@ import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginDisabledException; import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.integration.operator.DefaultPluginOperator; import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.MsgUtils; import com.gitee.starblues.utils.ObjectUtils; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.List; -import java.util.Objects; -import java.util.Set; /** * @author starBlues * @version 3.0.0 */ -public class DefaultPluginChecker implements PluginChecker { +public class DefaultPluginLauncherChecker implements PluginLauncherChecker { protected final RealizeProvider realizeProvider; protected final IntegrationConfiguration configuration; - private final Set enablePluginIds; - private final Set disabledPluginIds; - public DefaultPluginChecker(RealizeProvider realizeProvider, - IntegrationConfiguration configuration) { + public DefaultPluginLauncherChecker(RealizeProvider realizeProvider, + IntegrationConfiguration configuration) { this.realizeProvider = realizeProvider; this.configuration = configuration; - this.enablePluginIds = configuration.enablePluginIds(); - this.disabledPluginIds = configuration.disablePluginIds(); - } - - @Override - public void check(Path path) throws Exception { - if(path == null){ - throw new FileNotFoundException("path 文件路径不能为空"); - } - if(Files.notExists(path)){ - throw new FileNotFoundException("不存在文件: " + path.toString()); - } - } - - @Override - public void checkDescriptor(PluginDescriptor descriptor) throws PluginException { - Assert.isNotNull(descriptor, "PluginDescriptor 不能为空"); - - Assert.isNotEmpty(descriptor.getPluginPath(), "pluginPath 不能为空"); - - Assert.isNotNull(descriptor.getPluginId(), - PluginDescriptorKey.PLUGIN_ID + "不能为空"); - - Assert.isNotNull(descriptor.getPluginBootstrapClass(), - PluginDescriptorKey.PLUGIN_BOOTSTRAP_CLASS + "不能为空"); - - Assert.isNotNull(descriptor.getPluginVersion(), - PluginDescriptorKey.PLUGIN_VERSION + "不能为空"); - - String illegal = PackageStructure.getIllegal(descriptor.getPluginId()); - if(illegal != null){ - throw new PluginException(descriptor, "插件id不能包含:" + illegal); - } - illegal = PackageStructure.getIllegal(descriptor.getPluginVersion()); - if(illegal != null){ - throw new PluginException(descriptor, "插件版本号不能包含:" + illegal); - } } @Override public void checkCanStart(PluginInfo pluginInfo) throws PluginException { - checkDescriptor(pluginInfo.getPluginDescriptor()); PluginDisabledException.checkDisabled(pluginInfo, configuration, "启动"); PluginState pluginState = pluginInfo.getPluginState(); if(pluginState == PluginState.STARTED){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java similarity index 87% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java index ba327fe..74a4a3b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java @@ -2,7 +2,6 @@ package com.gitee.starblues.core.checker; import com.gitee.starblues.common.Constants; import com.gitee.starblues.common.DependencyPlugin; -import com.gitee.starblues.core.PluginChecker; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.core.PluginManager; import com.gitee.starblues.core.PluginState; @@ -20,11 +19,11 @@ import java.util.Objects; * @author starBlues * @version 3.0.0 */ -public class DependencyPluginChecker implements PluginChecker { +public class DependencyPluginLauncherChecker implements PluginLauncherChecker { private final PluginManager pluginManager; - public DependencyPluginChecker(PluginManager pluginManager) { + public DependencyPluginLauncherChecker(PluginManager pluginManager) { this.pluginManager = pluginManager; } @@ -56,7 +55,7 @@ public class DependencyPluginChecker implements PluginChecker { } String dependencyPluginUnique = MsgUtils.getPluginUnique(id, allowAllVersion ? null : version); if(!findDependency){ - throw new PluginException(descriptor, "需要依赖插件[" + dependencyPluginUnique + "]启动"); + throw new PluginException(descriptor, "需要依赖插件[" + dependencyPluginUnique + "]才能启动"); } if(dependencyPluginInfo.getPluginState() != PluginState.STARTED){ // 没有启动的话, 手动启动 @@ -66,15 +65,20 @@ public class DependencyPluginChecker implements PluginChecker { if(e instanceof PluginDisabledException){ // 依赖被禁用, 不能启动 throw new PluginDisabledException(descriptor, - "依赖插件[" + dependencyPluginUnique + "]被禁用, 无法启动当前插件"); + "依赖的插件[" + dependencyPluginUnique + "]被禁用, 无法启动当前插件"); } throw new PluginException(descriptor, - "依赖插件[" + dependencyPluginUnique + "]启动失败. 无法启动当前插件", e); + "依赖的插件[" + dependencyPluginUnique + "]启动失败. 无法启动当前插件", e); } } }); } + @Override + public void checkCanStop(PluginInfo pluginInfo) throws PluginException { + // 忽略 + } + private void resolveDependencyPlugin(PluginInfo pluginInfo, ResolveDependencyPlugin resolveDependencyPlugin) throws PluginException { List dependencyPlugins = pluginInfo.getPluginDescriptor().getDependencyPlugin(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java new file mode 100644 index 0000000..e64a8ae --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java @@ -0,0 +1,29 @@ +package com.gitee.starblues.core.checker; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.core.exception.PluginException; + +import java.nio.file.Path; + +/** + * 插件基本检查者 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginBasicChecker { + + /** + * 根据路径检查 + * @param path path + * @throws Exception 检查异常 + */ + void checkPath(Path path) throws Exception; + + /** + * 检查插件描述是否合法 + * @param descriptor 插件信息 + * @throws PluginException 检查异常 + */ + void checkDescriptor(PluginDescriptor descriptor) throws PluginException; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java similarity index 45% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java index b839fa2..a025e83 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java @@ -1,44 +1,31 @@ -package com.gitee.starblues.core; +package com.gitee.starblues.core.checker; +import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginException; import java.nio.file.Path; /** - * 插件检查者 + * 插件启动检查者 * @author starBlues * @version 3.0.0 */ -public interface PluginChecker { - - /** - * 根据路径检查 - * @param path path - * @throws Exception 检查异常 - */ - default void check(Path path) throws Exception{} - - /** - * 检查插件描述是否合法 - * @param descriptor 插件信息 - * @throws PluginException 检查异常 - */ - default void checkDescriptor(PluginDescriptor descriptor) throws PluginException{} +public interface PluginLauncherChecker { /** * 检查是否能启动 * @param pluginInfo 插件信息 * @throws PluginException 不能启动, 抛出PluginException异常即可 */ - default void checkCanStart(PluginInfo pluginInfo) throws PluginException{} + void checkCanStart(PluginInfo pluginInfo) throws PluginException; /** * 检查是否能停止 * @param pluginInfo 插件信息 * @throws PluginException 不能停止, 抛出PluginException异常即可 */ - default void checkCanStop(PluginInfo pluginInfo) throws PluginException{} + void checkCanStop(PluginInfo pluginInfo) throws PluginException; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index a9df159..cf6544f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -38,12 +38,12 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor try { manifest = getManifest(location); if(manifest == null){ - logger.warn("路径[{}]没有发现[{}]", location, MANIFEST); + logger.debug("路径[{}]没有发现[{}]", location, MANIFEST); return null; } return create(manifest, location); } catch (Exception e) { - logger.warn("路径[{}]中存在非法[{}]: {}", location, MANIFEST, e.getMessage()); + logger.error("路径[{}]中存在非法[{}]: {}", location, MANIFEST, e.getMessage()); return null; } } @@ -88,7 +88,8 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor } protected List getPluginDependency(Attributes attributes){ - return AbstractDependencyPlugin.toList(getValue(attributes, PLUGIN_DEPENDENCIES), DefaultDependencyPlugin::new); + return AbstractDependencyPlugin.toList(getValue(attributes, PLUGIN_DEPENDENCIES, false), + DefaultDependencyPlugin::new); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java new file mode 100644 index 0000000..52981c2 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java @@ -0,0 +1,59 @@ +package com.gitee.starblues.core.descriptor; + +import com.gitee.starblues.core.checker.PluginBasicChecker; +import com.gitee.starblues.core.exception.PluginException; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * 组合插件描述加载者 + * @author starBlues + * @version 3.0.0 + */ +public class ComposeDescriptorLoader implements PluginDescriptorLoader{ + + private final List pluginDescriptorLoaders = new ArrayList<>(); + + private final PluginBasicChecker pluginChecker; + + public ComposeDescriptorLoader(PluginBasicChecker pluginChecker) { + this.pluginChecker = pluginChecker; + addDefaultLoader(); + } + + protected void addDefaultLoader(){ + addLoader(new DevPluginDescriptorLoader()); + addLoader(new ProdPluginDescriptorLoader()); + } + + + public void addLoader(PluginDescriptorLoader descriptorLoader){ + if(descriptorLoader != null){ + pluginDescriptorLoaders.add(descriptorLoader); + } + } + + + @Override + public InsidePluginDescriptor load(Path location) throws PluginException { + for (PluginDescriptorLoader pluginDescriptorLoader : pluginDescriptorLoaders) { + try { + InsidePluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(location); + if(pluginDescriptor != null){ + pluginChecker.checkDescriptor(pluginDescriptor); + return pluginDescriptor; + } + } catch (Exception e){ + // 忽略异常 + } + } + return null; + } + + @Override + public void close() throws Exception { + + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index be6b4a8..4efa0fa 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -8,8 +8,9 @@ import org.slf4j.LoggerFactory; import java.nio.file.Path; /** + * 生产环境插件描述加载者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ProdPluginDescriptorLoader implements PluginDescriptorLoader{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 51e7914..62d2ce1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -65,9 +65,14 @@ public class PluginLauncher extends AbstractLauncher { @Override protected SpringPluginHook launch(ClassLoader classLoader, String... args) throws Exception { pluginLaunchInvolved.before(pluginDescriptor, classLoader); - SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive).run(classLoader); - pluginLaunchInvolved.after(pluginDescriptor, classLoader, springPluginHook); - return new SpringPluginHookWrapper(springPluginHook, pluginDescriptor, pluginLaunchInvolved, classLoader); + try { + SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive).run(classLoader); + pluginLaunchInvolved.after(pluginDescriptor, classLoader, springPluginHook); + return new SpringPluginHookWrapper(springPluginHook, pluginDescriptor, pluginLaunchInvolved, classLoader); + } catch (Throwable throwable){ + pluginLaunchInvolved.failure(pluginDescriptor,classLoader, throwable); + throw throwable; + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index a19951d..d0a914b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -1,11 +1,10 @@ package com.gitee.starblues.core.launcher.plugin; -import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.SpringBeanUtilsV3; +import com.gitee.starblues.utils.SpringBeanCustomUtils; import java.util.HashSet; import java.util.Set; @@ -99,7 +98,7 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef */ private BasicMainResourcePatternDefiner getPatternDefiner(PluginInteractive pluginInteractive){ final MainApplicationContext mainApplicationContext = pluginInteractive.getMainApplicationContext(); - BasicMainResourcePatternDefiner definer = SpringBeanUtilsV3.getExistBean( + BasicMainResourcePatternDefiner definer = SpringBeanCustomUtils.getExistBean( mainApplicationContext, BasicMainResourcePatternDefiner.class); if(definer == null){ return new BasicMainResourcePatternDefiner(mainPackage); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java new file mode 100644 index 0000000..1213676 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java @@ -0,0 +1,37 @@ +package com.gitee.starblues.core.launcher.plugin.involved; + +import com.gitee.starblues.core.PluginLauncherManager; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.spring.SpringPluginHook; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class PluginApplicationContextGetter implements PluginLaunchInvolved{ + + private static final Map PLUGIN_CONTEXTS = new ConcurrentHashMap<>(); + + @Override + public void after(InsidePluginDescriptor descriptor, ClassLoader classLoader, SpringPluginHook pluginHook) throws Exception { + PLUGIN_CONTEXTS.put(descriptor.getPluginId(), pluginHook.getApplicationContext()); + } + + @Override + public void close(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { + PLUGIN_CONTEXTS.remove(descriptor.getPluginId()); + } + + public static ApplicationContext get(String pluginId){ + return PLUGIN_CONTEXTS.get(pluginId); + } + + public static Map get(){ + return Collections.unmodifiableMap(PLUGIN_CONTEXTS); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java index 3c8ff5c..2f03f07 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java @@ -56,6 +56,7 @@ public class PluginLaunchInvolvedFactory implements PluginLaunchInvolved{ protected List getDefaultPluginLaunchInvolved(){ List defaultPluginLaunchInvolved = new ArrayList<>(); defaultPluginLaunchInvolved.add(new DefaultPluginLaunchInvolved()); + defaultPluginLaunchInvolved.add(new PluginApplicationContextGetter()); return defaultPluginLaunchInvolved; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index d2b835b..a74ce7f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -108,6 +108,24 @@ public interface IntegrationConfiguration { */ default void checkConfig(){}; + + /** + * 是否是开发环境 + * @return boolean + */ + default boolean isDev(){ + return environment() == RuntimeMode.DEV; + } + + /** + * 是否是生产环境 + * @return boolean + */ + default boolean isProd(){ + return environment() == RuntimeMode.PROD; + } + + /** * 是否被启动 * @param pluginId 插件id diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java index 5fb9465..e518aa4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java @@ -18,14 +18,21 @@ public class DefaultPluginListenerFactory implements PluginListenerFactory{ private final List listeners; public DefaultPluginListenerFactory(ApplicationContext applicationContext){ - listeners = SpringBeanUtils.getBeans(applicationContext, PluginListener.class); + listeners = new ArrayList<>(); addPluginListener(new SwaggerListener(applicationContext)); + addExtendPluginListener(applicationContext); } public DefaultPluginListenerFactory(){ listeners = new ArrayList<>(); } + + private void addExtendPluginListener(ApplicationContext applicationContext){ + List pluginListeners = SpringBeanUtils.getBeans(applicationContext, PluginListener.class); + listeners.addAll(pluginListeners); + } + @Override public synchronized void addPluginListener(PluginListener pluginListener) { if(pluginListener != null){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java index 32a1075..47aba8c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java @@ -1,5 +1,6 @@ package com.gitee.starblues.integration.listener; +import com.gitee.starblues.utils.SpringBeanUtils; import org.springframework.context.ApplicationContext; import java.util.ArrayList; @@ -21,6 +22,13 @@ public class PluginInitializerListenerFactory implements PluginInitializerListen this.applicationContext = applicationContext; // 添加默认的初始化监听者 pluginInitializerListeners.add(new DefaultInitializerListener(applicationContext)); + addExtendPluginListener(applicationContext); + } + + private void addExtendPluginListener(ApplicationContext applicationContext){ + List initializerListeners = SpringBeanUtils.getBeans(applicationContext, + PluginInitializerListener.class); + pluginInitializerListeners.addAll(initializerListeners); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 2bfe953..f0bdf47 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -146,12 +146,12 @@ public class DefaultPluginOperator implements PluginOperator { } @Override - public PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException { - return pluginManager.load(jarPath, unpackPlugin); + public PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException { + return pluginManager.load(pluginPath, unpackPlugin); } @Override - public boolean unload(String pluginId, boolean isBackup) throws PluginException { + public boolean unload(String pluginId) throws PluginException { pluginManager.unLoad(pluginId); return true; } @@ -172,9 +172,6 @@ public class DefaultPluginOperator implements PluginOperator { @Override public PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException { - if(isDev()){ - throw new RuntimeException("开发环境下不能上传插件"); - } Assert.isNotNull(uploadParam, "参数 uploadParam 不能为空"); try { if(uploadParam instanceof UploadByInputStreamParam){ @@ -196,8 +193,9 @@ public class DefaultPluginOperator implements PluginOperator { @Override public Path backupPlugin(Path backDirPath, String sign) throws PluginException { - if(isDev()){ - throw new RuntimeException("Plugin cannot backup in the 'dev' environment"); + if(configuration.isDev()){ + // 开发环境下不备份 + return backDirPath; } Objects.requireNonNull(backDirPath); return backup(backDirPath, sign, false); @@ -205,8 +203,9 @@ public class DefaultPluginOperator implements PluginOperator { @Override public Path backupPlugin(String pluginId, String sign) throws PluginException { - if(isDev()){ - throw new RuntimeException("Plugin cannot backup in the 'dev' environment"); + if(configuration.isDev()){ + // 开发环境下不备份 + return null; } PluginInfo pluginInfo = getPluginInfo(pluginId); return backupPlugin(Paths.get(pluginInfo.getPluginPath()), sign); @@ -235,7 +234,7 @@ public class DefaultPluginOperator implements PluginOperator { throw new PluginException(pluginId, "没有发现"); } pluginManager.uninstall(pluginId); - if(!isDelete || isDev()){ + if(!isDelete || configuration.isDev()){ return null; } // 删除插件 @@ -310,7 +309,7 @@ public class DefaultPluginOperator implements PluginOperator { */ protected Path backup(Path sourcePath, String sign, boolean deletedSourceFile) { try { - if(isDev()){ + if(configuration.isDev()){ // 如果是开发环境, 则不进行备份 return null; } @@ -378,13 +377,6 @@ public class DefaultPluginOperator implements PluginOperator { return FORMAT.format(localDateTime); } - /** - * 是否是开发环境 - * @return bolean - */ - protected boolean isDev(){ - return configuration.environment() == RuntimeMode.DEV; - } protected void touchBackupPath() throws IOException { String backupPath = configuration.backupPath(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java index dac4fdf..cb71a02 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java @@ -40,15 +40,16 @@ public class EmptyPluginOperator implements PluginOperator{ } @Override - public PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException { + public PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException { return null; } @Override - public boolean unload(String pluginId, boolean isBackup) throws PluginException { + public boolean unload(String pluginId) throws PluginException { return false; } + @Override public boolean start(String pluginId) throws PluginException { return false; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java index 733eb55..45f6259 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java @@ -19,32 +19,32 @@ import java.util.List; public interface PluginOperator { /** - * 初始化插件。该方法只能执行一次。 + * 初始化插件 [适用于 dev、prod 环境] + * 该方法只能执行一次。因程序启动时已经调用了该方法,在使用时不要再调用该方法。 * @param pluginInitializerListener 插件初始化监听者 - * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws PluginException 异常信息 + * @return true初始化成功, false初始化失败 + * @throws PluginException 抛出异常说明初始化失败 */ boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException; /** - * 校验插件jar包 - * @param pluginPath 插件包的路径 - * @return 成功: 返回true; 失败: 抛出异常或者返回false - * @throws PluginException 校验异常 + * 校验插件jar包 [适用于 dev、prod 环境] + * @param pluginPath 插件包绝对路径 + * @return true校验成功, false校验失败 + * @throws PluginException 抛出异常说明校验插件包失败 */ boolean verify(Path pluginPath) throws PluginException; /** - * 解析插件包 + * 解析插件包 [适用于 dev、prod 环境] * @param pluginPath 插件包路基 * @return 解析的插件信息 - * @throws PluginException 插件异常 + * @throws PluginException 抛出异常说明解析插件包失败 */ PluginInfo parse(Path pluginPath) throws PluginException; /** - * 通过路径安装插件(会启用), 该插件文件必须存在于服务器 [适用于生产环境] - * 如果在插件目录存在同名的插件包, 系统会自动备份该插件包。备份文件命名规则为;[install-backup][时间]_原jar名.jar + * 通过路径安装启动插件 [适用于 dev、prod 环境] * @param pluginPath 插件路径 * @param unpackPlugin 是否解压插件包. (如果插件包为压缩包时生效) * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null @@ -53,34 +53,33 @@ public interface PluginOperator { PluginInfo install(Path pluginPath, boolean unpackPlugin) throws PluginException; /** - * 卸载插件 [适用于生产环境] + * 卸载插件 [适用于 dev、prod 环境] * @param pluginId 插件id - * @param isDelete 卸载后是否删除插件文件. - * @param isBackup 删除插件文件前, 是否备份插件文件。备份文件命名规则为;[uninstall][时间]_原jar名.jar + * @param isDelete 卸载后是否删除插件文件. [适用于 prod 环境] + * @param isBackup 删除插件文件前, 是否备份插件文件。备份文件命名规则为;[uninstall][时间]_原jar名.jar [适用于 prod 环境] * @throws PluginException 异常信息 */ void uninstall(String pluginId, boolean isDelete, boolean isBackup) throws PluginException; /** - * 加载插件, 但不启动 [适用于生产环境] - * @param jarPath 插件路径 + * 加载插件, 但不启动 [适用于 dev、prod 环境] + * @param pluginPath 插件路径 * @param unpackPlugin 是否解压插件包. (如果插件包为压缩包时生效) * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null * @throws PluginException 异常信息 */ - PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException; + PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException; /** - * 配合load使用. 针对load的插件进行unload [适用于生产环境] + * 配合load使用. 针对load的插件进行unload [适用于 dev、prod 环境] * @param pluginId 插件id - * @param isBackup 是否备份原来的插件。备份文件命名规则为;[uninstall][时间]_原jar名.jar * @return 成功返回true.不成功抛出异常或者返回false * @throws PluginException 异常信息 */ - boolean unload(String pluginId, boolean isBackup) throws PluginException; + boolean unload(String pluginId) throws PluginException; /** - * 启用插件 [适用于生产环境、开发环境] + * 启用插件 [适用于 dev、prod 环境] * @param pluginId 插件id * @return 成功返回true.不成功抛出异常或者返回false * @throws PluginException 异常信息 @@ -89,7 +88,7 @@ public interface PluginOperator { /** - * 停止插件 [适用于生产环境、开发环境] + * 停止插件 [适用于 dev、prod 环境] * @param pluginId 插件id * @return 成功: 返回true; 失败: 抛出异常或者返回false * @throws PluginException 异常信息 @@ -97,12 +96,18 @@ public interface PluginOperator { boolean stop(String pluginId) throws PluginException; /** - * 上传插件. + * 上传插件. [适用于 dev、prod 环境] + * dev模式: + * 如果不存在相同插件(插件id不相同), 则正常上传到临时目录, 然后加载、启动。 + * 如果存在相同插件(插件id相同) + * 相同插件在启动状态, 则进入更新模式(满足上传的插件包版本必须大于已启动的插件版本), 系统会自动卸载旧版本, 然后对临时目录中的插件进行安装、启动。 + * 相同插件不在启动状态, 则直接对临时目录中的插件进行安装、启动。 + * prod模式: * 如果不存在相同插件(插件id不相同), 则正常上传到插件目录, 然后加载、启动。 * 如果存在相同插件(插件id相同) - * 相同插件在启动状态, 则进入更新模式, 满足上传的插件包版本必须大于已启动的插件版本, 系统会自动卸载旧版本, 安装新版本。 - * 相同插件不在启动状态, 则进入覆盖模式, 会对旧插件进行备份(可根据isBackOldPlugin配置不备份), 然后上传新插件包到插件目录, 然后加载、启动。 - * 如果存在同文件名称插件, 系统会抛出异常, 建议重命名插件名称, 再上传。 + * 相同插件在启动状态, 则进入更新模式(满足上传的插件包版本必须大于已启动的插件版本), 系统会自动卸载旧版本, 安装新版本。 + * 相同插件不在启动状态, 则进入覆盖模式, 会对旧插件进行备份(可根据isBackOldPlugin配置不备份), 然后上传新插件包到插件目录, 然后安装、启动。 + * 如果在插件根目录存在同文件名称插件, 系统会抛出异常, 建议重命名插件名称, 再上传。 * * @param uploadParam 上传参数 * @return 成功: 返回插件信息PluginInfo; 失败: 抛出异常或者返回null @@ -113,7 +118,7 @@ public interface PluginOperator { PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException; /** - * 通过路径备份文件。可备份插件和插件的配置文件。[适用于生产环境] + * 通过路径备份插件文件。[适用于 prod 环境] * @param backDirPath 备份的目录路径 * @param sign 备份文件的自定义标识 * @return 备份插件的路径 @@ -122,7 +127,7 @@ public interface PluginOperator { Path backupPlugin(Path backDirPath, String sign) throws PluginException; /** - * 通过插件id备份插件。[适用于生产环境] + * 通过插件id备份插件。 [适用于 prod 环境] * @param pluginId 插件id * @param sign 备份文件的自定义标识 * @return 备份插件的路径 @@ -131,13 +136,13 @@ public interface PluginOperator { Path backupPlugin(String pluginId, String sign) throws PluginException; /** - * 获取插件信息 [适用于生产环境、开发环境] + * 获取插件信息 [适用于 dev、prod 环境] * @return 返回插件信息列表 */ List getPluginInfo(); /** - * 根据插件id获取插件信息 [适用于生产环境、开发环境] + * 根据插件id获取插件信息 [适用于 dev、prod 环境] * @param pluginId 插件id * @return 插件信息 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index ac7e068..ec6c085 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -63,11 +63,11 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public boolean unload(String pluginId, boolean isBackup) throws PluginException { + public boolean unload(String pluginId) throws PluginException { if(isDisable()){ return false; } - return pluginOperator.unload(pluginId, isBackup); + return pluginOperator.unload(pluginId); } @Override @@ -79,11 +79,11 @@ public class PluginOperatorWrapper implements PluginOperator{ } @Override - public PluginInfo load(Path jarPath, boolean unpackPlugin) throws PluginException { + public PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException { if(isDisable()){ return null; } - return pluginOperator.install(jarPath, unpackPlugin); + return pluginOperator.install(pluginPath, unpackPlugin); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java new file mode 100644 index 0000000..85f6503 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java @@ -0,0 +1,34 @@ +package com.gitee.starblues.integration.user; + +import java.util.Map; + +/** + * bean包装类 + * @author starBlues + * @version 3.0.0 + */ +public class BeanWrapper { + + /** + * 主程序bean + */ + private final T mainBean; + + /** + * 插件bean. key为插件id + */ + private final Map pluginBean; + + public BeanWrapper(T mainBean, Map pluginBean) { + this.mainBean = mainBean; + this.pluginBean = pluginBean; + } + + public T getMainBean() { + return mainBean; + } + + public Map getPluginBean() { + return pluginBean; + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java index 70deb81..04ba05a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java @@ -1,12 +1,12 @@ package com.gitee.starblues.integration.user; +import com.gitee.starblues.core.exception.PluginException; +import com.gitee.starblues.core.launcher.plugin.involved.PluginApplicationContextGetter; +import com.gitee.starblues.spring.ApplicationContext; +import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; +import com.gitee.starblues.utils.SpringBeanCustomUtils; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.util.ObjectUtils; import java.lang.annotation.Annotation; import java.util.*; @@ -14,191 +14,128 @@ import java.util.*; /** * 默认插件使用者 * @author starBlues - * @version 2.4.0 + * @version 3.0.0 */ public class DefaultPluginUser implements PluginUser{ - protected final Logger log = LoggerFactory.getLogger(this.getClass()); - protected final GenericApplicationContext parentApplicationContext; - public DefaultPluginUser(ApplicationContext parentApplicationContext) { + public DefaultPluginUser(GenericApplicationContext parentApplicationContext) { Objects.requireNonNull(parentApplicationContext, "ApplicationContext can't be null"); - this.parentApplicationContext = (GenericApplicationContext)parentApplicationContext; + this.parentApplicationContext = parentApplicationContext; } - /** - * 通过bean名称得到插件的bean。(Spring管理的bean) - * @param name 插件bean的名称。spring体系中的bean名称。可以通过注解定义,也可以自定义生成。具体可百度 - * @param bean的类型 - * @return 返回bean - */ @Override - public T getBean(String name){ - return getBean(name, true); + public BeanWrapper> getBeanName(boolean includeMainBeans) { + Set mainBeanSet = new HashSet<>(); + if(includeMainBeans){ + mainBeanSet = SpringBeanUtils.getBeanName(parentApplicationContext); + } + Map applicationContexts = PluginApplicationContextGetter.get(); + Map> pluginBeanNames = new HashMap<>(applicationContexts.size()); + applicationContexts.forEach((k,v)->{ + pluginBeanNames.put(k, SpringBeanCustomUtils.getBeanName(v)); + }); + return new BeanWrapper<>(mainBeanSet, pluginBeanNames); } @Override - public T getBean(Class aClass) { - return getBean(aClass, true); + public Set getBeanName(String pluginId) { + return null; } @Override - public T getPluginBean(String name) { - return getBean(name, false); + public BeanWrapper getBean(String name, boolean includeMainBeans){ + Object mainBean = null; + if(includeMainBeans){ + mainBean = SpringBeanUtils.getExistBean(parentApplicationContext, name); + } + Map applicationContexts = PluginApplicationContextGetter.get(); + Map pluginBeans = new HashMap<>(applicationContexts.size()); + applicationContexts.forEach((k,v)->{ + Object existBean = SpringBeanCustomUtils.getExistBean(v, name); + if(existBean != null){ + pluginBeans.put(k, v); + } + }); + return new BeanWrapper<>(mainBean, pluginBeans); } - /** - * 在主程序中定义的接口。插件或者主程序实现该接口。可以该方法获取到实现该接口的所有实现类。(Spring管理的bean) - * @param aClass 接口的类 - * @param bean的类型 - * @return List - */ @Override - public List getBeans(Class aClass){ - return getBeans(aClass, 3); + public Object getBean(String pluginId, String name) { + ApplicationContext applicationContext = PluginApplicationContextGetter.get(pluginId); + if(applicationContext == null){ + return null; + } + return SpringBeanCustomUtils.getExistBean(applicationContext, name); } @Override - public List getMainBeans(Class aClass) { - return getBeans(aClass, 1); + public BeanWrapper> getBeanByInterface(Class interfaceClass, boolean includeMainBeans) { + checkInterface(interfaceClass); + List mainBeans = new ArrayList<>(); + if(includeMainBeans){ + mainBeans = SpringBeanUtils.getBeans(parentApplicationContext, interfaceClass); + } + Map applicationContexts = PluginApplicationContextGetter.get(); + Map> pluginBeans = new HashMap<>(applicationContexts.size()); + applicationContexts.forEach((k,v)->{ + List beans = SpringBeanCustomUtils.getBeans(v, interfaceClass); + if(!ObjectUtils.isEmpty(beans)){ + pluginBeans.put(k, beans); + } + }); + return new BeanWrapper<>(mainBeans, pluginBeans); } - /** - * 在主程序中定义的接口。获取插件中实现该接口的实现类。(Spring管理的bean) - * @param aClass 接口的类 - * @param bean的类型 - * @return List - */ @Override - public List getPluginBeans(Class aClass) { - return getBeans(aClass, 2); + public List getBeanByInterface(String pluginId, Class interfaceClass) { + checkInterface(interfaceClass); + List result = new ArrayList<>(); + ApplicationContext applicationContext = PluginApplicationContextGetter.get(pluginId); + if(applicationContext != null){ + result.addAll(SpringBeanCustomUtils.getBeans(applicationContext, interfaceClass)); + } + return result; } @Override - public List getPluginBeans(String pluginId, Class aClass) { -// ConfigurableApplicationContext pluginApplicationContext = -// PluginInfoContainers.getPluginApplicationContext(pluginId); -// if(pluginApplicationContext == null){ -// return Collections.emptyList(); -// } -// return SpringBeanUtils.getBeans(pluginApplicationContext, aClass); - return null; + public BeanWrapper> getBeansWithAnnotation(Class annotationType, + boolean includeMainBeans) { + List mainBeans = new ArrayList<>(); + if(includeMainBeans){ + mainBeans = SpringBeanUtils.getBeansWithAnnotation(parentApplicationContext, annotationType); + } + Map applicationContexts = PluginApplicationContextGetter.get(); + Map> pluginBeans = new HashMap<>(applicationContexts.size()); + applicationContexts.forEach((k,v)->{ + List beans = SpringBeanCustomUtils.getBeansWithAnnotation(v, annotationType); + if(!ObjectUtils.isEmpty(beans)){ + pluginBeans.put(k, beans); + } + }); + return new BeanWrapper<>(mainBeans, pluginBeans); } - @Override - public List getPluginBeansWithAnnotation(Class annotationType) { -// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); -// List beans = new ArrayList<>(); -// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { -// Map beanMap = pluginApplicationContext.getBeansWithAnnotation(annotationType); -// if(!ObjectUtils.isEmpty(beanMap)){ -// beans.addAll(beanMap.values()); -// } -// } -// return beans; - return null; - } @Override - public List getPluginBeansWithAnnotation(String pluginId, Class annotationType) { -// ConfigurableApplicationContext genericApplicationContext = PluginInfoContainers.getPluginApplicationContext(pluginId); -// if(genericApplicationContext == null){ -// return Collections.emptyList(); -// } -// Map beanMap = genericApplicationContext.getBeansWithAnnotation(annotationType); -// if(!ObjectUtils.isEmpty(beanMap)){ -// return new ArrayList<>(beanMap.values()); -// } else { -// return Collections.emptyList(); -// } - return null; - } - - @Override - public T generateNewInstance(T object) { -// if(object == null){ -// return null; -// } -// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); -// pluginApplicationContexts.add(parentApplicationContext); -// Class aClass = object.getClass(); -// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { -// try { -// // 判断是否存在 -// pluginApplicationContext.getBean(aClass); -// Object newBean = pluginApplicationContext.getBeanFactory() -// .createBean(aClass); -// return (T) newBean; -// } catch (Exception e){ -// // 忽略 -// } -// } - return null; - } - - - private T getBean(String name, boolean haveParent){ -// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); -// if(haveParent){ -// pluginApplicationContexts.add(parentApplicationContext); -// } -// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { -// if(pluginApplicationContext.containsBean(name)){ -// return (T) pluginApplicationContext.getBean(name); -// } -// } - return null; - } - - private T getBean(Class aClass, boolean haveParent) { -// List pluginApplicationContexts = PluginInfoContainers.getPluginApplicationContexts(); -// if(haveParent){ -// pluginApplicationContexts.add(parentApplicationContext); -// } -// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { -// try { -// T bean = pluginApplicationContext.getBean(aClass); -// if(bean != null){ -// return bean; -// } -// } catch (Exception e){ -// // 忽略 -// } -// } - return null; + public List getBeansWithAnnotation(String pluginId, Class annotationType) { + ApplicationContext applicationContext = PluginApplicationContextGetter.get(pluginId); + if(applicationContext != null){ + return SpringBeanCustomUtils.getBeansWithAnnotation(applicationContext, annotationType); + } + return new ArrayList<>(0); } /** - * 获取多个bean. - * @param aClass 接口或者抽象类类类型 - * @param type 1 获取主程序的, 2 获取插件中的, 3 获取所有的 - * @param 类类型 - * @return List + * 判断clazz是否是接口 + * @param clazz clazz */ - private List getBeans(Class aClass, int type) { -// List pluginApplicationContexts = new ArrayList<>(1); -// -// if(type == 1){ -// pluginApplicationContexts.add(parentApplicationContext); -// } else if(type == 2){ -// pluginApplicationContexts.addAll(PluginInfoContainers.getPluginApplicationContexts()); -// } else if(type == 3){ -// pluginApplicationContexts.add(parentApplicationContext); -// pluginApplicationContexts.addAll(PluginInfoContainers.getPluginApplicationContexts()); -// } else { -// return Collections.emptyList(); -// } -// -// List result = new ArrayList<>(); -// for (ConfigurableApplicationContext pluginApplicationContext : pluginApplicationContexts) { -// List pluginBeans = SpringBeanUtils.getBeans(pluginApplicationContext, aClass); -// if(!pluginBeans.isEmpty()){ -// result.addAll(pluginBeans); -// } -// } -// return result; - return null; + private void checkInterface(Class clazz) { + if (clazz.isInterface()) { + return; + } + throw new PluginException("[" + clazz.getName() + "]不是一个接口"); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java index d051211..67712f9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java @@ -2,59 +2,52 @@ package com.gitee.starblues.integration.user; import java.lang.annotation.Annotation; import java.util.List; +import java.util.Set; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class EmptyPluginUser implements PluginUser{ - @Override - public T getBean(String name) { - return null; - } - @Override - public T getBean(Class aClass) { - return null; - } @Override - public T getPluginBean(String name) { + public BeanWrapper> getBeanName(boolean includeMainBeans) { return null; } @Override - public List getBeans(Class aClass) { + public Set getBeanName(String pluginId) { return null; } @Override - public List getMainBeans(Class aClass) { + public BeanWrapper getBean(String name, boolean includeMainBeans) { return null; } @Override - public List getPluginBeans(Class aClass) { + public Object getBean(String pluginId, String name) { return null; } @Override - public List getPluginBeans(String pluginId, Class aClass) { + public BeanWrapper> getBeanByInterface(Class interfaceClass, boolean includeMainBeans) { return null; } @Override - public List getPluginBeansWithAnnotation(Class annotationType) { + public List getBeanByInterface(String pluginId, Class interfaceClass) { return null; } @Override - public List getPluginBeansWithAnnotation(String pluginId, Class annotationType) { + public BeanWrapper> getBeansWithAnnotation(Class annotationType, boolean includeMainBeans) { return null; } @Override - public T generateNewInstance(T object) { + public List getBeansWithAnnotation(String pluginId, Class annotationType) { return null; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java index e8c6fd1..987ff38 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java @@ -3,6 +3,7 @@ package com.gitee.starblues.integration.user; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; +import java.util.Set; /** * 该接口用于在主程序操作Spring管理的插件bean. @@ -13,104 +14,70 @@ import java.util.Map; public interface PluginUser { /** - * 通过bean名称得到bean。(Spring管理的bean) - * @param name bean的名称。spring体系中的bean名称。可以通过注解定义,也可以自定义生成。具体可百度 - * @param bean的类型 - * @return T + * 获取 Bean名称 + * @param includeMainBeans 是否包含主程序 Bean + * @return Bean 包装对象 */ - T getBean(String name); + BeanWrapper> getBeanName(boolean includeMainBeans); /** - * 通过aClass得到bean。(Spring管理的bean) - * @param aClass class - * @param bean的类型 - * @return T + * 获取插件中的Bean名称 + * @param pluginId 插件id + * @return Bean名称集合 */ - T getBean(Class aClass); + Set getBeanName(String pluginId); - /** - * 通过bean名称得到插件中的bean。(Spring管理的bean) - * @param name 插件中bean的名称。spring体系中的bean名称。可以通过注解定义,也可以自定义生成。具体可百度 - * @param bean的类型 - * @return T - */ - T getPluginBean(String name); /** - * 在主程序中定义的接口。 - * 插件或者主程序实现该接口。可以该方法获取到实现该接口的所有实现类。(Spring管理的bean) - * 使用场景: - * 1. 在主程序定义接口 - * 2. 在主程序和插件包中都存在实现该接口, 并使用Spring的组件注解(@Component、@Service) - * 3. 使用该方法可以获取到所以实现该接口的实现类(主程序和插件中)。 - * @param aClass 接口的类 - * @param bean的类型 - * @return List + * 通过 Bean名称获取 Bean 对象。 + * @param name Bean的名称。 + * @param includeMainBeans 是否包含主程序 Bean + * @return Bean包装对象 */ - List getBeans(Class aClass); + BeanWrapper getBean(String name, boolean includeMainBeans); /** - * 得到主函数中定义的类。 - * 使用场景: - * 1. 在主程序定义接口 - * 2. 在主程序和插件包中都存在实现该接口, 并使用Spring的组件注解(@Component、@Service) - * 3. 使用该方法可以获取到主程序实现该接口的实现类。 - * @param aClass 类/接口的类 - * @param bean 的类型 - * @return List + * 通过 Bean名称获取具体插件中的 Bean 对象 + * @param pluginId 插件id。 + * @param name Bean名称 + * @return Object */ - List getMainBeans(Class aClass); + Object getBean(String pluginId, String name); /** - * 在主程序中定义的接口。获取插件中实现该接口的实现类。(Spring管理的bean) - * 使用场景: - * 1. 在主程序定义接口 - * 2. 插件包中实现该接口, 并使用Spring的组件注解(@Component、@Service) - * 3. 使用该方法可以获取到插件中实现该接口的实现类(不包括主程序)。 - * @param aClass 接口的类 - * @param bean的类型 - * @return 实现 aClass 接口的实现类的集合 + * 通过接口获取实现的对象集合 + * @param interfaceClass 接口的类 + * @param includeMainBeans 是否包含主程序 Bean + * @param Bean的类型 + * @return Bean包装对象 */ - List getPluginBeans(Class aClass); + BeanWrapper> getBeanByInterface(Class interfaceClass, boolean includeMainBeans); /** - * 在主程序中定义的接口。获取指定插件中实现该接口的实现类。(Spring管理的bean) - * 使用场景: - * 1. 在主程序定义接口 - * 2. 插件包中实现该接口, 并使用Spring的组件注解(@Component、@Service) - * 3. 使用该方法可以获取到指定插件中实现该接口的实现类。 + * 通过接口获取具体插件中的实现对象集合 * @param pluginId 插件id - * @param aClass 接口的类 - * @param bean的类型 - * @return 实现 aClass 接口的实现类的集合 + * @param interfaceClass 接口的类 + * @param Bean的类型 + * @return List */ - List getPluginBeans(String pluginId, Class aClass); + List getBeanByInterface(String pluginId, Class interfaceClass); /** - * 通过注解获取所有插件中的bean。(Spring管理的bean) + * 通过注解获取 Bean * @param annotationType 注解类型 - * @return 该注解的bean集合 + * @param includeMainBeans 是否包含主程序 Bean + * @return Bean包装对象 */ - List getPluginBeansWithAnnotation(Class annotationType); + BeanWrapper> getBeansWithAnnotation(Class annotationType, boolean includeMainBeans); /** - * 通过注解获取具体插件中的bean。(Spring管理的bean) + * 通过注解获取具体插件中的 Bean * @param pluginId 插件id * @param annotationType 注解类型 - * @return 该注解的bean集合 + * @return 该注解的 Bean 集合 */ - List getPluginBeansWithAnnotation(String pluginId, Class annotationType); - + List getBeansWithAnnotation(String pluginId, Class annotationType); - /** - * 生成一个新的Spring实例Bean. - * 使用场景:主要用于非单例对象的生成。 - * @param object 旧实例对象 - * @param 实例泛型 - * @return 新实例对象 - */ - @Deprecated - T generateNewInstance(T object); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java index 0761121..3a6d865 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java @@ -23,9 +23,12 @@ public class CacheJdkSameTypeParamProxyFactory extends JdkSameTypeParamProxyFact public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Method targetMethod = methodCache.get(method); if(targetMethod == null){ - Class[] paramTypes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - paramTypes[i] = args[i].getClass(); + Class[] paramTypes = null; + if(args != null){ + paramTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + paramTypes[i] = args[i].getClass(); + } } targetMethod = ReflectionUtils.findMethod(target.getClass(), method.getName(), paramTypes); if(targetMethod != null){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java index 8d344f4..b131891 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java @@ -266,8 +266,6 @@ public class PluginStaticResourceResolver extends AbstractResourceResolver { PLUGIN_RESOURCE_MAP.remove(pluginId); } - - /** * 插件资源解析后的信息 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java similarity index 62% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java index 70e9be0..6fe3042 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtilsV3.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java @@ -4,13 +4,27 @@ import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.SpringBeanFactory; import org.springframework.util.ClassUtils; +import java.lang.annotation.Annotation; import java.util.*; /** * @author starBlues * @version 3.0.0 */ -public class SpringBeanUtilsV3 { +public class SpringBeanCustomUtils { + + /** + * 获取bean名称 + * @param applicationContext ApplicationContext + * @return bean名称集合 + */ + public static Set getBeanName(ApplicationContext applicationContext){ + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + String[] beanDefinitionNames = springBeanFactory.getBeanDefinitionNames(); + Set set = new HashSet<>(beanDefinitionNames.length); + set.addAll(Arrays.asList(beanDefinitionNames)); + return set; + } /** * 得到ApplicationContext中的bean的实现 @@ -28,46 +42,6 @@ public class SpringBeanUtilsV3 { return new ArrayList<>(beansOfTypeMap.values()); } - /** - * 得到某个接口的实现对象 - * @param sourceObject 遍历的对象 - * @param interfaceClass 接口类类型 - * @param 接口类型 - * @return 实现对象 - */ - public static T getObjectByInterfaceClass(Set sourceObject, Class interfaceClass){ - if(sourceObject == null || sourceObject.isEmpty()){ - return null; - } - for (Object configSingletonObject : sourceObject) { - Set> allInterfacesForClassAsSet = ClassUtils - .getAllInterfacesAsSet(configSingletonObject); - if(allInterfacesForClassAsSet.contains(interfaceClass)){ - return (T) configSingletonObject; - } - } - return null; - } - - /** - * 获取具体类的对象 - * @param sourceObject 源对象集合 - * @param aClass 对象对应的类类型 - * @param 类实现 - * @return T - */ - public static T getObjectClass(Set sourceObject, Class aClass){ - if(sourceObject == null || sourceObject.isEmpty()){ - return null; - } - for (Object configSingletonObject : sourceObject) { - if(Objects.equals(configSingletonObject.getClass(), aClass)){ - return (T) configSingletonObject; - } - } - return null; - } - /** * 得到存在的bean, 不存在则返回null * @param applicationContext applicationContext @@ -92,6 +66,7 @@ public class SpringBeanUtilsV3 { * @param 返回的bean类型 * @return 存在bean对象, 不存在返回null */ + @SuppressWarnings("unchecked") public static T getExistBean(ApplicationContext applicationContext, String beanName){ SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); if(springBeanFactory.containsBean(beanName)){ @@ -102,4 +77,17 @@ public class SpringBeanUtilsV3 { } } + /** + * 通过注解获取bean + * @param applicationContext applicationContext + * @param annotationType 注解类型 + * @return List + */ + public static List getBeansWithAnnotation(ApplicationContext applicationContext, + Class annotationType){ + SpringBeanFactory springBeanFactory = applicationContext.getSpringBeanFactory(); + Map beanMap = springBeanFactory.getBeansWithAnnotation(annotationType); + return new ArrayList<>(beanMap.values()); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java index fe68758..40dbca7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java @@ -1,17 +1,29 @@ package com.gitee.starblues.utils; import org.springframework.context.ApplicationContext; -import org.springframework.util.ClassUtils; +import java.lang.annotation.Annotation; import java.util.*; /** * 插件bean工具类 * @author starBlues - * @version 2.4.0 + * @version 3.0.0 */ public class SpringBeanUtils { + /** + * 获取bean名称 + * @param applicationContext ApplicationContext + * @return bean名称集合 + */ + public static Set getBeanName(ApplicationContext applicationContext){ + String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); + Set set = new HashSet<>(beanDefinitionNames.length); + set.addAll(Arrays.asList(beanDefinitionNames)); + return set; + } + /** * 得到ApplicationContext中的bean的实现 * @param applicationContext ApplicationContext @@ -27,46 +39,6 @@ public class SpringBeanUtils { return new ArrayList<>(beansOfTypeMap.values()); } - /** - * 得到某个接口的实现对象 - * @param sourceObject 遍历的对象 - * @param interfaceClass 接口类类型 - * @param 接口类型 - * @return 实现对象 - */ - public static T getObjectByInterfaceClass(Set sourceObject, Class interfaceClass){ - if(sourceObject == null || sourceObject.isEmpty()){ - return null; - } - for (Object configSingletonObject : sourceObject) { - Set> allInterfacesForClassAsSet = ClassUtils - .getAllInterfacesAsSet(configSingletonObject); - if(allInterfacesForClassAsSet.contains(interfaceClass)){ - return (T) configSingletonObject; - } - } - return null; - } - - /** - * 获取具体类的对象 - * @param sourceObject 源对象集合 - * @param aClass 对象对应的类类型 - * @param 类实现 - * @return T - */ - public static T getObjectClass(Set sourceObject, Class aClass){ - if(sourceObject == null || sourceObject.isEmpty()){ - return null; - } - for (Object configSingletonObject : sourceObject) { - if(Objects.equals(configSingletonObject.getClass(), aClass)){ - return (T) configSingletonObject; - } - } - return null; - } - /** * 得到存在的bean, 不存在则返回null * @param applicationContext ApplicationContext容器 @@ -90,6 +62,7 @@ public class SpringBeanUtils { * @param 返回的bean类型 * @return 存在bean对象, 不存在返回null */ + @SuppressWarnings("unchecked") public static T getExistBean(ApplicationContext applicationContext, String beanName){ if(applicationContext.containsBean(beanName)){ Object bean = applicationContext.getBean(beanName); @@ -99,4 +72,16 @@ public class SpringBeanUtils { } } + /** + * 通过注解获取bean + * @param applicationContext applicationContext + * @param annotationType 注解类型 + * @return List + */ + public static List getBeansWithAnnotation(ApplicationContext applicationContext, + Class annotationType){ + Map beanMap = applicationContext.getBeansWithAnnotation(annotationType); + return new ArrayList<>(beanMap.values()); + } + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java index 87f29a6..f173741 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java @@ -43,11 +43,14 @@ public class DevRepackager extends BasicRepackager { } protected Map getModuleDependencies(DevConfig devConfig) { - Map moduleDependenciesMap = new HashMap<>(); + if(devConfig == null){ + return Collections.emptyMap(); + } List moduleDependencies = devConfig.getModuleDependencies(); if(CommonUtils.isEmpty(moduleDependencies)){ - return moduleDependenciesMap; + return Collections.emptyMap(); } + Map moduleDependenciesMap = new HashMap<>(); for (Dependency dependency : moduleDependencies) { String moduleDependencyKey = getModuleDependencyKey(dependency.getGroupId(), dependency.getArtifactId()); -- Gitee From ed6d0ef85efcb5da007a358259c2fc28c58ff8b7 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Fri, 28 Jan 2022 20:36:37 +0800 Subject: [PATCH 26/37] update Oneself --- springboot-plugin-bootstrap/pom.xml | 12 +- .../ConfigureMainPluginEnvironment.java | 96 ++++++++++++ .../bootstrap/ConfigurePluginEnvironment.java | 17 ++- .../bootstrap/PluginOneselfInteractive.java | 16 +- .../bootstrap/PluginSpringApplication.java | 37 +++-- .../bootstrap/SpringPluginBootstrap.java | 8 +- .../bootstrap/annotation/OneselfConfig.java | 22 +++ .../ComposeSpringPluginProcessor.java | 17 ++- .../processor/DefaultProcessorContext.java | 13 +- .../processor/ExtractBeanProcessor.java | 4 +- .../processor/FrameDefineBeanProcessor.java | 14 +- .../processor/InvokeOtherPluginProcessor.java | 4 +- .../bootstrap/processor/ProcessorContext.java | 27 ++++ .../processor/SpringPluginProcessor.java | 21 +-- .../web/PluginControllerProcessor.java | 9 +- .../web/PluginInterceptorsProcessor.java | 4 +- .../PluginSpringDocControllerProcessor.java | 112 ++++++++++++++ .../web/PluginStaticResourceProcessor.java | 4 +- .../thymeleaf/PluginThymeleafProcessor.java | 4 +- .../bootstrap/utils/SpringBeanUtils.java | 66 ++++---- .../PluginMainResourcePatternDefiner.java | 6 +- .../support/SpringDocControllerProcessor.java | 71 --------- .../integration/user/PluginUser.java | 5 +- .../starblues/utils/ReflectionUtils.java | 5 +- .../gitee/starblues/utils/ResourceUtils.java | 42 ++---- .../plugin-help.xml | 142 ++++++++++++++++++ 26 files changed, 555 insertions(+), 223 deletions(-) create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java create mode 100644 springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index c547097..de49963 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -21,10 +21,12 @@ 1.9.6 1.7.7 + 2.11.3 + 2.5.6 5.3.2 4.0.1 - 2.11.3 + 1.6.5 @@ -71,6 +73,14 @@ true + + org.springdoc + springdoc-openapi-common + ${springdoc.version} + provided + true + + javax.servlet javax.servlet-api diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java new file mode 100644 index 0000000..59fbf0b --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java @@ -0,0 +1,96 @@ +package com.gitee.starblues.bootstrap; + +import com.gitee.starblues.bootstrap.annotation.OneselfConfig; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.utils.AnnotationUtils; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.PluginFileUtils; +import com.gitee.starblues.utils.ResourceUtils; +import org.springframework.boot.env.PropertiesPropertySourceLoader; +import org.springframework.boot.env.PropertySourceLoader; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.util.ClassUtils; + +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; + +/** + * 插件环境配置 + * @author starBlues + * @version 3.0.0 + */ +class ConfigureMainPluginEnvironment { + + private final ProcessorContext processorContext; + private final List propertySourceLoaders; + + ConfigureMainPluginEnvironment(ProcessorContext processorContext) { + this.processorContext = processorContext; + + this.propertySourceLoaders = new ArrayList<>(2); + this.propertySourceLoaders.add(new YamlPropertySourceLoader()); + this.propertySourceLoaders.add(new PropertiesPropertySourceLoader()); + } + + void configureEnvironment(ConfigurableEnvironment environment, String[] args) { + SpringPluginBootstrap springPluginBootstrap = processorContext.getSpringPluginBootstrap(); + OneselfConfig oneselfConfig = AnnotationUtils.findAnnotation(springPluginBootstrap.getClass(), + OneselfConfig.class); + if(oneselfConfig == null){ + return; + } + String[] mainConfigFileName = oneselfConfig.mainConfigFileName(); + if(mainConfigFileName.length == 0){ + return; + } + for (String fileName : mainConfigFileName) { + load(environment, fileName); + } + } + + + private void load(ConfigurableEnvironment environment, String fileName){ + String fileSuffix = ResourceUtils.getFileSuffix(fileName); + if(ObjectUtils.isEmpty(fileSuffix)){ + return; + } + PropertySourceLoader sourceLoader = null; + for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { + String[] fileExtensions = propertySourceLoader.getFileExtensions(); + for (String fileExtension : fileExtensions) { + if(fileSuffix.equalsIgnoreCase(fileExtension)){ + sourceLoader = propertySourceLoader; + break; + } + } + } + if(sourceLoader == null){ + return; + } + URL url = Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource(fileName); + if(url == null){ + return; + } + try { + Path path = Paths.get(url.toURI()); + Resource resource = new FileSystemResource(path); + List> propertySources = sourceLoader.load(fileName, resource); + for (PropertySource propertySource : propertySources) { + environment.getPropertySources().addFirst(propertySource); + } + } catch (Exception e){ + throw new RuntimeException(e); + } + } + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 90ec086..2629336 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -1,6 +1,8 @@ package com.gitee.starblues.bootstrap; +import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; @@ -28,11 +30,13 @@ class ConfigurePluginEnvironment { public static final String REGISTER_SHUTDOWN_HOOK_PROPERTY = "logging.register-shutdown-hook"; public static final String MBEAN_DOMAIN_PROPERTY_NAME = "spring.liveBeansView.mbeanDomain"; - + private final ProcessorContext processorContext; private final InsidePluginDescriptor pluginDescriptor; - ConfigurePluginEnvironment(InsidePluginDescriptor pluginDescriptor) { - this.pluginDescriptor = Assert.isNotNull(pluginDescriptor, "pluginDescriptor 不能为空"); + ConfigurePluginEnvironment(ProcessorContext processorContext) { + this.processorContext = Assert.isNotNull(processorContext, "processorContext 不能为空"); + this.pluginDescriptor = Assert.isNotNull(processorContext.getPluginDescriptor(), + "pluginDescriptor 不能为空"); } void configureEnvironment(ConfigurableEnvironment environment, String[] args) { @@ -42,11 +46,18 @@ class ConfigurePluginEnvironment { if(!ObjectUtils.isEmpty(configFileName)){ env.put(SPRING_CONFIG_NAME, PluginFileUtils.getFileName(configFileName)); } + env.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); env.put(SPRING_JMX_UNIQUE_NAMES, true); env.put(SPRING_ADMIN_JMX_NAME, SPRING_ADMIN_JMX_VALUE + pluginId); env.put(REGISTER_SHUTDOWN_HOOK_PROPERTY, false); env.put(MBEAN_DOMAIN_PROPERTY_NAME, null); environment.getPropertySources().addLast(new MapPropertySource(PLUGIN_PROPERTY_NAME, env)); + + if(processorContext.runMode() == ProcessorContext.RunMode.ONESELF){ + ConfigureMainPluginEnvironment configureMainPluginEnvironment = + new ConfigureMainPluginEnvironment(processorContext); + configureMainPluginEnvironment.configureEnvironment(environment, args); + } } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index a53dd53..ac39020 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -1,5 +1,6 @@ package com.gitee.starblues.bootstrap; +import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.core.descriptor.*; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.AutoIntegrationConfiguration; @@ -9,7 +10,9 @@ import com.gitee.starblues.spring.extract.DefaultOpExtractFactory; import com.gitee.starblues.spring.extract.OpExtractFactory; import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; import com.gitee.starblues.spring.invoke.InvokeSupperCache; +import com.gitee.starblues.utils.CommonUtils; +import java.nio.file.Path; import java.nio.file.Paths; /** @@ -33,7 +36,6 @@ public class PluginOneselfInteractive implements PluginInteractive { this.opExtractFactory = new DefaultOpExtractFactory(); } - @Override public InsidePluginDescriptor getPluginDescriptor() { return pluginDescriptor; @@ -60,16 +62,16 @@ public class PluginOneselfInteractive implements PluginInteractive { } private InsidePluginDescriptor createPluginDescriptor(){ - InsidePluginDescriptor pluginDescriptor; try (PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader()){ - pluginDescriptor = pluginDescriptorLoader.load( - Paths.get(this.getClass().getResource("/").toURI())); + Path classesPath = Paths.get(this.getClass().getResource("/").toURI()).getParent(); + String metaInf = CommonUtils.joiningFilePath(classesPath.toString(), PackageStructure.META_INF_NAME); + InsidePluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(Paths.get(metaInf)); if(pluginDescriptor == null){ - pluginDescriptor = new EmptyPluginDescriptor(); + throw new RuntimeException("没有发现插件信息, 请使用框架提供的Maven插件器对插件进行编译!"); } + return pluginDescriptor; } catch (Exception e){ - pluginDescriptor = new EmptyPluginDescriptor(); + throw new RuntimeException(e); } - return pluginDescriptor; } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java index 3830f19..da7393b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -2,6 +2,7 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.ApplicationContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -23,10 +24,13 @@ public class PluginSpringApplication extends SpringApplication { private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private final ProcessorContext.RunMode runMode; + private final SpringPluginProcessor pluginProcessor; private final ProcessorContext processorContext; private final GenericApplicationContext applicationContext; + private final DefaultListableBeanFactory beanFactory; private final ResourceLoader resourceLoader; private final ConfigurePluginEnvironment configurePluginEnvironment; @@ -35,22 +39,33 @@ public class PluginSpringApplication extends SpringApplication { ProcessorContext processorContext, Class... primarySources) { super(primarySources); + this.runMode = processorContext.runMode(); this.pluginProcessor = pluginProcessor; this.processorContext = processorContext; this.resourceLoader = processorContext.getResourceLoader(); this.beanFactory = new PluginListableBeanFactory(processorContext.getMainApplicationContext()); - this.applicationContext = new PluginApplicationContext(beanFactory, processorContext); - this.configurePluginEnvironment = new ConfigurePluginEnvironment(processorContext.getPluginDescriptor()); - setDefaultConfig(); + this.configurePluginEnvironment = new ConfigurePluginEnvironment(processorContext); + this.applicationContext = getApplicationContext(); + setDefaultPluginConfig(); + } + + protected GenericApplicationContext getApplicationContext(){ + if(runMode == ProcessorContext.RunMode.ONESELF){ + return (GenericApplicationContext) super.createApplicationContext(); + } else { + return new PluginApplicationContext(beanFactory, processorContext); + } } - private void setDefaultConfig(){ - setResourceLoader(resourceLoader); - setBannerMode(Banner.Mode.OFF); - setEnvironment(new StandardEnvironment()); - setWebApplicationType(WebApplicationType.NONE); - setRegisterShutdownHook(false); - setLogStartupInfo(false); + public void setDefaultPluginConfig(){ + if(runMode == ProcessorContext.RunMode.PLUGIN){ + setResourceLoader(resourceLoader); + setBannerMode(Banner.Mode.OFF); + setEnvironment(new StandardEnvironment()); + setWebApplicationType(WebApplicationType.NONE); + setRegisterShutdownHook(false); + setLogStartupInfo(false); + } } @Override @@ -61,7 +76,7 @@ public class PluginSpringApplication extends SpringApplication { @Override protected ConfigurableApplicationContext createApplicationContext() { - return applicationContext; + return this.applicationContext; } @Override diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java index 9ad1211..b49f60d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java @@ -17,7 +17,7 @@ import java.util.List; */ public abstract class SpringPluginBootstrap { - private SpringPluginProcessor.RunMode runMode = SpringPluginProcessor.RunMode.ONESELF; + private ProcessorContext.RunMode runMode = ProcessorContext.RunMode.ONESELF; private volatile PluginInteractive pluginInteractive; @@ -36,11 +36,11 @@ public abstract class SpringPluginBootstrap { } private SpringPluginHook start(Class[] primarySources, String[] args){ - addCustomSpringPluginProcessor(); createPluginInteractive(); + addCustomSpringPluginProcessor(); SpringPluginProcessor pluginProcessor = new ComposeSpringPluginProcessor(runMode, customPluginProcessors); ProcessorContext processorContext = new DefaultProcessorContext( - this, pluginInteractive, this.getClass() + runMode, this, pluginInteractive, this.getClass() ); PluginSpringApplication springApplication = new PluginSpringApplication( pluginProcessor, @@ -52,7 +52,7 @@ public abstract class SpringPluginBootstrap { public final SpringPluginBootstrap setPluginInteractive(PluginInteractive pluginInteractive) { this.pluginInteractive = pluginInteractive; - this.runMode = SpringPluginProcessor.RunMode.PLUGIN; + this.runMode = ProcessorContext.RunMode.PLUGIN; return this; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java new file mode 100644 index 0000000..736e699 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java @@ -0,0 +1,22 @@ +package com.gitee.starblues.bootstrap.annotation; + +import java.lang.annotation.*; + +/** + * 插件自主运行配置 + * @author starBlues + * @version 3.0.0 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface OneselfConfig { + + /** + * 主程序配置文件名称 + * @return String[] + */ + String[] mainConfigFileName() default {}; + + +} diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index 456a369..6cc097b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -4,9 +4,11 @@ import com.gitee.starblues.bootstrap.SpringPluginBootstrap; import com.gitee.starblues.bootstrap.annotation.DisablePluginWeb; import com.gitee.starblues.bootstrap.processor.web.PluginControllerProcessor; import com.gitee.starblues.bootstrap.processor.web.PluginInterceptorsProcessor; +import com.gitee.starblues.bootstrap.processor.web.PluginSpringDocControllerProcessor; import com.gitee.starblues.bootstrap.processor.web.PluginStaticResourceProcessor; import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; +import com.gitee.starblues.bootstrap.utils.ProcessorUtils; import com.gitee.starblues.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.OrderPriority; @@ -26,15 +28,15 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final RunMode runMode; + private final ProcessorContext.RunMode runMode; private List processors; - public ComposeSpringPluginProcessor(RunMode runMode) { + public ComposeSpringPluginProcessor(ProcessorContext.RunMode runMode) { this(runMode, null); } - public ComposeSpringPluginProcessor(RunMode runMode, List processors) { + public ComposeSpringPluginProcessor(ProcessorContext.RunMode runMode, List processors) { this.runMode = runMode; if(!ObjectUtils.isEmpty(processors)){ this.processors = processors; @@ -57,8 +59,8 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { processors.addAll(this.processors); this.processors = processors.stream() .filter(p->{ - RunMode runMode = p.runMode(); - return runMode == RunMode.ALL || runMode == this.runMode; + ProcessorContext.RunMode runMode = p.runMode(); + return runMode == ProcessorContext.RunMode.ALL || runMode == this.runMode; }) .sorted(CommonUtils.orderPriority(SpringPluginProcessor::order)) .collect(Collectors.toList()); @@ -121,8 +123,8 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { } @Override - public RunMode runMode() { - return RunMode.ALL; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.ALL; } /** @@ -153,6 +155,7 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { processors.add(new PluginInterceptorsProcessor()); processors.add(new PluginStaticResourceProcessor()); processors.add(new PluginThymeleafProcessor()); + ProcessorUtils.add(processors, PluginSpringDocControllerProcessor::new); } private void processException(SpringPluginProcessor processor, String executeType, diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 4963f24..d83cfbe 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -21,6 +21,8 @@ import org.springframework.util.ClassUtils; */ public class DefaultProcessorContext extends CacheRegistryInfo implements ProcessorContext{ + private final RunMode runMode; + private final SpringPluginBootstrap springPluginBootstrap; private final PluginInteractive pluginInteractive; private final Class runnerClass; @@ -33,9 +35,9 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces private GenericApplicationContext applicationContext; - public DefaultProcessorContext(SpringPluginBootstrap springPluginBootstrap, - PluginInteractive pluginInteractive, - Class runnerClass) { + public DefaultProcessorContext(RunMode runMode, SpringPluginBootstrap springPluginBootstrap, + PluginInteractive pluginInteractive, Class runnerClass) { + this.runMode = runMode; this.springPluginBootstrap = springPluginBootstrap; this.pluginInteractive = pluginInteractive; this.runnerClass = runnerClass; @@ -46,6 +48,11 @@ public class DefaultProcessorContext extends CacheRegistryInfo implements Proces this.webConfig = new WebConfig(); } + @Override + public RunMode runMode() { + return runMode; + } + @Override public SpringPluginBootstrap getSpringPluginBootstrap() { return springPluginBootstrap; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java index 2f3fe2d..9d9b6fa 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java @@ -39,7 +39,7 @@ public class ExtractBeanProcessor implements SpringPluginProcessor { } @Override - public RunMode runMode() { - return RunMode.ALL; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.ALL; } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java index 7f4afbf..aee9f1e 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java @@ -3,8 +3,11 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.integration.AutoIntegrationConfiguration; +import com.gitee.starblues.integration.ExtendPointConfiguration; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; /** * 框架内置bean注册 @@ -15,15 +18,20 @@ public class FrameDefineBeanProcessor implements SpringPluginProcessor { @Override public void refreshBefore(ProcessorContext context) throws ProcessorException { - ConfigurableApplicationContext applicationContext = context.getApplicationContext(); + GenericApplicationContext applicationContext = context.getApplicationContext(); InsidePluginDescriptor pluginDescriptor = context.getPluginDescriptor(); ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); beanFactory.registerSingleton("pluginDescriptor", pluginDescriptor.toPluginDescriptor()); + + if(context.runMode() == ProcessorContext.RunMode.ONESELF){ + beanFactory.registerSingleton("integrationConfiguration", new AutoIntegrationConfiguration()); + applicationContext.registerBean(ExtendPointConfiguration.class); + } } @Override - public RunMode runMode() { - return RunMode.ALL; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.ALL; } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java index 91a77dc..d8a41c5 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java @@ -52,8 +52,8 @@ public class InvokeOtherPluginProcessor implements SpringPluginProcessor { } @Override - public RunMode runMode() { - return RunMode.ALL; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.ALL; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index 527ec33..5f5c942 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -19,6 +19,12 @@ import org.springframework.core.io.ResourceLoader; */ public interface ProcessorContext extends RegistryInfo { + /** + * 当前运行模式 + * @return RunMode + */ + RunMode runMode(); + /** * 得到入口类对象-SpringPluginBootstrap * @return SpringPluginBootstrap @@ -92,4 +98,25 @@ public interface ProcessorContext extends RegistryInfo { */ void setApplicationContext(GenericApplicationContext applicationContext); + /** + * 运行模式 + */ + enum RunMode{ + /** + * 全部运行 + */ + ALL, + + /** + * 插件环境运行 + */ + PLUGIN, + + /** + * 插件独立运行 + */ + ONESELF + } + + } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java index fd12d6d..4b656d9 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java @@ -68,26 +68,7 @@ public interface SpringPluginProcessor extends Order { * 处理器运行模式 * @return RunMode */ - RunMode runMode(); + ProcessorContext.RunMode runMode(); - /** - * 运行模式 - */ - enum RunMode{ - /** - * 全部运行 - */ - ALL, - - /** - * 插件环境运行 - */ - PLUGIN, - - /** - * 插件独立运行 - */ - ONESELF - } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java index 942f610..fb9ee65 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java @@ -33,7 +33,7 @@ public class PluginControllerProcessor implements SpringPluginProcessor { private final static Logger LOG = LoggerFactory.getLogger(PluginControllerProcessor.class); - private static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; + static final String PROCESS_CONTROLLERS = "PROCESS_SUCCESS"; private RequestMappingHandlerMapping requestMappingHandlerMapping; @@ -116,11 +116,12 @@ public class PluginControllerProcessor implements SpringPluginProcessor { for (ControllerWrapper controllerWrapper : controllerWrappers) { unregister(controllerWrapper); } + controllerWrappers.clear(); } @Override - public RunMode runMode() { - return RunMode.PLUGIN; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.PLUGIN; } @@ -250,7 +251,7 @@ public class PluginControllerProcessor implements SpringPluginProcessor { } - private static class ControllerWrapper{ + static class ControllerWrapper{ /** * controller bean 名称 diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java index a1ac87b..1609ffc 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java @@ -96,8 +96,8 @@ public class PluginInterceptorsProcessor implements SpringPluginProcessor { } @Override - public RunMode runMode() { - return RunMode.PLUGIN; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.PLUGIN; } /** diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java new file mode 100644 index 0000000..e0005d4 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java @@ -0,0 +1,112 @@ +package com.gitee.starblues.bootstrap.processor.web; + +import com.gitee.starblues.bootstrap.processor.ProcessorContext; +import com.gitee.starblues.bootstrap.processor.ProcessorException; +import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; +import com.gitee.starblues.spring.MainApplicationContext; +import com.gitee.starblues.utils.ClassUtils; +import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ReflectionUtils; +import com.gitee.starblues.utils.SpringBeanCustomUtils; +import io.swagger.v3.oas.models.OpenAPI; +import org.springdoc.api.AbstractOpenApiResource; +import org.springdoc.core.OpenAPIService; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * spring doc + * @author starBlues + * @version 3.0.0 + */ +public class PluginSpringDocControllerProcessor implements SpringPluginProcessor { + + static final String CONTROLLER_API_CLASS = "controller_api_class"; + + private OpenAPIService openApiService; + private List> restControllers; + + @SuppressWarnings("unchecked") + @Override + public void initialize(ProcessorContext context) throws ProcessorException { + + try { + MainApplicationContext mainApplicationContext = context.getMainApplicationContext(); + openApiService = SpringBeanCustomUtils.getExistBean(mainApplicationContext, OpenAPIService.class); + AbstractOpenApiResource openApiResource = SpringBeanCustomUtils.getExistBean(mainApplicationContext, + AbstractOpenApiResource.class); + if(openApiResource == null){ + return; + } + restControllers = (List>) ReflectionUtils.getField(null, openApiResource.getClass(), + "ADDITIONAL_REST_CONTROLLERS", List.class); + } catch (Throwable e) { + restControllers = null; + } + } + + @Override + public void refreshAfter(ProcessorContext context) throws ProcessorException { + if(restControllers == null){ + return; + } + List controllerWrappers = context.getRegistryInfo( + PluginControllerProcessor.PROCESS_CONTROLLERS); + if(ObjectUtils.isEmpty(controllerWrappers)){ + return; + } + List> apiClass = new ArrayList<>(); + for (PluginControllerProcessor.ControllerWrapper controllerWrapper : controllerWrappers) { + Class beanClass = controllerWrapper.getBeanClass(); + restControllers.add(beanClass); + apiClass.add(beanClass); + } + context.addRegistryInfo(CONTROLLER_API_CLASS, apiClass); + refresh(); + } + + @Override + public void close(ProcessorContext context) throws ProcessorException { + if(restControllers == null){ + return; + } + List> apiClass = context.getRegistryInfo(CONTROLLER_API_CLASS); + if(ObjectUtils.isEmpty(apiClass)){ + return; + } + try { + for (Class controllerClass : apiClass) { + restControllers.remove(controllerClass); + } + refresh(); + } finally { + apiClass.clear(); + } + } + + private void refresh(){ + if(openApiService != null){ + try { + // 兼容版本: 1.5.x + Method setCachedOpenApiMethod = + ReflectionUtils.findMethod(openApiService.getClass(), "setCachedOpenAPI", OpenAPI.class); + if(setCachedOpenApiMethod != null){ + setCachedOpenApiMethod.invoke(openApiService, null); + } + } catch (Exception e){ + // 忽略 + } + openApiService.resetCalculatedOpenAPI(); + } + } + + + @Override + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.PLUGIN; + } +} + diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java index ee0b196..6912393 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java @@ -50,7 +50,7 @@ public class PluginStaticResourceProcessor implements SpringPluginProcessor { } @Override - public RunMode runMode() { - return RunMode.PLUGIN; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.PLUGIN; } } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java index 37e19c7..a55cfd0 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java @@ -33,8 +33,8 @@ public class PluginThymeleafProcessor implements SpringPluginProcessor { } @Override - public RunMode runMode() { - return RunMode.PLUGIN; + public ProcessorContext.RunMode runMode() { + return ProcessorContext.RunMode.PLUGIN; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java index 654f9e2..50978b8 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java @@ -3,6 +3,7 @@ package com.gitee.starblues.bootstrap.utils; import org.springframework.context.ApplicationContext; import org.springframework.util.ClassUtils; +import java.lang.annotation.Annotation; import java.util.*; /** @@ -11,6 +12,17 @@ import java.util.*; * @version 3.0.0 */ public class SpringBeanUtils { + /** + * 获取bean名称 + * @param applicationContext ApplicationContext + * @return bean名称集合 + */ + public static Set getBeanName(ApplicationContext applicationContext){ + String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); + Set set = new HashSet<>(beanDefinitionNames.length); + set.addAll(Arrays.asList(beanDefinitionNames)); + return set; + } /** * 得到ApplicationContext中的bean的实现 @@ -27,46 +39,6 @@ public class SpringBeanUtils { return new ArrayList<>(beansOfTypeMap.values()); } - /** - * 得到某个接口的实现对象 - * @param sourceObject 遍历的对象 - * @param interfaceClass 接口类类型 - * @param 接口类型 - * @return 实现对象 - */ - public static T getObjectByInterfaceClass(Set sourceObject, Class interfaceClass){ - if(sourceObject == null || sourceObject.isEmpty()){ - return null; - } - for (Object configSingletonObject : sourceObject) { - Set> allInterfacesForClassAsSet = ClassUtils - .getAllInterfacesAsSet(configSingletonObject); - if(allInterfacesForClassAsSet.contains(interfaceClass)){ - return (T) configSingletonObject; - } - } - return null; - } - - /** - * 获取具体类的对象 - * @param sourceObject 源对象集合 - * @param aClass 对象对应的类类型 - * @param 类实现 - * @return T - */ - public static T getObjectClass(Set sourceObject, Class aClass){ - if(sourceObject == null || sourceObject.isEmpty()){ - return null; - } - for (Object configSingletonObject : sourceObject) { - if(Objects.equals(configSingletonObject.getClass(), aClass)){ - return (T) configSingletonObject; - } - } - return null; - } - /** * 得到存在的bean, 不存在则返回null * @param applicationContext ApplicationContext容器 @@ -90,6 +62,7 @@ public class SpringBeanUtils { * @param 返回的bean类型 * @return 存在bean对象, 不存在返回null */ + @SuppressWarnings("unchecked") public static T getExistBean(ApplicationContext applicationContext, String beanName){ if(applicationContext.containsBean(beanName)){ Object bean = applicationContext.getBean(beanName); @@ -99,4 +72,17 @@ public class SpringBeanUtils { } } + /** + * 通过注解获取bean + * @param applicationContext applicationContext + * @param annotationType 注解类型 + * @return List + */ + public static List getBeansWithAnnotation(ApplicationContext applicationContext, + Class annotationType){ + Map beanMap = applicationContext.getBeansWithAnnotation(annotationType); + return new ArrayList<>(beanMap.values()); + } + + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index d0a914b..9b1a94c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -41,7 +41,7 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef } includeResourcePatterns.add(FRAMEWORK); addWebIncludeResourcePatterns(includeResourcePatterns); - addSwagger(includeResourcePatterns); + addApiDoc(includeResourcePatterns); // 配置插件自定义从主程序加载的资源匹配 Set includeMainResourcePatterns = descriptor.getIncludeMainResourcePatterns(); @@ -84,11 +84,13 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef patterns.add("org/springframework/ui/**"); patterns.add("com/fasterxml/jackson/**"); + } - protected void addSwagger(Set patterns){ + protected void addApiDoc(Set patterns){ patterns.add("springfox/documentation/**"); patterns.add("io/swagger/**"); + patterns.add("org/springdoc/**"); } /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java deleted file mode 100644 index e15f7bb..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/extension/support/SpringDocControllerProcessor.java +++ /dev/null @@ -1,71 +0,0 @@ -//package com.gitee.starblues.extension.support; -// -//import com.gitee.starblues.extension.PluginControllerProcessorExtend; -//import com.gitee.starblues.factory.process.post.bean.model.ControllerWrapper; -//import com.gitee.starblues.utils.ClassUtils; -//import com.gitee.starblues.utils.SpringBeanUtils; -//import org.springdoc.api.AbstractOpenApiResource; -//import org.springdoc.core.OpenAPIService; -//import org.springframework.context.ApplicationContext; -// -//import java.util.List; -// -///** -// * @author starBlues -// * @version 2.4.0 -// */ -//public class SpringDocControllerProcessor implements PluginControllerProcessorExtend { -// -// private final ApplicationContext applicationContext; -// -// private List> restControllers; -// private OpenAPIService openAPIService; -// -// public SpringDocControllerProcessor(ApplicationContext applicationContext) { -// this.applicationContext = applicationContext; -// } -// -// -// @Override -// public void initialize() { -// AbstractOpenApiResource openApiResource = SpringBeanUtils.getExistBean(applicationContext, AbstractOpenApiResource.class); -// if(openApiResource == null){ -// return; -// } -// try { -// restControllers = ClassUtils.getReflectionField(openApiResource, -// "ADDITIONAL_REST_CONTROLLERS"); -// } catch (IllegalAccessException e) { -// restControllers = null; -// } -// openAPIService = SpringBeanUtils.getExistBean(applicationContext, OpenAPIService.class); -// } -// -// @Override -// public void registry(String pluginId, List controllerWrappers) throws Exception { -// if(restControllers != null){ -// for (ControllerWrapper controllerWrapper : controllerWrappers) { -// restControllers.add(controllerWrapper.getBeanClass()); -// } -// refresh(); -// } -// } -// -// @Override -// public void unRegistry(String pluginId, List controllerWrappers) throws Exception { -// if(restControllers != null && !restControllers.isEmpty()){ -// for (ControllerWrapper controllerWrapper : controllerWrappers) { -// restControllers.remove(controllerWrapper.getBeanClass()); -// } -// refresh(); -// } -// } -// -// private void refresh(){ -// if(openAPIService != null){ -// openAPIService.setCachedOpenAPI(null); -// openAPIService.resetCalculatedOpenAPI(); -// } -// } -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java index 987ff38..c309f90 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java @@ -6,10 +6,9 @@ import java.util.Map; import java.util.Set; /** - * 该接口用于在主程序操作Spring管理的插件bean. - * 主要用途: 在主程序定义接口。插件中实现该接口做扩展, 主程序通过接口class可以获取到插件中的实现类。 + * 该接口用于在主程序操作获取主程序/插件中 Spring 管理 Bean * @author starBlues - * @version 2.2.2 + * @version 3.0.0 */ public interface PluginUser { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 7cee3ce..4030259 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -44,12 +44,9 @@ public abstract class ReflectionUtils { Field[] declaredFields = clazz.getDeclaredFields(); - if(declaredFields.length == 0){ - return null; - } while (true){ for (Field field : declaredFields) { - if(filter.filter(field)){ + if (filter.filter(field)) { return field; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 862d900..69e6c92 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -195,36 +195,6 @@ public class ResourceUtils { } -// /** -// * 根据 ~ 标记获取, 得到绝对路径 -// * @param pluginRegistryInfo pluginRegistryInfo -// * @param rootDir 根目录 -// * @return java.lang.String -// **/ -// public static String getAbsolutePath(PluginRegistryInfo pluginRegistryInfo, String rootDir){ -// if(StringUtils.isNullOrEmpty(rootDir)){ -// return rootDir; -// } -// String home = null; -// if(rootDir.startsWith(ResourceUtils.ROOT_PLUGIN_SIGN)){ -// String pluginRootDir; -// PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); -// RuntimeMode runtimeMode = pluginWrapper.getRuntimeMode(); -// if(runtimeMode == RuntimeMode.DEVELOPMENT){ -// pluginRootDir = pluginWrapper.getPluginPath().toString(); -// } else { -// pluginRootDir = System.getProperty("user.dir"); -// } -// // 如果root路径中开始存在ROOT_PLUGIN_SIGN,则说明进行插件根路替换 -// home = rootDir.replaceFirst("\\" + ResourceUtils.ROOT_PLUGIN_SIGN, ""); -// home = CommonUtils.joiningFilePath(pluginRootDir, home); -// } else { -// home = rootDir; -// } -// return home; -// } - - public static boolean isUrl(String resourceLocation) { if (resourceLocation == null) { return false; @@ -259,4 +229,16 @@ public class ResourceUtils { } } + public static String getFileSuffix(String fileName){ + if(fileName == null){ + return null; + } + int i = fileName.lastIndexOf("."); + if(i > 0 && fileName.length() >= (i + 1)){ + return fileName.substring(i + 1); + } else { + return ""; + } + } + } diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml new file mode 100644 index 0000000..926c24b --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml @@ -0,0 +1,142 @@ + + + + + + Spring Boot Plugin Maven Packager + com.gitee.starblues + springboot-plugin-maven-packager + 3.0.0-RELEASE + springboot-plugin + false + true + + + repackage + Repackage existing JAR and WAR archives so that they can be executed from the command + line using {@literal java -jar}. With <code>layout=NONE</code> can also be used simply + to package a JAR with nested dependencies (and no main class, so not executable). + compile+runtime + false + true + false + false + false + true + package + com.gitee.starblues.plugin.pack.RepackageMojo + java + per-lookup + once-per-session + 1.0.0 + compile+runtime + true + + + project + org.apache.maven.project.MavenProject + 1.0.0 + true + false + The Maven project. + + + outputDirectory + java.io.File + 1.0.0 + true + true + Directory containing the generated archive. + + + includes + java.util.List + 1.2.0 + false + true + Collection of artifact definitions to include. The {@link Include} element defines + mandatory {@code groupId} and {@code artifactId} properties and an optional + mandatory {@code groupId} and {@code artifactId} properties and an optional + {@code classifier} property. + + + excludes + java.util.List + 1.1.0 + false + true + Collection of artifact definitions to exclude. The {@link Exclude} element defines + mandatory {@code groupId} and {@code artifactId} properties and an optional + {@code classifier} property. + + + skip + boolean + 1.2.0 + false + true + Skip the execution. + + + mode + string + 3.0.0 + true + true + 打包模式: dev/prod ,默认为dev + + + pluginInfo + com.gitee.starblues.plugin.pack.PluginInfo + 3.0.0 + false + true + 插件信息 + + + loadMainResourcePattern + com.gitee.starblues.plugin.pack.LoadMainResourcePattern + 3.0.0 + false + true + 从主程序加载资源的定义 + + + devConfig + com.gitee.starblues.plugin.pack.dev.DevConfig + 3.0.0 + false + true + dev打包模式配置 + + + prodConfig + com.gitee.starblues.plugin.pack.prod.ProdConfig + 3.0.0 + false + true + prod打包模式配置 + + + + + + + + + + ${springboot-plugin.includes} + ${springboot-plugin.excludes} + + + + + + org.apache.maven.project.MavenProjectHelper + projectHelper + + + + + + \ No newline at end of file -- Gitee From c02834dec5e2a719b992125649b443a17b5313df Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sat, 29 Jan 2022 10:15:07 +0800 Subject: [PATCH 27/37] add license --- LICENSE | 2 +- README_zh.md | 78 ++++--------- .../ConfigureMainPluginEnvironment.java | 21 +++- .../bootstrap/ConfigurePluginEnvironment.java | 16 +++ .../bootstrap/DefaultSpringPluginHook.java | 16 +++ .../EmptyMainApplicationContext.java | 16 +++ .../bootstrap/EmptySpringBeanFactory.java | 16 +++ .../bootstrap/PluginApplicationContext.java | 16 +++ .../bootstrap/PluginListableBeanFactory.java | 16 +++ .../bootstrap/PluginOneselfInteractive.java | 16 +++ .../bootstrap/PluginSpringApplication.java | 16 +++ .../bootstrap/SpringPluginBootstrap.java | 16 +++ .../annotation/DisablePluginWeb.java | 16 +++ .../bootstrap/annotation/OneselfConfig.java | 16 +++ .../ComposeSpringPluginProcessor.java | 16 +++ .../processor/DefaultProcessorContext.java | 16 +++ .../processor/ExtractBeanProcessor.java | 16 +++ .../processor/FrameDefineBeanProcessor.java | 16 +++ .../processor/InvokeOtherPluginProcessor.java | 16 +++ .../bootstrap/processor/ProcessorContext.java | 16 +++ .../processor/ProcessorException.java | 16 +++ .../processor/SpringPluginProcessor.java | 16 +++ .../PluginInterceptorRegister.java | 16 +++ .../PluginInterceptorRegistration.java | 16 +++ .../PluginInterceptorRegistry.java | 16 +++ .../processor/invoke/InvokeBeanFactory.java | 16 +++ .../processor/invoke/InvokeProxyHandler.java | 16 +++ .../PluginClassPathBeanDefinitionScanner.java | 16 +++ .../web/PluginControllerProcessor.java | 16 +++ .../web/PluginInterceptorsProcessor.java | 16 +++ .../PluginSpringDocControllerProcessor.java | 18 ++- .../web/PluginStaticResourceProcessor.java | 16 +++ .../thymeleaf/PluginThymeleafProcessor.java | 16 +++ .../web/thymeleaf/ThymeleafConfigParse.java | 16 +++ .../bootstrap/realize/StopValidator.java | 16 +++ .../bootstrap/utils/AnnotationUtils.java | 16 +++ .../bootstrap/utils/DestroyUtils.java | 16 +++ .../bootstrap/utils/ProcessorUtils.java | 16 +++ .../bootstrap/utils/SpringBeanUtils.java | 16 +++ .../gitee/starblues/annotation/Caller.java | 16 +++ .../gitee/starblues/annotation/Extract.java | 16 +++ .../gitee/starblues/annotation/Supplier.java | 18 ++- .../core/DefaultPluginInsideInfo.java | 16 +++ .../starblues/core/DefaultPluginManager.java | 16 +++ .../core/DefaultRealizeProvider.java | 16 +++ .../starblues/core/PluginConfiguration.java | 46 -------- .../com/gitee/starblues/core/PluginInfo.java | 18 ++- .../gitee/starblues/core/PluginInfoFace.java | 17 ++- .../starblues/core/PluginInsideInfo.java | 18 ++- .../starblues/core/PluginLauncherManager.java | 16 +++ .../gitee/starblues/core/PluginManager.java | 16 +++ .../com/gitee/starblues/core/PluginState.java | 16 +++ .../gitee/starblues/core/RealizeProvider.java | 16 +++ .../com/gitee/starblues/core/RuntimeMode.java | 16 +++ .../checker/ComposePluginBasicChecker.java | 16 +++ .../checker/ComposePluginLauncherChecker.java | 16 +++ .../checker/DefaultPluginBasicChecker.java | 16 +++ .../checker/DefaultPluginLauncherChecker.java | 16 +++ .../DependencyPluginLauncherChecker.java | 16 +++ .../core/checker/PluginBasicChecker.java | 16 +++ .../core/checker/PluginLauncherChecker.java | 16 +++ .../AbstractPluginClassLoader.java | 16 +++ .../classloader/AbstractResourceLoader.java | 16 +++ .../classloader/CacheMainResourceMatcher.java | 16 +++ .../core/classloader/ClassPathLoader.java | 16 +++ .../DefaultMainResourceMatcher.java | 16 +++ .../EmptyMainResourcePatternDefiner.java | 16 +++ .../core/classloader/GenericClassLoader.java | 16 +++ .../core/classloader/JarResourceLoader.java | 16 +++ .../core/classloader/MainResourceMatcher.java | 16 +++ .../MainResourcePatternDefiner.java | 16 +++ .../classloader/NestedJarResourceLoader.java | 16 +++ .../core/classloader/PluginClassLoader.java | 16 +++ .../PluginResourceLoaderFactory.java | 16 +++ .../ProhibitMainResourceMatcher.java | 16 +++ .../starblues/core/classloader/Resource.java | 16 +++ .../classloader/ResourceLoaderFactory.java | 16 +++ .../AbstractPluginDescriptorLoader.java | 16 +++ .../descriptor/ComposeDescriptorLoader.java | 16 +++ .../descriptor/DefaultDependencyPlugin.java | 16 +++ .../DefaultInsidePluginDescriptor.java | 16 +++ .../descriptor/DefaultPluginDescriptor.java | 16 +++ .../descriptor/DevPluginDescriptorLoader.java | 16 +++ .../descriptor/EmptyPluginDescriptor.java | 109 ------------------ .../descriptor/InsidePluginDescriptor.java | 16 +++ .../core/descriptor/PluginDescriptor.java | 16 +++ .../descriptor/PluginDescriptorLoader.java | 16 +++ .../descriptor/PluginResourcesConfig.java | 16 +++ .../ProdDirPluginDescriptorLoader.java | 17 ++- .../ProdPackagePluginDescriptorLoader.java | 16 +++ .../ProdPluginDescriptorLoader.java | 16 +++ .../exception/PluginDisabledException.java | 16 +++ .../core/exception/PluginException.java | 16 +++ .../PluginProhibitStopException.java | 16 +++ .../core/launcher/AbstractLauncher.java | 17 ++- .../JavaMainResourcePatternDefiner.java | 16 +++ .../starblues/core/launcher/Launcher.java | 16 +++ .../core/launcher/MainMethodRunner.java | 16 +++ .../core/launcher/MainProgramLauncher.java | 16 +++ .../starblues/core/launcher/MethodRunner.java | 16 +++ .../core/launcher/PluginResourceStorage.java | 16 +++ .../core/launcher/SpringBootstrap.java | 16 +++ .../core/launcher/SpringMainBootstrap.java | 16 +++ .../core/launcher/archive/Archive.java | 3 +- .../launcher/archive/ExplodedArchive.java | 3 +- .../core/launcher/archive/JarFileArchive.java | 3 +- .../core/launcher/jar/AbstractJarFile.java | 3 +- .../core/launcher/jar/AsciiBytes.java | 3 +- .../starblues/core/launcher/jar/Bytes.java | 3 +- .../jar/CentralDirectoryEndRecord.java | 3 +- .../jar/CentralDirectoryFileHeader.java | 3 +- .../launcher/jar/CentralDirectoryParser.java | 3 +- .../launcher/jar/CentralDirectoryVisitor.java | 16 ++- .../core/launcher/jar/FileHeader.java | 3 +- .../starblues/core/launcher/jar/Handler.java | 3 +- .../starblues/core/launcher/jar/JarEntry.java | 3 +- .../launcher/jar/JarEntryCertification.java | 3 +- .../core/launcher/jar/JarEntryFilter.java | 3 +- .../starblues/core/launcher/jar/JarFile.java | 3 +- .../core/launcher/jar/JarFileEntries.java | 3 +- .../core/launcher/jar/JarFileWrapper.java | 3 +- .../core/launcher/jar/JarURLConnection.java | 3 +- .../core/launcher/jar/RandomAccessData.java | 3 +- .../launcher/jar/RandomAccessDataFile.java | 3 +- .../core/launcher/jar/StringSequence.java | 3 +- .../launcher/jar/ZipInflaterInputStream.java | 3 +- .../BasicMainResourcePatternDefiner.java | 16 +++ .../launcher/plugin/CacheRegistryInfo.java | 16 +++ .../plugin/DefaultPluginInteractive.java | 16 +++ .../launcher/plugin/PluginInteractive.java | 16 +++ .../core/launcher/plugin/PluginLauncher.java | 16 +++ .../PluginMainResourcePatternDefiner.java | 16 +++ .../launcher/plugin/PluginMethodRunner.java | 16 +++ .../core/launcher/plugin/RegistryInfo.java | 16 +++ .../plugin/SpringPluginHookWrapper.java | 16 +++ .../involved/DefaultPluginLaunchInvolved.java | 16 +++ .../PluginApplicationContextGetter.java | 17 ++- .../plugin/involved/PluginLaunchInvolved.java | 16 +++ .../involved/PluginLaunchInvolvedFactory.java | 16 +++ .../core/scanner/BasePluginScanner.java | 16 +++ .../core/scanner/ComposePathResolve.java | 18 ++- .../core/scanner/DevPathResolve.java | 16 +++ .../starblues/core/scanner/PathResolve.java | 16 +++ .../starblues/core/scanner/PluginScanner.java | 16 +++ .../core/scanner/ProdPathResolve.java | 16 +++ .../core/version/SemverVersionInspector.java | 16 +++ .../core/version/VersionInspector.java | 16 +++ .../AutoIntegrationConfiguration.java | 18 ++- .../DefaultIntegrationConfiguration.java | 18 ++- .../integration/ExtendPointConfiguration.java | 16 +++ .../ExtendPointWebConfiguration.java | 16 +++ .../integration/IntegrationConfiguration.java | 18 ++- .../integration/PluginListenerContext.java | 36 ------ .../integration/SpringBootPluginStarter.java | 16 +++ .../AbstractPluginApplication.java | 18 ++- .../application/AutoPluginApplication.java | 18 ++- .../application/DefaultPluginApplication.java | 18 ++- .../application/PluginApplication.java | 19 ++- .../listener/DefaultInitializerListener.java | 16 +++ .../DefaultPluginListenerFactory.java | 16 +++ .../listener/PluginInitializerListener.java | 18 ++- .../PluginInitializerListenerFactory.java | 18 ++- .../integration/listener/PluginListener.java | 16 +++ .../listener/PluginListenerFactory.java | 16 +++ .../integration/listener/SwaggerListener.java | 16 +++ .../operator/DefaultPluginOperator.java | 16 +++ .../operator/EmptyPluginOperator.java | 87 -------------- .../integration/operator/PluginOperator.java | 16 +++ .../operator/PluginOperatorWrapper.java | 18 ++- .../operator/module/PluginInfo.java | 74 ------------ .../upload/UploadByInputStreamParam.java | 16 +++ .../upload/UploadByMultipartFileParam.java | 18 ++- .../operator/upload/UploadParam.java | 16 +++ .../operator/verify/DefaultPluginVerify.java | 42 ------- .../operator/verify/PluginLegalVerify.java | 58 ---------- .../operator/verify/PluginVerify.java | 23 ---- .../integration/user/BeanWrapper.java | 16 +++ .../integration/user/DefaultPluginUser.java | 16 +++ .../integration/user/EmptyPluginUser.java | 53 --------- .../integration/user/PluginUser.java | 16 +++ .../starblues/spring/ApplicationContext.java | 16 +++ .../spring/ApplicationContextProxy.java | 18 ++- .../CacheJdkSameTypeParamProxyFactory.java | 16 +++ .../spring/GenericApplicationContext.java | 16 +++ .../spring/JdkSameTypeParamProxyFactory.java | 16 +++ .../spring/MainApplicationContext.java | 17 ++- .../spring/MainApplicationContextProxy.java | 16 +++ .../gitee/starblues/spring/ProxyFactory.java | 16 +++ .../starblues/spring/SpringBeanFactory.java | 16 +++ .../starblues/spring/SpringPluginHook.java | 16 +++ .../com/gitee/starblues/spring/WebConfig.java | 16 +++ .../spring/extract/DefaultExtractFactory.java | 16 +++ .../extract/DefaultOpExtractFactory.java | 16 +++ .../spring/extract/EmptyExtractFactory.java | 47 -------- .../spring/extract/ExtractCoordinate.java | 18 ++- .../spring/extract/ExtractFactory.java | 16 +++ .../spring/extract/OpExtractFactory.java | 16 +++ .../invoke/DefaultInvokeSupperCache.java | 19 ++- .../spring/invoke/InvokeSupperCache.java | 42 ++++++- .../starblues/spring/invoke/SupperCache.java | 19 ++- .../starblues/spring/web/PluginResource.java | 16 +++ .../web/PluginStaticResourceConfig.java | 16 +++ .../web/PluginStaticResourceResolver.java | 16 +++ .../PluginStaticResourceWebMvcConfigurer.java | 17 ++- .../thymeleaf/PluginThymeleafInvolved.java | 16 +++ .../spring/web/thymeleaf/ThymeleafConfig.java | 16 +++ .../starblues/utils/AnnotationsUtils.java | 16 +++ .../com/gitee/starblues/utils/Assert.java | 17 +++ .../com/gitee/starblues/utils/ClassUtils.java | 16 +++ .../gitee/starblues/utils/CommonUtils.java | 16 +++ .../utils/CompareClassTypeUtils.java | 16 +++ .../gitee/starblues/utils/FieldFilter.java | 19 ++- .../starblues/utils/GlobalRegistryInfo.java | 108 ----------------- .../com/gitee/starblues/utils/MsgUtils.java | 16 +++ .../gitee/starblues/utils/ObjectUtils.java | 16 +++ .../java/com/gitee/starblues/utils/Order.java | 17 +++ .../gitee/starblues/utils/OrderExecution.java | 33 ------ .../gitee/starblues/utils/OrderPriority.java | 16 +++ .../starblues/utils/PluginConfigUtils.java | 16 +++ .../starblues/utils/PluginFileUtils.java | 16 +++ .../starblues/utils/PluginOperatorInfo.java | 65 ----------- .../starblues/utils/ReflectionUtils.java | 18 ++- .../gitee/starblues/utils/ResourceUtils.java | 20 +++- .../com/gitee/starblues/utils/ScanUtils.java | 16 +++ .../utils/SpringBeanCustomUtils.java | 17 +++ .../starblues/utils/SpringBeanUtils.java | 16 +++ .../pack/AbstractDependencyFilterMojo.java | 16 +++ .../plugin/pack/AbstractPackagerMojo.java | 16 +++ .../plugin/pack/BasicRepackager.java | 19 ++- .../gitee/starblues/plugin/pack/Constant.java | 17 +++ .../plugin/pack/DependencyPlugin.java | 16 +++ .../plugin/pack/LoadMainResourcePattern.java | 16 +++ .../starblues/plugin/pack/PluginInfo.java | 17 ++- .../starblues/plugin/pack/RepackageMojo.java | 18 ++- .../starblues/plugin/pack/Repackager.java | 25 +++- .../starblues/plugin/pack/dev/Dependency.java | 16 +++ .../starblues/plugin/pack/dev/DevConfig.java | 16 +++ .../plugin/pack/dev/DevRepackager.java | 19 ++- .../plugin/pack/filter/DependencyFilter.java | 19 ++- .../starblues/plugin/pack/filter/Exclude.java | 18 ++- .../plugin/pack/filter/ExcludeFilter.java | 19 ++- .../pack/filter/FilterableDependency.java | 19 ++- .../starblues/plugin/pack/filter/Include.java | 19 ++- .../plugin/pack/filter/IncludeFilter.java | 19 ++- ...eGenerator.java => DirProdRepackager.java} | 23 +++- ...eGenerator.java => JarProdRepackager.java} | 23 +++- .../starblues/plugin/pack/prod/JarWriter.java | 14 --- .../plugin/pack/prod/PackageGenerator.java | 13 --- .../plugin/pack/prod/ProdConfig.java | 17 +++ .../plugin/pack/prod/ProdRepackager.java | 23 +++- .../plugin/pack/prod/ZipProdRepackager.java | 19 ++- .../plugin/pack/utils/CommonUtils.java | 16 +++ 252 files changed, 3568 insertions(+), 947 deletions(-) delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/GlobalRegistryInfo.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderExecution.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginOperatorInfo.java rename springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/{DirPackageGenerator.java => DirProdRepackager.java} (83%) rename springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/{JarPackageGenerator.java => JarProdRepackager.java} (58%) delete mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java delete mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java diff --git a/LICENSE b/LICENSE index 261eeb9..7fd89d0 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [2019-2022] [starBlues] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README_zh.md b/README_zh.md index b5bb019..508124b 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,51 +1,28 @@ # springboot插件式开发框架 -### 介绍 -此框架可在`SpringBoot`项目上开发出用于扩展项目的插件,可在插件模块中单独定义接口、静态文件、`Mybatis-xml`等扩展功能。 - -### 核心功能 -- 基于`Pf4j`开发。 -- 插件配置式插拔于`SpringBoot`项目。 -- 在`SpringBoot`上可以进行插件式开发, 扩展性极强, 可以针对不同项目开发不同插件, 进行不同插件`jar`包的部署。 -- 可通过配置文件指定要启用或者禁用插件, 可以指定启动插件顺序。 -- 支持上传插件和插件配置文件到服务器, 并且无需重启主程序, 动态部署插件、更新插件。 -- 支持查看插件运行状态, 查看插件安装位置。 -- 无需重启主程序, 通过接口动态的安装插件、卸载插件、启用插件、停止插件、备份插件、删除插件。 -- 在插件应用模块上可以使用`Spring`注解定义组件, 进行依赖注入。 -- 支持在插件中开发`Http-Restful`接口。 -- 支持在插件中单独定义持久层访问等需求。 -- 可以遵循主程序提供的插件接口开发任意扩展功能。 -- 支持注解进行任意业务场景扩展, 并使用定义的坐标进行场景命中。 -- 插件可以根据生产和开发环境自定义独立的配置文件。目前只支持yml文件。 -- 支持自定义扩展开发接口, 使用者可以在预留接口上扩展额外功能。 -- 支持插件之间的方法调用。 -- 支持插件`Http`接口文档: `Swagger`、`SpringDoc`。 -- 插件支持`拦截器`的定制开发。 -- 插件对`Spring-Aop`进行支持。 - -### 扩展包功能 -#### `SpringBoot-Mybatis`扩展包 - -1. 支持在插件中自定义`Mapper`接口、`Mapper xml` 以及对应的实体`bean` -2. 支持集成`Mybatis`、`Mybatis-Plus`、`Tk-Mybatis` -3. 支持可在插件中独立配置数据源 - -- 详见 [插件SpringBoot Mybatis扩展](http://www.starblues.cn/extension-doc/Mybatis%E6%89%A9%E5%B1%95.html) - -#### 静态资源访问扩展包 - -1. 支持通过http访问插件中静态资源 -2. 支持`Thymeleaf`模板引擎进行界面插件式开发 - -- 详见 [插件静态资源访问扩展](http://www.starblues.cn/extension-doc/%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E8%AE%BF%E9%97%AE%E6%89%A9%E5%B1%95.html) +- 全新3.0.0版本上线啦,为动态扩展系统而生的框架。 -#### 插件日志扩展包 - -1. 插件可自主配置集成`logback`日志 -2. 插件可自主配置集成`log4j2`日志 - -- 详见 [插件静态资源访问扩展](http://www.starblues.cn/extension-doc/Log%E6%89%A9%E5%B1%95.html) -- 感谢 [sousouki](https://gitee.com/caoshx_sousouki) 的开发提供 +### 介绍 +该框架可以在SpringBoot项目上开发出插件功能,在插件中可以和SpringBoot使用方式一模一样。使用了本框架您可以实现如下需求: +- 在插件中,您可以当成一个微型的Spring-Boot项目来开发,简单易用。 +- 在插件中扩展出系统各种功能点,用于系统灵活扩展,再也不用使用分支来交付不同需求的项目了。 +- 在插件中可以集成各种框架及其各种spring-boot-xxx-starter。 +- 在插件中可以定义独立依赖包了,再也不用在主程序中定义依赖包了。 +- 可以完美解决插件包与插件包、插件包与主程序因为同一框架的不同版本冲突问题了。各个插件可以定义同一依赖的不同版本框架。 +- 无需重启主程序,可以自由实现插件包的动态安装部署,来动态扩展系统的功能。 +- 插件也可以不依赖主程序独立集成微服务模块。 +- ~~~等等,您可以丰富想象该框架给您带来哪些迫切的需求和扩展。 + +### 特性 +1. 简化了框架的集成步骤,更容易上手。 +2. 使用Maven打包插件,支持对插件的自主打包编译。目前支持: +- 开发打包:将插件打包成开发环境下的插件(仅需打包一次)。 +- 生产打包:将插件打包成一个jar、zip、文件夹 +3. 插件支持两模式 +4. 插件模式: 作为一个插件,由主程序引导加载。 +5. 自主启动模式:单独作为一个SpringBoot项目来启动。 +6. 自主的开发的类加载器,支持插件定义各种的依赖jar包。 +7. 在插件中可以集成各种框架及其各种spring-boot-xxx-starter,比如集成mybatis、mybatis-plus、spring-jpa等。 ### 运行环境 1. jdk1.8+ @@ -58,7 +35,7 @@ ### 文档地址 -- [http://www.starblues.cn/](http://www.starblues.cn/) +- [https://www.yuque.com/starblues/iuyk4y/ypurcw](https://www.yuque.com/starblues/iuyk4y/ypurcw) ### 衍生产品 #### 携带前后端插件功能的后台管理系统 @@ -70,11 +47,4 @@ - [springboot-plugin-framework 功能测试+案例](https://gitee.com/starblues/springboot-plugin-framework-example) ### QQ交流群 -859570617(**点赞框架后可进群, 进群前请备注gitee昵称**) - -### 框架维护 -**欢迎各位开发爱好者参与到框架的维护和扩展开发当中** - -扩展开发文档见: - [springboot-plugin-framework 扩展功能](http://www.starblues.cn/extension-doc/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%89%A9%E5%B1%95.html) - - +859570617(**点赞框架后可进群, 进群前请备注gitee昵称**) \ No newline at end of file diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java index 59fbf0b..c2e0080 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigureMainPluginEnvironment.java @@ -1,19 +1,30 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.annotation.OneselfConfig; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; -import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.integration.AutoIntegrationConfiguration; -import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; import com.gitee.starblues.utils.ResourceUtils; import org.springframework.boot.env.PropertiesPropertySourceLoader; import org.springframework.boot.env.PropertySourceLoader; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 2629336..33083b1 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java index 1b5e534..e11e6dd 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java index 3ce3828..7b67746 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptyMainApplicationContext.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.spring.MainApplicationContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java index e79ec6d..b784bd5 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/EmptySpringBeanFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.spring.SpringBeanFactory; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java index bb6de9a..bab147c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java index a90d85c..fda8129 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginListableBeanFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.utils.DestroyUtils; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index ac39020..edcd048 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java index da7393b..c46e5f6 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginSpringApplication.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java index b49f60d..b54de8b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/SpringPluginBootstrap.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ComposeSpringPluginProcessor; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java index 72e8143..9a4fba0 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/DisablePluginWeb.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.annotation; import java.lang.annotation.*; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java index 736e699..1af29cd 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/annotation/OneselfConfig.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.annotation; import java.lang.annotation.*; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index 6cc097b..4d2c47e 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index d83cfbe..9cff8b0 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java index 9d9b6fa..0ed867c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ExtractBeanProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.annotation.Extract; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java index aee9f1e..159254b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java index d8a41c5..6c12254 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/InvokeOtherPluginProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.annotation.Caller; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java index 5f5c942..db4c125 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorContext.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java index a2a78a6..c0f6306 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ProcessorException.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; /** diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java index 4b656d9..5b95946 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/SpringPluginProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.utils.Order; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java index dc0304b..7d3454a 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegister.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.interceptor; /** diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java index 7f706ba..5be7829 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.interceptor; import com.gitee.starblues.utils.CommonUtils; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java index 9a5f45b..817bce8 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistry.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.interceptor; import org.springframework.core.OrderComparator; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java index 0e092eb..de9f62d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeBeanFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.invoke; import com.gitee.starblues.annotation.Caller; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java index acfa514..7d24f63 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.invoke; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java index 050b4ce..d864180 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/scanner/PluginClassPathBeanDefinitionScanner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.scanner; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java index fb9ee65..e06322c 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.web; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java index 1609ffc..79f4495 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.web; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java index e0005d4..4b2ce06 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginSpringDocControllerProcessor.java @@ -1,10 +1,25 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.web; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.ProcessorException; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; import com.gitee.starblues.spring.MainApplicationContext; -import com.gitee.starblues.utils.ClassUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ReflectionUtils; import com.gitee.starblues.utils.SpringBeanCustomUtils; @@ -15,7 +30,6 @@ import org.springdoc.core.OpenAPIService; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import java.util.Locale; /** * spring doc diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java index 6912393..1d2413b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginStaticResourceProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.web; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java index a55cfd0..0cca5ec 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/PluginThymeleafProcessor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.web.thymeleaf; import com.gitee.starblues.bootstrap.processor.ProcessorContext; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java index 8e93e60..411818b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/thymeleaf/ThymeleafConfigParse.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.processor.web.thymeleaf; import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java index 5699e0b..be1d74d 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/StopValidator.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.realize; /** diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java index dbf5588..aa778ae 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/AnnotationUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.utils; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java index 6a104d3..eec6ef1 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/DestroyUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.utils; import com.gitee.starblues.utils.ReflectionUtils; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java index 556f0da..15a8e5a 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/ProcessorUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.utils; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java index 50978b8..ceb1987 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/utils/SpringBeanUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.bootstrap.utils; import org.springframework.context.ApplicationContext; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java index 73bb1f7..49badbf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Caller.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.annotation; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java index b7c6678..2e465b1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Extract.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.annotation; import org.springframework.core.annotation.AliasFor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java index 2a3b995..44959b2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/annotation/Supplier.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.annotation; import org.springframework.core.annotation.AliasFor; @@ -9,7 +25,7 @@ import java.lang.annotation.*; * 被调用类的提供者。配合 @Caller 注解使用, 两者结合实现插件中的方法调用。 * * @author starBlues - * @version 1.0 + * @version 2.4.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java index 0a00166..26ecd30 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 79286c7..3a299ea 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.checker.ComposePluginLauncherChecker; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java index 229ad01..758d531 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultRealizeProvider.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.checker.ComposePluginBasicChecker; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java deleted file mode 100644 index 07f5cb6..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.gitee.starblues.core; - -import java.util.List; -import java.util.Set; - -/** - * 配置 - * @author starBlues - * @version 3.0.0 - */ -public class PluginConfiguration { - - private Set disabledPluginIds; - private List sortedPluginIds; - - public void setDisabledPluginIds(Set disabledPluginIds) { - this.disabledPluginIds = disabledPluginIds; - } - - public void setSortedPluginId(List sortedPluginId) { - this.sortedPluginIds = sortedPluginIds; - } - - - public boolean isDisabled(String pluginId){ - return disabledPluginIds != null && disabledPluginIds.contains(pluginId); - } - - - /** - * 得到禁用的插件id - * @return Set - */ - public Set getDisabledPluginIds(){ - return disabledPluginIds; - } - - /** - * 得到按照循序启动的插件id - * @return Set - */ - public List getSortedPluginIds(){ - return sortedPluginIds; - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java index 48afaf3..b451512 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java @@ -1,9 +1,25 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; /** - * 插件包装 + * 插件信息 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java index e21e9f4..ad7b0d9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java @@ -1,6 +1,21 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; -import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java index cee4cd9..1c2a39c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInsideInfo.java @@ -1,9 +1,25 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; /** - * 内部的 PluginWrapper + * 内部的 PluginInfo * @version 3.0.0 * @author starBlues */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index 0f18ec6..51ceb25 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.checker.PluginLauncherChecker; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java index 5d0c20f..b2f0832 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.exception.PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java index ed21df8..4951e35 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java index ee42ca3..59417d2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RealizeProvider.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; import com.gitee.starblues.core.checker.PluginBasicChecker; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java index b306962..ebd126a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/RuntimeMode.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java index f0d2b9b..de0bd8e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginBasicChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java index a451994..3984f63 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.core.PluginInfo; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java index 71148e4..846ab7e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginBasicChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java index 6fce534..61dd4ff 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.common.Constants; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java index 74a4a3b..3691f2c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DependencyPluginLauncherChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.common.Constants; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java index e64a8ae..100c878 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginBasicChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java index a025e83..c729f12 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.checker; import com.gitee.starblues.core.PluginInfo; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java index ab14170..357a3cb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import java.net.URL; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java index f277c44..3e76af2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.ResourceUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java index 709b713..58ed42a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/CacheMainResourceMatcher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java index 7234f52..f44cdd5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java index 2064850..29c95de 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/DefaultMainResourceMatcher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.ObjectUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java index 883e13d..57ca80a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/EmptyMainResourcePatternDefiner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import java.util.Set; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java index 884295d..bcfae4a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java index 8f2679c..85bd9fd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import org.apache.commons.io.IOUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java index c99999e..5977f35 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourceMatcher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java index ce63c12..5759573 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/MainResourcePatternDefiner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import java.util.Set; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java index 6417f26..d76864b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.core.exception.PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index ee832a8..d946bb9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java index 60efb80..ad763aa 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java index 23c29d6..296dacf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ProhibitMainResourceMatcher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java index 79ad636..8410131 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import java.net.URL; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java index e73c008..1c53061 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.classloader; import com.gitee.starblues.utils.ResourceUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index cf6544f..d921202 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java index 52981c2..475815e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ComposeDescriptorLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.core.checker.PluginBasicChecker; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java index ce831b5..bc5fdee 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultDependencyPlugin.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.AbstractDependencyPlugin; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java index 9333736..034100b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java index d187353..2753308 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.DependencyPlugin; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java index 8d51456..eadde2a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java deleted file mode 100644 index fb9aa42..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/EmptyPluginDescriptor.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.gitee.starblues.core.descriptor; - -import com.gitee.starblues.common.DependencyPlugin; - -import java.nio.file.Path; -import java.util.List; -import java.util.Set; -import java.util.jar.Manifest; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class EmptyPluginDescriptor implements InsidePluginDescriptor{ - @Override - public String getPluginId() { - return null; - } - - @Override - public String getPluginVersion() { - return null; - } - - @Override - public String getPluginBootstrapClass() { - return null; - } - - @Override - public String getPluginPath() { - return null; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String getRequires() { - return null; - } - - @Override - public String getProvider() { - return null; - } - - @Override - public String getLicense() { - return null; - } - - @Override - public List getDependencyPlugin() { - return null; - } - - @Override - public Type getType() { - return null; - } - - @Override - public Manifest getManifest() { - return null; - } - - @Override - public String getConfigFileName() { - return null; - } - - @Override - public Path getInsidePluginPath() { - return null; - } - - @Override - public String getPluginFileName() { - return null; - } - - @Override - public String getPluginClassPath() { - return null; - } - - @Override - public Set getPluginLibPaths() { - return null; - } - - @Override - public Set getIncludeMainResourcePatterns() { - return null; - } - - @Override - public Set getExcludeMainResourcePatterns() { - return null; - } - - @Override - public PluginDescriptor toPluginDescriptor() { - return null; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java index 6cfc67a..876f83b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java index 017592d..4293066 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.DependencyPlugin; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java index 77bcb08..e69c34e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptorLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.core.exception.PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java index 40ab957..5dc88a6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginResourcesConfig.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java index af2abda..78d52da 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -1,5 +1,20 @@ -package com.gitee.starblues.core.descriptor; +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.common.utils.ManifestUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java index 281c28d..4b046e5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index 4efa0fa..35aca22 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; import com.gitee.starblues.core.exception.PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java index 4d6b2e6..70251b7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginDisabledException.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.exception; import com.gitee.starblues.core.PluginInfo; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java index 3280be3..92b79a1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginException.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.exception; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java index 07327a8..d4fef65 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.exception; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java index 3b49ec6..2a25a80 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/AbstractLauncher.java @@ -1,5 +1,20 @@ -package com.gitee.starblues.core.launcher; +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitee.starblues.core.launcher; import com.gitee.starblues.core.launcher.jar.JarFile; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java index 3d967da..4e46c7e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/JavaMainResourcePatternDefiner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java index 94ef259..64fda92 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java index 1f9085a..1145dc3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java index 26c4514..192f985 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; import com.gitee.starblues.core.classloader.GenericClassLoader; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java index 24a560a..c3c1e12 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java index 4aa74d5..e668fa0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java index d4d2e79..26098bd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java index 3d1bade..2a32c1e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java index 48ea41f..168f543 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java @@ -8,8 +8,9 @@ import java.util.function.Consumer; import java.util.jar.Manifest; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface Archive extends Iterable, AutoCloseable { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java index 2a174f0..375d2bd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java @@ -10,8 +10,9 @@ import java.util.*; import java.util.jar.Manifest; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ExplodedArchive implements Archive { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java index 54a6e01..99f5de0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java @@ -19,8 +19,9 @@ import java.util.jar.JarEntry; import java.util.jar.Manifest; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarFileArchive implements Archive { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java index 1ce258b..bbe2210 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java @@ -8,8 +8,9 @@ import java.net.URL; import java.security.Permission; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public abstract class AbstractJarFile extends java.util.jar.JarFile{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java index 20ba4ba..be07e41 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java @@ -3,8 +3,9 @@ package com.gitee.starblues.core.launcher.jar; import java.nio.charset.StandardCharsets; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class AsciiBytes { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java index da137ec..04c4ec7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java @@ -1,8 +1,9 @@ package com.gitee.starblues.core.launcher.jar; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class Bytes { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java index 17c36ce..fef7b82 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java @@ -3,8 +3,9 @@ package com.gitee.starblues.core.launcher.jar; import java.io.IOException; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class CentralDirectoryEndRecord { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java index f098adf..a073e07 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java @@ -8,8 +8,9 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.ValueRange; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class CentralDirectoryFileHeader implements FileHeader { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java index 33420cd..8e0a0a9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java @@ -5,8 +5,9 @@ import java.util.ArrayList; import java.util.List; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class CentralDirectoryParser { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java index f7b29f3..3b8da51 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java @@ -1,15 +1,29 @@ package com.gitee.starblues.core.launcher.jar; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface CentralDirectoryVisitor { + /** + * visitStart + * @param endRecord endRecord + * @param centralDirectoryData centralDirectoryData + */ void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData); + /** + * visitFileHeader + * @param fileHeader fileHeader + * @param dataOffset dataOffset + */ void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset); + /** + * visitEnd + */ void visitEnd(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java index 2dc9142..7a7bedb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java @@ -3,8 +3,9 @@ package com.gitee.starblues.core.launcher.jar; import java.util.zip.ZipEntry; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface FileHeader { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java index e44956f..d767963 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java @@ -15,8 +15,9 @@ import java.util.logging.Logger; import java.util.regex.Pattern; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class Handler extends URLStreamHandler { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java index c20b388..bd5e385 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java @@ -9,8 +9,9 @@ import java.util.jar.Attributes; import java.util.jar.Manifest; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarEntry extends java.util.jar.JarEntry implements FileHeader { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java index 6f10107..c3c6212 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java @@ -4,8 +4,9 @@ import java.security.CodeSigner; import java.security.cert.Certificate; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarEntryCertification { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java index 9da34f9..6835020 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java @@ -1,8 +1,9 @@ package com.gitee.starblues.core.launcher.jar; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface JarEntryFilter { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java index bc4315f..4a63f21 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java @@ -21,8 +21,9 @@ import java.util.stream.StreamSupport; import java.util.zip.ZipEntry; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarFile extends AbstractJarFile implements Iterable { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java index 8090b30..d147e22 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileEntries.java @@ -9,8 +9,9 @@ import java.util.jar.Manifest; import java.util.zip.ZipEntry; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarFileEntries implements CentralDirectoryVisitor, Iterable { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java index e34eebb..ea842d5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFileWrapper.java @@ -17,8 +17,9 @@ import java.util.stream.Stream; import java.util.zip.ZipEntry; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarFileWrapper extends AbstractJarFile { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java index 4a834b0..0343be9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarURLConnection.java @@ -12,8 +12,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class JarURLConnection extends java.net.JarURLConnection { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java index 578828a..af32585 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessData.java @@ -5,8 +5,9 @@ import java.io.IOException; import java.io.InputStream; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface RandomAccessData { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java index 8f35b8a..60745b8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/RandomAccessDataFile.java @@ -3,8 +3,9 @@ package com.gitee.starblues.core.launcher.jar; import java.io.*; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class RandomAccessDataFile implements RandomAccessData{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java index c8d1986..e9f20bb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/StringSequence.java @@ -3,8 +3,9 @@ package com.gitee.starblues.core.launcher.jar; import java.util.Objects; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class StringSequence implements CharSequence { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java index f856a9a..ea86b41 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/ZipInflaterInputStream.java @@ -7,8 +7,9 @@ import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; /** + * copy from spring-boot-loader * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ZipInflaterInputStream extends InflaterInputStream { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java index aa14b82..4c5166f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java index e46783e..341680b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/CacheRegistryInfo.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import java.util.Map; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java index e2f9c9f..efca52c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java index c0467d6..6511f06 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 62d2ce1..c0b20ee 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.classloader.PluginClassLoader; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index 9b1a94c..fbab1e9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java index d86727e..9b4b57c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.RuntimeMode; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java index 38c0157..6673077 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/RegistryInfo.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import java.util.function.Supplier; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java index 85f1cfc..e25ac5f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/SpringPluginHookWrapper.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java index 743042e..4a80be4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin.involved; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java index 1213676..8a8754e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginApplicationContextGetter.java @@ -1,6 +1,21 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin.involved; -import com.gitee.starblues.core.PluginLauncherManager; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.spring.ApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java index ffa9f7a..93fc5a1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolved.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin.involved; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java index 2f03f07..d3fc5ec 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.launcher.plugin.involved; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java index 0bfd072..a17c756 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/BasePluginScanner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.scanner; import com.gitee.starblues.utils.ObjectUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java index ff300c7..56cee67 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ComposePathResolve.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.scanner; import com.gitee.starblues.utils.ObjectUtils; @@ -10,7 +26,7 @@ import java.util.List; /** * 组合的PathResolve * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ComposePathResolve implements PathResolve{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java index cd06edf..6c1e944 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/DevPathResolve.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.scanner; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java index 3961ac9..e6be248 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PathResolve.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.scanner; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java index e48ea87..32b4069 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/PluginScanner.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.scanner; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java index 3ce507c..7f59f53 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.scanner; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java index d4b86b2..22c1e5c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/SemverVersionInspector.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.version; import com.github.zafarkhaja.semver.Version; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java index 0702df8..be6a573 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/version/VersionInspector.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.version; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index 6ef8ad5..a7f5ce5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; @@ -13,7 +29,7 @@ import java.util.Set; /** * 自动集成的配置 * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ @Component @ConfigurationProperties(prefix = "plugin") diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index 4ccb689..8466305 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; @@ -12,7 +28,7 @@ import java.util.Set; * 默认的插件集成配置。给非必须配置设置了默认值 * * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public abstract class DefaultIntegrationConfiguration implements IntegrationConfiguration{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java index 889e7b0..6807104 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration; import com.gitee.starblues.core.DefaultRealizeProvider; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java index 2df20b7..75d473f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration; import com.gitee.starblues.integration.listener.SwaggerListener; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java index a74ce7f..ace9016 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/IntegrationConfiguration.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration; @@ -13,7 +29,7 @@ import java.util.Set; /** * 插件集成时的配置接口。插件集成的配置接口 * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public interface IntegrationConfiguration { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java deleted file mode 100644 index c6fc06a..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/PluginListenerContext.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gitee.starblues.integration; - - -import com.gitee.starblues.integration.listener.PluginListener; - -import java.util.List; - -/** - * 插件bean监听者上下文。 - * 注意: 监听者必须在初始化插件前添加,否则在初始化阶段可能无法触发添加的监听者。 - * @author starBlues - * @version 2.4.0 - */ -public interface PluginListenerContext { - - /** - * 添加监听者 - * @param pluginListener 插件 bean 监听者 - */ - void addListener(PluginListener pluginListener); - - - /** - * 添加监听者 - * @param pluginListenerClass 插件监听者Class类 - * @param 继承PluginListener的子类 - */ - void addListener(Class pluginListenerClass); - - /** - * 追加多个监听者 - * @param pluginListeners 插件 bean 监听者集合 - */ - void addListener(List pluginListeners); - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java index feddab2..1c85dad 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration; import com.gitee.starblues.integration.application.AutoPluginApplication; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java index f2fd9cc..b666cfb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AbstractPluginApplication.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.application; import com.gitee.starblues.integration.IntegrationConfiguration; @@ -12,7 +28,7 @@ import java.util.List; * 公用的的插件应用 * * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public abstract class AbstractPluginApplication implements PluginApplication { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java index 46f7c5a..7d19440 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/AutoPluginApplication.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.application; import com.gitee.starblues.integration.ExtendPointConfiguration; @@ -15,7 +31,7 @@ import org.springframework.context.annotation.Import; * 自动初始化的 PluginApplication。该PluginApplication 基于 Spring InitializingBean 自动初始化插件。 * * @author starBlues - * @version 2.2.0 + * @version 3.0.0 */ @Import({ExtendPointConfiguration.class, ExtendPointWebConfiguration.class}) public class AutoPluginApplication extends DefaultPluginApplication diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java index 7b4d676..0f069eb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/DefaultPluginApplication.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.application; import com.gitee.starblues.annotation.Extract; @@ -27,7 +43,7 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * 默认的插件 PluginApplication * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public class DefaultPluginApplication extends AbstractPluginApplication { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java index f8f377e..e415503 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/application/PluginApplication.java @@ -1,6 +1,21 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.application; -import com.gitee.starblues.integration.PluginListenerContext; import com.gitee.starblues.integration.listener.PluginInitializerListener; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.user.PluginUser; @@ -9,7 +24,7 @@ import org.springframework.context.ApplicationContext; /** * 插件应用。 * @author starBlues - * @version 2.4.3 + * @version 3.0.0 */ public interface PluginApplication{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java index c5f7e6a..b33bb6f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; import com.gitee.starblues.utils.SpringBeanUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java index e518aa4..070659a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultPluginListenerFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; import com.gitee.starblues.core.PluginInfo; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java index 5b37787..ab25f60 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; @@ -5,7 +21,7 @@ package com.gitee.starblues.integration.listener; * 插件初始化监听者 * * @author starBlues - * @version 1.0 + * @version 1.0.0 */ public interface PluginInitializerListener { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java index 47aba8c..01d8698 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListenerFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; import com.gitee.starblues.utils.SpringBeanUtils; @@ -10,7 +26,7 @@ import java.util.List; * 插件初始化监听者工厂 * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class PluginInitializerListenerFactory implements PluginInitializerListener { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java index 9286882..53bd629 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListener.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java index b707735..e529262 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginListenerFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; import java.util.List; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java index daa7eb1..f1ca6c5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.listener; import com.gitee.starblues.core.PluginInfo; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index f0bdf47..4524ef7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.*; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java deleted file mode 100644 index cb71a02..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/EmptyPluginOperator.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.gitee.starblues.integration.operator; - -import com.gitee.starblues.core.exception.PluginException; -import com.gitee.starblues.core.PluginInfo; -import com.gitee.starblues.integration.listener.PluginInitializerListener; -import com.gitee.starblues.integration.operator.upload.UploadParam; - -import java.nio.file.Path; -import java.util.List; - -/** - * @author starBlues - * @version 1.0 - */ -public class EmptyPluginOperator implements PluginOperator{ - - - @Override - public boolean initPlugins(PluginInitializerListener pluginInitializerListener) throws PluginException { - return false; - } - - @Override - public boolean verify(Path jarPath) throws PluginException { - return false; - } - - @Override - public PluginInfo parse(Path pluginPath) throws PluginException { - return null; - } - - @Override - public PluginInfo install(Path jarPath, boolean unpackPlugin) throws PluginException { - return null; - } - - @Override - public void uninstall(String pluginId, boolean isDelete, boolean isBackup) throws PluginException { - } - - @Override - public PluginInfo load(Path pluginPath, boolean unpackPlugin) throws PluginException { - return null; - } - - @Override - public boolean unload(String pluginId) throws PluginException { - return false; - } - - - @Override - public boolean start(String pluginId) throws PluginException { - return false; - } - - @Override - public boolean stop(String pluginId) throws PluginException { - return false; - } - - @Override - public PluginInfo uploadPlugin(UploadParam uploadParam) throws PluginException { - return null; - } - - @Override - public Path backupPlugin(Path backDirPath, String sign) throws PluginException { - return null; - } - - @Override - public Path backupPlugin(String pluginId, String sign) throws PluginException { - return null; - } - - @Override - public List getPluginInfo() { - return null; - } - - @Override - public PluginInfo getPluginInfo(String pluginId) { - return null; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java index 45f6259..c16758b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperator.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.exception.PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java index ec6c085..aaf9007 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/PluginOperatorWrapper.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.operator; import com.gitee.starblues.core.exception.PluginException; @@ -15,7 +31,7 @@ import java.util.List; /** * 插件操作包装者 * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public class PluginOperatorWrapper implements PluginOperator{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java deleted file mode 100644 index 4a104c4..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/module/PluginInfo.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.gitee.starblues.integration.operator.module; - - -import com.gitee.starblues.core.PluginState; -import com.gitee.starblues.core.descriptor.PluginDescriptor; - -/** - * 插件信息 - * @author starBlues - * @version 1.0 - */ -public class PluginInfo { - - /** - * 插件基本信息 - */ - private final PluginDescriptor pluginDescriptor; - - /** - * 插件状态 - */ - private final PluginState pluginState; - - /** - * 插件路径 - */ - private final String path; - - /** - * 运行模式 - */ - private final String runMode; - - - public PluginInfo(PluginDescriptor pluginDescriptor, - PluginState pluginState, - String path, - String runMode) { - this.pluginDescriptor = pluginDescriptor; - this.pluginState = pluginState; - this.path = path; - this.runMode = runMode; - } - - public PluginDescriptor getPluginDescriptor() { - return pluginDescriptor; - } - - public PluginState getPluginState() { - return pluginState; - } - - public String getPluginStateString() { - return pluginState.toString(); - } - - public String getPath() { - return path; - } - - public String getRunMode() { - return runMode; - } - - @Override - public String toString() { - return "PluginInfo{" + - "pluginDescriptor=" + pluginDescriptor + - ", pluginState=" + pluginState + - ", path='" + path + '\'' + - ", runMode='" + runMode + '\'' + - '}'; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java index e485c87..356356d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByInputStreamParam.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.operator.upload; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java index 581a5cd..b9b7c47 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadByMultipartFileParam.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.operator.upload; import com.gitee.starblues.utils.Assert; @@ -6,7 +22,7 @@ import org.springframework.web.multipart.MultipartFile; /** * 上传插件参数 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class UploadByMultipartFileParam extends UploadParam{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java index 0839b53..0f2b418 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/upload/UploadParam.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.operator.upload; import org.springframework.web.multipart.MultipartFile; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java deleted file mode 100644 index 859125b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/DefaultPluginVerify.java +++ /dev/null @@ -1,42 +0,0 @@ -//package com.gitee.starblues.integration.operator.verify; -// -//import com.gitee.starblues.integration.pf4j.DefaultPf4jFactory; -//import org.pf4j.*; -// -//import java.nio.file.Path; -//import java.util.Objects; -// -///** -// * 默认的插件校验器 -// * @author starBlues -// * @version 2.2.2 -// */ -//@Deprecated -//public class DefaultPluginVerify extends PluginLegalVerify{ -// -// private final PluginManager pluginManager; -// -// public DefaultPluginVerify(PluginManager pluginManager) { -// super(DefaultPf4jFactory.getPluginDescriptorFinder(pluginManager.getRuntimeMode())); -// Objects.requireNonNull(pluginManager); -// this.pluginManager = pluginManager; -// } -// -// -// @Override -// protected Path postVerify(Path path, PluginDescriptor pluginDescriptor) throws Exception { -// PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginDescriptor.getPluginId()); -// if(pluginWrapper == null){ -// // 当前没有该插件包运行 -// return path; -// } -// // 如果当前插件在当前环境存在, 则抛出异常 -// PluginDescriptor runPluginDescriptor = pluginWrapper.getDescriptor(); -// StringBuffer errorMsg = new StringBuffer("The plugin (") -// .append("id:<").append(runPluginDescriptor.getPluginId()) -// .append("> ; version <").append(runPluginDescriptor.getVersion()) -// .append("> ) is already exist in the current environment。 ") -// .append("Please uninstall the plugin, then upload and update the plugin"); -// throw new Exception(errorMsg.toString()); -// } -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java deleted file mode 100644 index 217678e..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginLegalVerify.java +++ /dev/null @@ -1,58 +0,0 @@ -//package com.gitee.starblues.integration.operator.verify; -// -//import com.gitee.starblues.core.descriptor.PluginDescriptor; -//import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; -// -//import java.nio.file.Path; -//import java.util.Objects; -// -///** -// * 插件包合法校验 -// * @author starBlues -// * @version 1.0 -// */ -//@Deprecated -//public class PluginLegalVerify implements PluginVerify{ -// -// protected final PluginDescriptorLoader pluginDescriptorLoader; -// -// public PluginLegalVerify(PluginDescriptorLoader pluginDescriptorLoader) { -// Objects.requireNonNull(pluginDescriptorLoader); -// this.pluginDescriptorLoader = pluginDescriptorLoader; -// } -// -// @Override -// public Path verify(Path path) throws Exception { -//// if(path == null){ -//// throw new IllegalArgumentException("path can not be null"); -//// } -//// if(!pluginDescriptorFinder.isApplicable(path)){ -//// // 插件包不合法 -//// throw new Exception(path.toString() + " : plugin illegal"); -//// } -//// PluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(path); -//// if(pluginDescriptor == null){ -//// throw new Exception(path.toString() + " : Not found plugin Descriptor"); -//// } -//// if(Objects.isEmpty(pluginDescriptor.getPluginId())){ -//// throw new Exception(path.toString() + " : Plugin id can't be empty"); -//// } -//// if(StringUtils.isEmpty(pluginDescriptor.getPluginClass())){ -//// throw new Exception(path.toString() + " : Not found plugin Class"); -//// } -//// return postVerify(path, pluginDescriptor); -// return null; -// } -// -// /** -// * 合法后的校验.可扩展校验 -// * @param path 路径 -// * @param pluginDescriptor 插件解析者 -// * @return 返回路径 -// * @throws Exception 插件异常 -// */ -// protected Path postVerify(Path path, PluginDescriptor pluginDescriptor) throws Exception{ -// return path; -// } -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java deleted file mode 100644 index 5a98afd..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/verify/PluginVerify.java +++ /dev/null @@ -1,23 +0,0 @@ -//package com.gitee.starblues.integration.operator.verify; -// -// -//import java.nio.file.Path; -// -///** -// * 插件合法校验接口 -// * @author starBlues -// * @version 1.0 -// * @see DefaultPluginVerify -// * @see PluginLegalVerify -// */ -//public interface PluginVerify { -// -// /** -// * 校验插件包 -// * @param path 插件路径 -// * @return 返回校验成功的路径 -// * @throws Exception 插件异常 -// */ -// Path verify(Path path) throws Exception; -// -//} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java index 85f6503..6fb78a4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/BeanWrapper.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.user; import java.util.Map; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java index 04ba05a..d63c705 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/DefaultPluginUser.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.user; import com.gitee.starblues.core.exception.PluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java deleted file mode 100644 index 67712f9..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/EmptyPluginUser.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.gitee.starblues.integration.user; - -import java.lang.annotation.Annotation; -import java.util.List; -import java.util.Set; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class EmptyPluginUser implements PluginUser{ - - - @Override - public BeanWrapper> getBeanName(boolean includeMainBeans) { - return null; - } - - @Override - public Set getBeanName(String pluginId) { - return null; - } - - @Override - public BeanWrapper getBean(String name, boolean includeMainBeans) { - return null; - } - - @Override - public Object getBean(String pluginId, String name) { - return null; - } - - @Override - public BeanWrapper> getBeanByInterface(Class interfaceClass, boolean includeMainBeans) { - return null; - } - - @Override - public List getBeanByInterface(String pluginId, Class interfaceClass) { - return null; - } - - @Override - public BeanWrapper> getBeansWithAnnotation(Class annotationType, boolean includeMainBeans) { - return null; - } - - @Override - public List getBeansWithAnnotation(String pluginId, Class annotationType) { - return null; - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java index c309f90..1864e8a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/user/PluginUser.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.integration.user; import java.lang.annotation.Annotation; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java index bb727ef..9056235 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContext.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java index 2f3fb2a..706c7a9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ApplicationContextProxy.java @@ -1,7 +1,23 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; /** - * + * ApplicationContext 代理 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java index 3a6d865..5c3f7f7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/CacheJdkSameTypeParamProxyFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; import com.gitee.starblues.utils.ReflectionUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java index f40ea4f..922899c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/GenericApplicationContext.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; import com.gitee.starblues.utils.Assert; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java index 51b6184..2e9cfd0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/JdkSameTypeParamProxyFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; import com.gitee.starblues.utils.ReflectionUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java index 439e7a5..9e4f1a4 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContext.java @@ -1,5 +1,20 @@ -package com.gitee.starblues.spring; +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitee.starblues.spring; /** * 主程序 ApplicationContext 接口 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java index 0e74bff..11dfb18 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/MainApplicationContextProxy.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java index feb65e3..9ff2087 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/ProxyFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java index e44ee69..8830eed 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringBeanFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; import org.springframework.beans.factory.ListableBeanFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java index dfb8502..55cdc24 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/SpringPluginHook.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java index 89a26f8..bbbf7dc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring; import java.util.Set; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java index 0b83b22..ed5d69b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultExtractFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.extract; import java.util.*; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java index 7eef6e5..48b05fc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/DefaultOpExtractFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.extract; import com.gitee.starblues.annotation.Extract; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java deleted file mode 100644 index 3644852..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/EmptyExtractFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gitee.starblues.spring.extract; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author starBlues - * @version 1.0 - */ -public class EmptyExtractFactory implements ExtractFactory{ - @Override - public T getExtractByCoordinate(ExtractCoordinate coordinate) { - return null; - } - - @Override - public T getExtractByCoordinate(String pluginId, ExtractCoordinate coordinate) { - return null; - } - - @Override - public T getExtractByCoordinateOfMain(ExtractCoordinate coordinate) { - return null; - } - - @Override - public List getExtractByInterClass(Class interfaceClass) { - return Collections.emptyList(); - } - - @Override - public List getExtractByInterClass(String pluginId, Class interfaceClass) { - return Collections.emptyList(); - } - - @Override - public List getExtractByInterClassOfMain(Class interfaceClass) { - return Collections.emptyList(); - } - - @Override - public Map> getExtractCoordinates() { - return Collections.emptyMap(); - } -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java index 4bfa682..8139983 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractCoordinate.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.extract; import com.gitee.starblues.annotation.Extract; @@ -8,7 +24,7 @@ import java.util.Objects; /** * 执行器坐标 * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public class ExtractCoordinate { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java index 33cbaed..898c572 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/ExtractFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.extract; import java.util.*; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java index 8bfe73a..0a934b6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/extract/OpExtractFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.extract; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java index 896c3d3..2917f8d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/DefaultInvokeSupperCache.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.invoke; import com.gitee.starblues.spring.ApplicationContext; @@ -9,8 +25,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * 默认的 InvokeSupperCache * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DefaultInvokeSupperCache implements InvokeSupperCache{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java index c33c188..8422c5c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/InvokeSupperCache.java @@ -1,15 +1,55 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.invoke; /** + * 插件调用提供者缓存 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface InvokeSupperCache { + /** + * 获取提供者bean + * @param pluginId 插件id + * @param supperKey 提供者key + * @return Object + */ Object getSupperBean(String pluginId, String supperKey); + + /** + * 获取提供者bean + * @param supperKey 提供者key + * @return Object + */ Object getSupperBean(String supperKey); + + /** + * 添加提供者 + * @param pluginId 插件id + * @param cache 提供者缓存 + */ void add(String pluginId, SupperCache cache); + + /** + * 移除插件提供者 + * @param pluginId 插件id + */ void remove(String pluginId); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java index 71e813f..de290f0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/invoke/SupperCache.java @@ -1,10 +1,27 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.invoke; import com.gitee.starblues.spring.ApplicationContext; /** + * 提供者缓存包装 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class SupperCache { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java index 6767fae..d7e9bf9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginResource.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.web; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java index ff86eff..8aa2ce5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.web; import org.slf4j.Logger; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java index b131891..b4aed6a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceResolver.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.web; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java index 9c797b8..dc725ac 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceWebMvcConfigurer.java @@ -1,6 +1,21 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.web; -import com.gitee.starblues.integration.IntegrationConfiguration; import org.springframework.http.CacheControl; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java index f5adbc7..999816e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/PluginThymeleafInvolved.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.web.thymeleaf; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java index 3b2793f..479b1c7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/thymeleaf/ThymeleafConfig.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.spring.web.thymeleaf; import java.nio.charset.Charset; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java index 7ed5143..6d3836d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.lang.annotation.Annotation; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java index 20bec8f..546bcc7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java @@ -1,9 +1,26 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.util.function.Supplier; /** + * 参数校验工具类 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java index b37ca66..8a98b45 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.lang.reflect.Field; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java index 68b2973..ca0c82e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import com.gitee.starblues.integration.IntegrationConfiguration; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java index acd5e26..fe03645 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java index 8b31208..5f421b6 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java @@ -1,10 +1,27 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.lang.reflect.Field; /** + * 文过滤接口 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @FunctionalInterface public interface FieldFilter { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/GlobalRegistryInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/GlobalRegistryInfo.java deleted file mode 100644 index 827f261..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/GlobalRegistryInfo.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.gitee.starblues.utils; - - -import com.gitee.starblues.integration.IntegrationConfiguration; - -import java.util.HashMap; -import java.util.Map; - -/** - * 全局注册信息 - * - * @author starBlues - * @version 2.2.0 - */ -public final class GlobalRegistryInfo { - - private GlobalRegistryInfo(){} - - /** - * 全局插件安装次数 - */ - private static Map operatorPluginInfos = new HashMap<>(); - - /** - * 全局扩展信息 - */ - private static Map extensionMap = new HashMap<>(); - - - /** - * 添加操作插件信息 - * @param pluginId 插件id - * @param operatorType 操作类型 - * @param isLock 是否加锁 - */ - public static synchronized void addOperatorPluginInfo(String pluginId, - PluginOperatorInfo.OperatorType operatorType, - boolean isLock){ - PluginOperatorInfo operatorPluginInfo = operatorPluginInfos.get(pluginId); - if(operatorPluginInfo == null){ - operatorPluginInfo = new PluginOperatorInfo(); - operatorPluginInfos.put(pluginId, operatorPluginInfo); - } - operatorPluginInfo.setOperatorType(operatorType); - operatorPluginInfo.setLock(isLock); - } - - - /** - * 设置操作插件的信息 - * @param pluginId 插件id - * @param isLock 是否加锁 - */ - public static synchronized void setOperatorPluginInfo(String pluginId, boolean isLock){ - PluginOperatorInfo operatorPluginInfo = operatorPluginInfos.get(pluginId); - if(operatorPluginInfo != null){ - operatorPluginInfo.setLock(isLock); - } - } - - - - /** - * 获取插件安装次数 - * @param pluginId 插件id - * @return 操作插件类型 - */ - public static synchronized PluginOperatorInfo getPluginInstallNum(String pluginId){ - return operatorPluginInfos.get(pluginId); - } - - - /** - * 添加全局扩展数据 - * @param key 扩展的key - * @param value 扩展值 - */ - public static synchronized void addExtension(String key, Object value){ - extensionMap.put(key, value); - } - - /** - * 删除全局扩展数据 - * @param key 扩展的key - */ - public static synchronized void removeExtension(String key){ - extensionMap.remove(key); - } - - /** - * 获取全局扩展值 - * @param key 全局扩展的key - * @param 返回值泛型 - * @return 扩展值 - */ - public static synchronized T getExtension(String key){ - Object o = extensionMap.get(key); - if(o == null){ - return null; - } else { - return (T) o; - } - } - - - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java index cb3d3d0..37a797e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import com.gitee.starblues.core.descriptor.PluginDescriptor; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java index 27afded..aae7b4a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import org.springframework.util.CollectionUtils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java index 663132a..904c60e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Order.java @@ -1,6 +1,23 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; /** + * 排序接口 * @author starBlues * @version 1.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderExecution.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderExecution.java deleted file mode 100644 index 4f30f3b..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderExecution.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.gitee.starblues.utils; - -/** - * 执行顺序 - * - * @author starBlues - * @version 1.0 - */ -public class OrderExecution { - - private OrderExecution(){} - - /** - * 低优先级 - */ - public static final int LOW = Integer.MAX_VALUE; - - - /** - * 中优先级 - */ - public static final int MIDDLE = Integer.MAX_VALUE; - - - - /** - * 高优先级 - */ - public static final int HIGH = Integer.MIN_VALUE; - - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderPriority.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderPriority.java index 82b2551..e96f4eb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderPriority.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderPriority.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java index def234d..63f352c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import com.gitee.starblues.core.RuntimeMode; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java index 24a58df..d7ef031 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginOperatorInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginOperatorInfo.java deleted file mode 100644 index be3b0ec..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginOperatorInfo.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.gitee.starblues.utils; - -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * 操作插件信息。为了解决连续上传安装后, 停止后, 无法启动的问题。 - * - * @author starBlues - * @version 2.2.0 - */ -public class PluginOperatorInfo { - - - /** - * 当前操作类型 - */ - private OperatorType operatorType; - - /** - * 是否锁定。如果锁定, 则不允许更新操作类型。 - * 该参数主要解决在安装插件时 setOperatorType 一次操作类型,但是它又调用了启动插件,而启动插件也要 setOperatorType 一次操作类型 - * 所以, 使用该参数, 用于在安装插件时, 锁定 setOperatorType, 在启动时就无法再 setOperatorType 了, 就不会覆盖该值 - */ - private final AtomicBoolean isLock = new AtomicBoolean(false); - - /** - * 设置操作类型 - * @param operatorType 操作类型 - */ - public void setOperatorType(OperatorType operatorType) { - if(operatorType != null && !isLock.get()){ - // 如果锁定了, 则不能更新操作类型 - this.operatorType = operatorType; - } - } - - /** - * 主要用于锁定或者解锁。 - * @param isLock 是否锁定。true 锁定, false 解锁 - */ - public void setLock(boolean isLock){ - this.isLock.set(isLock); - } - - public OperatorType getOperatorType() { - return operatorType; - } - - /** - * 操作类型 - */ - public enum OperatorType{ - /** - * 启动插件 - */ - START, - - /** - * 安装插件 - */ - INSTALL, - } - - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index 4030259..f23ad88 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -1,6 +1,20 @@ -package com.gitee.starblues.utils; - +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitee.starblues.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 69e6c92..2a12885 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import org.slf4j.Logger; @@ -14,10 +30,10 @@ import java.util.Objects; import java.util.function.Consumer; /** - * 对资源解析的工具类 + * 资源工具类 * * @author starBlues - * @version 2.4.4 + * @version 3.0.0 */ public class ResourceUtils { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java index d4e349e..d80fed9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ScanUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java index 6fe3042..43dabc0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanCustomUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import com.gitee.starblues.spring.ApplicationContext; @@ -8,6 +24,7 @@ import java.lang.annotation.Annotation; import java.util.*; /** + * 自定义插件bean工具类 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java index 40dbca7..0380495 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/SpringBeanUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import org.springframework.context.ApplicationContext; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java index e26ca41..fdaa348 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import com.gitee.starblues.plugin.pack.filter.Exclude; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java index 16a0ed6..54aaef2 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import com.gitee.starblues.common.PackageStructure; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index 754d496..ee4a5ff 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import com.gitee.starblues.common.AbstractDependencyPlugin; @@ -26,8 +42,9 @@ import static com.gitee.starblues.plugin.pack.utils.CommonUtils.isEmpty; import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; /** + * 基础打包 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class BasicRepackager implements Repackager{ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java index 7e39cf9..937ccfe 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -1,6 +1,23 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; /** + * 静态类 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java index 420a28b..10c916c 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/DependencyPlugin.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import com.gitee.starblues.common.AbstractDependencyPlugin; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java index d2d296d..ed82626 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadMainResourcePattern.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import lombok.Data; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java index 5520b86..35b7828 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -1,6 +1,21 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; -import com.gitee.starblues.common.AbstractDependencyPlugin; import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java index 7099f24..6ea075e 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import com.gitee.starblues.plugin.pack.dev.DevConfig; @@ -14,7 +30,7 @@ import org.apache.maven.plugins.annotations.ResolutionScope; /** * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java index 8dda151..0da4a27 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java @@ -1,15 +1,36 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** + * 重新打包者 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public interface Repackager { - + /** + * 重新打包 + * @throws MojoExecutionException MojoExecutionException + * @throws MojoFailureException MojoFailureException + */ void repackage() throws MojoExecutionException, MojoFailureException; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java index 9931b25..b0126d4 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.dev; import lombok.Data; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java index a681bf0..a64dddd 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.dev; import lombok.Data; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java index f173741..fb8ab53 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.dev; import com.gitee.starblues.plugin.pack.BasicRepackager; @@ -10,8 +26,9 @@ import org.apache.maven.plugin.MojoExecutionException; import java.util.*; /** + * 开发环境打包 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class DevRepackager extends BasicRepackager { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java index c4c6ceb..3d2daba 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.filter; import com.gitee.starblues.plugin.pack.utils.CommonUtils; @@ -10,8 +26,9 @@ import java.util.List; import java.util.Set; /** + * 依赖过滤 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public abstract class DependencyFilter extends AbstractArtifactsFilter { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java index 000c35e..999dace 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java @@ -1,7 +1,23 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.filter; /** - * 排除依赖定义 + * 排除的依赖定义 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java index 283c1ef..dce74ec 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/ExcludeFilter.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.filter; import org.apache.maven.artifact.Artifact; @@ -6,8 +22,9 @@ import java.util.Arrays; import java.util.List; /** + * 排除过滤 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ExcludeFilter extends DependencyFilter { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java index 96cad7a..7f24259 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/FilterableDependency.java @@ -1,11 +1,28 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.filter; import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; /** + * 可过滤依赖bean * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @Data public abstract class FilterableDependency { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java index 675ccce..55ae558 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Include.java @@ -1,8 +1,25 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.filter; /** + * 包含的依赖定义 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class Include extends FilterableDependency{ } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java index 9694403..1ab20ea 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/IncludeFilter.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.filter; import org.apache.maven.artifact.Artifact; @@ -5,8 +21,9 @@ import org.apache.maven.artifact.Artifact; import java.util.List; /** + * 包含过滤器 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class IncludeFilter extends DependencyFilter { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java similarity index 83% rename from springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java index 76fc6c5..a0a474d 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirPackageGenerator.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.common.PackageStructure; @@ -20,15 +36,16 @@ import java.util.jar.Manifest; import static com.gitee.starblues.common.PackageStructure.*; /** + * 文件夹包生成 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ -public class DirPackageGenerator extends DevRepackager { +public class DirProdRepackager extends DevRepackager { private final ProdConfig prodConfig; - public DirPackageGenerator(RepackageMojo repackageMojo, ProdConfig prodConfig) { + public DirProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { super(repackageMojo); this.prodConfig = prodConfig; } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java similarity index 58% rename from springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java index 5502bcb..4f022ed 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarPackageGenerator.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.plugin.pack.RepackageMojo; @@ -11,13 +27,14 @@ import org.apache.maven.plugin.MojoFailureException; import java.io.*; /** + * jar包生成 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ -public class JarPackageGenerator extends ZipProdRepackager { +public class JarProdRepackager extends ZipProdRepackager { - public JarPackageGenerator(RepackageMojo repackageMojo, ProdConfig prodConfig) { + public JarProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { super(repackageMojo, prodConfig); } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java deleted file mode 100644 index 585beee..0000000 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarWriter.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.starblues.plugin.pack.prod; - -import java.io.IOException; -import java.io.InputStream; - -/** - * @author starBlues - * @version 1.0 - */ -public interface JarWriter { - - void writeEntry(String name, InputStream inputStream) throws IOException; - -} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java deleted file mode 100644 index 989abc0..0000000 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/PackageGenerator.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.gitee.starblues.plugin.pack.prod; - -import org.apache.maven.plugin.MojoFailureException; - -/** - * @author starBlues - * @version 1.0 - */ -public interface PackageGenerator { - - void pack() throws MojoFailureException; - -} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java index a29f306..76cbd35 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java @@ -1,5 +1,22 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.prod; + import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java index 96dc33e..cda85fc 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.common.PackageStructure; @@ -13,8 +29,9 @@ import org.apache.maven.plugin.MojoFailureException; /** + * 生产环境打包 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ProdRepackager implements Repackager { @@ -39,9 +56,9 @@ public class ProdRepackager implements Repackager { // jar repackager = new ZipProdRepackager(repackageMojo, prodConfig); } else if(Constant.PACKAGE_TYPE_JAR.equalsIgnoreCase(packageType)){ - repackager = new JarPackageGenerator(repackageMojo, prodConfig); + repackager = new JarProdRepackager(repackageMojo, prodConfig); } else if(Constant.PACKAGE_TYPE_DIR.equalsIgnoreCase(packageType)){ - repackager = new DirPackageGenerator(repackageMojo, prodConfig); + repackager = new DirProdRepackager(repackageMojo, prodConfig); } else { throw new MojoFailureException("Not found packageType:" + packageType); } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java index 481a059..ca3fb0f 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.common.PluginDescriptorKey; @@ -32,8 +48,9 @@ import static com.gitee.starblues.plugin.pack.Constant.SCOPE_PROVIDED; import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; /** + * zip 打包 * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class ZipProdRepackager extends DevRepackager { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java index 01d286e..295f635 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.plugin.pack.utils; import java.io.File; -- Gitee From 138e01e113ccc100ec9ba45f22de4b9b77a6430e Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sat, 29 Jan 2022 14:39:20 +0800 Subject: [PATCH 28/37] update version --- pom.xml | 3 +- spring-plugin-framework-common/pom.xml | 2 +- springboot-plugin-bootstrap/pom.xml | 11 +- springboot-plugin-framework-extension/pom.xml | 21 -- .../pom.xml | 222 ------------ .../extension/cloud/SpringCloudExtension.java | 66 ---- .../cloud/nacos/NacosBeanRegistrar.java | 155 -------- .../cloud/nacos/NacosDataParserHandler.java | 159 --------- .../cloud/nacos/NacosPropertySource.java | 95 ----- .../nacos/config/NacosConfigProperties.java | 81 ----- .../cloud/nacos/config/NacosProperties.java | 30 -- .../nacos/config/SpringCloudProperties.java | 20 -- .../cloud/openfeign/FeignClientBeanGroup.java | 40 --- .../openfeign/FeignClientSpecification.java | 70 ---- .../cloud/openfeign/OpenFeignRegistrar.java | 332 ----------------- .../nacos/NacosRibbonClientConfiguration.java | 43 --- .../nacos/RibbonNacosAutoConfiguration.java | 23 -- .../pom.xml | 213 ----------- .../starblues/extension/log/LogRegistry.java | 31 -- .../log/PluginLogConfigProcessor.java | 104 ------ .../starblues/extension/log/PropertyKey.java | 12 - .../extension/log/SpringBootLogExtension.java | 50 --- .../extension/log/annotation/ConfigItem.java | 26 -- .../extension/log/config/LogConfig.java | 140 -------- .../extension/log/log4j/Log4jLogRegistry.java | 209 ----------- .../log/logback/LogbackLogRegistry.java | 185 ---------- .../extension/log/util/LogConfigUtil.java | 131 ------- .../extension/log/util/ObjectUtil.java | 55 --- .../pom.xml | 221 ------------ .../extension/mybatis/CommonRegister.java | 27 -- .../extension/mybatis/MapperHandler.java | 110 ------ .../mybatis/MybatisCommonConfig.java | 40 --- .../extension/mybatis/MybatisProcessor.java | 103 ------ .../mybatis/PluginFollowCoreConfig.java | 146 -------- .../mybatis/PluginResourceFinder.java | 129 ------- .../mybatis/SpringBootMybatisConfig.java | 30 -- .../mybatis/SpringBootMybatisExtension.java | 77 ---- .../mybatis/group/MybatisConfigGroup.java | 46 --- .../group/PluginEntityAliasesGroup.java | 62 ---- .../mybatis/group/PluginMapperGroup.java | 37 -- .../mybatisplus/MybatisPlusProcessor.java | 130 ------- .../mybatisplus/ServiceImplWrapper.java | 161 --------- .../SpringBootMybatisPlusConfig.java | 36 -- .../tkmyabtis/SpringBootTkMybatisConfig.java | 36 -- .../mybatis/tkmyabtis/TkMybatisProcessor.java | 146 -------- .../pom.xml | 235 ------------ .../PluginResourceResolverProcess.java | 91 ----- .../extension/resources/PropertyKey.java | 23 -- .../resources/StaticResourceConfig.java | 30 -- .../resources/StaticResourceExtension.java | 118 ------ .../resolver/PluginResourceResolver.java | 335 ------------------ .../resolver/ResourceWebMvcConfigurer.java | 38 -- .../thymeleaf/SpringBootThymeleafConfig.java | 14 - .../resources/thymeleaf/ThymeleafConfig.java | 16 - .../thymeleaf/ThymeleafProcessor.java | 157 -------- springboot-plugin-framework/pom.xml | 21 +- .../core/launcher/plugin/PluginLauncher.java | 2 - .../AutoIntegrationConfiguration.java | 144 +------- .../com/gitee/starblues/spring/WebConfig.java | 18 +- .../web/PluginStaticResourceConfig.java | 22 +- springboot-plugin-maven-packager/pom.xml | 4 +- .../plugin-help.xml | 2 +- .../main/resources/META-INF/maven/plugin.xml | 2 +- 63 files changed, 26 insertions(+), 5312 deletions(-) delete mode 100644 springboot-plugin-framework-extension/pom.xml delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/LogRegistry.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PluginLogConfigProcessor.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PropertyKey.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/SpringBootLogExtension.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/annotation/ConfigItem.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/config/LogConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/log4j/Log4jLogRegistry.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/logback/LogbackLogRegistry.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/LogConfigUtil.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/ObjectUtil.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/CommonRegister.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MapperHandler.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisCommonConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisProcessor.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginFollowCoreConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginResourceFinder.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisExtension.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/MybatisConfigGroup.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginEntityAliasesGroup.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginMapperGroup.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/MybatisPlusProcessor.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/ServiceImplWrapper.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/SpringBootMybatisPlusConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/SpringBootTkMybatisConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/TkMybatisProcessor.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PluginResourceResolverProcess.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PropertyKey.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceExtension.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/PluginResourceResolver.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/ResourceWebMvcConfigurer.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/SpringBootThymeleafConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java delete mode 100644 springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafProcessor.java diff --git a/pom.xml b/pom.xml index 94ab37e..4341d44 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.gitee.starblues springboot-plugin-framework-parent pom - 3.0.0-RELEASE + 3.0.0-alpha spring boot 插件开发集成包 @@ -15,7 +15,6 @@ spring-plugin-framework-common springboot-plugin-framework springboot-plugin-bootstrap - springboot-plugin-framework-example springboot-plugin-maven-packager diff --git a/spring-plugin-framework-common/pom.xml b/spring-plugin-framework-common/pom.xml index 59c6a68..07b3ef3 100644 --- a/spring-plugin-framework-common/pom.xml +++ b/spring-plugin-framework-common/pom.xml @@ -6,7 +6,7 @@ com.gitee.starblues spring-plugin-framework-common - 3.0.0-RELEASE + 3.0.0-alpha jar diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index de49963..f83d961 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -5,7 +5,7 @@ springboot-plugin-framework-parent com.gitee.starblues - 3.0.0-RELEASE + 3.0.0-alpha 4.0.0 @@ -30,25 +30,21 @@ - org.aspectj aspectjweaver ${aspectj.version} - org.slf4j slf4j-api ${slf4j.version} - com.fasterxml.jackson.core jackson-databind ${jackson.version} - com.gitee.starblues springboot-plugin-framework @@ -56,7 +52,6 @@ provided true - org.springframework.boot spring-boot @@ -64,7 +59,6 @@ provided true - org.springframework spring-webmvc @@ -72,7 +66,6 @@ provided true - org.springdoc springdoc-openapi-common @@ -80,7 +73,6 @@ provided true - javax.servlet javax.servlet-api @@ -88,7 +80,6 @@ provided true - diff --git a/springboot-plugin-framework-extension/pom.xml b/springboot-plugin-framework-extension/pom.xml deleted file mode 100644 index 69f4f83..0000000 --- a/springboot-plugin-framework-extension/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 4.0.0 - - - com.gitee.starblues - springboot-plugin-framework-extension - pom - 3.0.0-RELEASE - - spring boot 插件式开发集成包--扩展模块 - - springboot-plugin-framework-extension-mybatis - springboot-plugin-framework-extension-resources - springboot-plugin-framework-extension-log - - - \ No newline at end of file diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml deleted file mode 100644 index ebe70af..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/pom.xml +++ /dev/null @@ -1,222 +0,0 @@ - - - - springboot-plugin-framework-parent - com.gitee.starblues - 2.4.6-RELEASE - - 4.0.0 - - springboot-plugin-framework-extension-cloud - 插件扩展-微服务模块扩展 - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - https://gitee.com/starblues/springboot-plugin-framework-parent - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - 1.0 - - - - - sonatype-nexus-snapshots - oss Snapshots Repository - https://oss.sonatype.org/content/repositories/snapshots - - - sonatype-nexus-staging - oss Staging Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - StarBlues - starblues@foxmail.com - https://gitee.com/starblues/ - - - - - 1.8 - UTF-8 - - 3.8.1 - 3.1.0 - 3.1.0 - 3.1.0 - 1.6 - - 2.4.6-RELEASE - 5.0.7.RELEASE - 2.2.6.RELEASE - - - - - com.gitee.starblues - springboot-plugin-framework - ${springboot-plugin-framework.version} - provided - - - - org.springframework - spring-context - ${spring-version} - provided - - - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-discovery - ${nacos-cloud-version} - provided - - - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-config - ${nacos-cloud-version} - provided - - - - org.springframework.cloud - spring-cloud-starter-openfeign - 2.2.6.RELEASE - provided - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - 2.2.6.RELEASE - provided - - - - - - - dev - - true - - - true - - - - - release - - false - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-assembly-plugin - ${maven-assembly-plugin.version} - - - jar-with-dependencies - - ${project.artifactId}-${project.version} - false - false - - - true - true - - - - - - make-assembly - package - - single - - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - ${plugin.skip} - - - - package - - jar - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - ${plugin.skip} - - - - sign-artifacts - verify - - sign - - - - - - - - \ No newline at end of file diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java deleted file mode 100644 index 01689b9..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/SpringCloudExtension.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.gitee.starblues.extension.cloud; - -import com.gitee.starblues.extension.AbstractExtension; -import com.gitee.starblues.extension.cloud.nacos.NacosBeanRegistrar; -import com.gitee.starblues.extension.cloud.openfeign.FeignClientBeanGroup; -import com.gitee.starblues.extension.cloud.openfeign.OpenFeignRegistrar; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import org.springframework.context.ApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author starBlues - * @version 2.4.6 - */ -public class SpringCloudExtension extends AbstractExtension { - - private final Type type; - private final boolean enableOpenFeign; - - public SpringCloudExtension(Type type, boolean enableOpenFeign){ - this.type = type; - this.enableOpenFeign = enableOpenFeign; - } - - public SpringCloudExtension(Type type){ - this(type, false); - } - - @Override - public String key() { - return "SpringCloud"; - } - - @Override - public List getPluginBeanRegistrar(ApplicationContext mainApplicationContext) { - List pluginBeanRegistrarExtends = new ArrayList<>(); - if(type == Type.NACOS){ - pluginBeanRegistrarExtends.add(new NacosBeanRegistrar()); - } - if(enableOpenFeign){ - pluginBeanRegistrarExtends.add(new OpenFeignRegistrar()); - } - return pluginBeanRegistrarExtends; - } - - @Override - public List getPluginClassGroup(ApplicationContext mainApplicationContext) { - if(enableOpenFeign){ - List pluginClassGroupExtends = new ArrayList<>(1); - pluginClassGroupExtends.add(new FeignClientBeanGroup()); - return pluginClassGroupExtends; - } - return null; - } - - public enum Type{ - /** - * nacos - */ - NACOS - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java deleted file mode 100644 index d646f9d..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosBeanRegistrar.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.gitee.starblues.extension.cloud.nacos; - -import com.alibaba.cloud.nacos.NacosConfigManager; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.NacosServiceManager; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; -import com.gitee.starblues.extension.cloud.nacos.config.NacosConfigProperties; -import com.gitee.starblues.extension.cloud.nacos.config.NacosProperties; -import com.gitee.starblues.extension.cloud.nacos.config.SpringCloudProperties; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.utils.PluginConfigUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.PropertySource; -import org.springframework.util.StringUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -/** - * @author starBlues - * @version 2.4.6 - */ -public class NacosBeanRegistrar implements PluginBeanRegistrarExtend { - - private final static Logger log = LoggerFactory.getLogger(NacosBeanRegistrar.class); - - @Override - public String key() { - return "SpringCloud-Nacos"; - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - GenericApplicationContext mainApplicationContext = pluginRegistryInfo.getMainApplicationContext(); - NacosConfigManager nacosConfigManager = mainApplicationContext.getBean(NacosConfigManager.class); - - SpringCloudProperties springCloudProperties = pluginRegistryInfo.getPluginBinder() - .bind(SpringCloudProperties.PREFIX, Bindable.of(SpringCloudProperties.class)) - .orElseGet(() -> null); - - if(springCloudProperties == null){ - // todo 注释 - return; - } - - ConfigService configService = nacosConfigManager.getConfigService(); - NacosProperties nacos = springCloudProperties.getNacos(); - if(nacos != null && nacos.getConfigs() != null){ - // 处理配置文件 - List configs = nacos.getConfigs(); - ConfigurableEnvironment environment = pluginRegistryInfo.getPluginApplicationContext().getEnvironment(); - processConfig(configService, environment, configs, nacos.getTimeout()); - } - - - // 注册中心 - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - springBeanRegister.registerSingleton("nacosDiscoveryProperties", - mainApplicationContext.getBean(NacosDiscoveryProperties.class)); - springBeanRegister.registerSingleton("nacosServiceManager", - mainApplicationContext.getBean(NacosServiceManager.class)); - } - - - private void processConfig(ConfigService configService, - ConfigurableEnvironment environment, - List configProperties, - Integer timeout){ - checkConfiguration(configProperties, "nacos-config"); - for (NacosConfigProperties properties : configProperties) { - if(properties == null){ - continue; - } - List dataIds = new ArrayList<>(); - if(properties.isFollowProfile()){ - String[] activeProfiles = environment.getActiveProfiles(); - for (String activeProfile : activeProfiles) { - NacosConfigProperties nacosConfigProperties = new NacosConfigProperties(); - BeanUtils.copyProperties(properties, nacosConfigProperties); - String dataId = PluginConfigUtils.joinConfigFileName(properties.getDataId(), activeProfile); - nacosConfigProperties.setDataId(dataId); - dataIds.add(nacosConfigProperties); - } - } else { - dataIds.add(properties); - } - - for (NacosConfigProperties config : dataIds) { - List> propertySources = loadNacosData(configService, config.getDataId(), - config.getGroup(), - config.getFileExtension(), timeout); - NacosPropertySource nacosPropertySource = new NacosPropertySource(propertySources, config.getGroup(), - config.getDataId(), new Date(), - config.isRefresh()); - if(!nacosPropertySource.getSource().isEmpty()){ - environment.getPropertySources().addLast(nacosPropertySource); - } - } - } - } - - - - private List> loadNacosData(ConfigService configService, - String dataId, String group, String fileExtension, - Integer timeout){ - String data = null; - try { - data = configService.getConfig(dataId, group, timeout); - if (StringUtils.isEmpty(data)) { - log.warn( - "Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]", - dataId, group); - return Collections.emptyList(); - } - if (log.isDebugEnabled()) { - log.debug(String.format( - "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId, - group, data)); - } - return NacosDataParserHandler.getInstance().parseNacosData(dataId, data, - fileExtension); - } - catch (NacosException e) { - log.error("get data from Nacos error,dataId:{} ", dataId, e); - } - catch (Exception e) { - log.error("parse data from Nacos error,dataId:{},data:{}", dataId, data, e); - } - return Collections.emptyList(); - } - - private void checkConfiguration(List configs, - String tips) { - for (int i = 0; i < configs.size(); i++) { - String dataId = configs.get(i).getDataId(); - if (dataId == null || dataId.trim().length() == 0) { - throw new IllegalStateException(String.format( - "the [ spring.cloud.nacos.config.%s[%s] ] must give a dataId", - tips, i)); - } - } - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java deleted file mode 100644 index 4eb2057..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosDataParserHandler.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.gitee.starblues.extension.cloud.nacos; - -import com.alibaba.cloud.nacos.parser.NacosByteArrayResource; -import com.alibaba.cloud.nacos.parser.NacosJsonPropertySourceLoader; -import com.alibaba.cloud.nacos.parser.NacosXmlPropertySourceLoader; -import com.alibaba.cloud.nacos.utils.NacosConfigUtils; -import org.springframework.boot.env.OriginTrackedMapPropertySource; -import org.springframework.boot.env.PropertiesPropertySourceLoader; -import org.springframework.boot.env.PropertySourceLoader; -import org.springframework.boot.env.YamlPropertySourceLoader; -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import java.io.IOException; -import java.util.*; -import java.util.stream.Collectors; - - -/** - * copy from com.alibaba.cloud.nacos.parser.NacosDataParserHandler - * @author starBlues - * @version 2.4.6 - * @see com.alibaba.cloud.nacos.parser.NacosDataParserHandler - */ -public class NacosDataParserHandler { - - static final String DOT = "."; - - /** - * default extension. - */ - private static final String DEFAULT_EXTENSION = "properties"; - - private static List propertySourceLoaders; - - private NacosDataParserHandler() { - propertySourceLoaders = new ArrayList<>(); - propertySourceLoaders.add(new PropertiesPropertySourceLoader()); - propertySourceLoaders.add(new YamlPropertySourceLoader()); - propertySourceLoaders.add(new NacosJsonPropertySourceLoader()); - propertySourceLoaders.add(new NacosXmlPropertySourceLoader()); - } - - /** - * Parsing nacos configuration content. - * @param configName name of nacos-config - * @param configValue value from nacos-config - * @param extension identifies the type of configValue - * @return result of Map - * @throws IOException thrown if there is a problem parsing config. - */ - public List> parseNacosData(String configName, String configValue, - String extension) throws IOException { - if (StringUtils.isEmpty(configValue)) { - return Collections.emptyList(); - } - if (StringUtils.isEmpty(extension)) { - extension = this.getFileExtension(configName); - } - for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { - if (!canLoadFileExtension(propertySourceLoader, extension)) { - continue; - } - NacosByteArrayResource nacosByteArrayResource; - if (propertySourceLoader instanceof PropertiesPropertySourceLoader) { - // PropertiesPropertySourceLoader internal is to use the ISO_8859_1, - // the Chinese will be garbled, needs to transform into unicode. - nacosByteArrayResource = new NacosByteArrayResource( - NacosConfigUtils.selectiveConvertUnicode(configValue).getBytes(), - configName); - } - else { - nacosByteArrayResource = new NacosByteArrayResource( - configValue.getBytes(), configName); - } - nacosByteArrayResource.setFilename(getFileName(configName, extension)); - List> propertySourceList = propertySourceLoader - .load(configName, nacosByteArrayResource); - if (CollectionUtils.isEmpty(propertySourceList)) { - return Collections.emptyList(); - } - return propertySourceList.stream().filter(Objects::nonNull) - .map(propertySource -> { - if (propertySource instanceof EnumerablePropertySource) { - String[] propertyNames = ((EnumerablePropertySource) propertySource) - .getPropertyNames(); - if (propertyNames != null && propertyNames.length > 0) { - Map map = new LinkedHashMap<>(); - Arrays.stream(propertyNames).forEach(name -> { - map.put(name, propertySource.getProperty(name)); - }); - return new OriginTrackedMapPropertySource( - propertySource.getName(), map, true); - } - } - return propertySource; - }).collect(Collectors.toList()); - } - return Collections.emptyList(); - } - - /** - * check the current extension can be processed. - * @param loader the propertySourceLoader - * @param extension file extension - * @return if can match extension - */ - private boolean canLoadFileExtension(PropertySourceLoader loader, String extension) { - return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(extension, - fileExtension)); - } - - /** - * @param name filename - * @return file extension, default {@code DEFAULT_EXTENSION} if don't get - */ - public String getFileExtension(String name) { - if (StringUtils.isEmpty(name)) { - return DEFAULT_EXTENSION; - } - int idx = name.lastIndexOf(DOT); - if (idx > 0 && idx < name.length() - 1) { - return name.substring(idx + 1); - } - return DEFAULT_EXTENSION; - } - - private String getFileName(String name, String extension) { - if (StringUtils.isEmpty(extension)) { - return name; - } - if (StringUtils.isEmpty(name)) { - return extension; - } - int idx = name.lastIndexOf(DOT); - if (idx > 0 && idx < name.length() - 1) { - String ext = name.substring(idx + 1); - if (extension.equalsIgnoreCase(ext)) { - return name; - } - } - return name + DOT + extension; - } - - public static NacosDataParserHandler getInstance() { - return ParserHandler.HANDLER; - } - - private static class ParserHandler { - - private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler(); - - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java deleted file mode 100644 index 82ecdd3..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/NacosPropertySource.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.gitee.starblues.extension.cloud.nacos; - -import com.alibaba.cloud.nacos.NacosConfigProperties; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.util.CollectionUtils; - -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; - - -/** - * copy from com.alibaba.cloud.nacos.client.NacosPropertySource - * @author starBlues - * @version 2.4.6 - * @see com.alibaba.cloud.nacos.client.NacosPropertySource - */ -public class NacosPropertySource extends MapPropertySource { - - /** - * Nacos Group. - */ - private final String group; - - /** - * Nacos dataID. - */ - private final String dataId; - - /** - * timestamp the property get. - */ - private final Date timestamp; - - /** - * Whether to support dynamic refresh for this Property Source. - */ - private final boolean isRefreshable; - - NacosPropertySource(String group, String dataId, Map source, - Date timestamp, boolean isRefreshable) { - super(String.join(NacosConfigProperties.COMMAS, dataId, group), source); - this.group = group; - this.dataId = dataId; - this.timestamp = timestamp; - this.isRefreshable = isRefreshable; - } - - NacosPropertySource(List> propertySources, String group, - String dataId, Date timestamp, boolean isRefreshable) { - this(group, dataId, getSourceMap(group, dataId, propertySources), timestamp, - isRefreshable); - } - - @SuppressWarnings("all") - private static Map getSourceMap(String group, String dataId, - List> propertySources) { - if (CollectionUtils.isEmpty(propertySources)) { - return Collections.emptyMap(); - } - // If only one, return the internal element, otherwise wrap it. - if (propertySources.size() == 1) { - PropertySource propertySource = propertySources.get(0); - if (propertySource != null && propertySource.getSource() instanceof Map) { - return (Map) propertySource.getSource(); - } - } - // If it is multiple, it will be returned as it is, and the internal elements - // cannot be directly retrieved, so the user needs to implement the retrieval - // logic by himself - return Collections.singletonMap( - String.join(NacosConfigProperties.COMMAS, dataId, group), - propertySources); - } - - public String getGroup() { - return this.group; - } - - public String getDataId() { - return dataId; - } - - public Date getTimestamp() { - return timestamp; - } - - public boolean isRefreshable() { - return isRefreshable; - } - -} - diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java deleted file mode 100644 index 8878e29..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosConfigProperties.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.gitee.starblues.extension.cloud.nacos.config; - -import java.util.Objects; - -/** - * @author starBlues - * @version 2.4.5 - */ -public class NacosConfigProperties { - - private String dataId; - - private String group = "DEFAULT_GROUP"; - - private String fileExtension = "properties"; - - private boolean refresh = false; - - private boolean followProfile = false; - - public String getDataId() { - return dataId; - } - - public void setDataId(String dataId) { - this.dataId = dataId; - } - - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } - - public String getFileExtension() { - return fileExtension; - } - - public void setFileExtension(String fileExtension) { - this.fileExtension = fileExtension; - } - - public boolean isRefresh() { - return refresh; - } - - public void setRefresh(boolean refresh) { - this.refresh = refresh; - } - - public boolean isFollowProfile() { - return followProfile; - } - - public void setFollowProfile(boolean followProfile) { - this.followProfile = followProfile; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof NacosConfigProperties)) { - return false; - } - NacosConfigProperties that = (NacosConfigProperties) o; - return isRefresh() == that.isRefresh() && - isFollowProfile() == that.isFollowProfile() && - getDataId().equals(that.getDataId()) && - getGroup().equals(that.getGroup()) && - getFileExtension().equals(that.getFileExtension()); - } - - @Override - public int hashCode() { - return Objects.hash(getDataId(), getGroup(), getFileExtension(), isRefresh(), isFollowProfile()); - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java deleted file mode 100644 index b1b994a..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/NacosProperties.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.starblues.extension.cloud.nacos.config; - -import java.util.List; - -/** - * @author starBlues - * @version 2.4.5 - */ -public class NacosProperties { - - private List configs; - - private Integer timeout = 1000; - - public List getConfigs() { - return configs; - } - - public void setConfigs(List configs) { - this.configs = configs; - } - - public Integer getTimeout() { - return timeout; - } - - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java deleted file mode 100644 index 7606fde..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/nacos/config/SpringCloudProperties.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.gitee.starblues.extension.cloud.nacos.config; - -/** - * @author starBlues - * @version 2.4.5 - */ -public class SpringCloudProperties { - - public static final String PREFIX = "spring-cloud"; - - private NacosProperties nacos; - - public NacosProperties getNacos() { - return nacos; - } - - public void setNacos(NacosProperties nacos) { - this.nacos = nacos; - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java deleted file mode 100644 index faa41d5..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientBeanGroup.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gitee.starblues.extension.cloud.openfeign; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.springframework.cloud.openfeign.FeignClient; - -/** - * FeignClient bean class 分组 - * @author starBlues - * @version 2.4.6 - */ -public class FeignClientBeanGroup implements PluginClassGroupExtend { - - public static final String KEY = "feignClientBeanClass"; - public static final String GROUP_ID = "feignClientBeanClassGroupExtend"; - - @Override - public String key() { - return KEY ; - } - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - if(aClass == null){ - return false; - } - return AnnotationsUtils.haveAnnotations(aClass, false, FeignClient.class); - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java deleted file mode 100644 index 0ade998..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/FeignClientSpecification.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.gitee.starblues.extension.cloud.openfeign; - -import org.springframework.cloud.context.named.NamedContextFactory; - -import java.util.Arrays; -import java.util.Objects; - -/** - * copy org.springframework.cloud.openfeign.FeignClientSpecification - * @author starBlues - * @version 2.4.6 - */ -public class FeignClientSpecification implements NamedContextFactory.Specification { - - private String name; - - private Class[] configuration; - - FeignClientSpecification() { - } - - FeignClientSpecification(String name, Class[] configuration) { - this.name = name; - this.configuration = configuration; - } - - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public Class[] getConfiguration() { - return this.configuration; - } - - public void setConfiguration(Class[] configuration) { - this.configuration = configuration; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - FeignClientSpecification that = (FeignClientSpecification) o; - return Objects.equals(this.name, that.name) - && Arrays.equals(this.configuration, that.configuration); - } - - @Override - public int hashCode() { - return Objects.hash(this.name, this.configuration); - } - - @Override - public String toString() { - return new StringBuilder("FeignClientSpecification{").append("name='") - .append(this.name).append("', ").append("configuration=") - .append(Arrays.toString(this.configuration)).append("}").toString(); - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java deleted file mode 100644 index 4f977ef..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/OpenFeignRegistrar.java +++ /dev/null @@ -1,332 +0,0 @@ -package com.gitee.starblues.extension.cloud.openfeign; - -import com.gitee.starblues.extension.cloud.openfeign.nacos.RibbonNacosAutoConfiguration; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.realize.BasePlugin; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.openfeign.FeignAutoConfiguration; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.cloud.openfeign.FeignClientFactoryBean; -import org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoConfiguration; -import org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration; -import org.springframework.cloud.openfeign.hateoas.FeignHalAutoConfiguration; -import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.io.support.SpringFactoriesLoader; -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.*; - -/** - * OpenFeign 注册者 - * @author starBlues - * @version 2.4.6 - */ -public class OpenFeignRegistrar implements PluginBeanRegistrarExtend { - - @Override - public String key() { - return "OpenFeignRegistrar"; - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - // 先注册 feignClient bean - boolean isRegistry = registryFeignClientBean(pluginRegistryInfo); - if(!isRegistry){ - // 如果发现 FeignClient 则, 不进行注册 openFeign - return; - } - installAutoConfiguration(pluginRegistryInfo); - } - - private void installAutoConfiguration(PluginRegistryInfo pluginRegistryInfo) { - List basePlugins = SpringFactoriesLoader - .loadFactories(pluginRegistryInfo.getBasePlugin().getClass(), pluginRegistryInfo.getPluginClassLoader()); - - - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - pluginApplicationContext.registerBean(FeignRibbonClientAutoConfiguration.class); - pluginApplicationContext.registerBean(FeignHalAutoConfiguration.class); - pluginApplicationContext.registerBean(FeignAutoConfiguration.class); - pluginApplicationContext.registerBean(FeignAcceptGzipEncodingAutoConfiguration.class); - pluginApplicationContext.registerBean(FeignContentGzipEncodingAutoConfiguration.class); - //pluginApplicationContext.registerBean(FeignLoadBalancerAutoConfiguration.class); - pluginApplicationContext.registerBean(RibbonNacosAutoConfiguration.class); - pluginApplicationContext.registerBean(RibbonAutoConfiguration.class); - pluginApplicationContext.registerBean(HttpMessageConvertersAutoConfiguration.class); - } - - private boolean registryFeignClientBean(PluginRegistryInfo pluginRegistryInfo) { - List> groupClasses = pluginRegistryInfo.getGroupClasses(FeignClientBeanGroup.GROUP_ID); - if(ObjectUtils.isEmpty(groupClasses)){ - return false; - } - GenericApplicationContext registry = pluginRegistryInfo.getPluginApplicationContext(); - for (Class groupClass : groupClasses) { - AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(groupClass); - AnnotationMetadata annotationMetadata = beanDefinition.getMetadata(); - Assert.isTrue(annotationMetadata.isInterface(), - "@FeignClient can only be specified on an interface"); - - Map attributes = annotationMetadata - .getAnnotationAttributes(FeignClient.class.getCanonicalName()); - if(attributes == null){ - continue; - } - String name = getClientName(attributes); - registerClientConfiguration(registry, name, attributes.get("configuration")); - - BeanDefinitionHolder beanDefinitionHolder = getBeanDefinition(registry, annotationMetadata, attributes); - pluginRegistryInfo.getSpringBeanRegister().registerBeanDefinition(beanDefinitionHolder); - } - return true; - } - - private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, - Object configuration) { - if(configuration == null){ - return; - } - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(FeignClientSpecification.class); - builder.addConstructorArgValue(name); - builder.addConstructorArgValue(configuration); - registry.registerBeanDefinition( - name + "." + FeignClientSpecification.class.getSimpleName(), - builder.getBeanDefinition()); - } - - private BeanDefinitionHolder getBeanDefinition(GenericApplicationContext applicationContext, - AnnotationMetadata annotationMetadata, - Map attributes) { - String className = annotationMetadata.getClassName(); - Class clazz = ClassUtils.resolveClassName(className, applicationContext.getClassLoader()); - String contextId = getContextId(applicationContext, attributes); - String name = getName(applicationContext, attributes); - FeignClientFactoryBean factoryBean = new FeignClientFactoryBean(); - factoryBean.setBeanFactory(applicationContext); - factoryBean.setName(name); - factoryBean.setContextId(contextId); - factoryBean.setType(clazz); - BeanDefinitionBuilder definition = BeanDefinitionBuilder - .genericBeanDefinition(clazz, () -> { - factoryBean.setUrl(getUrl(applicationContext, attributes)); - factoryBean.setPath(getPath(applicationContext, attributes)); - factoryBean.setDecode404(Boolean - .parseBoolean(String.valueOf(attributes.get("decode404")))); - Object fallback = attributes.get("fallback"); - if (fallback != null) { - factoryBean.setFallback(fallback instanceof Class - ? (Class) fallback - : ClassUtils.resolveClassName(fallback.toString(), null)); - } - Object fallbackFactory = attributes.get("fallbackFactory"); - if (fallbackFactory != null) { - factoryBean.setFallbackFactory(fallbackFactory instanceof Class - ? (Class) fallbackFactory - : ClassUtils.resolveClassName(fallbackFactory.toString(), - null)); - } - return factoryBean.getObject(); - }); - definition.setAutowireMode(2); - definition.setLazyInit(true); - validate(attributes); - - AbstractBeanDefinition beanDefinition = definition.getBeanDefinition(); - beanDefinition.setAttribute("factoryBeanObjectType", className); - beanDefinition.setAttribute("feignClientsRegistrarFactoryBean", factoryBean); - - // has a default, won't be null - boolean primary = (Boolean) attributes.get("primary"); - - beanDefinition.setPrimary(primary); - - String[] qualifiers = getQualifiers(attributes); - if (ObjectUtils.isEmpty(qualifiers)) { - qualifiers = new String[] { contextId + "FeignClient" }; - } - - return new BeanDefinitionHolder(beanDefinition, className, qualifiers); - } - - private void validate(Map attributes) { - AnnotationAttributes annotation = AnnotationAttributes.fromMap(attributes); - // This blows up if an aliased property is overspecified - // FIXME annotation.getAliasedString("name", FeignClient.class, null); - validateFallback(annotation.getClass("fallback")); - validateFallbackFactory(annotation.getClass("fallbackFactory")); - } - - private void validateFallback(final Class clazz) { - Assert.isTrue(!clazz.isInterface(), - "Fallback class must implement the interface annotated by @FeignClient"); - } - - private void validateFallbackFactory(final Class clazz) { - Assert.isTrue(!clazz.isInterface(), "Fallback factory must produce instances " - + "of fallback classes that implement the interface annotated by @FeignClient"); - } - - private String getContextId(GenericApplicationContext applicationContext, - Map attributes) { - String contextId = (String) attributes.get("contextId"); - if (!StringUtils.hasText(contextId)) { - return getName(applicationContext, attributes); - } - - contextId = resolve(applicationContext, contextId); - return getName(contextId); - } - - private String getQualifier(Map client) { - if (client == null) { - return null; - } - String qualifier = (String) client.get("qualifier"); - if (StringUtils.hasText(qualifier)) { - return qualifier; - } - return null; - } - - private String[] getQualifiers(Map client) { - if (client == null) { - return null; - } - List qualifierList = new ArrayList<>( - Arrays.asList((String[]) client.get("qualifiers"))); - qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier)); - if (qualifierList.isEmpty() && getQualifier(client) != null) { - qualifierList = Collections.singletonList(getQualifier(client)); - } - return !qualifierList.isEmpty() ? qualifierList.toArray(new String[0]) : null; - } - - private String getName(GenericApplicationContext applicationContext, - Map attributes) { - String name = (String) attributes.get("serviceId"); - if (!StringUtils.hasText(name)) { - name = (String) attributes.get("name"); - } - if (!StringUtils.hasText(name)) { - name = (String) attributes.get("value"); - } - name = resolve(applicationContext, name); - return getName(name); - } - - private String getName(String name) { - if (!StringUtils.hasText(name)) { - return ""; - } - - String host = null; - try { - String url; - if (!name.startsWith("http://") && !name.startsWith("https://")) { - url = "http://" + name; - } - else { - url = name; - } - host = new URI(url).getHost(); - - } catch (URISyntaxException e) { - // 忽略 - } - Assert.state(host != null, "Service id not legal hostname (" + name + ")"); - return name; - } - - private String getUrl(GenericApplicationContext applicationContext, - Map attributes) { - String url = resolve(applicationContext, (String) attributes.get("url")); - return getUrl(url); - } - - private String getUrl(String url) { - if (StringUtils.hasText(url) && !(url.startsWith("#{") && url.contains("}"))) { - if (!url.contains("://")) { - url = "http://" + url; - } - try { - new URL(url); - } - catch (MalformedURLException e) { - throw new IllegalArgumentException(url + " is malformed", e); - } - } - return url; - } - - - private String getPath(GenericApplicationContext applicationContext, - Map attributes) { - String path = resolve(applicationContext, (String) attributes.get("path")); - return getPath(path); - } - - - private String getPath(String path) { - if (StringUtils.hasText(path)) { - path = path.trim(); - if (!path.startsWith("/")) { - path = "/" + path; - } - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - } - return path; - } - - private String getClientName(Map client) { - if (client == null) { - return null; - } - String value = (String) client.get("contextId"); - if (!StringUtils.hasText(value)) { - value = (String) client.get("value"); - } - if (!StringUtils.hasText(value)) { - value = (String) client.get("name"); - } - if (!StringUtils.hasText(value)) { - value = (String) client.get("serviceId"); - } - if (StringUtils.hasText(value)) { - return value; - } - - throw new IllegalStateException("Either 'name' or 'value' must be provided in @" - + FeignClient.class.getSimpleName()); - } - - private String resolve(GenericApplicationContext applicationContext, String value) { - if (StringUtils.hasText(value)) { - return applicationContext.getEnvironment().resolvePlaceholders(value); - } - return value; - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java deleted file mode 100644 index c6f2e1a..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/NacosRibbonClientConfiguration.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gitee.starblues.extension.cloud.openfeign.nacos; - -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.ribbon.NacosServerIntrospector; -import com.alibaba.cloud.nacos.ribbon.NacosServerList; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ServerList; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.netflix.ribbon.PropertiesFactory; -import org.springframework.context.annotation.Bean; - -/** - * @author zhangzhuo@acoinfo.com - * @version 1.0 - * @date 2021-11-05 - */ -public class NacosRibbonClientConfiguration { - - @Autowired - private PropertiesFactory propertiesFactory; - - @Bean - @ConditionalOnMissingBean - public ServerList ribbonServerList(IClientConfig config, - NacosDiscoveryProperties nacosDiscoveryProperties) { - if (this.propertiesFactory.isSet(ServerList.class, config.getClientName())) { - ServerList serverList = this.propertiesFactory.get(ServerList.class, config, - config.getClientName()); - return serverList; - } - NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); - serverList.initWithNiwsConfig(config); - return serverList; - } - - @Bean - @ConditionalOnMissingBean - public NacosServerIntrospector nacosServerIntrospector() { - return new NacosServerIntrospector(); - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java deleted file mode 100644 index fde8549..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-cloud/src/main/java/com/gitee/starblues/extension/cloud/openfeign/nacos/RibbonNacosAutoConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.starblues.extension.cloud.openfeign.nacos; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Configuration; - -/** - * @author zhangzhuo@acoinfo.com - * @version 1.0 - * @date 2021-11-05 - */ -@Configuration -//@EnableConfigurationProperties -//@ConditionalOnBean(SpringClientFactory.class) -//@ConditionalOnRibbonNacos -//@ConditionalOnNacosDiscoveryEnabled -@AutoConfigureAfter(RibbonAutoConfiguration.class) -@RibbonClients(defaultConfiguration = { - NacosRibbonClientConfiguration.class -}) -public class RibbonNacosAutoConfiguration { -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml deleted file mode 100644 index 0d505c9..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/pom.xml +++ /dev/null @@ -1,213 +0,0 @@ - - - - org.sonatype.oss - oss-parent - 7 - - - 4.0.0 - - com.gitee.starblues - springboot-plugin-framework-extension-log - 3.0.0-RELEASE - - 插件扩展-日志模块扩展 - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - https://gitee.com/starblues/springboot-plugin-framework-parent - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - 1.0 - - - - - sonatype-nexus-snapshots - oss Snapshots Repository - https://oss.sonatype.org/content/repositories/snapshots - - - sonatype-nexus-staging - oss Staging Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - sousouki - caoshx@outlook.com - https://gitee.com/caoshx_sousouki/ - - - - - 1.8 - UTF-8 - - 3.8.1 - 3.1.0 - 3.1.0 - 3.1.0 - 1.6 - - 3.0.0-RELEASE - 5.0.7.RELEASE - 1.2.3 - 2.14.1 - - - - - ch.qos.logback - logback-classic - ${logback.version} - provided - - - org.apache.logging.log4j - log4j-core - ${log4j.version} - provided - - - org.springframework - spring-context - ${spring-version} - provided - - - com.gitee.starblues - springboot-plugin-framework - ${springboot-plugin-framework.version} - provided - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-assembly-plugin - ${maven-assembly-plugin.version} - - - jar-with-dependencies - - ${project.artifactId}-${project.version} - false - false - - - true - true - - - - - - make-assembly - package - - single - - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - ${plugin.skip} - - - - package - - jar - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - ${plugin.skip} - - - - sign-artifacts - verify - - sign - - - - - - - - - - - - - dev - - true - - - true - - - - - release - - false - - - - - \ No newline at end of file diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/LogRegistry.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/LogRegistry.java deleted file mode 100644 index aab1010..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/LogRegistry.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.gitee.starblues.extension.log; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import org.pf4j.PluginWrapper; -import org.springframework.core.io.Resource; - -import java.util.List; - -/** - * 日志注册统一接口 - * @author starBlues - * @version 2.4.3 - */ -public interface LogRegistry { - - /** - * 注册日志 - * @param resources 日志配置文件资源 - * @param pluginRegistryInfo 当前插件的信息 - * @throws Exception 注册异常 - **/ - void registry(List resources, PluginRegistryInfo pluginRegistryInfo) throws Exception; - - /** - * 注册日志 - * @param pluginRegistryInfo 当前插件的信息 - * @throws Exception 卸载异常 - **/ - void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception; - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PluginLogConfigProcessor.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PluginLogConfigProcessor.java deleted file mode 100644 index 9659cc7..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PluginLogConfigProcessor.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.gitee.starblues.extension.log; - -import com.gitee.starblues.extension.log.log4j.Log4jLogRegistry; -import com.gitee.starblues.extension.log.logback.LogbackLogRegistry; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.ResourceUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.util.ObjectUtils; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * 接口处理者 - * @author sousouki - * @version 2.4.3 - */ -class PluginLogConfigProcessor implements PluginPipeProcessorExtend { - - private final static Logger LOG = LoggerFactory.getLogger(PluginLogConfigProcessor.class); - private final LogRegistry logRegistry; - - public PluginLogConfigProcessor(SpringBootLogExtension.Type type){ - if(type == SpringBootLogExtension.Type.LOG4J){ - logRegistry = new Log4jLogRegistry(); - } else if(type == SpringBootLogExtension.Type.LOGBACK){ - logRegistry = new LogbackLogRegistry(); - } else { - logRegistry = null; - } - } - - @Override - public String key() { - return "SpringBootLogConfigProcessor"; - } - - @Override - public OrderPriority order() { - return OrderPriority.getLowPriority(); - } - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - if (logRegistry == null) { - return; - } - Resource resource = getLogConfigFile(pluginRegistryInfo); - List resources = new ArrayList<>(1); - resources.add(resource); - logRegistry.registry(resources, pluginRegistryInfo); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - if (logRegistry == null) { - return; - } - logRegistry.unRegistry(pluginRegistryInfo); - } - - /** - * 加载日志配置文件资源 - * 文件路径配置为

file:D://log.xml


- * resources路径配置为

classpath:log.xml


- * @param pluginRegistryInfo 当前插件注册的信息 - * @throws IOException 获取不到配置文件异常 - **/ - private Resource getLogConfigFile(PluginRegistryInfo pluginRegistryInfo) throws IOException { - GenericApplicationContext pluginApplicationContext = pluginRegistryInfo.getPluginApplicationContext(); - String logConfigLocation = pluginApplicationContext.getEnvironment() - .getProperty(PropertyKey.LOG_CONFIG_LOCATION); - if (ObjectUtils.isEmpty(logConfigLocation)) { - return null; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - String matchLocation = ResourceUtils.getMatchLocation(logConfigLocation); - if (matchLocation == null || "".equals(matchLocation)) { - LOG.warn("Plugin '{}' not match {}: {}", pluginId, PropertyKey.LOG_CONFIG_LOCATION, - logConfigLocation); - return null; - } - if(ResourceUtils.isFile(logConfigLocation)){ - String absolutePath = ResourceUtils.getAbsolutePath(pluginRegistryInfo, matchLocation); - return new FileSystemResource(absolutePath); - } else { - return new ClassPathResource(matchLocation, pluginRegistryInfo.getPluginClassLoader()); - } - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PropertyKey.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PropertyKey.java deleted file mode 100644 index 2f48a09..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/PropertyKey.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.gitee.starblues.extension.log; - -/** - * 配置文件key - * @author starBlues - * @version 2.4.3 - */ -public class PropertyKey { - - public final static String LOG_CONFIG_LOCATION = "plugin.log-config-location"; - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/SpringBootLogExtension.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/SpringBootLogExtension.java deleted file mode 100644 index 93cb475..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/SpringBootLogExtension.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.gitee.starblues.extension.log; - - -import com.gitee.starblues.extension.AbstractExtension; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import org.springframework.context.ApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * 日志扩展 - * @author sousouki starBlues - * @version 2.4.3 - */ -public class SpringBootLogExtension extends AbstractExtension { - - private static final String KEY = "SpringBootLogExtension"; - - private final Type type; - - public SpringBootLogExtension(Type type){ - this.type = type; - } - - - @Override - public String key() { - return KEY; - } - - @Override - public List getPluginPipeProcessor(ApplicationContext mainApplicationContext) { - List pipeProcessorExtends = new ArrayList<>(); - pipeProcessorExtends.add(new PluginLogConfigProcessor(type)); - return pipeProcessorExtends; - } - - public enum Type{ - /** - * 集成log4j - **/ - LOG4J, - - /** - * 集成 logback - **/ - LOGBACK - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/annotation/ConfigItem.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/annotation/ConfigItem.java deleted file mode 100644 index 38d9811..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/annotation/ConfigItem.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gitee.starblues.extension.log.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 配置的默认值注解 - * @author sousouki - * @version 2.4.3 - */ -@Documented -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface ConfigItem { - - - /** - * 默认值 - * @return String - */ - String defaultValue() default ""; - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/config/LogConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/config/LogConfig.java deleted file mode 100644 index 596d4e9..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/config/LogConfig.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.gitee.starblues.extension.log.config; - -import com.gitee.starblues.extension.log.annotation.ConfigItem; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -/** - * 日志配置 - * @author sousouki - * @version 2.4.3 - */ -@XmlRootElement(name = "log") -public class LogConfig { - - public static final String ROOT_PLUGIN_SIGN = "~"; - - /** - * 日志存储根目录,默认为当前插件存放目录。 - * ~: 符号表示当前插件根目录 - **/ - @XmlElement(name = "rootDir") - @ConfigItem(defaultValue = ROOT_PLUGIN_SIGN + "/logs/") - private String rootDir; - - - /** - * 日志文件名称 - **/ - @XmlElement(name = "fileName") - private String fileName; - - /** - * 日志级别 - **/ - @XmlElement(name = "level") - @ConfigItem(defaultValue = "INFO") - private String level; - - /** - * 日志文件最大容量 - **/ - @XmlElement(name = "maxFileSize") - @ConfigItem(defaultValue = "10MB") - private String maxFileSize; - - /** - * 日志文件总容量 - **/ - @XmlElement(name = "totalFileSize") - @ConfigItem(defaultValue = "10GB") - private String totalFileSize; - - /** - * 最大保存时间 - **/ - @XmlElement(name = "maxHistory") - @ConfigItem(defaultValue = "30") - private Integer maxHistory; - - /** - * 日志内容格式 - **/ - @XmlElement(name = "pattern") - @ConfigItem(defaultValue = "%d{yyyy-MM-dd HH:mm:ss.SSS} -%5p --- [%t] %-40.40logger{39} : %m%n") - private String pattern; - - /** - * 包名, 自定义当前插件的日志包名, 默认为 BasePlugin 实现类的 包名 - **/ - @XmlTransient - private String packageName; - - @XmlTransient - public String getRootDir() { - return rootDir; - } - - public void setRootDir(String rootDir) { - this.rootDir = rootDir; - } - - @XmlTransient - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - @XmlTransient - public String getLevel() { - return level; - } - - public void setLevel(String level) { - this.level = level; - } - @XmlTransient - public String getMaxFileSize() { - return maxFileSize; - } - - public void setMaxFileSize(String maxFileSize) { - this.maxFileSize = maxFileSize; - } - @XmlTransient - public String getTotalFileSize() { - return totalFileSize; - } - - public void setTotalFileSize(String totalFileSize) { - this.totalFileSize = totalFileSize; - } - @XmlTransient - public Integer getMaxHistory() { - return maxHistory; - } - - public void setMaxHistory(Integer maxHistory) { - this.maxHistory = maxHistory; - } - @XmlTransient - public String getPattern() { - return pattern; - } - - public void setPattern(String pattern) { - this.pattern = pattern; - } - @XmlTransient - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/log4j/Log4jLogRegistry.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/log4j/Log4jLogRegistry.java deleted file mode 100644 index c314075..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/log4j/Log4jLogRegistry.java +++ /dev/null @@ -1,209 +0,0 @@ -package com.gitee.starblues.extension.log.log4j; - -import com.gitee.starblues.extension.log.LogRegistry; -import com.gitee.starblues.extension.log.config.LogConfig; -import com.gitee.starblues.extension.log.logback.LogbackLogRegistry; -import com.gitee.starblues.extension.log.util.LogConfigUtil; -import com.gitee.starblues.factory.PluginRegistryInfo; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.core.*; -import org.apache.logging.log4j.core.appender.RollingFileAppender; -import org.apache.logging.log4j.core.appender.rolling.*; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.DefaultConfiguration; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.filter.AbstractFilter; -import org.apache.logging.log4j.core.layout.PatternLayout; -import org.apache.logging.log4j.message.Message; -import org.pf4j.PluginWrapper; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -import java.nio.charset.Charset; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 日志注册统一接口 - * @author starBlues - * @version 2.4.3 - */ -public class Log4jLogRegistry implements LogRegistry { - - private final org.slf4j.Logger log = LoggerFactory.getLogger(LogbackLogRegistry.class); - private final Map> pluginAppenderInfo = new ConcurrentHashMap<>(); - - - @Override - public void registry(List resources, PluginRegistryInfo pluginRegistryInfo) throws Exception { - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false); - Configuration configuration = loggerContext.getConfiguration(); - LoggerConfig rootLogger = configuration.getRootLogger(); - Set allAppender = new HashSet<>(); - for (Resource resource : resources) { - if(resource == null){ - continue; - } - LogConfig logConfig; - try { - logConfig = LogConfigUtil.getLogConfig(resource, pluginRegistryInfo); - } catch (Exception e){ - log.error("Failed to read log configuration.", e); - continue; - } - Set appenderSet = getAppender(pluginRegistryInfo, logConfig); - for (Appender appender : appenderSet) { - configuration.addAppender(appender); - rootLogger.addAppender(appender, Level.toLevel(logConfig.getLevel()), null); - allAppender.add(appender); - } - } - pluginAppenderInfo.put(pluginWrapper.getPluginId(), allAppender); - } - - - private Set getAppender(PluginRegistryInfo pluginRegistryInfo, LogConfig logConfig){ - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - Filter filter = new LogFilter(pluginRegistryInfo.getBasePlugin().scanPackage()); - PatternLayout patternLayout = PatternLayout.newBuilder() - .withPattern(logConfig.getPattern()) - .withCharset(Charset.defaultCharset()) - .build(); - - final TriggeringPolicy policy = - CompositeTriggeringPolicy.createPolicy( - SizeBasedTriggeringPolicy.createPolicy( - logConfig.getMaxFileSize() - ), - TimeBasedTriggeringPolicy.createPolicy("1", "true") - ); - - RolloverStrategy strategy = DefaultRolloverStrategy.newBuilder() - .withFileIndex(logConfig.getTotalFileSize()) - .withConfig(new DefaultConfiguration()) - .withMax(String.valueOf(logConfig.getMaxHistory())) - .build(); - - RollingFileAppender appender = RollingFileAppender.newBuilder() - .withFilter(filter) - .withName(pluginWrapper.getPluginId()) - .withLayout(patternLayout) - .withIgnoreExceptions(false) - .withFileName(LogConfigUtil.getLogFile(pluginRegistryInfo, logConfig).concat(".log")) - .withFilePattern(".%d{yyyy-MM-dd}-%i.log") - .withAppend(true) - .withPolicy(policy) - .withStrategy(strategy) - .build(); - - appender.start(); - filter.start(); - - return Collections.singleton(appender); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - Set allAppender = pluginAppenderInfo.get(pluginRegistryInfo.getPluginWrapper().getPluginId()); - if(allAppender == null || allAppender.isEmpty()){ - return; - } - LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false); - Configuration configuration = loggerContext.getConfiguration(); - for (Appender appender : allAppender) { - configuration.getAppenders().remove(appender.getName()); - } - } - - private static class LogFilter extends AbstractFilter{ - - private final String packageName; - - private LogFilter(String packageName) { - this.packageName = packageName; - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9) { - return filter(logger.getName()); - } - - @Override - public Result filter(LogEvent event) { - return filter(event.getLoggerName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7) { - return filter(logger.getName()); - } - - @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8) { - return filter(logger.getName()); - } - - private Result filter(String loggerName){ - if (loggerName.startsWith(packageName)) { - return Result.ACCEPT; - } - return Result.DENY; - } - } - - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/logback/LogbackLogRegistry.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/logback/LogbackLogRegistry.java deleted file mode 100644 index d81d723..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/logback/LogbackLogRegistry.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.gitee.starblues.extension.log.logback; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.ConsoleAppender; -import ch.qos.logback.core.filter.Filter; -import ch.qos.logback.core.rolling.RollingFileAppender; -import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy; -import ch.qos.logback.core.spi.FilterReply; -import ch.qos.logback.core.util.FileSize; -import ch.qos.logback.core.util.OptionHelper; -import com.gitee.starblues.extension.log.LogRegistry; -import com.gitee.starblues.extension.log.config.LogConfig; -import com.gitee.starblues.extension.log.util.LogConfigUtil; -import com.gitee.starblues.factory.PluginRegistryInfo; -import org.pf4j.PluginWrapper; -import org.pf4j.util.StringUtils; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 日志配置处理者 - * @author sousouki - * @version 2.4.3 - */ -public class LogbackLogRegistry implements LogRegistry { - - private final org.slf4j.Logger log = LoggerFactory.getLogger(LogbackLogRegistry.class); - - private final Map>> pluginAppenderInfo = new ConcurrentHashMap<>(); - - @Override - public void registry(List resources, PluginRegistryInfo pluginRegistryInfo) throws Exception { - Set> appenderSet = new HashSet<>(); - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - for (Resource resource : resources) { - if(resource == null){ - continue; - } - LogConfig logConfig; - try { - logConfig = LogConfigUtil.getLogConfig(resource, pluginRegistryInfo); - } catch (Exception e){ - log.error("Failed to read log configuration.", e); - continue; - } - Set> logAppenderSet = addAppender(pluginRegistryInfo, logConfig); - appenderSet.addAll(logAppenderSet); - } - pluginAppenderInfo.put(pluginWrapper.getPluginId(), appenderSet); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - Set> logAppenderSet = pluginAppenderInfo.get(pluginWrapper.getPluginId()); - if(logAppenderSet == null || logAppenderSet.isEmpty()){ - return; - } - String packageName = pluginRegistryInfo.getBasePlugin().scanPackage(); - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - Logger logger = context.getLogger(packageName); - for (Appender appender : logAppenderSet) { - logger.detachAppender(appender); - } - pluginAppenderInfo.remove(pluginWrapper.getPluginId()); - } - - private Set> addAppender(PluginRegistryInfo pluginRegistryInfo, LogConfig logConfig) { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - String packageName = logConfig.getPackageName(); - Logger logger = context.getLogger(packageName); - logger.detachAndStopAllAppenders(); - - ConsoleAppender consoleAppender = createConsoleAppender(pluginRegistryInfo.getPluginWrapper(), - logConfig, packageName); - RollingFileAppender fileAppender = createFileAppender(pluginRegistryInfo, - logConfig, packageName); - - logger.setAdditive(false); - logger.setLevel(Level.toLevel(logConfig.getLevel())); - logger.addAppender(consoleAppender); - logger.addAppender(fileAppender); - - Set> appenderSet = new HashSet<>(); - appenderSet.add(consoleAppender); - appenderSet.add(fileAppender); - return appenderSet; - } - - private ConsoleAppender createConsoleAppender(PluginWrapper pluginWrapper, - LogConfig logConfig, - String packageName) { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - ConsoleAppender appender = new ConsoleAppender<>(); - Filter filter = new LogFilter(packageName); - filter.start(); - appender.addFilter(filter); - appender.setContext(context); - appender.setName(pluginWrapper.getPluginId().concat("-console")); - - PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - encoder.setContext(context); - encoder.setPattern(logConfig.getPattern()); - encoder.start(); - - appender.setEncoder(encoder); - appender.start(); - return appender; - } - - private RollingFileAppender createFileAppender(PluginRegistryInfo pluginRegistryInfo, - LogConfig logConfig, - String packageName) { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - - RollingFileAppender appender = new RollingFileAppender<>(); - if(StringUtils.isNotNullOrEmpty(packageName)){ - Filter filter = new LogFilter(packageName); - filter.start(); - appender.addFilter(filter); - } - - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - appender.setContext(context); - appender.setName(pluginWrapper.getPluginId()); - - String logFilePrefix = LogConfigUtil.getLogFile(pluginRegistryInfo, logConfig); - appender.setFile(OptionHelper.substVars(logFilePrefix.concat(".log"), context)); - - appender.setAppend(true); - appender.setPrudent(false); - - SizeAndTimeBasedRollingPolicy policy = new SizeAndTimeBasedRollingPolicy<>(); - - String fp = OptionHelper.substVars(logFilePrefix.concat(".%d{yyyy-MM-dd}-%i.log"), context); - policy.setMaxFileSize(FileSize.valueOf(logConfig.getMaxFileSize())); - policy.setFileNamePattern(fp); - policy.setMaxHistory(logConfig.getMaxHistory()); - policy.setTotalSizeCap(FileSize.valueOf(logConfig.getTotalFileSize())); - policy.setParent(appender); - policy.setContext(context); - policy.start(); - - PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - encoder.setContext(context); - encoder.setPattern(logConfig.getPattern()); - encoder.start(); - - appender.setRollingPolicy(policy); - appender.setEncoder(encoder); - appender.start(); - return appender; - } - - private static class LogFilter extends Filter { - - private final String packageName; - private final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - - private LogFilter(String packageName) { - this.packageName = packageName; - } - - @Override - public FilterReply decide(ILoggingEvent event) { - Logger logger = loggerContext.getLogger(packageName); - if (event.getLoggerName().startsWith(packageName) && event.getLevel().isGreaterOrEqual(logger.getLevel())) { - return FilterReply.ACCEPT; - } - return FilterReply.DENY; - } - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/LogConfigUtil.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/LogConfigUtil.java deleted file mode 100644 index f9b2e55..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/LogConfigUtil.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.gitee.starblues.extension.log.util; - -import com.gitee.starblues.extension.log.annotation.ConfigItem; -import com.gitee.starblues.extension.log.config.LogConfig; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.utils.CommonUtils; -import com.gitee.starblues.utils.ResourceUtils; -import org.pf4j.PluginWrapper; -import org.pf4j.RuntimeMode; -import org.pf4j.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.lang.reflect.Field; - -/** - * LogConfig 对象和 xml 映射的工具类 - * @author starBlues - * @version 2.4.3 - */ -public class LogConfigUtil { - - private static final Logger LOG = LoggerFactory.getLogger(LogConfigUtil.class); - public static final String ROOT_PLUGIN_SIGN = "~"; - - public static LogConfig getLogConfig(Resource xmlResource, PluginRegistryInfo pluginRegistryInfo) - throws Exception{ - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - String configText = readConfigText(xmlResource); - LogConfig logConfig = (LogConfig) xml2object(configText); - checkLogConfig(logConfig, pluginWrapper.getPluginId()); - String packageName = logConfig.getPackageName(); - if(StringUtils.isNullOrEmpty(packageName)){ - logConfig.setPackageName(pluginRegistryInfo.getBasePlugin().scanPackage()); - } - return logConfig; - } - - - public static String getLogFile(PluginRegistryInfo pluginRegistryInfo, LogConfig logConfig){ - String rootDir = logConfig.getRootDir(); - String home; - PluginWrapper pluginWrapper = pluginRegistryInfo.getPluginWrapper(); - IntegrationConfiguration configuration = pluginRegistryInfo.getConfiguration(); - String pluginRootDir; - RuntimeMode runtimeMode = pluginWrapper.getRuntimeMode(); - if(runtimeMode == RuntimeMode.DEVELOPMENT){ - pluginRootDir = pluginWrapper.getPluginPath().toString(); - } else { - pluginRootDir = configuration.pluginPath().get(0); - } - if(StringUtils.isNullOrEmpty(rootDir)){ - home = CommonUtils.joiningFilePath(pluginRootDir, "logs"); - } else { - home = ResourceUtils.getAbsolutePath(pluginRegistryInfo, rootDir); - } - String fileName = logConfig.getFileName(); - if (StringUtils.isNullOrEmpty(fileName)) { - fileName = pluginWrapper.getPluginId(); - } - return CommonUtils.joiningFilePath(home, pluginWrapper.getPluginId(), fileName); - } - - private static void checkLogConfig(LogConfig logConfig, String pluginId) { - String fileName = logConfig.getFileName(); - if (StringUtils.isNullOrEmpty(fileName)) { - logConfig.setFileName(pluginId.concat("-log")); - } - Field[] fields = LogConfig.class.getDeclaredFields(); - for (Field field : fields) { - if (!field.isAccessible()) { - field.setAccessible(true); - } - ConfigItem configItem = field.getDeclaredAnnotation(ConfigItem.class); - if (configItem == null) { - continue; - } - try { - Object fieldValue = field.get(logConfig); - Class fieldType = field.getType(); - if (fieldValue == null || "".equals(fieldValue.toString()) || - ObjectUtil.isEmptyObject(fieldType, fieldValue)) { - String defaultValue = configItem.defaultValue(); - LOG.debug("Field {} is not config or invalid in log config of plugin {}, set it to default value {}.", field.getName(), defaultValue, pluginId); - Object fixedValue = ObjectUtil.parseBasicTypeValue(fieldType, defaultValue); - field.set(logConfig, fixedValue); - } - } catch (IllegalAccessException e) { - LOG.error("Failed to check config item {} in log config.", field.getName()); - } - } - } - - private static String readConfigText(Resource resource) throws IOException { - String fileContent; - try (InputStream inputStream = resource.getInputStream(); - ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - byte[] buff = new byte[1024]; - int len; - while ((len = inputStream.read(buff)) != -1) { - stream.write(buff, 0, len); - } - byte[] data = stream.toByteArray(); - fileContent = new String(data); - } - return fileContent; - } - - private static Object xml2object(String xml) throws Exception { - Object object; - try { - JAXBContext context = JAXBContext.newInstance(LogConfig.class); - Unmarshaller unmarshaller = context.createUnmarshaller(); - StringReader stringReader = new StringReader(xml); - object = unmarshaller.unmarshal(stringReader); - } catch (JAXBException e) { - e.printStackTrace(); - throw new Exception("Invalid xml definition"); - } - return object; - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/ObjectUtil.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/ObjectUtil.java deleted file mode 100644 index 5cd95b6..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-log/src/main/java/com/gitee/starblues/extension/log/util/ObjectUtil.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.gitee.starblues.extension.log.util; - -/** - * 对象工具类 - * @author sousouki - * @version 2.4.3 - */ -public class ObjectUtil { - - private ObjectUtil(){ - - } - - public static Object parseBasicTypeValue(Class fieldType, String defaultValue) { - Object fixedValue; - if (Byte.class == fieldType || byte.class == fieldType) { - fixedValue = Byte.parseByte(defaultValue); - } else if (Integer.class == fieldType || int.class == fieldType) { - fixedValue = Integer.parseInt(defaultValue); - } else if (Double.class == fieldType || double.class == fieldType) { - fixedValue = Double.parseDouble(defaultValue); - } else if (Short.class == fieldType || short.class == fieldType) { - fixedValue = Short.parseShort(defaultValue); - } else if (Long.class == fieldType || long.class == fieldType) { - fixedValue = Long.parseLong(defaultValue); - } else if (Float.class == fieldType || float.class == fieldType) { - fixedValue = Float.parseFloat(defaultValue); - } else if (Boolean.class == fieldType || boolean.class == fieldType) { - fixedValue = Boolean.parseBoolean(defaultValue); - } else if (Character.class == fieldType || char.class == fieldType) { - fixedValue = defaultValue.charAt(0); - } else { - fixedValue = defaultValue; - } - return fixedValue; - } - - public static boolean isEmptyObject(Class fieldType, Object fieldValue) { - if (Byte.class == fieldType || byte.class == fieldType) { - return (byte) fieldValue == 0; - } else if (Integer.class == fieldType || int.class == fieldType) { - return (int) fieldValue == 0; - } else if (Double.class == fieldType || double.class == fieldType) { - return (double) fieldValue == 0; - } else if (Short.class == fieldType || short.class == fieldType) { - return (short) fieldValue == 0; - } else if (Long.class == fieldType || long.class == fieldType) { - return (long) fieldValue == 0; - } else if (Float.class == fieldType || float.class == fieldType) { - return (float) fieldValue == 0; - } - return false; - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml deleted file mode 100644 index ff2d825..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/pom.xml +++ /dev/null @@ -1,221 +0,0 @@ - - - - 4.0.0 - - - org.sonatype.oss - oss-parent - 7 - - - com.gitee.starblues - springboot-plugin-framework-extension-mybatis - 3.0.0-RELEASE - jar - - 插件扩展-spring boot mybatis 集成扩展 - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - https://gitee.com/starblues/springboot-plugin-framework-parent - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - 1.0 - - - - - sonatype-nexus-snapshots - oss Snapshots Repository - https://oss.sonatype.org/content/repositories/snapshots - - - sonatype-nexus-staging - oss Staging Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - StarBlues - starblues@foxmail.com - https://gitee.com/starblues/ - - - - - 1.8 - UTF-8 - - 3.8.1 - 3.1.0 - 3.1.0 - 3.1.0 - 1.6 - - 3.0.0-RELEASE - 2.0.1 - 3.4.1 - 2.1.5 - - - - - - com.gitee.starblues - springboot-plugin-framework - ${springboot-plugin-framework.version} - provided - - - - org.mybatis.spring.boot - mybatis-spring-boot-starter - ${mybatis-spring-boot-starter.version} - provided - - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus-boot-starter.version} - provided - - - - tk.mybatis - mapper-spring-boot-starter - ${tk-mybatis-spring-boot-starter.version} - provided - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-assembly-plugin - ${maven-assembly-plugin.version} - - - jar-with-dependencies - - ${project.artifactId}-${project.version} - false - false - - - true - true - - - - - - make-assembly - package - - single - - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - ${plugin.skip} - - - - package - - jar - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - ${plugin.skip} - - - - sign-artifacts - verify - - sign - - - - - - - - - - - - - dev - - true - - - true - - - - - release - - false - - - - - - \ No newline at end of file diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/CommonRegister.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/CommonRegister.java deleted file mode 100644 index a9ef69e..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/CommonRegister.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.SpringBeanRegister; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionTemplate; - -/** - * 公共注册 - * @author starBlues - * @version 2.4.2 - */ -public class CommonRegister { - - private CommonRegister(){} - - - public static void commonRegister(PluginRegistryInfo pluginRegistryInfo, - SqlSessionFactory sqlSessionFactory, - SqlSessionTemplate sqlSessionTemplate){ - // 注册SqlSessionFactory - SpringBeanRegister springBeanRegister = pluginRegistryInfo.getSpringBeanRegister(); - springBeanRegister.registerSingleton("sqlSessionFactory", sqlSessionFactory); - springBeanRegister.registerSingleton("sqlSession", sqlSessionTemplate); - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MapperHandler.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MapperHandler.java deleted file mode 100644 index 0997584..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MapperHandler.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import com.gitee.starblues.extension.mybatis.group.PluginMapperGroup; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.bean.name.PluginAnnotationBeanNameGenerator; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.mapper.MapperFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigUtils; -import org.springframework.context.annotation.AnnotationScopeMetadataResolver; -import org.springframework.context.annotation.ScopeMetadata; -import org.springframework.context.annotation.ScopeMetadataResolver; -import org.springframework.context.support.GenericApplicationContext; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Mapper 接口处理者 - * @author starBlues - * @version 2.4.0 - */ -public class MapperHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(MapperHandler.class); - - private static final String MAPPER_INTERFACE_NAMES = "MybatisMapperInterfaceNames"; - - private final ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver(); - - - public MapperHandler() { - } - - /** - * 处理插件中的Mapper - * @param pluginRegistryInfo 插件信息 - * @param processMapper Mapper的具体处理者 - */ - public void processMapper(PluginRegistryInfo pluginRegistryInfo, - MapperHandler.ProcessMapper processMapper){ - GenericApplicationContext applicationContext = pluginRegistryInfo.getPluginApplicationContext(); - List> groupClasses = pluginRegistryInfo.getGroupClasses(PluginMapperGroup.GROUP_ID); - if(groupClasses == null || groupClasses.isEmpty()){ - return; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - Set beanNames = new HashSet<>(); - for (Class groupClass : groupClasses) { - if (groupClass == null) { - continue; - } - BeanNameGenerator beanNameGenerator = new PluginAnnotationBeanNameGenerator(pluginId); - AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(groupClass); - ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(abd); - abd.setScope(scopeMetadata.getScopeName()); - String beanName = beanNameGenerator.generateBeanName(abd, applicationContext); - BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); - AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); - BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, applicationContext); - try { - processMapper.process(definitionHolder, groupClass); - beanNames.add(beanName); - } catch (Exception e) { - LOGGER.error("process mapper '{}' error. {}", groupClass.getName(), e.getMessage(), e); - } - } - pluginRegistryInfo.addExtension(MAPPER_INTERFACE_NAMES, beanNames); - } - - - /** - * 公共注册生成代理Mapper接口 - * @param holder ignore - * @param mapperClass ignore - * @param sqlSessionFactory ignore - * @param sqlSessionTemplate ignore - */ - public void commonProcessMapper(BeanDefinitionHolder holder, - Class mapperClass, - SqlSessionFactory sqlSessionFactory, - SqlSessionTemplate sqlSessionTemplate) { - GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition(); - definition.getConstructorArgumentValues().addGenericArgumentValue(mapperClass); - definition.setBeanClass(MapperFactoryBean.class); - definition.getPropertyValues().add("addToConfig", true); - definition.getPropertyValues().add("sqlSessionFactory", sqlSessionFactory); - definition.getPropertyValues().add("sqlSessionTemplate", sqlSessionTemplate); - definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); - } - - - - @FunctionalInterface - public interface ProcessMapper{ - void process(BeanDefinitionHolder holder, Class mapperClass) throws Exception; - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisCommonConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisCommonConfig.java deleted file mode 100644 index 3cbdad7..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisCommonConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import java.util.Set; - -/** - * Springboot mybatis 公用的配置 - * @author starBlues - * @version 2.3 - */ -public interface MybatisCommonConfig { - - /** - * 数据库表对应的实体类的包名集合。可配置多个 - * @return Set - */ - Set entityPackage(); - - /** - * mybatis xml mapper 匹配规则
- * ? 匹配一个字符
- * * 匹配零个或多个字符
- * ** 匹配路径中的零或多个目录
- * 例如:
- * 文件路径配置为

file:D://xml/*PluginMapper.xml


- * resources路径配置为

classpath:xml/mapper/*PluginMapper.xml


- * 包路径配置为

package:com.plugin.xml.mapper.*PluginMapper.xml


- * @return Set - */ - Set xmlLocationsMatch(); - - /** - * 插件是否自主启用配置. 默认进行禁用, 使用主程序的配置 - * @return 返回true, 表示进行插件自主进行Mybatis相关配置 - */ - default boolean enableOneselfConfig(){ - return false; - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisProcessor.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisProcessor.java deleted file mode 100644 index 1d2ddc0..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/MybatisProcessor.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.mapping.DatabaseIdProvider; -import org.apache.ibatis.plugin.Interceptor; -import org.apache.ibatis.scripting.LanguageDriver; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.Resource; - -/** - * mybatis 处理者 - * @author starBlues - * @version 2.4.0 - */ -public class MybatisProcessor implements PluginBeanRegistrarExtend { - - private static final Logger LOGGER = LoggerFactory.getLogger(MybatisProcessor.class); - - public MybatisProcessor() { - } - - @Override - public String key() { - return "MybatisProcessor"; - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - SpringBootMybatisConfig config = SpringBeanUtils.getObjectByInterfaceClass( - pluginRegistryInfo.getConfigSingletons(), - SpringBootMybatisConfig.class); - if(config == null){ - return; - } - - SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); - - if(config.enableOneselfConfig()){ - config.oneselfConfig(factory); - } else { - GenericApplicationContext mainApplicationContext = pluginRegistryInfo.getMainApplicationContext(); - PluginFollowCoreConfig followCoreConfig = new PluginFollowCoreConfig(mainApplicationContext); - factory.setDataSource(followCoreConfig.getDataSource()); - Configuration configuration = followCoreConfig.getConfiguration(SpringBootMybatisExtension.Type.MYBATIS); - factory.setConfiguration(configuration); - Interceptor[] interceptor = followCoreConfig.getInterceptor(); - if(interceptor != null && interceptor.length > 0){ - factory.setPlugins(interceptor); - } - DatabaseIdProvider databaseIdProvider = followCoreConfig.getDatabaseIdProvider(); - if(databaseIdProvider != null){ - factory.setDatabaseIdProvider(databaseIdProvider); - } - LanguageDriver[] languageDrivers = followCoreConfig.getLanguageDriver(); - if(languageDrivers != null){ - for (LanguageDriver languageDriver : languageDrivers) { - configuration.getLanguageRegistry().register(languageDriver); - } - } - - } - PluginResourceFinder pluginResourceFinder = new PluginResourceFinder(pluginRegistryInfo); - - Class[] aliasesClasses = pluginResourceFinder.getAliasesClasses(config.entityPackage()); - if(aliasesClasses != null && aliasesClasses.length > 0){ - factory.setTypeAliases(aliasesClasses); - } - - Resource[] xmlResource = pluginResourceFinder.getXmlResource(config.xmlLocationsMatch()); - if(xmlResource != null && xmlResource.length > 0){ - factory.setMapperLocations(xmlResource); - } - - ClassLoader defaultClassLoader = Resources.getDefaultClassLoader(); - try { - Resources.setDefaultClassLoader(pluginRegistryInfo.getPluginClassLoader()); - SqlSessionFactory sqlSessionFactory = factory.getObject(); - if(sqlSessionFactory == null){ - throw new Exception("Get mybatis sqlSessionFactory is null"); - } - SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory); - MapperHandler mapperHandler = new MapperHandler(); - mapperHandler.processMapper(pluginRegistryInfo, (holder, mapperClass) -> { - mapperHandler.commonProcessMapper(holder, mapperClass, sqlSessionFactory, sqlSessionTemplate); - }); - CommonRegister.commonRegister(pluginRegistryInfo, sqlSessionFactory, sqlSessionTemplate); - } finally { - Resources.setDefaultClassLoader(defaultClassLoader); - } - - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginFollowCoreConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginFollowCoreConfig.java deleted file mode 100644 index 97cc067..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginFollowCoreConfig.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import com.baomidou.mybatisplus.core.MybatisConfiguration; -import org.apache.ibatis.mapping.DatabaseIdProvider; -import org.apache.ibatis.plugin.Interceptor; -import org.apache.ibatis.scripting.LanguageDriver; -import org.apache.ibatis.scripting.LanguageDriverRegistry; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; -import org.springframework.context.ApplicationContext; -import org.springframework.util.ReflectionUtils; - -import javax.sql.DataSource; -import java.lang.reflect.Field; -import java.util.*; - -/** - * 插件跟随主程序时, 获取主程序的Mybatis定义的一些配置 - * @author starBlues - * @version 2.3 - */ -public class PluginFollowCoreConfig { - - private final ApplicationContext mainApplicationContext; - - public PluginFollowCoreConfig(ApplicationContext mainApplicationContext) { - this.mainApplicationContext = mainApplicationContext; - } - - - public DataSource getDataSource(){ - return mainApplicationContext.getBean(DataSource.class); - } - - public Configuration getConfiguration(SpringBootMybatisExtension.Type type){ - Configuration configuration = new Configuration(); - if(type == SpringBootMybatisExtension.Type.MYBATIS){ - try { - Map customizerMap = mainApplicationContext.getBeansOfType(ConfigurationCustomizer.class); - if(!customizerMap.isEmpty()){ - for (ConfigurationCustomizer customizer : customizerMap.values()) { - customizer.customize(configuration); - } - } - } catch (Exception e){ - // ignore - } - } - return configuration; - } - - public MybatisConfiguration getMybatisPlusConfiguration(){ - MybatisConfiguration configuration = new MybatisConfiguration(); - try { - Map customizerMap = - mainApplicationContext.getBeansOfType(com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer.class); - if(!customizerMap.isEmpty()){ - for (com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer customizer : customizerMap.values()) { - customizer.customize(configuration); - } - } - } catch (Exception e){ - // ignore - } - return configuration; - } - - public Interceptor[] getInterceptor(){ - Map, Interceptor> interceptorMap = new HashMap<>(); - try { - SqlSessionFactory sqlSessionFactory = mainApplicationContext.getBean(SqlSessionFactory.class); - // 先从 SqlSessionFactory 工厂中获取拦截器 - List interceptors = sqlSessionFactory.getConfiguration().getInterceptors(); - if(interceptors != null){ - for (Interceptor interceptor : interceptors) { - if(interceptor == null){ - continue; - } - interceptorMap.put(interceptor.getClass(), interceptor); - } - } - } catch (Exception e){ - // ignore - } - // 再从定义Bean中获取拦截器 - Map beanInterceptorMap = mainApplicationContext.getBeansOfType(Interceptor.class); - if(!beanInterceptorMap.isEmpty()){ - beanInterceptorMap.forEach((k, v)->{ - // 如果Class一致, 则会覆盖 - interceptorMap.put(v.getClass(), v); - }); - } - if(interceptorMap.isEmpty()) { - return null; - } else { - return interceptorMap.values().toArray(new Interceptor[0]); - } - } - - public DatabaseIdProvider getDatabaseIdProvider(){ - String[] beanNamesForType = mainApplicationContext.getBeanNamesForType(DatabaseIdProvider.class, false, false); - if(beanNamesForType.length > 0){ - return mainApplicationContext.getBean(DatabaseIdProvider.class); - } - return null; - } - - @SuppressWarnings("unchecked") - public LanguageDriver[] getLanguageDriver(){ - Map, LanguageDriver> languageDriverMap = new HashMap<>(); - try { - SqlSessionFactory sqlSessionFactory = mainApplicationContext.getBean(SqlSessionFactory.class); - LanguageDriverRegistry languageRegistry = sqlSessionFactory.getConfiguration() - .getLanguageRegistry(); - // 先从 SqlSessionFactory 工厂中获取LanguageDriver - Field proxyTypesField = ReflectionUtils.findField(languageRegistry.getClass(), "LANGUAGE_DRIVER_MAP"); - Map, LanguageDriver> driverMap = null; - if(proxyTypesField != null){ - if (!proxyTypesField.isAccessible()) { - proxyTypesField.setAccessible(true); - } - driverMap = (Map, LanguageDriver>) proxyTypesField.get(languageRegistry); - } - if(driverMap != null){ - languageDriverMap.putAll(driverMap); - } - } catch (Exception e){ - // ignore - } - Map beansLanguageDriver = mainApplicationContext.getBeansOfType(LanguageDriver.class); - if(!beansLanguageDriver.isEmpty()){ - beansLanguageDriver.forEach((k, v)->{ - // 如果Class一致, 则会覆盖 - languageDriverMap.put(v.getClass(), v); - }); - } - if(languageDriverMap.isEmpty()){ - return null; - } - return languageDriverMap.values().toArray(new LanguageDriver[0]); - } - - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginResourceFinder.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginResourceFinder.java deleted file mode 100644 index 58e3c3c..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/PluginResourceFinder.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - - -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.utils.ResourceUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.type.ClassMetadata; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -import java.io.IOException; -import java.util.*; - -/** - * 插件资源发现者 - * @author starBlues - * @version 2.4.0 - */ -public class PluginResourceFinder { - - private static final Logger LOGGER = LoggerFactory.getLogger(PluginResourceFinder.class); - - private final static String TYPE_FILE = "file"; - private final static String TYPE_CLASSPATH = "classpath"; - private final static String TYPE_PACKAGE = "package"; - - - private final ClassLoader classLoader; - private final ResourcePatternResolver resourcePatternResolver; - private final MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); - - - public PluginResourceFinder(PluginRegistryInfo pluginRegistryInfo) { - this.classLoader = pluginRegistryInfo.getPluginClassLoader(); - this.resourcePatternResolver = new PathMatchingResourcePatternResolver(classLoader); - } - - /** - * 获取插件中xml资源 - * @param xmlLocationsMatchSet xml资源匹配集合 - * @return xml Resource 数组 - * @throws IOException 获取xml资源异常 - */ - public Resource[] getXmlResource(Set xmlLocationsMatchSet) throws IOException { - if(xmlLocationsMatchSet == null || xmlLocationsMatchSet.isEmpty()){ - return null; - } - List resources = new ArrayList<>(); - for (String xmlLocationsMatch : xmlLocationsMatchSet) { - if(StringUtils.isEmpty(xmlLocationsMatch)){ - continue; - } - List loadResources = getXmlResources(xmlLocationsMatch); - if(loadResources != null && !loadResources.isEmpty()){ - resources.addAll(loadResources); - } - } - - if(resources.isEmpty()){ - return null; - } - - return resources.toArray(new Resource[0]); - } - - - - /** - * 获取插件的实体类及其别名 - * @param packagePatterns 实体类包名 - * @return class 数组 - * @throws IOException 获取医院异常 - */ - public Class[] getAliasesClasses(Set packagePatterns) throws IOException { - if(packagePatterns == null || packagePatterns.isEmpty()){ - return null; - } - Set> aliasesClasses = new HashSet<>(); - for (String packagePattern : packagePatterns) { - Resource[] resources = resourcePatternResolver.getResources( - ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX - + ClassUtils.convertClassNameToResourcePath(packagePattern) + "/**/*.class"); - for (Resource resource : resources) { - try { - ClassMetadata classMetadata = metadataReaderFactory.getMetadataReader(resource).getClassMetadata(); - Class clazz = classLoader.loadClass(classMetadata.getClassName()); - aliasesClasses.add(clazz); - } catch (Throwable e) { - LOGGER.warn("Cannot load the '{}'. Cause by {}", resource, e.toString()); - } - } - } - return aliasesClasses.toArray(new Class[0]); - } - - /** - * 得到Xml资源 - * @param mybatisMapperXmlLocationMatch mybatis xml 批量规则 - * @return 匹配到的xml资源 - * @throws IOException IO 异常 - */ - private List getXmlResources(String mybatisMapperXmlLocationMatch) throws IOException { - String matchLocation = ResourceUtils.getMatchLocation(mybatisMapperXmlLocationMatch); - if(matchLocation == null){ - LOGGER.error("mybatisMapperXmlLocation {} illegal", mybatisMapperXmlLocationMatch); - return null; - } - try { - Resource[] resources = resourcePatternResolver.getResources(matchLocation); - if(resources.length > 0){ - return Arrays.asList(resources); - } else { - return null; - } - } catch (IOException e) { - LOGGER.error("mybatis xml resource '{}' match error : {}", mybatisMapperXmlLocationMatch, - e.getMessage(), e); - throw e; - } - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisConfig.java deleted file mode 100644 index 75ec57f..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import org.apache.ibatis.session.Configuration; -import org.mybatis.spring.SqlSessionFactoryBean; - -/** - * Springboot mybatis 的配置接口 - * @author starBlues - * @version 2.3 - */ -public interface SpringBootMybatisConfig extends MybatisCommonConfig{ - - - /** - * 插件自主配置Mybatis的SqlSessionFactoryBean - * SqlSessionFactoryBean 具体配置说明参考 Mybatis 官网 - * @param sqlSessionFactoryBean SqlSessionFactoryBean - */ - default void oneselfConfig(SqlSessionFactoryBean sqlSessionFactoryBean){ - } - - /** - * 重写配置当前跟随主程序的配置 - * 只有 enableOneselfConfig 返回 false, 实现该方法才生效 - * @param configuration Mybatis Configuration 的配置 - */ - default void reSetMainConfig(Configuration configuration){ - - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisExtension.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisExtension.java deleted file mode 100644 index fa73ffe..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/SpringBootMybatisExtension.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.gitee.starblues.extension.mybatis; - -import com.gitee.starblues.extension.AbstractExtension; -import com.gitee.starblues.extension.mybatis.group.MybatisConfigGroup; -import com.gitee.starblues.extension.mybatis.group.PluginEntityAliasesGroup; -import com.gitee.starblues.extension.mybatis.group.PluginMapperGroup; -import com.gitee.starblues.extension.mybatis.mybatisplus.MybatisPlusProcessor; -import com.gitee.starblues.extension.mybatis.tkmyabtis.TkMybatisProcessor; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import org.springframework.context.ApplicationContext; - -import java.util.ArrayList; -import java.util.List; - -/** - * mybatis 扩展 - * @author starBlues - * @version 2.4.0 - */ -public class SpringBootMybatisExtension extends AbstractExtension { - - private static final String KEY = "SpringBootMybatisPlusExtension"; - - private final Type type; - - /** - * 初始化扩展 - * @param type 根据当前环境所集成的框架来选择Type类型 - */ - public SpringBootMybatisExtension(Type type) { - if(type == null){ - this.type = Type.MYBATIS; - } else { - this.type = type; - } - } - - @Override - public String key() { - return KEY; - } - - @Override - public void initialize(ApplicationContext mainApplicationContext) throws Exception { - } - - @Override - public List getPluginClassGroup(ApplicationContext mainApplicationContext) { - final List pluginClassGroups = new ArrayList<>(); - pluginClassGroups.add(new MybatisConfigGroup()); - pluginClassGroups.add(new PluginEntityAliasesGroup()); - pluginClassGroups.add(new PluginMapperGroup()); - return pluginClassGroups; - } - - @Override - public List getPluginBeanRegistrar(ApplicationContext mainApplicationContext) { - final List pluginBeanRegistrarExtends = new ArrayList<>(3); - if(type == Type.MYBATIS_PLUS){ - pluginBeanRegistrarExtends.add(new MybatisPlusProcessor()); - } else if(type == Type.TK_MYBATIS){ - pluginBeanRegistrarExtends.add(new TkMybatisProcessor()); - } else { - pluginBeanRegistrarExtends.add(new MybatisProcessor()); - } - return pluginBeanRegistrarExtends; - } - - public enum Type{ - MYBATIS, - MYBATIS_PLUS, - TK_MYBATIS - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/MybatisConfigGroup.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/MybatisConfigGroup.java deleted file mode 100644 index 87a6db4..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/MybatisConfigGroup.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.gitee.starblues.extension.mybatis.group; - -import com.gitee.starblues.extension.mybatis.SpringBootMybatisConfig; -import com.gitee.starblues.extension.mybatis.mybatisplus.SpringBootMybatisPlusConfig; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import com.gitee.starblues.realize.BasePlugin; -import org.springframework.util.ClassUtils; - -import java.util.Set; - -/** - * mybatis 配置分组 - * @author starBlues - * @version 2.3 - */ -public class MybatisConfigGroup implements PluginClassGroupExtend { - - public static final String KEY = "plugin_mybatis_config"; - - @Override - public String key() { - return KEY; - } - - @Override - public String groupId() { - return "MybatisConfigGroup"; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - if(aClass == null){ - return false; - } - Set> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(aClass); - - return allInterfacesForClassAsSet.contains(SpringBootMybatisConfig.class) - || allInterfacesForClassAsSet.contains(SpringBootMybatisPlusConfig.class); - - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginEntityAliasesGroup.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginEntityAliasesGroup.java deleted file mode 100644 index 1fd08b5..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginEntityAliasesGroup.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.gitee.starblues.extension.mybatis.group; - -import com.gitee.starblues.extension.mybatis.mybatisplus.SpringBootMybatisPlusConfig; -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.apache.ibatis.type.Alias; - -import java.util.Set; - -/** - * 插件中的实体类别名 - * - * @author starBlues - * @version 2.3 - */ -public class PluginEntityAliasesGroup implements PluginClassGroupExtend { - - public static final String KEY = "plugin_mybatis_alias"; - - private Set typeAliasesPackage; - - public PluginEntityAliasesGroup() { - } - - @Override - public String groupId() { - return KEY; - } - - @Override - public void initialize(BasePlugin basePlugin) { - if(basePlugin instanceof SpringBootMybatisPlusConfig){ - SpringBootMybatisPlusConfig mybatisPlusConfig = (SpringBootMybatisPlusConfig) basePlugin; - typeAliasesPackage = null; - } - } - - - @Override - public boolean filter(Class aClass) { - if(AnnotationsUtils.haveAnnotations(aClass, false, Alias.class)){ - return true; - } - if(typeAliasesPackage == null || typeAliasesPackage.isEmpty()){ - return false; - } - for (String packageName : typeAliasesPackage) { - if(aClass.getPackage().getName().equals(packageName)){ - return true; - } - } - return false; - } - - @Override - public String key() { - return "PluginEntityAliasesGroup"; - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginMapperGroup.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginMapperGroup.java deleted file mode 100644 index f7d65df..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/group/PluginMapperGroup.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gitee.starblues.extension.mybatis.group; - -import com.gitee.starblues.factory.process.pipe.classs.PluginClassGroupExtend; -import com.gitee.starblues.realize.BasePlugin; -import com.gitee.starblues.utils.AnnotationsUtils; -import org.apache.ibatis.annotations.Mapper; - -/** - * 插件中的Mapper接口分组 - * - * @author starBlues - * @version 2.3 - */ -public class PluginMapperGroup implements PluginClassGroupExtend { - - public static final String GROUP_ID = "plugin_mybatis_mapper"; - - @Override - public String groupId() { - return GROUP_ID; - } - - @Override - public void initialize(BasePlugin basePlugin) { - - } - - @Override - public boolean filter(Class aClass) { - return AnnotationsUtils.haveAnnotations(aClass, false, Mapper.class); - } - - @Override - public String key() { - return "PluginMybatisMapperGroup"; - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/MybatisPlusProcessor.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/MybatisPlusProcessor.java deleted file mode 100644 index e4b263e..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/MybatisPlusProcessor.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.gitee.starblues.extension.mybatis.mybatisplus; - -import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties; -import com.baomidou.mybatisplus.core.MybatisConfiguration; -import com.baomidou.mybatisplus.core.config.GlobalConfig; -import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; -import com.gitee.starblues.extension.mybatis.CommonRegister; -import com.gitee.starblues.extension.mybatis.MapperHandler; -import com.gitee.starblues.extension.mybatis.PluginFollowCoreConfig; -import com.gitee.starblues.extension.mybatis.PluginResourceFinder; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.mapping.DatabaseIdProvider; -import org.apache.ibatis.plugin.Interceptor; -import org.apache.ibatis.scripting.LanguageDriver; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.Resource; - - -/** - * springboot-mybatis plus 处理者 - * @author starBlues - * @version 2.4.1 - */ -public class MybatisPlusProcessor implements PluginBeanRegistrarExtend { - - private static final Logger LOGGER = LoggerFactory.getLogger(MybatisPlusProcessor.class); - - - public MybatisPlusProcessor() { - } - - @Override - public String key() { - return "MybatisPlusProcessor"; - } - - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - SpringBootMybatisPlusConfig config = SpringBeanUtils.getObjectByInterfaceClass( - pluginRegistryInfo.getConfigSingletons(), - SpringBootMybatisPlusConfig.class); - if(config == null){ - return; - } - final MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean(); - - if(config.enableOneselfConfig()){ - config.oneselfConfig(factory); - } else { - PluginFollowCoreConfig followCoreConfig = new PluginFollowCoreConfig( - pluginRegistryInfo.getMainApplicationContext() - ); - MybatisConfiguration mybatisPlusConfiguration = followCoreConfig.getMybatisPlusConfiguration(); - factory.setDataSource(followCoreConfig.getDataSource()); - factory.setConfiguration(mybatisPlusConfiguration); - Interceptor[] interceptor = followCoreConfig.getInterceptor(); - if(interceptor != null && interceptor.length > 0){ - factory.setPlugins(interceptor); - } - DatabaseIdProvider databaseIdProvider = followCoreConfig.getDatabaseIdProvider(); - if(databaseIdProvider != null){ - factory.setDatabaseIdProvider(databaseIdProvider); - } - LanguageDriver[] languageDriver = followCoreConfig.getLanguageDriver(); - if(languageDriver != null){ - factory.setScriptingLanguageDrivers(languageDriver); - } - // 配置mybatis-plus私有的配置 - GlobalConfig globalConfig = mybatisPlusFollowCoreConfig(factory, pluginRegistryInfo.getMainApplicationContext()); - config.reSetMainConfig(mybatisPlusConfiguration, globalConfig); - } - - PluginResourceFinder pluginResourceFinder = new PluginResourceFinder(pluginRegistryInfo); - - Class[] aliasesClasses = pluginResourceFinder.getAliasesClasses(config.entityPackage()); - if(aliasesClasses != null && aliasesClasses.length > 0){ - factory.setTypeAliases(aliasesClasses); - } - - Resource[] xmlResource = pluginResourceFinder.getXmlResource(config.xmlLocationsMatch()); - if(xmlResource != null && xmlResource.length > 0){ - factory.setMapperLocations(xmlResource); - } - ClassLoader defaultClassLoader = Resources.getDefaultClassLoader(); - try { - Resources.setDefaultClassLoader(pluginRegistryInfo.getPluginClassLoader()); - SqlSessionFactory sqlSessionFactory = factory.getObject(); - if(sqlSessionFactory == null){ - throw new Exception("Get mybatis-plus sqlSessionFactory is null"); - } - SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory); - MapperHandler mapperHandler = new MapperHandler(); - mapperHandler.processMapper(pluginRegistryInfo, (holder, mapperClass) -> { - mapperHandler.commonProcessMapper(holder, mapperClass, sqlSessionFactory, sqlSessionTemplate); - }); - CommonRegister.commonRegister(pluginRegistryInfo, sqlSessionFactory, sqlSessionTemplate); - } finally { - Resources.setDefaultClassLoader(defaultClassLoader); - } - - } - - - - private GlobalConfig mybatisPlusFollowCoreConfig(MybatisSqlSessionFactoryBean factory, - GenericApplicationContext mainApplicationContext){ - MybatisPlusProperties plusProperties = mainApplicationContext.getBean(MybatisPlusProperties.class); - - GlobalConfig currentGlobalConfig = new GlobalConfig(); - currentGlobalConfig.setBanner(false); - GlobalConfig globalConfig = plusProperties.getGlobalConfig(); - if(globalConfig != null){ - currentGlobalConfig.setDbConfig(globalConfig.getDbConfig()); - currentGlobalConfig.setIdentifierGenerator(globalConfig.getIdentifierGenerator()); - currentGlobalConfig.setMetaObjectHandler(globalConfig.getMetaObjectHandler()); - currentGlobalConfig.setSqlInjector(globalConfig.getSqlInjector()); - } - factory.setGlobalConfig(currentGlobalConfig); - return currentGlobalConfig; - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/ServiceImplWrapper.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/ServiceImplWrapper.java deleted file mode 100644 index 8b5414a..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/ServiceImplWrapper.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.gitee.starblues.extension.mybatis.mybatisplus; - -import com.baomidou.mybatisplus.core.conditions.Wrapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.baomidou.mybatisplus.extension.service.IService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; - -/** - * mybatis plus ServiceImpl 的包装。解决原生mybatis plus 中ServiceImpl Mapper无法注入的问题 - * 升级mybatis-plus到3.4.1 - * @author starBlues - * @version 2.4.0 - */ -public class ServiceImplWrapper, T> implements IService { - - private final ServiceImpl serviceImpl; - - protected M baseMapper; - - - public ServiceImplWrapper(M baseMapper) { - this.baseMapper = Objects.requireNonNull(baseMapper); - this.serviceImpl = new ServiceImpl(); - setMapper(); - } - - /** - * 给ServiceImpl设置Mapper - */ - private void setMapper(){ - Class aClass = serviceImpl.getClass(); - Field[] fields = aClass.getDeclaredFields(); - for (Field field : fields) { - if(Objects.equals(field.getName(), "baseMapper") - || (baseMapper != null && baseMapper.getClass() == field.getType())){ - field.setAccessible(true); - try { - field.set(serviceImpl, baseMapper); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - } - - - @Override - public boolean save(T entity) { - return serviceImpl.save(entity); - } - - @Override - public boolean saveBatch(Collection entityList, int batchSize) { - return serviceImpl.saveBatch(entityList, batchSize); - } - - @Override - public boolean saveOrUpdateBatch(Collection entityList, int batchSize) { - return serviceImpl.saveOrUpdateBatch(entityList, batchSize); - } - - @Override - public boolean removeById(Serializable id) { - return serviceImpl.removeById(id); - } - - @Override - public boolean removeByMap(Map columnMap) { - return serviceImpl.removeByMap(columnMap); - } - - @Override - public boolean remove(Wrapper queryWrapper) { - return serviceImpl.remove(queryWrapper); - } - - @Override - public boolean removeByIds(Collection idList) { - return serviceImpl.removeByIds(idList); - } - - @Override - public boolean updateById(T entity) { - return serviceImpl.updateById(entity); - } - - @Override - public boolean update(T entity, Wrapper updateWrapper) { - return serviceImpl.update(entity, updateWrapper); - } - - @Override - public boolean updateBatchById(Collection entityList, int batchSize) { - return serviceImpl.updateBatchById(entityList, batchSize); - } - - @Override - public boolean saveOrUpdate(T entity) { - return serviceImpl.saveOrUpdate(entity); - } - - @Override - public T getById(Serializable id) { - return serviceImpl.getById(id); - } - - @Override - public T getOne(Wrapper queryWrapper, boolean throwEx) { - return serviceImpl.getOne(queryWrapper, throwEx); - } - - @Override - public Map getMap(Wrapper queryWrapper) { - return serviceImpl.getMap(queryWrapper); - } - - @Override - public V getObj(Wrapper queryWrapper, Function mapper) { - return serviceImpl.getObj(queryWrapper, mapper); - } - - @Override - public int count(Wrapper queryWrapper) { - return serviceImpl.count(queryWrapper); - } - - @Override - public List list(Wrapper queryWrapper) { - return serviceImpl.list(queryWrapper); - } - - - @Override - public List> listMaps(Wrapper queryWrapper) { - return serviceImpl.listMaps(queryWrapper); - } - - @Override - public List listObjs(Wrapper queryWrapper, Function mapper) { - return serviceImpl.listObjs(queryWrapper, mapper); - } - - @Override - public M getBaseMapper() { - return this.baseMapper; - } - - @Override - public Class getEntityClass() { - return serviceImpl.getEntityClass(); - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/SpringBootMybatisPlusConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/SpringBootMybatisPlusConfig.java deleted file mode 100644 index 0eeac07..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/mybatisplus/SpringBootMybatisPlusConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gitee.starblues.extension.mybatis.mybatisplus; - -import com.baomidou.mybatisplus.core.MybatisConfiguration; -import com.baomidou.mybatisplus.core.config.GlobalConfig; -import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; -import com.gitee.starblues.extension.mybatis.MybatisCommonConfig; - -/** - * springboot mybatis plus 配置接口 - * @author starBlues - * @version 2.3 - */ -public interface SpringBootMybatisPlusConfig extends MybatisCommonConfig { - - - - /** - * 插件自主配置Mybatis-Plus的MybatisSqlSessionFactoryBean - * MybatisSqlSessionFactoryBean 具体配置说明参考 Mybatis-plus 官网 - * @param sqlSessionFactoryBean MybatisSqlSessionFactoryBean - */ - default void oneselfConfig(MybatisSqlSessionFactoryBean sqlSessionFactoryBean){ - } - - /** - * 重写设置配置 - * 只有 enableOneselfConfig 返回 false, 实现该方法才生效 - * @param configuration 当前 MybatisConfiguration - * @param globalConfig 当前全局配置GlobalConfig - */ - default void reSetMainConfig(MybatisConfiguration configuration, GlobalConfig globalConfig){ - - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/SpringBootTkMybatisConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/SpringBootTkMybatisConfig.java deleted file mode 100644 index eeeb9ef..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/SpringBootTkMybatisConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gitee.starblues.extension.mybatis.tkmyabtis; - -import com.gitee.starblues.extension.mybatis.MybatisCommonConfig; -import org.apache.ibatis.session.Configuration; -import org.mybatis.spring.SqlSessionFactoryBean; -import tk.mybatis.mapper.entity.Config; - -/** - * springboot tk-mybatis 配置接口 - * @author starBlues - * @version 2.3 - */ -public interface SpringBootTkMybatisConfig extends MybatisCommonConfig { - - - - /** - * 插件自主配置Mybatis的 SqlSessionFactoryBean - * SqlSessionFactoryBean 具体配置说明参考 Mybatis 官网 - * @param sqlSessionFactoryBean SqlSessionFactoryBean - * @param config 插件自主配置tk的 Config 具体配置说明参考 https://gitee.com/free/Mapper/wikis/1.1-java?sort_id=208196 - */ - default void oneselfConfig(SqlSessionFactoryBean sqlSessionFactoryBean, Config config){ - } - - /** - * 重写配置当前跟随主程序的配置 - * 只有 enableOneselfConfig 返回 false, 实现该方法才生效 - * @param config 插件自主配置tk的 Config 具体配置说明参考 https://gitee.com/free/Mapper/wikis/1.1-java?sort_id=208196 - * @param configuration Mybatis Configuration 的配置 - */ - default void reSetMainConfig(Configuration configuration, Config config){ - - } - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/TkMybatisProcessor.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/TkMybatisProcessor.java deleted file mode 100644 index 1005696..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-mybatis/src/main/java/com/gitee/starblues/extension/mybatis/tkmyabtis/TkMybatisProcessor.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.gitee.starblues.extension.mybatis.tkmyabtis; - -import com.gitee.starblues.extension.mybatis.*; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.bean.PluginBeanRegistrarExtend; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.mapping.DatabaseIdProvider; -import org.apache.ibatis.plugin.Interceptor; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.Resource; -import tk.mybatis.mapper.entity.Config; -import tk.mybatis.mapper.mapperhelper.MapperHelper; -import tk.mybatis.spring.mapper.MapperFactoryBean; - -/** - * tk-mybatis处理者 - * @author starBlues - * @version 2.4.0 - */ -public class TkMybatisProcessor implements PluginBeanRegistrarExtend { - - private static final Logger LOGGER = LoggerFactory.getLogger(TkMybatisProcessor.class); - - private final MapperFactoryBean mapperFactoryBean = new MapperFactoryBean(); - - public TkMybatisProcessor() { - } - - @Override - public String key() { - return "TkMybatisProcessor"; - } - - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - SpringBootTkMybatisConfig config = SpringBeanUtils.getObjectByInterfaceClass( - pluginRegistryInfo.getConfigSingletons(), - SpringBootTkMybatisConfig.class); - if(config == null){ - return; - } - - SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); - - Config tkConfig = null; - if(config.enableOneselfConfig()){ - tkConfig = new Config(); - config.oneselfConfig(factory, tkConfig); - } else { - GenericApplicationContext mainApplicationContext = pluginRegistryInfo.getMainApplicationContext(); - PluginFollowCoreConfig followCoreConfig = new PluginFollowCoreConfig(mainApplicationContext); - factory.setDataSource(followCoreConfig.getDataSource()); - Configuration configuration = followCoreConfig.getConfiguration(SpringBootMybatisExtension.Type.TK_MYBATIS); - factory.setConfiguration(configuration); - Interceptor[] interceptor = followCoreConfig.getInterceptor(); - if(interceptor != null && interceptor.length > 0){ - factory.setPlugins(interceptor); - } - DatabaseIdProvider databaseIdProvider = followCoreConfig.getDatabaseIdProvider(); - if(databaseIdProvider != null){ - factory.setDatabaseIdProvider(databaseIdProvider); - } - if(mainApplicationContext.getBeanNamesForType(Config.class, - false, false).length > 0){ - tkConfig = mainApplicationContext.getBean(Config.class); - } - config.reSetMainConfig(configuration, tkConfig); - } - - MapperHelper mapperHelper = new MapperHelper(); - if(tkConfig != null){ - mapperHelper.setConfig(tkConfig); - } - - - PluginResourceFinder pluginResourceFinder = new PluginResourceFinder(pluginRegistryInfo); - - Class[] aliasesClasses = pluginResourceFinder.getAliasesClasses(config.entityPackage()); - if(aliasesClasses != null && aliasesClasses.length > 0){ - factory.setTypeAliases(aliasesClasses); - } - - Resource[] xmlResource = pluginResourceFinder.getXmlResource(config.xmlLocationsMatch()); - if(xmlResource != null && xmlResource.length > 0){ - factory.setMapperLocations(xmlResource); - } - ClassLoader pluginClassLoader = pluginRegistryInfo.getPluginClassLoader(); - ClassLoader defaultClassLoader = Resources.getDefaultClassLoader(); - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - try { - Resources.setDefaultClassLoader(pluginClassLoader); - SqlSessionFactory sqlSessionFactory = factory.getObject(); - if(sqlSessionFactory == null){ - throw new Exception("Get tk-mybatis sqlSessionFactory is null"); - } - SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory); - // 用于解决Tk中MsUtil的ClassLoader的问题 - Thread.currentThread().setContextClassLoader(pluginClassLoader); - MapperHandler mapperHandler = new MapperHandler(); - mapperHandler.processMapper(pluginRegistryInfo, (holder, mapperClass) -> { - processMapper(holder, mapperClass, mapperHelper, sqlSessionFactory, sqlSessionTemplate); - }); - CommonRegister.commonRegister(pluginRegistryInfo, sqlSessionFactory, sqlSessionTemplate); - } finally { - Resources.setDefaultClassLoader(defaultClassLoader); - Thread.currentThread().setContextClassLoader(contextClassLoader); - } - } - - /** - * 处理Mapper接口 - * @param holder ignore - * @param mapperClass ignore - * @param mapperHelper ignore - * @param sqlSessionFactory ignore - * @param sqlSessionTemplate ignore - */ - private void processMapper(BeanDefinitionHolder holder, - Class mapperClass, - MapperHelper mapperHelper, - SqlSessionFactory sqlSessionFactory, - SqlSessionTemplate sqlSessionTemplate){ - GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition(); - definition.getConstructorArgumentValues().addGenericArgumentValue(mapperClass); - definition.setBeanClass(this.mapperFactoryBean.getClass()); - //设置通用 Mapper - definition.getPropertyValues().add("mapperHelper", mapperHelper); - definition.getPropertyValues().add("addToConfig", true); - definition.getPropertyValues().add("sqlSessionFactory", sqlSessionFactory); - definition.getPropertyValues().add("sqlSessionTemplate", sqlSessionTemplate); - definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml deleted file mode 100644 index d589dfb..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/pom.xml +++ /dev/null @@ -1,235 +0,0 @@ - - - 4.0.0 - - - org.sonatype.oss - oss-parent - 7 - - - - com.gitee.starblues - springboot-plugin-framework-extension-resources - 3.0.0-RELEASE - jar - - 插件扩展-通过url读取插件中的静态资源 - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - https://gitee.com/starblues/springboot-plugin-framework-parent - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - scm:https://gitee.com/starblues/springboot-plugin-framework-parent.git - 1.0 - - - - - sonatype-nexus-snapshots - oss Snapshots Repository - https://oss.sonatype.org/content/repositories/snapshots - - - sonatype-nexus-staging - oss Staging Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - StarBlues - starblues@foxmail.com - https://gitee.com/starblues/ - - - - - - - 1.8 - UTF-8 - - 3.8.1 - 3.1.0 - 3.1.0 - 3.1.0 - 1.6 - - 5.0.7.RELEASE - 4.0.1 - - 3.0.0-RELEASE - 2.0.3.RELEASE - 2.1.1.RELEASE - - 4.11 - - - - - - - com.gitee.starblues - springboot-plugin-framework - ${springboot-plugin-framework.version} - provided - - - - org.springframework.boot - spring-boot-starter-thymeleaf - ${spring-boot-starter-thymeleaf.version} - provided - - - - org.springframework - spring-webmvc - ${spring-version} - provided - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - true - - - - junit - junit - ${junit.version} - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-assembly-plugin - ${maven-assembly-plugin.version} - - - jar-with-dependencies - - ${project.artifactId}-${project.version} - false - false - - - true - true - - - - - - make-assembly - package - - single - - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - ${plugin.skip} - - - - package - - jar - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - ${plugin.skip} - - - - sign-artifacts - verify - - sign - - - - - - - - - - - - - dev - - true - - - true - - - - - release - - false - - - - - - \ No newline at end of file diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PluginResourceResolverProcess.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PluginResourceResolverProcess.java deleted file mode 100644 index c930a3a..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PluginResourceResolverProcess.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.gitee.starblues.extension.resources; - -import com.gitee.starblues.extension.resources.resolver.PluginResourceResolver; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.util.ObjectUtils; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * 插件资源处理器 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginResourceResolverProcess implements PluginPostProcessorExtend { - - private static final Logger LOGGER = LoggerFactory.getLogger(PluginResourceResolverProcess.class); - private static final String KEY = "PluginResourceResolverProcess"; - - - PluginResourceResolverProcess() { - } - - @Override - public String key() { - return KEY; - } - - @Override - public OrderPriority order() { - return OrderPriority.getMiddlePriority(); - } - - @Override - public void initialize() throws Exception { - - } - - @Override - public synchronized void registry(List pluginRegistryInfos) throws Exception { - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - if(pluginRegistryInfo == null){ - continue; - } - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - try { - // 直接从配置文件获取, 后续版本移除从实现类中获取配置 - Set locations = pluginRegistryInfo.getPluginBinder() - .bind(PropertyKey.STATIC_LOCATIONS, Bindable.setOf(String.class)) - .orElseGet(()->null); - if(ObjectUtils.isEmpty(locations)){ - StaticResourceConfig config = SpringBeanUtils.getObjectByInterfaceClass( - pluginRegistryInfo.getConfigSingletons(), - StaticResourceConfig.class); - if(config != null){ - locations = config.locations(); - } - } - if(ObjectUtils.isEmpty(locations)){ - return; - } - PluginResourceResolver.parse(pluginRegistryInfo, locations); - } catch (Exception e){ - LOGGER.error("Parse plugin '{}' static resource failure.", pluginId, e); - } - } - } - - @Override - public void unRegistry(List pluginRegistryInfos) throws Exception { - for (PluginRegistryInfo pluginRegistryInfo : pluginRegistryInfos) { - try { - PluginResourceResolver.remove(pluginRegistryInfo.getPluginWrapper().getPluginId()); - } catch (Exception e){ - LOGGER.error("Remove plugin '{}' static resource failure.", - pluginRegistryInfo.getPluginWrapper().getPluginId(), - e); - } - } - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PropertyKey.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PropertyKey.java deleted file mode 100644 index 385f987..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/PropertyKey.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.starblues.extension.resources; - -/** - * 配置文件key - * - * @author starBlues - * @version 2.4.3 - */ -public class PropertyKey { - - /** - * 静态文件路径 - * classpath: static/ - * file: D://path/test - */ - public final static String STATIC_LOCATIONS = "plugin.static.locations"; - - - /** - * Thymeleaf 配置前缀 - */ - public final static String THYMELEAF_CONFIG = "plugin.thymeleaf"; -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceConfig.java deleted file mode 100644 index 917a9f4..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.starblues.extension.resources; - -import java.util.Set; - -/** - * 插件静态资源的配置 - * 建议从配置文件中进行配置: - * plugin: - * static: - * locations: - * - classpath: static/ - * - file: D://path/test - * @author starBlues - * @version 2.3 - */ -@Deprecated -public interface StaticResourceConfig { - - - /** - * 静态文件路径 - * classpath: static/ - * file: D://path/test - * @return 路径集合 - */ - Set locations(); - - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceExtension.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceExtension.java deleted file mode 100644 index 1f92529..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/StaticResourceExtension.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.gitee.starblues.extension.resources; - -import com.gitee.starblues.extension.AbstractExtension; -import com.gitee.starblues.extension.resources.resolver.ResourceWebMvcConfigurer; -import com.gitee.starblues.extension.resources.thymeleaf.ThymeleafProcessor; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import com.gitee.starblues.factory.process.post.PluginPostProcessorExtend; -import org.springframework.context.ApplicationContext; -import org.springframework.http.CacheControl; -import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import java.util.*; -import java.util.concurrent.TimeUnit; - -/** - * 插件静态资源访问的扩展插件 - * - * @author starBlues - * @version 2.4.3 - */ -public class StaticResourceExtension extends AbstractExtension { - - private final static String KEY = "StaticResourceExtension"; - - /** - * 访问插件静态资源前缀。默认为: static-plugin。 - */ - private static String pluginStaticResourcePathPrefix = "static-plugin"; - - /** - * 访问静态资源的缓存控制。默认最大1小时。主要针对http协议的缓存。 - */ - private static CacheControl pluginStaticResourcesCacheControl = - CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic(); - - private final Set includes = new HashSet<>(1); - - public StaticResourceExtension(){ - } - - public StaticResourceExtension(Include... includes){ - if(includes != null){ - this.includes.addAll(Arrays.asList(includes)); - } - } - - @Override - public String key() { - return KEY; - } - - @Override - public void initialize(ApplicationContext mainApplicationContext) throws Exception{ - WebMvcConfigurer webMvcConfigurer = new ResourceWebMvcConfigurer(); - List webMvcConfigurers = new ArrayList<>(); - webMvcConfigurers.add(webMvcConfigurer); - DelegatingWebMvcConfiguration support = - mainApplicationContext.getBean(DelegatingWebMvcConfiguration.class); - support.setConfigurers(webMvcConfigurers); - } - - @Override - public List getPluginPipeProcessor(ApplicationContext mainApplicationContext) { - if(includes.contains(Include.THYMELEAF)){ - final List pluginPipeProcessorExtends = new ArrayList<>(1); - pluginPipeProcessorExtends.add(new ThymeleafProcessor()); - return pluginPipeProcessorExtends; - } - return null; - } - - @Override - public List getPluginPostProcessor(ApplicationContext mainApplicationContext) { - final List pluginPostProcessorExtends = new ArrayList<>(); - pluginPostProcessorExtends.add(new PluginResourceResolverProcess()); - return pluginPostProcessorExtends; - } - - /** - * 设置访问插件静态资源前缀 - * @param pluginStaticResourcePathPrefix 静态资源前缀。默认为: static-plugin。 - * @return StaticResourceExtension - */ - public StaticResourceExtension setPathPrefix(String pluginStaticResourcePathPrefix){ - if(pluginStaticResourcePathPrefix != null && !"".equals(pluginStaticResourcePathPrefix)){ - StaticResourceExtension.pluginStaticResourcePathPrefix = pluginStaticResourcePathPrefix; - } - return this; - } - - /** - * 设置缓存控制 - * @param pluginStaticResourcesCacheControl 访问静态资源的缓存控制。默认最大1小时。主要针对http协议的缓存。 - * @return StaticResourceExtension - */ - public StaticResourceExtension setCacheControl(CacheControl pluginStaticResourcesCacheControl){ - if(pluginStaticResourcesCacheControl == null){ - StaticResourceExtension.pluginStaticResourcesCacheControl = null; - } else { - StaticResourceExtension.pluginStaticResourcesCacheControl = pluginStaticResourcesCacheControl; - } - return this; - } - - public static String getPluginStaticResourcePathPrefix() { - return pluginStaticResourcePathPrefix; - } - - public static CacheControl getPluginStaticResourcesCacheControl() { - return pluginStaticResourcesCacheControl; - } - - - public enum Include{ - THYMELEAF - } -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/PluginResourceResolver.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/PluginResourceResolver.java deleted file mode 100644 index 1a8d2b1..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/PluginResourceResolver.java +++ /dev/null @@ -1,335 +0,0 @@ -package com.gitee.starblues.extension.resources.resolver; - -import com.gitee.starblues.extension.resources.StaticResourceConfig; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.loader.PluginResource; -import com.gitee.starblues.realize.BasePlugin; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.FileUrlResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.util.StringUtils; -import org.springframework.web.servlet.resource.AbstractResourceResolver; -import org.springframework.web.servlet.resource.ResourceResolverChain; - -import javax.servlet.http.HttpServletRequest; -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -/** - * 插件资源发现者 - * - * @author starBlues - * @version 2.4.0 - */ -public class PluginResourceResolver extends AbstractResourceResolver { - - private final static Logger logger = LoggerFactory.getLogger(PluginResourceResolver.class); - - private final static String RESOLVED_RESOURCE_CACHE_KEY_PREFIX = "resolvedPluginResource:"; - - private final static Map PLUGIN_RESOURCE_MAP = new ConcurrentHashMap<>(); - - PluginResourceResolver() { - } - - - @Override - protected Resource resolveResourceInternal(HttpServletRequest request, - String requestPath, List locations, - ResourceResolverChain chain) { - - int startOffset = (requestPath.startsWith("/") ? 1 : 0); - int endOffset = requestPath.indexOf('/', 1); - if (endOffset != -1) { - String pluginId = requestPath.substring(startOffset, endOffset); - String partialPath = requestPath.substring(endOffset + 1); - PluginStaticResource pluginResource = PLUGIN_RESOURCE_MAP.get(pluginId); - - if(pluginResource == null){ - return null; - } - - String key = computeKey(request, requestPath); - // 先判断缓存中是否存在。 - Resource resource = pluginResource.getCacheResource(key); - if(resource != null){ - return resource; - } - - // 从classpath 获取资源 - resource = resolveClassPath(pluginResource, partialPath); - if(resource != null){ - pluginResource.putCacheResource(key, resource); - return resource; - } - - // 从外置文件路径获取资源 - resource = resolveFilePath(pluginResource, partialPath); - if(resource != null){ - pluginResource.putCacheResource(key, resource); - return resource; - } - return null; - - } - return chain.resolveResource(request, requestPath, locations); - } - - /** - * 解决 ClassPath 的资源文件。也就是插件中定义的 classpath:/xx/xx/ 配置 - * @param pluginResource 插件资源配置Bean - * @param partialPath 部分路径 - * @return 资源。没有发现则返回null - */ - private Resource resolveClassPath(PluginStaticResource pluginResource, - String partialPath){ - Set classPaths = pluginResource.getClassPaths(); - if(classPaths == null || classPaths.isEmpty()){ - return null; - } - PluginRegistryInfo pluginRegistryInfo = pluginResource.getPluginRegistryInfo(); - BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin(); - if(basePlugin == null){ - return null; - } - - ClassLoader pluginClassLoader = pluginRegistryInfo.getPluginClassLoader(); - for (String classPath : classPaths) { - try { - PluginResource resource = new PluginResource(classPath + partialPath, pluginRegistryInfo); - resource.setClassLoader(pluginClassLoader); - if(resource.exists()){ - return resource; - } - } catch (Exception e){ - logger.debug("Get static resources of classpath '{}' error.", classPath, e); - } - } - return null; - } - - /** - * 解决插件中配置的绝对文件路径的文件资源。也就是插件中定义的 file:D://xx/xx/ 配置 - * @param pluginResource 插件资源配置Bean - * @param partialPath 部分路径 - * @return 资源。没有发现则返回null - */ - private Resource resolveFilePath(PluginStaticResource pluginResource, String partialPath) { - Set filePaths = pluginResource.getFilePaths(); - if(filePaths == null || filePaths.isEmpty()){ - return null; - } - - for (String filePath : filePaths) { - Path fullPath = Paths.get(filePath + partialPath); - if(!Files.exists(fullPath)){ - continue; - } - try { - FileUrlResource fileUrlResource = new FileUrlResource(fullPath.toString()); - if(fileUrlResource.exists()){ - return fileUrlResource; - } - } catch (Exception e) { - logger.debug("Get static resources of path '{}' error.", fullPath, e); - } - } - return null; - } - - - @Override - protected String resolveUrlPathInternal(String resourceUrlPath, - List locations, - ResourceResolverChain chain) { - return null; - } - - /** - * 计算key - * @param request request - * @param requestPath 请求路径 - * @return 返回key - */ - protected String computeKey(HttpServletRequest request, String requestPath) { - StringBuilder key = new StringBuilder(RESOLVED_RESOURCE_CACHE_KEY_PREFIX); - key.append(requestPath); - if (request != null) { - String codingKey = getContentCodingKey(request); - if (StringUtils.hasText(codingKey)) { - key.append("+encoding=").append(codingKey); - } - } - return key.toString(); - } - - /** - * 根据请求获取内容code key - * @param request request - * @return key - */ - private String getContentCodingKey(HttpServletRequest request) { - String header = request.getHeader(HttpHeaders.ACCEPT_ENCODING); - if (!StringUtils.hasText(header)) { - return null; - } - return Arrays.stream(StringUtils.tokenizeToStringArray(header, ",")) - .map(token -> { - int index = token.indexOf(';'); - return (index >= 0 ? token.substring(0, index) : token).trim().toLowerCase(); - }) - .sorted() - .collect(Collectors.joining(",")); - } - - - - /** - * 每新增一个插件, 都需要调用该方法,来解析该插件的 StaticResourceConfig 配置。并将其保存到 StaticResourceConfig bean 中。 - * @param pluginRegistryInfo 插件信息 - * @param locations 静态资源配置 - */ - public static synchronized void parse(PluginRegistryInfo pluginRegistryInfo, - Set locations){ - if(locations == null || locations.isEmpty()){ - return; - } - - Set classPaths = new HashSet<>(); - Set filePaths = new HashSet<>(); - - String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId(); - - for (String location : locations) { - if(StringUtils.isEmpty(location)){ - continue; - } - final int first = location.indexOf(":"); - if(first == -1){ - logger.warn("This plugin '{}' location config '{}' cannot be resolved", pluginId, location); - continue; - } - String type = location.substring(0, first); - String path = location.substring(first+1); - - if("classpath".equalsIgnoreCase(type)){ - if(path.startsWith("/")){ - path = path.substring(1); - } - if(!path.endsWith("/")){ - path = path + "/"; - } - classPaths.add(path); - } else if("file".equalsIgnoreCase(type)){ - if(!path.endsWith(File.separator)){ - path = path + File.separator; - } - filePaths.add(path); - } else { - logger.warn("The plugin '{}' type '{}' cannot be resolved", pluginId, type); - } - } - - PluginStaticResource pluginResource = new PluginStaticResource(); - pluginResource.setClassPaths(classPaths); - pluginResource.setFilePaths(filePaths); - pluginResource.setPluginRegistryInfo(pluginRegistryInfo); - - logger.info("PluginResources '{}' set classpath resources: {}, set file resources: {}", pluginId, - classPaths, filePaths); - - if(PLUGIN_RESOURCE_MAP.containsKey(pluginId)){ - // 如果存在该插件id的插件资源信息, 则先移除它 - remove(pluginId); - } - PLUGIN_RESOURCE_MAP.put(pluginId, pluginResource); - } - - - - /** - * 卸载插件时。调用该方法移除插件的资源信息 - * @param pluginId 插件id - */ - public static synchronized void remove(String pluginId){ - PluginStaticResource pluginResource = PLUGIN_RESOURCE_MAP.get(pluginId); - if(pluginResource == null){ - return; - } - PLUGIN_RESOURCE_MAP.remove(pluginId); - } - - - - /** - * 插件资源解析后的信息 - */ - private static class PluginStaticResource { - - /** - * basePlugin bean - */ - private PluginRegistryInfo pluginRegistryInfo; - - /** - * 定义的classpath集合 - */ - private Set classPaths; - - /** - * 定义的文件路径集合 - */ - private Set filePaths; - - /** - * 缓存的资源。key 为资源的可以。值为资源 - */ - private Map cacheResourceMaps = new ConcurrentHashMap<>(); - - PluginRegistryInfo getPluginRegistryInfo() { - return pluginRegistryInfo; - } - - void setPluginRegistryInfo(PluginRegistryInfo pluginRegistryInfo) { - this.pluginRegistryInfo = pluginRegistryInfo; - } - - Set getClassPaths() { - return classPaths; - } - - void setClassPaths(Set classPaths) { - this.classPaths = classPaths; - } - - Set getFilePaths() { - return filePaths; - } - - void setFilePaths(Set filePaths) { - this.filePaths = filePaths; - } - - - Resource getCacheResource(String key){ - return cacheResourceMaps.get(key); - } - - void putCacheResource(String key, Resource resource){ - if(StringUtils.isEmpty(key) || resource == null){ - return; - } - cacheResourceMaps.put(key, resource); - } - - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/ResourceWebMvcConfigurer.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/ResourceWebMvcConfigurer.java deleted file mode 100644 index 9a56830..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/resolver/ResourceWebMvcConfigurer.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.starblues.extension.resources.resolver; - -import com.gitee.starblues.extension.resources.StaticResourceExtension; -import org.springframework.http.CacheControl; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -/** - * 注册插件的WebMvc的配置 - * - * @author starBlues - * @version 2.2.1 - */ -public class ResourceWebMvcConfigurer implements WebMvcConfigurer { - - - public ResourceWebMvcConfigurer() { - } - - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - String pathPattern = "/" + StaticResourceExtension.getPluginStaticResourcePathPrefix() + "/**"; - ResourceHandlerRegistration resourceHandlerRegistration = registry.addResourceHandler(pathPattern); - CacheControl cacheControl = StaticResourceExtension.getPluginStaticResourcesCacheControl(); - if(cacheControl != null){ - resourceHandlerRegistration.setCacheControl(cacheControl); - } else { - resourceHandlerRegistration.setCacheControl(CacheControl.noStore()); - } - resourceHandlerRegistration - .resourceChain(false) - .addResolver(new PluginResourceResolver()); - } - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/SpringBootThymeleafConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/SpringBootThymeleafConfig.java deleted file mode 100644 index 4001c58..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/SpringBootThymeleafConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.starblues.extension.resources.thymeleaf; - - -/** - * @author starBlues - * @version 2.3 - */ -public interface SpringBootThymeleafConfig { - - - void config(ThymeleafConfig thymeleafConfig); - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java deleted file mode 100644 index c632611..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.gitee.starblues.extension.resources.thymeleaf; - -import org.thymeleaf.templatemode.TemplateMode; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -/** - * @author starBlues - * @version 2.3 - */ -public class ThymeleafConfig { - - - -} diff --git a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafProcessor.java b/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafProcessor.java deleted file mode 100644 index c1eca8e..0000000 --- a/springboot-plugin-framework-extension/springboot-plugin-framework-extension-resources/src/main/java/com/gitee/starblues/extension/resources/thymeleaf/ThymeleafProcessor.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.gitee.starblues.extension.resources.thymeleaf; - -import com.gitee.starblues.extension.resources.PropertyKey; -import com.gitee.starblues.factory.PluginRegistryInfo; -import com.gitee.starblues.factory.process.pipe.PluginPipeProcessorExtend; -import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.OrderPriority; -import com.gitee.starblues.utils.SpringBeanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; -import org.thymeleaf.spring5.SpringTemplateEngine; -import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; -import org.thymeleaf.templateresolver.ITemplateResolver; - -import java.lang.reflect.Field; -import java.util.Set; - -/** - * Thymeleaf 处理者 - * @author starBlues - * @version 2.4.0 - */ -public class ThymeleafProcessor implements PluginPipeProcessorExtend { - - private static final String TEMPLATE_RESOLVER_BEAN = "ClassLoaderTemplateResolver"; - private static final Logger LOGGER = LoggerFactory.getLogger(ThymeleafProcessor.class); - - public ThymeleafProcessor() { - } - - @Override - public String key() { - return "ThymeleafProcessor"; - } - - @Override - public OrderPriority order() { - return OrderPriority.getMiddlePriority(); - } - - @Override - public void initialize() throws Exception { - - } - - @Override - public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - SpringTemplateEngine springTemplateEngine = getSpringTemplateEngine(pluginRegistryInfo); - if(springTemplateEngine == null){ - return; - } - - ThymeleafConfig thymeleafConfig = pluginRegistryInfo.getPluginBinder() - .bind(PropertyKey.THYMELEAF_CONFIG, ThymeleafConfig.class) - .orElse(null); - if(thymeleafConfig == null){ - SpringBootThymeleafConfig config = SpringBeanUtils.getObjectByInterfaceClass( - pluginRegistryInfo.getConfigSingletons(), - SpringBootThymeleafConfig.class); - if(config == null){ - return; - } - thymeleafConfig = new ThymeleafConfig(); - config.config(thymeleafConfig); - } - - String prefix = thymeleafConfig.getPrefix(); - if(StringUtils.isEmpty(prefix)){ - throw new IllegalArgumentException("prefix can't be empty"); - } else { - if(!prefix.endsWith("/")){ - thymeleafConfig.setPrefix(prefix + "/"); - } - } - if(StringUtils.isEmpty(thymeleafConfig.getSuffix())){ - throw new IllegalArgumentException("suffix can't be empty"); - } - - if(thymeleafConfig.getMode() == null){ - throw new IllegalArgumentException("mode can't be null"); - } - - ClassLoader pluginClassLoader = pluginRegistryInfo.getPluginWrapper().getPluginClassLoader(); - ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver( - pluginClassLoader - ); - resolver.setPrefix(thymeleafConfig.getPrefix() + "/"); - resolver.setSuffix(thymeleafConfig.getSuffix()); - resolver.setTemplateMode(thymeleafConfig.getMode()); - - resolver.setCacheable(thymeleafConfig.getCache()); - if(thymeleafConfig.getEncoding() != null){ - resolver.setCharacterEncoding(thymeleafConfig.getEncoding().name()); - } - Integer order = thymeleafConfig.getTemplateResolverOrder(); - if(order != null){ - resolver.setOrder(order); - } - resolver.setCheckExistence(true); - Set templateResolvers = getITemplateResolvers(springTemplateEngine); - if(templateResolvers != null){ - templateResolvers.add(resolver); - } else { - LOGGER.error("You can't use Thymeleaf, because not fount 'Set' " + - "from Bean:SpringTemplateEngine by reflect"); - return; - } - pluginRegistryInfo.addExtension(TEMPLATE_RESOLVER_BEAN, resolver); - } - - @Override - public void unRegistry(PluginRegistryInfo pluginRegistryInfo) throws Exception { - Object resolver = pluginRegistryInfo.getExtension(TEMPLATE_RESOLVER_BEAN); - if(resolver == null){ - return; - } - try { - SpringTemplateEngine springTemplateEngine = getSpringTemplateEngine(pluginRegistryInfo); - Set templateResolvers = getITemplateResolvers(springTemplateEngine); - if(templateResolvers != null && resolver instanceof ClassLoaderTemplateResolver){ - templateResolvers.remove(resolver); - } - } catch (Exception e){ - LOGGER.error("unRegistry plugin '{}' templateResolver failure", - pluginRegistryInfo.getPluginWrapper().getPluginId(),e); - } - } - - private SpringTemplateEngine getSpringTemplateEngine(PluginRegistryInfo pluginRegistryInfo){ - GenericApplicationContext applicationContext = pluginRegistryInfo.getMainApplicationContext(); - String[] beanNamesForType = applicationContext.getBeanNamesForType(SpringTemplateEngine.class, - false, false); - if(beanNamesForType.length == 0){ - return null; - } - try { - return applicationContext.getBean(SpringTemplateEngine.class); - } catch (Exception e){ - return null; - } - } - - private Set getITemplateResolvers (SpringTemplateEngine springTemplateEngine) throws IllegalAccessException { - if(springTemplateEngine == null){ - return null; - } - return ClassUtils.getReflectionField(springTemplateEngine, "templateResolvers"); - } - - -} diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index f00201f..ce55024 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -13,7 +13,7 @@ com.gitee.starblues springboot-plugin-framework jar - 3.0.0-RELEASE + 3.0.0-alpha spring boot 插件式开发集成包 @@ -74,29 +74,26 @@ 1.5.2 4.0.1 0.9.0 + 1.18.20 4.11 - org.slf4j slf4j-api ${slf4j.version} - commons-io commons-io ${commons-io.version} - com.github.zafarkhaja java-semver ${java-semver.version} - com.gitee.starblues spring-plugin-framework-common @@ -110,7 +107,6 @@ provided true - org.springframework spring-webmvc @@ -118,7 +114,6 @@ provided true - org.thymeleaf thymeleaf-spring5 @@ -126,7 +121,6 @@ provided true - javax.servlet javax.servlet-api @@ -134,7 +128,6 @@ provided true - io.springfox springfox-spring-web @@ -142,7 +135,6 @@ provided true - org.springdoc springdoc-openapi-ui @@ -150,14 +142,19 @@ provided true - + + org.projectlombok + lombok + ${lombok.version} + provided + true + junit junit ${junit.version} test - diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index c0b20ee..8956a33 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -55,8 +55,6 @@ public class PluginLauncher extends AbstractLauncher { @Override protected ClassLoader createClassLoader() throws Exception { PluginClassLoader pluginClassLoader = getPluginClassLoader(); - //TODO 添加框架的引导 - pluginClassLoader.addResource(Paths.get("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-bootstrap\\target\\classes")); pluginClassLoader.addResource(pluginDescriptor); return pluginClassLoader; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index a7f5ce5..1fd65e5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -18,6 +18,8 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.RuntimeMode; import com.gitee.starblues.utils.ResourceUtils; +import lombok.Data; +import lombok.EqualsAndHashCode; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -31,8 +33,10 @@ import java.util.Set; * @author starBlues * @version 3.0.0 */ +@EqualsAndHashCode(callSuper = true) @Component @ConfigurationProperties(prefix = "plugin") +@Data public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguration{ public static final String ENABLE_KEY = "plugin.enable"; @@ -185,144 +189,4 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio } } - @Override - public Set enablePluginIds() { - return enablePluginIds; - } - - @Override - public Set disablePluginIds() { - return disablePluginIds; - } - - @Override - public List sortInitPluginIds() { - return sortInitPluginIds; - } - - @Override - public String version() { - return version; - } - - @Override - public boolean exactVersion() { - if(exactVersion == null){ - return false; - } - return exactVersion; - } - - public Boolean getEnable() { - return enable; - } - - public void setEnable(Boolean enable) { - this.enable = enable; - } - - public String getRunMode() { - return runMode; - } - - public void setRunMode(String runMode) { - this.runMode = runMode; - } - - public String getMainPackage() { - return mainPackage; - } - - public void setMainPackage(String mainPackage) { - this.mainPackage = mainPackage; - } - - public List getPluginPath() { - return pluginPath; - } - - public void setPluginPath(List pluginPath) { - this.pluginPath = pluginPath; - } - - public String getPluginRestPathPrefix() { - return pluginRestPathPrefix; - } - - public void setPluginRestPathPrefix(String pluginRestPathPrefix) { - this.pluginRestPathPrefix = pluginRestPathPrefix; - } - - public Boolean getEnablePluginRestController() { - return enablePluginRestController; - } - - public void setEnablePluginRestController(Boolean enablePluginRestController) { - this.enablePluginRestController = enablePluginRestController; - } - - public Boolean getEnablePluginIdRestPathPrefix() { - return enablePluginIdRestPathPrefix; - } - - public void setEnablePluginIdRestPathPrefix(Boolean enablePluginIdRestPathPrefix) { - this.enablePluginIdRestPathPrefix = enablePluginIdRestPathPrefix; - } - - public String getBackupPath() { - return backupPath; - } - - public void setBackupPath(String backupPath) { - this.backupPath = backupPath; - } - - public String getUploadTempPath() { - return uploadTempPath; - } - - public void setUploadTempPath(String uploadTempPath) { - this.uploadTempPath = uploadTempPath; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public Boolean getExactVersion() { - return exactVersion; - } - - public void setExactVersion(Boolean exactVersion) { - this.exactVersion = exactVersion; - } - - public Set getEnablePluginIds() { - return enablePluginIds; - } - - public void setEnablePluginIds(Set enablePluginIds) { - this.enablePluginIds = enablePluginIds; - } - - public Set getDisablePluginIds() { - return disablePluginIds; - } - - public void setDisablePluginIds(Set disablePluginIds) { - this.disablePluginIds = disablePluginIds; - } - - public List getSortInitPluginIds() { - return sortInitPluginIds; - } - - public void setSortInitPluginIds(List sortInitPluginIds) { - this.sortInitPluginIds = sortInitPluginIds; - } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java index bbbf7dc..a056f33 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/WebConfig.java @@ -16,6 +16,8 @@ package com.gitee.starblues.spring; +import lombok.Data; + import java.util.Set; /** @@ -23,24 +25,10 @@ import java.util.Set; * @author starBlues * @version 3.0.0 */ +@Data public class WebConfig { private boolean enable = false; private Set resourceLocations = null; - public void setEnable(boolean enable) { - this.enable = enable; - } - - public boolean isEnable() { - return enable; - } - - public Set getResourceLocations() { - return resourceLocations; - } - - public void setResourceLocations(Set resourceLocations) { - this.resourceLocations = resourceLocations; - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java index 8aa2ce5..6cb835d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/spring/web/PluginStaticResourceConfig.java @@ -16,6 +16,7 @@ package com.gitee.starblues.spring.web; +import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.CacheControl; @@ -25,6 +26,7 @@ import org.springframework.http.CacheControl; * @author starBlues * @version 3.0.0 */ +@Data public class PluginStaticResourceConfig { public static final String DEFAULT_PLUGIN_STATIC_RESOURCE_PATH_PREFIX = "static-plugin"; @@ -33,26 +35,6 @@ public class PluginStaticResourceConfig { private String pathPrefix = DEFAULT_PLUGIN_STATIC_RESOURCE_PATH_PREFIX; private CacheControl cacheControl = CacheControl.noCache(); - public PluginStaticResourceConfig(){ - - } - - public String getPathPrefix() { - return pathPrefix; - } - - public void setPathPrefix(String pathPrefix) { - this.pathPrefix = pathPrefix; - } - - public CacheControl getCacheControl() { - return cacheControl; - } - - public void setCacheControl(CacheControl cacheControl) { - this.cacheControl = cacheControl; - } - public void logPathPrefix(){ log.info("插件静态资源访问前缀配置为: /{}/{pluginId}", pathPrefix); } diff --git a/springboot-plugin-maven-packager/pom.xml b/springboot-plugin-maven-packager/pom.xml index c01d790..0ee35f8 100644 --- a/springboot-plugin-maven-packager/pom.xml +++ b/springboot-plugin-maven-packager/pom.xml @@ -6,7 +6,7 @@ com.gitee.starblues springboot-plugin-maven-packager - 3.0.0-RELEASE + 3.0.0-alpha 8 @@ -63,6 +63,8 @@ org.projectlombok lombok ${lombok.version} + provided + true junit diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml index 926c24b..10a23f2 100644 --- a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml @@ -6,7 +6,7 @@ Spring Boot Plugin Maven Packager com.gitee.starblues springboot-plugin-maven-packager - 3.0.0-RELEASE + 3.0.0-alpha springboot-plugin false true diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml index 926c24b..10a23f2 100644 --- a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml @@ -6,7 +6,7 @@ Spring Boot Plugin Maven Packager com.gitee.starblues springboot-plugin-maven-packager - 3.0.0-RELEASE + 3.0.0-alpha springboot-plugin false true -- Gitee From 284fea92e7840a14d25bed2fc018e30002b20dbe Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sat, 19 Feb 2022 15:03:36 +0800 Subject: [PATCH 29/37] main jar in jar --- pom.xml | 31 ++- .../com/gitee/starblues/common/Constants.java | 2 + .../gitee/starblues/common/ManifestKey.java | 53 ++++ .../com/gitee/starblues/utils/Assert.java | 0 .../utils/CompareClassTypeUtils.java | 0 .../gitee/starblues/utils/FieldFilter.java | 0 .../com/gitee/starblues/utils/FilesUtils.java | 93 +------ .../{common => }/utils/ManifestUtils.java | 2 +- .../gitee/starblues/utils/ObjectUtils.java | 5 +- .../starblues/utils/ReflectionUtils.java | 0 .../gitee/starblues/utils/ResourceUtils.java | 9 +- .../gitee/starblues/utils/StringUtils.java | 44 ++++ springboot-plugin-bootstrap/pom.xml | 2 +- .../bootstrap/PluginApplicationContext.java | 1 - .../bootstrap/PluginOneselfInteractive.java | 8 +- .../ComposeSpringPluginProcessor.java | 4 +- .../processor/DefaultProcessorContext.java | 1 - .../processor/FrameDefineBeanProcessor.java | 2 - .../PluginInterceptorRegistration.java | 8 +- .../web/PluginControllerProcessor.java | 4 +- .../web/PluginInterceptorsProcessor.java | 5 +- springboot-plugin-framework-loader/pom.xml | 16 ++ .../loader}/PluginResourceStorage.java | 25 +- .../starblues/loader}/archive/Archive.java | 2 +- .../loader}/archive/ExplodedArchive.java | 2 +- .../loader}/archive/JarFileArchive.java | 4 +- .../AbstractPluginClassLoader.java | 2 +- .../classloader/AbstractResourceLoader.java | 18 +- .../loader}/classloader/ClassPathLoader.java | 20 +- .../classloader/GenericClassLoader.java | 41 ++-- .../classloader/JarFileResourceLoader.java | 85 +++++++ .../classloader/JarResourceLoader.java | 27 ++- .../loader}/classloader/Resource.java | 4 +- .../classloader/ResourceLoaderFactory.java | 16 +- .../classloader/filter/ExcludeResource.java | 17 ++ .../loader}/jar/AbstractJarFile.java | 2 +- .../starblues/loader}/jar/AsciiBytes.java | 2 +- .../gitee/starblues/loader}/jar/Bytes.java | 2 +- .../jar/CentralDirectoryEndRecord.java | 2 +- .../jar/CentralDirectoryFileHeader.java | 2 +- .../loader}/jar/CentralDirectoryParser.java | 2 +- .../loader}/jar/CentralDirectoryVisitor.java | 2 +- .../starblues/loader}/jar/FileHeader.java | 2 +- .../gitee/starblues/loader}/jar/Handler.java | 7 +- .../gitee/starblues/loader}/jar/JarEntry.java | 2 +- .../loader}/jar/JarEntryCertification.java | 2 +- .../starblues/loader}/jar/JarEntryFilter.java | 2 +- .../gitee/starblues/loader}/jar/JarFile.java | 4 +- .../starblues/loader}/jar/JarFileEntries.java | 2 +- .../starblues/loader}/jar/JarFileWrapper.java | 7 +- .../loader}/jar/JarURLConnection.java | 10 +- .../loader}/jar/RandomAccessData.java | 2 +- .../loader}/jar/RandomAccessDataFile.java | 2 +- .../starblues/loader}/jar/StringSequence.java | 2 +- .../loader}/jar/ZipInflaterInputStream.java | 2 +- .../loader}/launcher/AbstractLauncher.java | 7 +- .../starblues/loader}/launcher/Launcher.java | 2 +- .../launcher/MainJarProgramLauncher.java | 92 +++++++ .../loader}/launcher/MainProgramLauncher.java | 17 +- .../loader}/launcher/SpringBootstrap.java | 3 +- .../loader}/launcher/SpringMainBootstrap.java | 34 +-- .../launcher/SpringMainProdBootstrap.java | 76 ++++++ .../launcher/runner}/MainMethodRunner.java | 2 +- .../loader/launcher/runner}/MethodRunner.java | 54 ++++- .../launcher/runner/SpringBootRunner.java | 30 +++ .../gitee/starblues/loader/utils/Assert.java | 87 +++++++ .../loader/utils/CompareClassTypeUtils.java | 82 +++++++ .../gitee/starblues/loader/utils/IOUtils.java | 73 ++++++ .../starblues/loader/utils/ObjectUtils.java | 43 ++++ .../starblues/loader/utils/ResourceUtils.java | 43 ++++ springboot-plugin-framework/pom.xml | 27 +-- .../starblues/core/DefaultPluginManager.java | 10 +- .../gitee/starblues/core/PluginManager.java | 1 + .../checker/ComposePluginLauncherChecker.java | 2 - .../checker/DefaultPluginLauncherChecker.java | 8 - .../core/checker/PluginLauncherChecker.java | 3 - ...ava => NestedPluginJarResourceLoader.java} | 13 +- .../core/classloader/PluginClassLoader.java | 2 +- .../PluginResourceLoaderFactory.java | 26 +- .../AbstractPluginDescriptorLoader.java | 10 +- .../DefaultInsidePluginDescriptor.java | 4 +- .../descriptor/DefaultPluginDescriptor.java | 8 +- .../descriptor/DevPluginDescriptorLoader.java | 8 +- .../core/descriptor/PluginDescriptor.java | 29 +-- .../starblues/core/descriptor/PluginType.java | 29 +++ .../ProdDirPluginDescriptorLoader.java | 18 +- .../ProdPackagePluginDescriptorLoader.java | 13 +- .../ProdPluginDescriptorLoader.java | 4 +- .../PluginProhibitStopException.java | 2 +- .../BasicMainResourcePatternDefiner.java | 1 - .../plugin/DefaultPluginInteractive.java | 1 - .../launcher/plugin/PluginInteractive.java | 1 - .../core/launcher/plugin/PluginLauncher.java | 8 +- .../PluginMainResourcePatternDefiner.java | 7 +- .../launcher/plugin/PluginMethodRunner.java | 3 +- .../involved/DefaultPluginLaunchInvolved.java | 4 +- .../involved/PluginLaunchInvolvedFactory.java | 6 +- .../core/scanner/ProdPathResolve.java | 5 +- .../integration/ExtendPointConfiguration.java | 8 - .../operator/DefaultPluginOperator.java | 10 +- .../com/gitee/starblues/utils/ClassUtils.java | 3 + .../com/gitee/starblues/utils/LogUtils.java | 34 +++ .../com/gitee/starblues/utils/MsgUtils.java | 6 +- .../com/gitee/starblues/utils/OrderUtils.java | 68 ++++++ .../starblues/utils/PluginConfigUtils.java | 24 ++ .../starblues/utils/PluginFileUtils.java | 26 +- .../starblues/utils/CommonUtilsTest.java | 21 -- .../starblues/utils/ResourceUtilsTest.java | 34 --- .../pack/AbstractDependencyFilterMojo.java | 7 +- .../plugin/pack/AbstractPackagerMojo.java | 37 +-- .../plugin/pack/BasicRepackager.java | 69 ++++-- .../gitee/starblues/plugin/pack/Constant.java | 5 + .../starblues/plugin/pack/RepackageMojo.java | 10 +- .../plugin/pack/dev/DevRepackager.java | 7 +- .../plugin/pack/filter/DependencyFilter.java | 3 +- .../plugin/pack/main/JarNestPackager.java | 122 ++++++++++ .../plugin/pack/main/MainConfig.java | 52 ++++ .../plugin/pack/main/MainRepackager.java | 79 ++++++ .../plugin/pack/prod/DirProdRepackager.java | 15 +- .../plugin/pack/prod/JarProdRepackager.java | 16 +- .../plugin/pack/prod/ProdConfig.java | 14 +- .../plugin/pack/prod/ProdRepackager.java | 24 +- .../plugin/pack/prod/ZipProdRepackager.java | 179 ++------------ .../plugin/pack/utils/CommonUtils.java | 95 ++------ .../plugin/pack/utils/PackageJar.java | 55 +++++ .../plugin/pack/utils/PackageZip.java | 227 ++++++++++++++++++ .../plugin-help.xml | 9 + .../main/resources/META-INF/maven/plugin.xml | 9 + 128 files changed, 1962 insertions(+), 817 deletions(-) create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java rename {springboot-plugin-framework => spring-plugin-framework-common}/src/main/java/com/gitee/starblues/utils/Assert.java (100%) rename {springboot-plugin-framework => spring-plugin-framework-common}/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java (100%) rename {springboot-plugin-framework => spring-plugin-framework-common}/src/main/java/com/gitee/starblues/utils/FieldFilter.java (100%) rename springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java => spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java (48%) rename spring-plugin-framework-common/src/main/java/com/gitee/starblues/{common => }/utils/ManifestUtils.java (95%) rename {springboot-plugin-framework => spring-plugin-framework-common}/src/main/java/com/gitee/starblues/utils/ObjectUtils.java (98%) rename {springboot-plugin-framework => spring-plugin-framework-common}/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java (100%) rename {springboot-plugin-framework => spring-plugin-framework-common}/src/main/java/com/gitee/starblues/utils/ResourceUtils.java (95%) create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java create mode 100644 springboot-plugin-framework-loader/pom.xml rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/PluginResourceStorage.java (81%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/archive/Archive.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/archive/ExplodedArchive.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/archive/JarFileArchive.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/AbstractPluginClassLoader.java (94%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/AbstractResourceLoader.java (88%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/ClassPathLoader.java (82%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/GenericClassLoader.java (90%) create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/JarResourceLoader.java (71%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/Resource.java (94%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/classloader/ResourceLoaderFactory.java (89%) create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/AbstractJarFile.java (96%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/AsciiBytes.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/Bytes.java (89%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/CentralDirectoryEndRecord.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/CentralDirectoryFileHeader.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/CentralDirectoryParser.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/CentralDirectoryVisitor.java (92%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/FileHeader.java (95%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/Handler.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarEntry.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarEntryCertification.java (96%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarEntryFilter.java (90%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarFile.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarFileEntries.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarFileWrapper.java (96%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/JarURLConnection.java (97%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/RandomAccessData.java (97%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/RandomAccessDataFile.java (99%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/StringSequence.java (98%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/jar/ZipInflaterInputStream.java (97%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/launcher/AbstractLauncher.java (92%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/launcher/Launcher.java (95%) create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/launcher/MainProgramLauncher.java (83%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/launcher/SpringBootstrap.java (95%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader}/launcher/SpringMainBootstrap.java (70%) create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner}/MainMethodRunner.java (95%) rename {springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher => springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner}/MethodRunner.java (53%) create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/Assert.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java rename springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/{NestedJarResourceLoader.java => NestedPluginJarResourceLoader.java} (85%) create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/LogUtils.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java delete mode 100644 springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/CommonUtilsTest.java delete mode 100644 springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/ResourceUtilsTest.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageJar.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java diff --git a/pom.xml b/pom.xml index 4341d44..cea5ce1 100644 --- a/pom.xml +++ b/pom.xml @@ -4,6 +4,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + + org.sonatype.oss + oss-parent + 7 + + com.gitee.starblues springboot-plugin-framework-parent pom @@ -13,11 +19,32 @@ spring-plugin-framework-common + springboot-plugin-framework-loader springboot-plugin-framework springboot-plugin-bootstrap - springboot-plugin-framework-example springboot-plugin-maven-packager + springboot-plugin-framework-example - + + + 1.8 + UTF-8 + 3.8.1 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + \ No newline at end of file diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java index dc4dc7a..53fe8ec 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java @@ -20,4 +20,6 @@ public abstract class Constants { */ public final static String ALLOW_VERSION = "0.0.0"; + + } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java new file mode 100644 index 0000000..aacf013 --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java @@ -0,0 +1,53 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.common; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class ManifestKey { + + /** + * Manifest version + */ + public static final String MANIFEST_VERSION = "Manifest-Version"; + + /** + * Manifest-version: 1.0 + */ + public static final String MANIFEST_VERSION_1_0 = "1.0"; + + + /** + * main class + */ + public static final String MAIN_CLASS = "Main-Class"; + + /** + * jar in jar: main class value + */ + public static final String MAIN_CLASS_VALUE = "com.gitee.starblues.loader.launcher.SpringMainProdBootstrap"; + + /** + * jar in jar: start class + */ + public static final String START_CLASS = "Start-Class"; + + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/Assert.java similarity index 100% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/Assert.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/Assert.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java similarity index 100% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FieldFilter.java similarity index 100% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/FieldFilter.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FieldFilter.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java similarity index 48% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java index ca0c82e..decc412 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/CommonUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java @@ -1,96 +1,30 @@ -/** - * Copyright [2019-2022] [starBlues] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package com.gitee.starblues.utils; -import com.gitee.starblues.integration.IntegrationConfiguration; - import java.io.File; -import java.util.Comparator; -import java.util.List; -import java.util.function.Function; +import java.util.function.Supplier; /** - * 通用工具 - * * @author starBlues * @version 3.0.0 */ -public class CommonUtils { - - private CommonUtils(){} +public class FilesUtils { - /** - * list按照int排序. 数字越大, 越排在前面 - * @param list list集合 - * @param orderImpl 排序实现 - * @param T - * @return List - */ - public static List order(List list, Function orderImpl){ - if(list == null){ - return null; + public static File getExistFile(String pathStr){ + File file = new File(pathStr); + if(file.exists()){ + return file; } - list.sort(Comparator.comparing(orderImpl, Comparator.nullsLast(Comparator.reverseOrder()))); - return list; - } - - - /** - * 对 OrderPriority 进行排序操作 - * @param order OrderPriority - * @param 当前操作要被排序的bean - * @return Comparator - */ - public static Comparator orderPriority(final Function order){ - return Comparator.comparing(t -> { - OrderPriority orderPriority = order.apply(t); - if(orderPriority == null){ - orderPriority = OrderPriority.getLowPriority(); - } - return orderPriority.getPriority(); - }, Comparator.nullsLast(Comparator.reverseOrder())); + return null; } - - /** - * 得到插件接口前缀 - * @param configuration 配置 - * @param pluginId 插件id - * @return 接口前缀 - */ - public static String getPluginRestPrefix(IntegrationConfiguration configuration, String pluginId){ - String pathPrefix = configuration.pluginRestPathPrefix(); - if(configuration.enablePluginIdRestPathPrefix()){ - if(pathPrefix != null && !"".equals(pathPrefix)){ - pathPrefix = restJoiningPath(pathPrefix, pluginId); - } else { - pathPrefix = pluginId; - } - return pathPrefix; - } else { - if(pathPrefix == null || "".equals(pathPrefix)){ - // 不启用插件id作为路径前缀, 并且路径前缀为空, 则直接返回。 - return null; - } + public static File getExistFile(String pathStr, Supplier secondPathSupplier){ + File existFile = getExistFile(pathStr); + if(existFile != null){ + return existFile; } - return pathPrefix; + return getExistFile(secondPathSupplier.get()); } - /** * rest接口拼接路径 * @param path1 路径1 @@ -121,7 +55,7 @@ public class CommonUtils { * @param paths 拼接的路径 * @return 拼接的路径 */ - public static String joiningPath(String ...paths){ + public static String joiningUrlPath(String ...paths){ if(paths == null || paths.length == 0){ return ""; } @@ -176,5 +110,4 @@ public class CommonUtils { return stringBuilder.toString(); } - } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java similarity index 95% rename from spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java index a7ae2db..acc5613 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/utils/ManifestUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.common.utils; +package com.gitee.starblues.utils; import java.util.jar.Attributes; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java index aae7b4a..32b623f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ObjectUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java @@ -16,7 +16,6 @@ package com.gitee.starblues.utils; -import org.springframework.util.CollectionUtils; import java.lang.reflect.Array; import java.util.*; @@ -128,7 +127,7 @@ public class ObjectUtils { } public static String[] toStringArray(Collection collection) { - return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); + return (!isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); } @@ -166,7 +165,7 @@ public class ObjectUtils { public static String collectionToDelimitedString( Collection coll, String delim, String prefix, String suffix) { - if (CollectionUtils.isEmpty(coll)) { + if (isEmpty(coll)) { return ""; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java similarity index 100% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ResourceUtils.java similarity index 95% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ResourceUtils.java index 2a12885..a75d3ec 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ResourceUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ResourceUtils.java @@ -16,12 +16,8 @@ package com.gitee.starblues.utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.io.Closeable; import java.io.File; -import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; @@ -37,8 +33,6 @@ import java.util.function.Consumer; */ public class ResourceUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class); - public static final String URL_PROTOCOL_FILE = "file"; public final static String TYPE_FILE = "file"; @@ -83,7 +77,6 @@ public class ResourceUtils { String location = locationMatch.replaceFirst(packageType, ""); return replacePackage(location); } - LOGGER.error("locationMatch {} illegal", locationMatch); return null; } @@ -156,7 +149,7 @@ public class ResourceUtils { } public static boolean isJarFileURL(URL url) { - return (URL_PROTOCOL_FILE.equals(url.getProtocol()) && + return (URL_PROTOCOL_FILE.equals(url.getProtocol()) || url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION)); } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java new file mode 100644 index 0000000..825b520 --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java @@ -0,0 +1,44 @@ +package com.gitee.starblues.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.StringTokenizer; + +/** + * @author starBlues + * @version 1.0 + */ +public class StringUtils { + + private static final String[] EMPTY_STRING_ARRAY = {}; + + private static String[] tokenizeLocaleSource(String localeSource) { + return tokenizeToStringArray(localeSource, "_ ", false, false); + } + + public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { + + if (str == null) { + return EMPTY_STRING_ARRAY; + } + + StringTokenizer st = new StringTokenizer(str, delimiters); + List tokens = new ArrayList<>(); + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (trimTokens) { + token = token.trim(); + } + if (!ignoreEmptyTokens || token.length() > 0) { + tokens.add(token); + } + } + return toStringArray(tokens); + } + + public static String[] toStringArray(Collection collection) { + return (!ObjectUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); + } + +} diff --git a/springboot-plugin-bootstrap/pom.xml b/springboot-plugin-bootstrap/pom.xml index f83d961..85dfe0e 100644 --- a/springboot-plugin-bootstrap/pom.xml +++ b/springboot-plugin-bootstrap/pom.xml @@ -17,7 +17,7 @@ UTF-8 3.8.1 - 3.0.0-RELEASE + 3.0.0-alpha 1.9.6 1.7.7 diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java index bab147c..2ed37d0 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginApplicationContext.java @@ -21,7 +21,6 @@ import com.gitee.starblues.core.descriptor.PluginDescriptor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.core.io.ResourceLoader; /** * 插件ApplicationContext实现 diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java index edcd048..dfd07fa 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/PluginOneselfInteractive.java @@ -17,7 +17,9 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.core.descriptor.*; +import com.gitee.starblues.core.descriptor.DevPluginDescriptorLoader; +import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginDescriptorLoader; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.integration.IntegrationConfiguration; @@ -26,7 +28,7 @@ import com.gitee.starblues.spring.extract.DefaultOpExtractFactory; import com.gitee.starblues.spring.extract.OpExtractFactory; import com.gitee.starblues.spring.invoke.DefaultInvokeSupperCache; import com.gitee.starblues.spring.invoke.InvokeSupperCache; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; import java.nio.file.Path; import java.nio.file.Paths; @@ -80,7 +82,7 @@ public class PluginOneselfInteractive implements PluginInteractive { private InsidePluginDescriptor createPluginDescriptor(){ try (PluginDescriptorLoader pluginDescriptorLoader = new DevPluginDescriptorLoader()){ Path classesPath = Paths.get(this.getClass().getResource("/").toURI()).getParent(); - String metaInf = CommonUtils.joiningFilePath(classesPath.toString(), PackageStructure.META_INF_NAME); + String metaInf = FilesUtils.joiningFilePath(classesPath.toString(), PackageStructure.META_INF_NAME); InsidePluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(Paths.get(metaInf)); if(pluginDescriptor == null){ throw new RuntimeException("没有发现插件信息, 请使用框架提供的Maven插件器对插件进行编译!"); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java index 4d2c47e..05d4847 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/ComposeSpringPluginProcessor.java @@ -25,7 +25,7 @@ import com.gitee.starblues.bootstrap.processor.web.PluginStaticResourceProcessor import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; import com.gitee.starblues.bootstrap.utils.AnnotationUtils; import com.gitee.starblues.bootstrap.utils.ProcessorUtils; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.OrderUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.OrderPriority; import org.slf4j.Logger; @@ -78,7 +78,7 @@ public class ComposeSpringPluginProcessor implements SpringPluginProcessor { ProcessorContext.RunMode runMode = p.runMode(); return runMode == ProcessorContext.RunMode.ALL || runMode == this.runMode; }) - .sorted(CommonUtils.orderPriority(SpringPluginProcessor::order)) + .sorted(OrderUtils.orderPriority(SpringPluginProcessor::order)) .collect(Collectors.toList()); for (SpringPluginProcessor processor : this.processors) { try { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java index 9cff8b0..d9d85e0 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/DefaultProcessorContext.java @@ -18,7 +18,6 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.bootstrap.SpringPluginBootstrap; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.launcher.plugin.CacheRegistryInfo; import com.gitee.starblues.core.launcher.plugin.PluginInteractive; import com.gitee.starblues.integration.IntegrationConfiguration; diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java index 159254b..b4c6549 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/FrameDefineBeanProcessor.java @@ -18,11 +18,9 @@ package com.gitee.starblues.bootstrap.processor; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.integration.ExtendPointConfiguration; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; /** diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java index 5be7829..9c098d1 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/interceptor/PluginInterceptorRegistration.java @@ -16,7 +16,7 @@ package com.gitee.starblues.bootstrap.processor.interceptor; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; import org.springframework.lang.Nullable; import org.springframework.util.PathMatcher; @@ -87,7 +87,7 @@ public class PluginInterceptorRegistration { if(ObjectUtils.isEmpty(pattern)){ continue; } - this.includePatterns.add(CommonUtils.joiningPath(pluginRestApiPrefix, pattern)); + this.includePatterns.add(FilesUtils.joiningUrlPath(pluginRestApiPrefix, pattern)); } return this; } @@ -105,7 +105,7 @@ public class PluginInterceptorRegistration { if(ObjectUtils.isEmpty(pattern)){ continue; } - this.excludePatterns.add(CommonUtils.joiningPath(pluginRestApiPrefix, pattern)); + this.excludePatterns.add(FilesUtils.joiningUrlPath(pluginRestApiPrefix, pattern)); } return this; } @@ -153,7 +153,7 @@ public class PluginInterceptorRegistration { protected Object getInterceptor() { if(type == PluginInterceptorRegistry.Type.PLUGIN){ if(this.includePatterns.isEmpty()){ - this.includePatterns.add(CommonUtils.joiningPath(pluginRestApiPrefix, "/**")); + this.includePatterns.add(FilesUtils.joiningUrlPath(pluginRestApiPrefix, "/**")); } } if (this.includePatterns.isEmpty() && this.excludePatterns.isEmpty()) { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java index e06322c..596801b 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java @@ -217,7 +217,7 @@ public class PluginControllerProcessor implements SpringPluginProcessor { private void changePathForClass(String beanName, Class aClass, RequestMapping requestMapping){ String pluginId = processorContext.getPluginDescriptor().getPluginId(); IntegrationConfiguration configuration = processorContext.getConfiguration(); - String pathPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginId); + String pathPrefix = PluginConfigUtils.getPluginRestPrefix(configuration, pluginId); if(ObjectUtils.isEmpty(pathPrefix)){ LOG.error("插件 [{}] Controller类 [{}] 未发现 path 配置, {}", @@ -241,7 +241,7 @@ public class PluginControllerProcessor implements SpringPluginProcessor { if(definePath.contains(pathPrefix)){ newPath[i++] = definePath; } else { - newPath[i++] = CommonUtils.restJoiningPath(pathPrefix, definePath); + newPath[i++] = FilesUtils.restJoiningPath(pathPrefix, definePath); } } if(newPath.length == 0){ diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java index 79f4495..48bb8fb 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginInterceptorsProcessor.java @@ -25,7 +25,8 @@ import com.gitee.starblues.bootstrap.utils.SpringBeanUtils; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.utils.ClassUtils; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.OrderUtils; +import com.gitee.starblues.utils.PluginConfigUtils; import com.gitee.starblues.utils.SpringBeanCustomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -75,7 +76,7 @@ public class PluginInterceptorsProcessor implements SpringPluginProcessor { } IntegrationConfiguration configuration = context.getConfiguration(); String pluginId = context.getPluginDescriptor().getPluginId(); - String pluginRestPrefix = CommonUtils.getPluginRestPrefix(configuration, pluginId); + String pluginRestPrefix = PluginConfigUtils.getPluginRestPrefix(configuration, pluginId); for (PluginInterceptorRegister interceptorRegister : interceptorRegisters) { PluginInterceptorRegistry interceptorRegistry = new PluginInterceptorRegistry(pluginRestPrefix); diff --git a/springboot-plugin-framework-loader/pom.xml b/springboot-plugin-framework-loader/pom.xml new file mode 100644 index 0000000..d2a4a04 --- /dev/null +++ b/springboot-plugin-framework-loader/pom.xml @@ -0,0 +1,16 @@ + + + + springboot-plugin-framework-parent + com.gitee.starblues + 3.0.0-alpha + + 4.0.0 + + springboot-plugin-framework-loader + + + + \ No newline at end of file diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java similarity index 81% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java index e668fa0..0d25864 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/PluginResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java @@ -14,13 +14,12 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader; -import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.launcher.jar.AbstractJarFile; -import com.gitee.starblues.core.launcher.jar.JarFile; -import com.gitee.starblues.core.launcher.jar.JarFileWrapper; -import org.apache.commons.io.IOUtils; +import com.gitee.starblues.loader.jar.AbstractJarFile; +import com.gitee.starblues.loader.jar.JarFile; +import com.gitee.starblues.loader.jar.JarFileWrapper; +import com.gitee.starblues.loader.utils.IOUtils; import java.io.Closeable; import java.io.File; @@ -40,11 +39,11 @@ public class PluginResourceStorage { public final static Map STORAGES = new ConcurrentHashMap<>(); - public static void addPlugin(InsidePluginDescriptor descriptor){ - if(STORAGES.containsKey(descriptor.getPluginId())){ + public static void addPlugin(String pluginId, String pluginFileName){ + if(STORAGES.containsKey(pluginId)){ return; } - STORAGES.put(descriptor.getPluginId(), new Storage(descriptor)); + STORAGES.put(pluginId, new Storage(pluginFileName)); } @@ -81,19 +80,18 @@ public class PluginResourceStorage { private static class Storage implements Closeable { - private final InsidePluginDescriptor descriptor; + private final String pluginFileName; private final Map rootJarFileMap = new ConcurrentHashMap<>(); private final Map> jarFileMap = new ConcurrentHashMap<>(); - public Storage(InsidePluginDescriptor descriptor) { - this.descriptor = descriptor; + public Storage(String pluginFileName) { + this.pluginFileName = pluginFileName; } public void addJarFile(String name, AbstractJarFile jarFile){ if(name == null || jarFile == null){ return; } - String pluginFileName = descriptor.getPluginFileName(); if(name.contains(pluginFileName)){ List jarFiles = jarFileMap.computeIfAbsent(name, k -> new ArrayList<>()); jarFiles.add(jarFile); @@ -101,7 +99,6 @@ public class PluginResourceStorage { } public void addRootJarFile(File file, JarFile jarFile){ - String pluginFileName = descriptor.getPluginFileName(); String absolutePath = file.getAbsolutePath(); if(absolutePath.contains(pluginFileName)){ rootJarFileMap.put(file, jarFile); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java index 168f543..639e3b8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/Archive.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.archive; +package com.gitee.starblues.loader.archive; import java.io.IOException; import java.net.MalformedURLException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java index 375d2bd..0047be3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/ExplodedArchive.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.archive; +package com.gitee.starblues.loader.archive; import java.io.File; import java.io.FileInputStream; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java index 99f5de0..3f363af 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/archive/JarFileArchive.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java @@ -1,6 +1,6 @@ -package com.gitee.starblues.core.launcher.archive; +package com.gitee.starblues.loader.archive; -import com.gitee.starblues.core.launcher.jar.JarFile; +import com.gitee.starblues.loader.jar.JarFile; import java.io.File; import java.io.IOException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractPluginClassLoader.java similarity index 94% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractPluginClassLoader.java index 357a3cb..2915e5c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractPluginClassLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractPluginClassLoader.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; import java.net.URL; import java.net.URLClassLoader; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java similarity index 88% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java index 3e76af2..4d13a67 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java @@ -14,10 +14,10 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; -import com.gitee.starblues.utils.ResourceUtils; -import org.apache.commons.io.IOUtils; + +import com.gitee.starblues.loader.utils.IOUtils; import java.io.*; import java.net.URL; @@ -33,6 +33,8 @@ import java.util.concurrent.ConcurrentHashMap; */ public abstract class AbstractResourceLoader { + private static final String CLASS_FILE_EXTENSION = ".class"; + protected final URL baseUrl; private final Map resourceCache = new ConcurrentHashMap<>(); @@ -71,6 +73,7 @@ public abstract class AbstractResourceLoader { try (InputStream inputStream = resourceInfo.getUrl().openStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){ IOUtils.copy(inputStream, byteArrayOutputStream); + return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } catch (Exception e){ e.printStackTrace(); @@ -90,7 +93,7 @@ public abstract class AbstractResourceLoader { } protected byte[] getClassBytes(String path, InputStream inputStream, boolean isClose) throws Exception{ - if(!ResourceUtils.isClass(path)){ + if(!isClass(path)){ return null; } final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); @@ -105,4 +108,11 @@ public abstract class AbstractResourceLoader { } } + private static boolean isClass(String path){ + if(path == null || "".equals(path)){ + return false; + } + return path.toLowerCase().endsWith(CLASS_FILE_EXTENSION); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java similarity index 82% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java index f44cdd5..3cff944 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java @@ -14,20 +14,12 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ResourceUtils; -import org.apache.commons.io.IOUtils; - -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; -import java.net.MalformedURLException; import java.net.URL; -import java.nio.file.Paths; -import java.util.Set; +import java.util.Objects; /** * classpath 资源加载者 @@ -36,11 +28,13 @@ import java.util.Set; */ public class ClassPathLoader extends AbstractResourceLoader{ + + private final URL url; public ClassPathLoader(URL url) { super(url); - this.url = Assert.isNotNull(url, "url 不能为空"); + this.url = Objects.requireNonNull(url, "url 不能为空"); } @Override @@ -58,7 +52,7 @@ public class ClassPathLoader extends AbstractResourceLoader{ if("".equals(currentPackageName)){ currentPackageName = file.getName(); } else { - currentPackageName = currentPackageName + ResourceUtils.PACKAGE_SPLIT + file.getName(); + currentPackageName = currentPackageName + Resource.PACKAGE_SPLIT + file.getName(); } loadResource(file, currentPackageName); } @@ -75,7 +69,7 @@ public class ClassPathLoader extends AbstractResourceLoader{ private void loadResource(File file, String packageName) throws Exception{ if(file.isDirectory()){ - addResource(file, packageName + ResourceUtils.PACKAGE_SPLIT); + addResource(file, packageName + Resource.PACKAGE_SPLIT); } else { addResource(file, packageName); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java similarity index 90% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java index bcfae4a..bd1ee33 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/GenericClassLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java @@ -14,12 +14,11 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ResourceUtils; -import org.apache.commons.io.IOUtils; + +import com.gitee.starblues.loader.utils.IOUtils; +import com.gitee.starblues.loader.utils.ObjectUtils; import java.io.*; import java.net.URL; @@ -55,7 +54,10 @@ public class GenericClassLoader extends URLClassLoader { public GenericClassLoader(String name, ClassLoader parent, ResourceLoaderFactory loaderFactory) { super(new URL[]{}, null); - this.name = Assert.isNotEmpty(name, "参数 name 不能为空"); + if(ObjectUtils.isEmpty(name)){ + throw new IllegalArgumentException("参数 name 不能为空"); + } + this.name = name; this.parent = parent; if(loaderFactory == null){ resourceLoaderFactory = new ResourceLoaderFactory(); @@ -85,6 +87,10 @@ public class GenericClassLoader extends URLClassLoader { resourceLoaderFactory.addResource(url); } + public ResourceLoaderFactory getResourceLoaderFactory(){ + return resourceLoaderFactory; + } + @Override public Class loadClass(String className) throws ClassNotFoundException { synchronized (getClassLoadingLock(className)) { @@ -110,10 +116,14 @@ public class GenericClassLoader extends URLClassLoader { } protected Class findClassFromParent(String className) throws ClassNotFoundException{ - if(parent != null){ - return parent.loadClass(className); + try { + if(parent != null){ + return parent.loadClass(className); + } + return null; + } catch (Exception e){ + return null; } - return null; } protected Class findClassFromLocal(String name) { @@ -159,8 +169,7 @@ public class GenericClassLoader extends URLClassLoader { byte[] bytes = null; try { if(inputStream instanceof ByteArrayInputStream){ - ByteArrayInputStream arrayInputStream = (ByteArrayInputStream) inputStream; - bytes = IOUtils.readFully(inputStream, arrayInputStream.available()); + bytes = IOUtils.read(inputStream); } else { byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(inputStream, byteArrayOutputStream); @@ -264,7 +273,7 @@ public class GenericClassLoader extends URLClassLoader { protected Enumeration findResourcesFromLocal(String name) throws IOException{ List resourceList = resourceLoaderFactory.findResources(name); - if(!ObjectUtils.isEmpty(resourceList)){ + if(resourceList != null && !resourceList.isEmpty()){ Vector vector = new Vector<>(); for (Resource resource : resourceList) { vector.add(resource.getUrl()); @@ -283,7 +292,7 @@ public class GenericClassLoader extends URLClassLoader { private String formatResourceName(String resourceName){ if(ObjectUtils.isEmpty(resourceName)) { - return ResourceUtils.PACKAGE_SPLIT; + return Resource.PACKAGE_SPLIT; } String[] split = resourceName.split("/"); StringBuilder newPath = new StringBuilder(); @@ -295,11 +304,11 @@ public class GenericClassLoader extends URLClassLoader { if(i == 0){ newPath = new StringBuilder(s); } else { - newPath.append(ResourceUtils.PACKAGE_SPLIT).append(s); + newPath.append(Resource.PACKAGE_SPLIT).append(s); } } - if(resourceName.endsWith(ResourceUtils.PACKAGE_SPLIT)){ - newPath.append(ResourceUtils.PACKAGE_SPLIT); + if(resourceName.endsWith(Resource.PACKAGE_SPLIT)){ + newPath.append(Resource.PACKAGE_SPLIT); } return newPath.toString(); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java new file mode 100644 index 0000000..631c72c --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java @@ -0,0 +1,85 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader; + +import com.gitee.starblues.loader.classloader.filter.ExcludeResource; + + +import java.net.URL; +import java.util.function.Function; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +/** + * jar 资源加载者 + * @author starBlues + * @version 3.0.0 + */ +public class JarFileResourceLoader extends AbstractResourceLoader{ + + private final JarInputStream jarInputStream; + + private ExcludeResource excludeResource = (name)->false; + + private Function function = name->name; + + public JarFileResourceLoader(URL url) throws Exception{ + super(url); + this.jarInputStream = new JarInputStream(url.openStream()); + } + + public JarFileResourceLoader(URL url, JarInputStream jarInputStream) throws Exception{ + super(url); + this.jarInputStream = jarInputStream; + } + + public void setExcludeResource(ExcludeResource excludeResource) { + if(excludeResource == null){ + return; + } + this.excludeResource = excludeResource; + } + + public void setFunction(Function function) { + this.function = function; + } + + @Override + public void init() throws Exception { + super.init(); + // 解析 + try { + JarEntry jarEntry = null; + while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { + String name = jarEntry.getName(); + name = function.apply(name); + if(excludeResource.exclude(name)){ + continue; + } + URL url = new URL(baseUrl.toString() + name); + Resource resource = new Resource(name, baseUrl, url); + resource.setBytes(getClassBytes(name, jarInputStream, false)); + addResource(name, resource); + jarInputStream.closeEntry(); + } + } finally { + jarInputStream.close(); + } + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java similarity index 71% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java index 85bd9fd..d610d8a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java @@ -14,11 +14,12 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; -import org.apache.commons.io.IOUtils; +import com.gitee.starblues.loader.classloader.filter.ExcludeResource; import java.net.URL; +import java.util.function.Function; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; @@ -31,6 +32,11 @@ public class JarResourceLoader extends AbstractResourceLoader{ private final JarInputStream jarInputStream; + private ExcludeResource excludeResource = (name)->false; + + + private Function function = name->name; + public JarResourceLoader(URL url) throws Exception{ super(new URL("jar:" + url.toString() + "!/")); this.jarInputStream = new JarInputStream(url.openStream()); @@ -41,6 +47,17 @@ public class JarResourceLoader extends AbstractResourceLoader{ this.jarInputStream = jarInputStream; } + public void setExcludeResource(ExcludeResource excludeResource) { + if(excludeResource == null){ + return; + } + this.excludeResource = excludeResource; + } + + public void setFunction(Function function) { + this.function = function; + } + @Override public void init() throws Exception { super.init(); @@ -49,6 +66,10 @@ public class JarResourceLoader extends AbstractResourceLoader{ JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String name = jarEntry.getName(); + name = function.apply(name); + if(excludeResource.exclude(name)){ + continue; + } URL url = new URL(baseUrl.toString() + name); Resource resource = new Resource(name, baseUrl, url); resource.setBytes(getClassBytes(name, jarInputStream, false)); @@ -56,7 +77,7 @@ public class JarResourceLoader extends AbstractResourceLoader{ jarInputStream.closeEntry(); } } finally { - IOUtils.closeQuietly(jarInputStream); + jarInputStream.close(); } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/Resource.java similarity index 94% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/Resource.java index 8410131..fa5547f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/Resource.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/Resource.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; import java.net.URL; import java.nio.file.Paths; @@ -26,6 +26,8 @@ import java.nio.file.Paths; */ public class Resource { + public static final String PACKAGE_SPLIT = "/"; + private final String name; private final URL baseUrl; private final URL url; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java similarity index 89% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java index 1c53061..de1dd30 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java @@ -14,9 +14,10 @@ * limitations under the License. */ -package com.gitee.starblues.core.classloader; +package com.gitee.starblues.loader.classloader; -import com.gitee.starblues.utils.ResourceUtils; + +import com.gitee.starblues.loader.utils.ResourceUtils; import java.io.File; import java.io.InputStream; @@ -40,7 +41,7 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { super(null); } - void addResourceLoader(AbstractResourceLoader resourceLoader){ + public void addResourceLoader(AbstractResourceLoader resourceLoader){ if(resourceLoader != null){ resourceLoaders.add(resourceLoader); } @@ -73,9 +74,9 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { public void addResource(URL url) throws Exception{ AbstractResourceLoader resourceLoader = null; - if(ResourceUtils.isJarFileURL(url)) { + if(ResourceUtils.isJarFileUrl(url)) { resourceLoader = new JarResourceLoader(url); - } else if(ResourceUtils.isFileURL(url)){ + } else if(ResourceUtils.isFileUrl(url)){ resourceLoader = new ClassPathLoader(url); } if(resourceLoader != null){ @@ -84,6 +85,11 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { } } + public void addResource(AbstractResourceLoader resourceLoader) throws Exception { + resourceLoader.init(); + resourceLoaders.add(resourceLoader); + } + @Override public List getResources() { List resources = new ArrayList<>(); diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java new file mode 100644 index 0000000..cfd592e --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java @@ -0,0 +1,17 @@ +package com.gitee.starblues.loader.classloader.filter; + +/** + * @author starBlues + * @version 3.0.0 + */ +@FunctionalInterface +public interface ExcludeResource { + + /** + * 过滤排除 + * @param name 资源名称 + * @return boolean + */ + boolean exclude(String name); + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java similarity index 96% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java index bbe2210..38b0aa9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AbstractJarFile.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.io.File; import java.io.IOException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java index be07e41..22d65d3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/AsciiBytes.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.nio.charset.StandardCharsets; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java similarity index 89% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java index 04c4ec7..13e46ab 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Bytes.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; /** * copy from spring-boot-loader diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java index fef7b82..f9ef4a3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryEndRecord.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.io.IOException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java index a073e07..62c00ce 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryFileHeader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.io.IOException; import java.time.ZoneId; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java index 8e0a0a9..72d91bd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryParser.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.io.IOException; import java.util.ArrayList; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java similarity index 92% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java index 3b8da51..62cc7e9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/CentralDirectoryVisitor.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; /** * copy from spring-boot-loader diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java similarity index 95% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java index 7a7bedb..64b93d7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/FileHeader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.util.zip.ZipEntry; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java index d767963..4e00ad2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/Handler.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java @@ -1,13 +1,12 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; -import com.gitee.starblues.core.launcher.PluginResourceStorage; + +import com.gitee.starblues.loader.PluginResourceStorage; import java.io.File; import java.io.IOException; import java.lang.ref.SoftReference; import java.net.*; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java similarity index 98% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java index bd5e385..0d68445 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntry.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.io.IOException; import java.net.MalformedURLException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java similarity index 96% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java index c3c6212..c4b1d5e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryCertification.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.security.CodeSigner; import java.security.cert.Certificate; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java similarity index 90% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java index 6835020..54cb294 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarEntryFilter.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; /** * copy from spring-boot-loader diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java similarity index 99% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java index 4a63f21..841b1b1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/jar/JarFile.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java @@ -1,4 +1,4 @@ -package com.gitee.starblues.core.launcher.jar; +package com.gitee.starblues.loader.jar; import java.io.File; import java.io.FilePermission; @@ -32,7 +32,7 @@ public class JarFile extends AbstractJarFile implements Iterable implements Launcher { - @Override public R run(String... args) throws Exception { - JarFile.registerUrlProtocolHandler(); ClassLoader classLoader = createClassLoader(); Thread thread = Thread.currentThread(); ClassLoader oldClassLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); + JarFile.registerUrlProtocolHandler(); return launch(classLoader, args); } finally { thread.setContextClassLoader(oldClassLoader); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/Launcher.java similarity index 95% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/Launcher.java index 64fda92..cee4f12 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/Launcher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/Launcher.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader.launcher; /** * 启动引导器 diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java new file mode 100644 index 0000000..02477d4 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java @@ -0,0 +1,92 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.launcher; + +import com.gitee.starblues.loader.archive.Archive; +import com.gitee.starblues.loader.archive.ExplodedArchive; +import com.gitee.starblues.loader.archive.JarFileArchive; +import com.gitee.starblues.loader.classloader.GenericClassLoader; +import com.gitee.starblues.loader.classloader.JarFileResourceLoader; +import com.gitee.starblues.loader.launcher.runner.MethodRunner; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Iterator; +import java.util.Objects; + +/** + * 主程序jar in jar 模式启动者 + * @author starBlues + * @version 3.0.0 + */ +public class MainJarProgramLauncher extends MainProgramLauncher{ + + private static final String PROD_CLASSES_PATH = "classes/"; + + private static final String PROD_LIB_PATH = "lib/"; + + private final static Archive.EntryFilter ENTRY_FILTER = (entry)->{ + String name = entry.getName(); + return name.startsWith(PROD_CLASSES_PATH) || name.startsWith(PROD_LIB_PATH); + }; + + private final static Archive.EntryFilter INCLUDE_FILTER = (entry) -> { + if (entry.isDirectory()) { + return entry.getName().equals(PROD_CLASSES_PATH); + } + return entry.getName().startsWith(PROD_LIB_PATH); + }; + + private final File rootJarFile; + + public MainJarProgramLauncher(MethodRunner methodRunner, File rootJarFile) { + super(methodRunner); + this.rootJarFile = Objects.requireNonNull(rootJarFile, "参数 rootJarFile 不能为空"); + } + + @Override + protected void addResource(GenericClassLoader classLoader) throws Exception { + super.addResource(classLoader); + Archive archive = getArchive(); + Iterator archiveIterator = archive.getNestedArchives(ENTRY_FILTER, INCLUDE_FILTER); + addLibResource(archiveIterator, classLoader); + } + + private Archive getArchive() throws IOException { + return (rootJarFile.isDirectory() ? new ExplodedArchive(rootJarFile) : new JarFileArchive(rootJarFile)); + } + + private void addLibResource(Iterator archives, GenericClassLoader classLoader) throws Exception { + while (archives.hasNext()){ + Archive archive = archives.next(); + URL url = archive.getUrl(); + String path = url.getPath(); + if(path.contains("/classes!/")){ + JarFileResourceLoader jarResourceLoader = new JarFileResourceLoader(url); + jarResourceLoader.setFunction(name->{ + return name.replace("classes/", ""); + }); + classLoader.getResourceLoaderFactory().addResource(jarResourceLoader); + } else { + JarFileResourceLoader jarResourceLoader = new JarFileResourceLoader(archive.getUrl()); + classLoader.getResourceLoaderFactory().addResource(jarResourceLoader); + } + } + } +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java similarity index 83% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java index 192f985..472b308 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java @@ -14,10 +14,12 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader.launcher; + +import com.gitee.starblues.loader.classloader.GenericClassLoader; +import com.gitee.starblues.loader.launcher.runner.MethodRunner; +import com.gitee.starblues.loader.utils.ObjectUtils; -import com.gitee.starblues.core.classloader.GenericClassLoader; -import com.gitee.starblues.utils.ObjectUtils; import java.lang.management.ManagementFactory; import java.net.URL; @@ -32,10 +34,10 @@ public class MainProgramLauncher extends AbstractLauncher{ private static final String MAIN_CLASS_LOADER_NAME = "MainProgramLauncherClassLoader"; - private final SpringBootstrap springBootstrap; + private final MethodRunner methodRunner; - public MainProgramLauncher(SpringBootstrap springBootstrap) { - this.springBootstrap = springBootstrap; + public MainProgramLauncher(MethodRunner methodRunner) { + this.methodRunner = methodRunner; } @Override @@ -47,8 +49,7 @@ public class MainProgramLauncher extends AbstractLauncher{ @Override protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception { - MethodRunner run = new MethodRunner(springBootstrap.getClass().getName(), "run", args); - run.run(classLoader); + methodRunner.run(classLoader); return classLoader; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringBootstrap.java similarity index 95% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringBootstrap.java index 26098bd..2a34660 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringBootstrap.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringBootstrap.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader.launcher; /** * 主程序实现该接口引导启动SpringBoot @@ -22,6 +22,7 @@ package com.gitee.starblues.core.launcher; * @version 3.0.0 */ public interface SpringBootstrap { + /** * 启动 * @param args 启动参数 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java similarity index 70% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java index 2a32c1e..2b56a09 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/SpringMainBootstrap.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java @@ -14,10 +14,12 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader.launcher; -import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.loader.launcher.runner.MainMethodRunner; +import com.gitee.starblues.loader.launcher.runner.MethodRunner; +import java.util.Objects; import java.util.concurrent.CountDownLatch; /** @@ -27,12 +29,14 @@ import java.util.concurrent.CountDownLatch; */ public class SpringMainBootstrap { - private static final String MAIN_RUN_METHOD = "main"; + static final String MAIN_RUN_METHOD = "main"; + static final String SPRING_BOOTSTRAP_RUN_METHOD = "run"; private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1); private static SpringBootstrap springBootstrap; + public static void launch(Class bootstrapClass, String[] args) { try { SpringBootstrap springBootstrap = bootstrapClass.getConstructor().newInstance(); @@ -43,7 +47,7 @@ public class SpringMainBootstrap { } public static void launch(SpringBootstrap springBootstrap, String[] args) { - SpringMainBootstrap.springBootstrap = Assert.isNotNull(springBootstrap, "springBootBootstrap 不能为空"); + SpringMainBootstrap.springBootstrap = Objects.requireNonNull(springBootstrap, "springBootBootstrap 不能为空"); MainMethodRunner mainMethodRunner = new MainMethodRunner(SpringMainBootstrap.class.getName(), MAIN_RUN_METHOD, args); Thread launchThread = new Thread(new Runner(mainMethodRunner)); @@ -55,26 +59,19 @@ public class SpringMainBootstrap { } } - private static void main(String[] args) throws Exception { - Assert.isNotNull(springBootstrap, "springBootstrap 不能为空"); - MainProgramLauncher launcher = new MainProgramLauncher(springBootstrap); - launcher.run(args); - } - - private static class Runner implements Runnable{ - private final MainMethodRunner mainMethodRunner; + private final MethodRunner methodRunner; - private Runner(MainMethodRunner mainMethodRunner) { - this.mainMethodRunner = mainMethodRunner; + public Runner(MethodRunner methodRunner) { + this.methodRunner = methodRunner; } @Override public void run() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { - mainMethodRunner.run(contextClassLoader); + methodRunner.run(contextClassLoader); } catch (Exception e) { e.printStackTrace(); } finally { @@ -83,4 +80,11 @@ public class SpringMainBootstrap { } } + private static void main(String[] args) throws Exception { + Objects.requireNonNull(springBootstrap, "springBootBootstrap 不能为空"); + MethodRunner run = new MethodRunner(springBootstrap.getClass().getName(), SPRING_BOOTSTRAP_RUN_METHOD, args); + Launcher launcher = new MainProgramLauncher(run); + launcher.run(args); + } + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java new file mode 100644 index 0000000..c7c40cf --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java @@ -0,0 +1,76 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.launcher; + +import com.gitee.starblues.loader.jar.JarFile; +import com.gitee.starblues.loader.launcher.runner.MethodRunner; +import com.gitee.starblues.loader.utils.ObjectUtils; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.util.jar.Manifest; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class SpringMainProdBootstrap { + + private static final String START_CLASS = "Start-Class"; + + public static void main(String[] args) throws Exception { + new SpringMainProdBootstrap().run(args); + } + + private void run(String[] args) throws Exception{ + File rootJarFile = getRootJarFile(); + String startClass = null; + try (JarFile jarFile = new JarFile(rootJarFile)){ + Manifest manifest = jarFile.getManifest(); + IllegalStateException exception = new IllegalStateException("当前启动包非法包!"); + if(manifest == null || manifest.getMainAttributes() == null){ + throw exception; + } + startClass = manifest.getMainAttributes().getValue(START_CLASS); + if (ObjectUtils.isEmpty(startClass)) { + throw exception; + } + } + MethodRunner methodRunner = new MethodRunner(startClass, SpringMainBootstrap.SPRING_BOOTSTRAP_RUN_METHOD, args); + Launcher launcher = new MainJarProgramLauncher(methodRunner, rootJarFile); + launcher.run(args); + } + + private File getRootJarFile() throws URISyntaxException { + ProtectionDomain protectionDomain = SpringMainBootstrap.class.getProtectionDomain(); + CodeSource codeSource = protectionDomain.getCodeSource(); + URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null; + String path = (location != null) ? location.getSchemeSpecificPart() : null; + if (path == null) { + throw new IllegalStateException("Unable to determine code source archive"); + } + File root = new File(path); + if (!root.exists()) { + throw new IllegalStateException("Unable to determine code source archive from " + root); + } + return root; + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MainMethodRunner.java similarity index 95% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MainMethodRunner.java index 1145dc3..2695ac3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MainMethodRunner.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MainMethodRunner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader.launcher.runner; /** * 主程序方法启动者 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java similarity index 53% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java index c3c1e12..425c980 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/MethodRunner.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java @@ -14,13 +14,13 @@ * limitations under the License. */ -package com.gitee.starblues.core.launcher; +package com.gitee.starblues.loader.launcher.runner; -import com.gitee.starblues.utils.Assert; -import com.gitee.starblues.utils.ReflectionUtils; +import com.gitee.starblues.loader.utils.CompareClassTypeUtils; +import com.gitee.starblues.loader.utils.ObjectUtils; import java.lang.reflect.Method; -import java.util.StringJoiner; +import java.util.Objects; /** * 反射运行方法 @@ -35,8 +35,8 @@ public class MethodRunner { protected final String[] args; public MethodRunner(String className, String runMethodName, String[] args) { - this.className = Assert.isNotEmpty(className, "className 不能为空"); - this.runMethodName = Assert.isNotEmpty(runMethodName, "runMethod 不能为空"); + this.className = checkEmpty(className, "className 不能为空"); + this.runMethodName = checkEmpty(runMethodName, "runMethod 不能为空"); this.args = (args != null) ? args.clone() : null; } @@ -57,7 +57,7 @@ public class MethodRunner { } protected Object runMethod(Class runClass) throws Exception { - Method runMethod = ReflectionUtils.findMethod(runClass, runMethodName, String[].class); + Method runMethod = findRunMethod(runClass); if(runMethod == null) { throw new NoSuchMethodException(runClass.getName() + "." + runMethodName + "(String[] args)"); } @@ -71,4 +71,44 @@ public class MethodRunner { return runClass.getConstructor().newInstance(); } + private String checkEmpty(String value, String msg){ + if(ObjectUtils.isEmpty(value)){ + throw new IllegalArgumentException(msg); + } + return value; + } + + private Method findRunMethod(Class runClass){ + Class searchType = runClass; + Class[] argClasses = new Class[]{ String[].class }; + while (searchType != null) { + Method[] methods = searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods(); + for (Method method : methods) { + if(!Objects.equals(method.getName(), runMethodName)){ + continue; + } + if(hasSameParams(method, argClasses)){ + return method; + } + } + searchType = searchType.getSuperclass(); + } + return null; + } + + private boolean hasSameParams(Method method, Class[] paramTypes) { + if(paramTypes.length != method.getParameterCount()){ + return false; + } + Class[] parameterTypes = method.getParameterTypes(); + for (int i = 0; i < paramTypes.length; i++) { + Class paramType = paramTypes[i]; + Class methodParamType = parameterTypes[i]; + if(CompareClassTypeUtils.compare(methodParamType, paramType)){ + return true; + } + } + return false; + } + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java new file mode 100644 index 0000000..9786bd1 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java @@ -0,0 +1,30 @@ +package com.gitee.starblues.loader.launcher.runner; + +import java.util.concurrent.CountDownLatch; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class SpringBootRunner implements Runnable{ + + private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1); + + private final MethodRunner methodRunner; + + public SpringBootRunner(MethodRunner methodRunner) { + this.methodRunner = methodRunner; + } + + @Override + public void run() { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + try { + methodRunner.run(contextClassLoader); + } catch (Exception e) { + e.printStackTrace(); + } finally { + COUNT_DOWN_LATCH.countDown(); + } + } +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/Assert.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/Assert.java new file mode 100644 index 0000000..bf8d51c --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/Assert.java @@ -0,0 +1,87 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.utils; + + +import java.util.function.Supplier; + +/** + * 参数校验工具类 + * @author starBlues + * @version 3.0.0 + */ +public abstract class Assert { + + private Assert(){}; + + public static void isTrue(boolean expression, String message) { + if (!expression) { + throw new IllegalArgumentException(message); + } + } + + public static void isTrue(boolean expression, Supplier messageSupplier) { + if (!expression) { + throw new IllegalArgumentException(nullSafeGet(messageSupplier)); + } + } + + public static void state(boolean expression, String message) { + if (!expression) { + throw new IllegalStateException(message); + } + } + + public static void state(boolean expression, Supplier messageSupplier) { + if (!expression) { + throw new IllegalStateException(nullSafeGet(messageSupplier)); + } + } + + public static T isNotNull(T t, String message) { + if (t == null) { + throw new IllegalArgumentException(message); + } + return t; + } + + public static T isNotNull(T t, Supplier messageSupplier) { + if (t == null) { + throw new IllegalArgumentException(nullSafeGet(messageSupplier)); + } + return t; + } + + public static T isNotEmpty(T t, String message) { + if (ObjectUtils.isEmpty(t)) { + throw new IllegalArgumentException(message); + } + return t; + } + + public static T isNotEmpty(T t, Supplier messageSupplier) { + if (ObjectUtils.isEmpty(t)) { + throw new IllegalArgumentException(nullSafeGet(messageSupplier)); + } + return t; + } + + private static String nullSafeGet(Supplier messageSupplier) { + return (messageSupplier != null ? messageSupplier.get() : null); + } + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java new file mode 100644 index 0000000..13e8ba5 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java @@ -0,0 +1,82 @@ +package com.gitee.starblues.loader.utils; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class CompareClassTypeUtils { + + private CompareClassTypeUtils(){} + + public static boolean compare(Class class1, Class class2){ + if(class1.isAssignableFrom(class2)){ + return true; + } + if(isBoolean(class1) && isBoolean(class2)){ + return true; + } + if(isChar(class1) && isChar(class2)){ + return true; + } + if(isByte(class1) && isByte(class2)){ + return true; + } + if(isShort(class1) && isShort(class2)){ + return true; + } + if(isInt(class1) && isInt(class2)){ + return true; + } + if(isLong(class1) && isLong(class2)){ + return true; + } + if(isFloat(class1) && isFloat(class2)){ + return true; + } + if(isDouble(class1) && isDouble(class2)){ + return true; + } + if(isVoid(class1) && isVoid(class2)){ + return true; + } + return false; + } + + + public static boolean isBoolean(Class class1){ + return class1.isAssignableFrom(Boolean.class) || class1.isAssignableFrom(boolean.class); + } + + public static boolean isChar(Class class1){ + return class1.isAssignableFrom(Character.class) || class1.isAssignableFrom(char.class); + } + + public static boolean isByte(Class class1){ + return class1.isAssignableFrom(Byte.class) || class1.isAssignableFrom(byte.class); + } + + public static boolean isShort(Class class1){ + return class1.isAssignableFrom(Short.class) || class1.isAssignableFrom(short.class); + } + + public static boolean isInt(Class class1){ + return class1.isAssignableFrom(Integer.class) || class1.isAssignableFrom(int.class); + } + + public static boolean isLong(Class class1){ + return class1.isAssignableFrom(Long.class) || class1.isAssignableFrom(long.class); + } + + public static boolean isFloat(Class class1){ + return class1.isAssignableFrom(Float.class) || class1.isAssignableFrom(float.class); + } + + public static boolean isDouble(Class class1){ + return class1.isAssignableFrom(Double.class) || class1.isAssignableFrom(double.class); + } + + public static boolean isVoid(Class class1){ + return class1.isAssignableFrom(Void.class) || class1.isAssignableFrom(void.class); + } + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java new file mode 100644 index 0000000..6947e01 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java @@ -0,0 +1,73 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitee.starblues.loader.utils; + +import java.io.*; +import java.util.function.Consumer; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class IOUtils { + + public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { + if(inputStream == null){ + throw new IllegalArgumentException("参数inputStream不能为空"); + } + if(outputStream == null){ + throw new IllegalArgumentException("参数inputStream不能为空"); + } + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); + BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); + byte[] arr = new byte[1024]; + int len ; + while ((len = bufferedInputStream.read(arr)) != -1) { + bufferedOutputStream.write(arr, 0, len); + } + bufferedOutputStream.flush(); + } + + public static byte[] read(InputStream inputStream) throws IOException { + if(inputStream == null){ + throw new IllegalArgumentException("参数inputStream不能为空"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int n = 0; + while (-1 != (n = inputStream.read(buffer))) { + output.write(buffer, 0, n); + } + return output.toByteArray(); + } + + public static void closeQuietly(final Closeable closeable) { + closeQuietly(closeable, null); + } + + public static void closeQuietly(final Closeable closeable, final Consumer consumer) { + if (closeable != null) { + try { + closeable.close(); + } catch (final IOException e) { + if (consumer != null) { + consumer.accept(e); + } + } + } + } + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java new file mode 100644 index 0000000..817ad6f --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java @@ -0,0 +1,43 @@ +package com.gitee.starblues.loader.utils; + +import java.lang.reflect.Array; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class ObjectUtils { + + private ObjectUtils(){} + + public static boolean isEmpty(CharSequence cs) { + return cs == null || cs.length() == 0; + } + + public static boolean isEmpty(Object obj) { + if (obj == null) { + return true; + } + + if (obj instanceof Optional) { + return !((Optional) obj).isPresent(); + } + if (obj instanceof CharSequence) { + return ((CharSequence) obj).length() == 0; + } + if (obj.getClass().isArray()) { + return Array.getLength(obj) == 0; + } + if (obj instanceof Collection) { + return ((Collection) obj).isEmpty(); + } + if (obj instanceof Map) { + return ((Map) obj).isEmpty(); + } + return false; + } + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java new file mode 100644 index 0000000..3ddf9ec --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java @@ -0,0 +1,43 @@ +package com.gitee.starblues.loader.utils; + +import java.net.URL; + +/** + * 资源工具 + * @author starBlues + * @version 3.0.0 + */ +public class ResourceUtils { + + public static final String URL_PROTOCOL_FILE = "file"; + public static final String URL_PROTOCOL_JAR_FILE = "jar"; + public static final String JAR_FILE_EXTENSION = ".jar"; + + public static final String URL_PROTOCOL_VFSFILE = "vfsfile"; + public static final String URL_PROTOCOL_VFS = "vfs"; + + private ResourceUtils(){} + + /** + * 是否为jar文件 + * @param url url + * @return boolean + */ + public static boolean isJarFileUrl(URL url) { + String protocol = url.getProtocol(); + boolean extensionIsJar = url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION); + return (URL_PROTOCOL_FILE.equals(protocol) && extensionIsJar) + || (URL_PROTOCOL_JAR_FILE.equals(protocol) || extensionIsJar); + } + + /** + * 是否为普通文件 + * @param url url + * @return boolean + */ + public static boolean isFileUrl(URL url) { + String protocol = url.getProtocol(); + return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) || + URL_PROTOCOL_VFS.equals(protocol)); + } +} diff --git a/springboot-plugin-framework/pom.xml b/springboot-plugin-framework/pom.xml index ce55024..4c832fe 100644 --- a/springboot-plugin-framework/pom.xml +++ b/springboot-plugin-framework/pom.xml @@ -5,12 +5,11 @@ 4.0.0 - org.sonatype.oss - oss-parent - 7 + springboot-plugin-framework-parent + com.gitee.starblues + 3.0.0-alpha - com.gitee.starblues springboot-plugin-framework jar 3.0.0-alpha @@ -55,10 +54,6 @@ - 1.8 - UTF-8 - - 3.8.1 3.1.0 3.1.0 3.1.0 @@ -99,7 +94,11 @@ spring-plugin-framework-common ${project.version} - + + com.gitee.starblues + springboot-plugin-framework-loader + ${project.version} + org.springframework.boot spring-boot @@ -160,16 +159,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - org.apache.maven.plugins maven-shade-plugin diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index 3a299ea..c170cc8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -270,7 +270,7 @@ public class DefaultPluginManager implements PluginManager{ } startedPlugins.remove(pluginId); unLoad(pluginId); - MsgUtils.info(log, wrapperInside.getPluginDescriptor(), "卸载成功"); + LogUtils.info(log, wrapperInside.getPluginDescriptor(), "卸载成功"); } @Override @@ -402,7 +402,7 @@ public class DefaultPluginManager implements PluginManager{ throw new PluginException(pluginInsideInfo.getPluginDescriptor(), "已经被加载"); } resolvedPlugins.put(pluginId, pluginInsideInfo); - MsgUtils.info(log, pluginInsideInfo.getPluginDescriptor(), "加载成功"); + LogUtils.info(log, pluginInsideInfo.getPluginDescriptor(), "加载成功"); return pluginInsideInfo; } @@ -465,7 +465,7 @@ public class DefaultPluginManager implements PluginManager{ if(targetFile.isFile() && unpackPlugin){ // 需要解压, 检查解压后的文件名称是否存在同名文件 checkExistFile(pluginRootDir, resolvePluginFileName); - String unpackPluginPath = CommonUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName); + String unpackPluginPath = FilesUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName); PluginFileUtils.decompressZip(targetFile.getPath(), unpackPluginPath); resultPath = Paths.get(unpackPluginPath); PluginFileUtils.deleteFile(targetFile); @@ -478,11 +478,11 @@ public class DefaultPluginManager implements PluginManager{ File pluginRootDirFile = new File(getDefaultPluginRoot()); // 检查是否存在同名文件 checkExistFile(pluginRootDirFile, resolvePluginFileName); - targetFile = Paths.get(CommonUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName)).toFile(); + targetFile = Paths.get(FilesUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName)).toFile(); if(pluginFile.isFile()){ if(unpackPlugin){ // 需要解压 - String unpackPluginPath = CommonUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName); + String unpackPluginPath = FilesUtils.joiningFilePath(pluginRootDir.getPath(), resolvePluginFileName); PluginFileUtils.decompressZip(pluginFile.getPath(), unpackPluginPath); resultPath = Paths.get(unpackPluginPath); } else { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java index b2f0832..b1da15f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginManager.java @@ -24,6 +24,7 @@ import java.util.List; /** * 插件管理者 * @author starBlues + * @version 3.0.0 */ public interface PluginManager { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java index 3984f63..716f788 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/ComposePluginLauncherChecker.java @@ -17,10 +17,8 @@ package com.gitee.starblues.core.checker; import com.gitee.starblues.core.PluginInfo; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginException; -import java.nio.file.Path; import java.util.ArrayList; import java.util.List; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java index 61dd4ff..d93de10 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/DefaultPluginLauncherChecker.java @@ -17,22 +17,14 @@ package com.gitee.starblues.core.checker; import com.gitee.starblues.common.Constants; -import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.core.PluginInfo; import com.gitee.starblues.core.PluginState; import com.gitee.starblues.core.RealizeProvider; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginDisabledException; import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.utils.Assert; import com.gitee.starblues.utils.ObjectUtils; -import java.io.FileNotFoundException; -import java.nio.file.Files; -import java.nio.file.Path; - /** * @author starBlues * @version 3.0.0 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java index c729f12..c44f9ae 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/checker/PluginLauncherChecker.java @@ -17,11 +17,8 @@ package com.gitee.starblues.core.checker; import com.gitee.starblues.core.PluginInfo; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.core.exception.PluginException; -import java.nio.file.Path; - /** * 插件启动检查者 * @author starBlues diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java similarity index 85% rename from springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java rename to springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java index d76864b..e6cd34b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java @@ -16,8 +16,13 @@ package com.gitee.starblues.core.classloader; + import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.loader.classloader.AbstractResourceLoader; +import com.gitee.starblues.loader.classloader.JarResourceLoader; +import com.gitee.starblues.loader.classloader.Resource; +import com.gitee.starblues.loader.classloader.ResourceLoaderFactory; import java.io.InputStream; import java.net.URL; @@ -29,17 +34,17 @@ import java.util.jar.JarInputStream; import java.util.zip.ZipEntry; /** - * 嵌套jar加载者 + * 嵌套插件jar加载者 * @author starBlues * @version 3.0.0 */ -public class NestedJarResourceLoader extends AbstractResourceLoader{ +public class NestedPluginJarResourceLoader extends AbstractResourceLoader { private final InsidePluginDescriptor pluginDescriptor; private final ResourceLoaderFactory resourceLoaderFactory; - public NestedJarResourceLoader(InsidePluginDescriptor pluginDescriptor, - ResourceLoaderFactory resourceLoaderFactory) throws Exception { + public NestedPluginJarResourceLoader(InsidePluginDescriptor pluginDescriptor, + ResourceLoaderFactory resourceLoaderFactory) throws Exception { super(new URL("jar:" + pluginDescriptor.getInsidePluginPath().toUri().toURL() + "!/")); this.pluginDescriptor = pluginDescriptor; this.resourceLoaderFactory = resourceLoaderFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index d946bb9..74f66f0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -17,7 +17,7 @@ package com.gitee.starblues.core.classloader; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.loader.classloader.*; import com.gitee.starblues.utils.Assert; import java.io.IOException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java index ad763aa..f3375c8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java @@ -16,10 +16,11 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.core.descriptor.PluginType; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; +import com.gitee.starblues.loader.classloader.ResourceLoaderFactory; +import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; import java.io.File; import java.util.Set; @@ -29,24 +30,25 @@ import java.util.Set; * @author starBlues * @version 3.0.0 */ -public class PluginResourceLoaderFactory extends ResourceLoaderFactory{ +public class PluginResourceLoaderFactory extends ResourceLoaderFactory { - public synchronized void addResource(InsidePluginDescriptor pluginDescriptor) throws Exception{ - PluginDescriptor.Type type = pluginDescriptor.getType(); - if(type == PluginDescriptor.Type.JAR || type == PluginDescriptor.Type.ZIP){ - NestedJarResourceLoader resourceLoader = new NestedJarResourceLoader(pluginDescriptor, this); + public synchronized void addResource(InsidePluginDescriptor descriptor) throws Exception{ + PluginType pluginType = descriptor.getType(); + if(pluginType == PluginType.JAR || pluginType == PluginType.ZIP){ + NestedPluginJarResourceLoader resourceLoader = + new NestedPluginJarResourceLoader(descriptor, this); resourceLoader.init(); addResourceLoader(resourceLoader); - } else if(type == PluginDescriptor.Type.DIR || type == PluginDescriptor.Type.DEV){ - addClasspath(pluginDescriptor); - addLibFile(pluginDescriptor); + } else if(pluginType == PluginType.DIR || pluginType == PluginType.DEV){ + addClasspath(descriptor); + addLibFile(descriptor); } } private void addClasspath(InsidePluginDescriptor pluginDescriptor) throws Exception { String pluginClassPath = pluginDescriptor.getPluginClassPath(); - File existFile = PluginFileUtils.getExistFile(pluginClassPath); + File existFile = FilesUtils.getExistFile(pluginClassPath); if(existFile != null){ addResource(existFile); } @@ -58,7 +60,7 @@ public class PluginResourceLoaderFactory extends ResourceLoaderFactory{ return; } for (String pluginLibPath : pluginLibPaths) { - File existFile = PluginFileUtils.getExistFile(pluginLibPath); + File existFile = FilesUtils.getExistFile(pluginLibPath); if(existFile != null){ addResource(existFile); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index d921202..c0c21ab 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -20,7 +20,7 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.AbstractDependencyPlugin; import com.gitee.starblues.common.DependencyPlugin; import com.gitee.starblues.core.exception.PluginException; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,13 +30,13 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; +import static com.gitee.starblues.common.PackageStructure.MANIFEST; import static com.gitee.starblues.common.PluginDescriptorKey.*; -import static com.gitee.starblues.common.PackageStructure.*; -import static com.gitee.starblues.common.utils.ManifestUtils.*; +import static com.gitee.starblues.utils.ManifestUtils.getValue; /** * 抽象的 PluginDescriptorLoader @@ -118,7 +118,7 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor if(!file.exists()){ // 如果绝对路径不存在, 则判断相对路径 String pluginPath = getValue(attributes, PLUGIN_PATH); - file = new File(CommonUtils.joiningFilePath(pluginPath, libIndex)); + file = new File(FilesUtils.joiningFilePath(pluginPath, libIndex)); } if(!file.exists()){ // 都不存在, 则返回为空 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java index 034100b..e6ab6c9 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -25,7 +25,7 @@ import java.util.jar.Manifest; * @author starBlues * @version 3.0.0 */ -public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor implements InsidePluginDescriptor{ +public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor implements InsidePluginDescriptor { private final Path pluginPath; private final String pluginFileName; @@ -110,7 +110,7 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple @Override public PluginDescriptor toPluginDescriptor() { Path pluginPath = getInsidePluginPath(); - if(getType() == Type.DEV) { + if(getType() == PluginType.DEV) { // dev模式 插件路径展示项目目录 pluginPath = pluginPath.getParent().getParent(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java index 2753308..d642dbd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultPluginDescriptor.java @@ -31,7 +31,7 @@ import static com.gitee.starblues.common.PluginDescriptorKey.*; * @author starBlues * @version 3.0.0 */ -public class DefaultPluginDescriptor implements PluginDescriptor{ +public class DefaultPluginDescriptor implements PluginDescriptor { private final String pluginId; private final String pluginVersion; @@ -39,7 +39,7 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ private final String pluginPath; - private Type type; + private PluginType type; private String description; private String requires; private String provider; @@ -72,7 +72,7 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ this.license = license; } - void setType(Type type) { + void setType(PluginType type) { this.type = type; } @@ -127,7 +127,7 @@ public class DefaultPluginDescriptor implements PluginDescriptor{ @Override - public Type getType() { + public PluginType getType() { return type; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java index eadde2a..f398106 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java @@ -17,17 +17,11 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.common.PluginDescriptorKey; -import com.gitee.starblues.common.utils.ManifestUtils; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Properties; -import java.util.jar.Attributes; import java.util.jar.Manifest; /** @@ -60,7 +54,7 @@ public class DevPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ @Override protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { final DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); - descriptor.setType(PluginDescriptor.Type.DEV); + descriptor.setType(PluginType.DEV); return descriptor; } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java index 4293066..03919dc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -17,6 +17,7 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.DependencyPlugin; +import com.gitee.starblues.core.descriptor.PluginType; import java.util.List; @@ -85,33 +86,7 @@ public interface PluginDescriptor { * 得到插件类型 * @return 插件类型 */ - Type getType(); - - - /** - * 插件类型 - */ - enum Type{ - /** - * jar文件 - */ - JAR, - - /** - * zip 文件 - */ - ZIP, - - /** - * 生产模式目录 - */ - DIR, - - /** - * 开发模式目录 - */ - DEV; - } + PluginType getType(); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java new file mode 100644 index 0000000..24bd2ce --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java @@ -0,0 +1,29 @@ +package com.gitee.starblues.core.descriptor; + +/** + * @author starBlues + * @version 3.0.0 + */ +public enum PluginType { + + /** + * jar文件 + */ + JAR, + + /** + * zip 文件 + */ + ZIP, + + /** + * 生产模式目录 + */ + DIR, + + /** + * 开发模式目录 + */ + DEV; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java index 78d52da..1b9ffcd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -17,10 +17,9 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PluginDescriptorKey; -import com.gitee.starblues.common.utils.ManifestUtils; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.ManifestUtils; +import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.ResourceUtils; import org.apache.commons.io.FileUtils; import java.io.File; @@ -28,7 +27,6 @@ import java.io.FileInputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -47,7 +45,7 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade @Override protected Manifest getManifest(Path location) throws Exception { - File file = new File(CommonUtils.joiningFilePath(location.toString(), resolvePath(PROD_MANIFEST_PATH))); + File file = new File(FilesUtils.joiningFilePath(location.toString(), resolvePath(PROD_MANIFEST_PATH))); if(!file.exists()){ return null; } @@ -61,9 +59,9 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade @Override protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); - descriptor.setType(PluginDescriptor.Type.DIR); + descriptor.setType(PluginType.DIR); String pathStr = path.toFile().getPath(); - descriptor.setPluginClassPath(CommonUtils.joiningPath( + descriptor.setPluginClassPath(FilesUtils.joiningFilePath( pathStr, CLASSES_NAME )); System.out.println(descriptor.getPluginClassPath()); @@ -91,7 +89,7 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade File file = new File(index); if(!file.exists()){ // 如果直接读取的路径不存在, 则从相对路径读取 - file = new File(CommonUtils.joiningFilePath( + file = new File(FilesUtils.joiningFilePath( pathStr, index )); } @@ -107,12 +105,12 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade libIndexPath = resolvePath(libIndexPath); if(ObjectUtils.isEmpty(libIndexPath)){ // 如果配置为空, 直接从默认路径读取 - libIndexPath = CommonUtils.joiningFilePath(rootPath, resolvePath(PROD_RESOURCES_DEFINE_PATH)); + libIndexPath = FilesUtils.joiningFilePath(rootPath, resolvePath(PROD_RESOURCES_DEFINE_PATH)); } else { if(Files.exists(Paths.get(libIndexPath))){ return libIndexPath; } - libIndexPath = CommonUtils.joiningFilePath(rootPath, libIndexPath); + libIndexPath = FilesUtils.joiningFilePath(rootPath, libIndexPath); } if(Files.exists(Paths.get(libIndexPath))){ return libIndexPath; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java index 4b046e5..84bb572 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -18,9 +18,8 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.common.utils.ManifestUtils; +import com.gitee.starblues.utils.ManifestUtils; import com.gitee.starblues.utils.ObjectUtils; -import com.gitee.starblues.utils.PluginFileUtils; import org.apache.commons.io.IOUtils; import java.io.InputStream; @@ -41,21 +40,17 @@ import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_RESOURCES_CO */ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorLoader{ - private final PluginDescriptor.Type type; + private final PluginType type; private PluginResourcesConfig pluginResourcesConfig; - public ProdPackagePluginDescriptorLoader(PluginDescriptor.Type type) { + public ProdPackagePluginDescriptorLoader(PluginType type) { this.type = type; } @Override protected Manifest getManifest(Path location) throws Exception { try (JarFile jarFile = new JarFile(location.toFile())){ - JarEntry jarEntry = jarFile.getJarEntry(PackageStructure.PROD_MANIFEST_PATH); - // TODO - InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); - Manifest manifest = PluginFileUtils.getManifest(jarFileInputStream); - jarFileInputStream.close(); + Manifest manifest = jarFile.getManifest(); pluginResourcesConfig = getPluginResourcesConfig(jarFile, manifest); return manifest; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index 35aca22..49aa8fe 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -37,9 +37,9 @@ public class ProdPluginDescriptorLoader implements PluginDescriptorLoader{ @Override public InsidePluginDescriptor load(Path location) throws PluginException { if(ResourceUtils.isJarFile(location)){ - target = new ProdPackagePluginDescriptorLoader(PluginDescriptor.Type.JAR); + target = new ProdPackagePluginDescriptorLoader(PluginType.JAR); } else if(ResourceUtils.isZipFile(location)){ - target = new ProdPackagePluginDescriptorLoader(PluginDescriptor.Type.ZIP); + target = new ProdPackagePluginDescriptorLoader(PluginType.ZIP); } else if(ResourceUtils.isDirFile(location)){ target = new ProdDirPluginDescriptorLoader(); } else { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java index d4fef65..a5095d5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/exception/PluginProhibitStopException.java @@ -24,7 +24,7 @@ import com.gitee.starblues.utils.MsgUtils; * @author starBlues * @version 3.0.0 */ -public class PluginProhibitStopException extends PluginException{ +public class PluginProhibitStopException extends PluginException { public PluginProhibitStopException(PluginDescriptor pluginDescriptor, String message) { super(pluginDescriptor, "被禁止卸载. " + MsgUtils.getThrowableMsg(message)); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java index 4c5166f..c3a2eb5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/BasicMainResourcePatternDefiner.java @@ -17,7 +17,6 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.classloader.MainResourcePatternDefiner; -import com.gitee.starblues.core.launcher.JavaMainResourcePatternDefiner; import java.util.HashSet; import java.util.Set; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java index efca52c..c26810d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/DefaultPluginInteractive.java @@ -17,7 +17,6 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.extract.DefaultExtractFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java index 6511f06..e9e87e1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginInteractive.java @@ -17,7 +17,6 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.extract.OpExtractFactory; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 8956a33..7537524 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -16,16 +16,12 @@ package com.gitee.starblues.core.launcher.plugin; -import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.launcher.AbstractLauncher; -import com.gitee.starblues.core.launcher.PluginResourceStorage; +import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; -import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolvedFactory; +import com.gitee.starblues.loader.launcher.AbstractLauncher; import com.gitee.starblues.spring.SpringPluginHook; -import com.gitee.starblues.spring.web.PluginStaticResourceResolver; -import java.nio.file.Paths; import java.util.Map; import java.util.WeakHashMap; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index fbab1e9..ac848cc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -58,6 +58,7 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef includeResourcePatterns.add(FRAMEWORK); addWebIncludeResourcePatterns(includeResourcePatterns); addApiDoc(includeResourcePatterns); + addDbDriver(includeResourcePatterns); // 配置插件自定义从主程序加载的资源匹配 Set includeMainResourcePatterns = descriptor.getIncludeMainResourcePatterns(); @@ -91,8 +92,6 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef return excludeResourcePatterns; } - - protected void addWebIncludeResourcePatterns(Set patterns){ patterns.add("org/springframework/web/**"); patterns.add("org/springframework/http/**"); @@ -109,6 +108,10 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef patterns.add("org/springdoc/**"); } + protected void addDbDriver(Set patterns){ + patterns.add("com/mysql/**"); + } + /** * 获取基本的 MainResourcePatternDefiner * @param pluginInteractive PluginInteractive diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java index 9b4b57c..2fa4072 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java @@ -17,12 +17,11 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.RuntimeMode; -import com.gitee.starblues.core.launcher.MethodRunner; +import com.gitee.starblues.loader.launcher.runner.MethodRunner; import com.gitee.starblues.utils.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java index 4a80be4..33fee5b 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/DefaultPluginLaunchInvolved.java @@ -17,7 +17,7 @@ package com.gitee.starblues.core.launcher.plugin.involved; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.core.launcher.PluginResourceStorage; +import com.gitee.starblues.loader.PluginResourceStorage; import com.gitee.starblues.spring.SpringPluginHook; import com.gitee.starblues.spring.web.PluginStaticResourceResolver; @@ -30,7 +30,7 @@ public class DefaultPluginLaunchInvolved implements PluginLaunchInvolved{ @Override public void before(InsidePluginDescriptor descriptor, ClassLoader classLoader) throws Exception { - PluginResourceStorage.addPlugin(descriptor); + PluginResourceStorage.addPlugin(descriptor.getPluginId(), descriptor.getPluginFileName()); } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java index d3fc5ec..8330ce2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/involved/PluginLaunchInvolvedFactory.java @@ -18,13 +18,11 @@ package com.gitee.starblues.core.launcher.plugin.involved; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.integration.IntegrationConfiguration; -import com.gitee.starblues.spring.MainApplicationContext; import com.gitee.starblues.spring.SpringPluginHook; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.OrderUtils; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import java.util.ArrayList; @@ -65,7 +63,7 @@ public class PluginLaunchInvolvedFactory implements PluginLaunchInvolved{ if(!ObjectUtils.isEmpty(pluginLaunchInvolvedMap)){ pluginLaunchInvolvedList.addAll(pluginLaunchInvolvedMap.values()); } - pluginLaunchInvolvedList.sort(CommonUtils.orderPriority(PluginLaunchInvolved::order)); + pluginLaunchInvolvedList.sort(OrderUtils.orderPriority(PluginLaunchInvolved::order)); return pluginLaunchInvolvedList; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java index 7f59f53..9a8f7a7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/scanner/ProdPathResolve.java @@ -17,7 +17,8 @@ package com.gitee.starblues.core.scanner; import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; +import com.gitee.starblues.utils.OrderUtils; import com.gitee.starblues.utils.ObjectUtils; import java.io.File; @@ -69,7 +70,7 @@ public class ProdPathResolve implements PathResolve{ return false; } - file = new File(CommonUtils.joiningFilePath(path.toString(), PackageStructure.resolvePath( + file = new File(FilesUtils.joiningFilePath(path.toString(), PackageStructure.resolvePath( PackageStructure.PROD_MANIFEST_PATH ))); return file.exists() && file.isFile(); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java index 6807104..46bb11a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointConfiguration.java @@ -19,23 +19,15 @@ package com.gitee.starblues.integration; import com.gitee.starblues.core.DefaultRealizeProvider; import com.gitee.starblues.core.RealizeProvider;; import com.gitee.starblues.core.launcher.plugin.BasicMainResourcePatternDefiner; -import com.gitee.starblues.integration.listener.SwaggerListener; import com.gitee.starblues.integration.operator.DefaultPluginOperator; import com.gitee.starblues.integration.operator.PluginOperator; import com.gitee.starblues.integration.operator.PluginOperatorWrapper; import com.gitee.starblues.integration.user.DefaultPluginUser; import com.gitee.starblues.integration.user.PluginUser; import com.gitee.starblues.spring.extract.ExtractFactory; -import com.gitee.starblues.spring.web.PluginStaticResourceConfig; -import com.gitee.starblues.spring.web.PluginStaticResourceWebMvcConfigurer; -import com.gitee.starblues.spring.web.thymeleaf.PluginThymeleafInvolved; import org.springframework.boot.autoconfigure.condition.*; import org.springframework.context.annotation.Bean; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.web.servlet.resource.ResourceResolver; -import org.thymeleaf.spring5.SpringTemplateEngine; -import org.thymeleaf.templatemode.TemplateMode; -import springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper; /** * 系统Bean配置 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java index 4524ef7..0a8c6b1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/operator/DefaultPluginOperator.java @@ -16,7 +16,10 @@ package com.gitee.starblues.integration.operator; -import com.gitee.starblues.core.*; +import com.gitee.starblues.core.PluginInfo; +import com.gitee.starblues.core.PluginLauncherManager; +import com.gitee.starblues.core.PluginManager; +import com.gitee.starblues.core.RealizeProvider; import com.gitee.starblues.core.exception.PluginDisabledException; import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.integration.IntegrationConfiguration; @@ -43,7 +46,8 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -274,7 +278,7 @@ public class DefaultPluginOperator implements PluginOperator { throw new PluginException("插件文件类型错误, 请上传 jar/zip 类型文件"); } - String tempPathString = CommonUtils.joiningFilePath(configuration.uploadTempPath(), pluginFileName); + String tempPathString = FilesUtils.joiningFilePath(configuration.uploadTempPath(), pluginFileName); Path tempFilePath = Paths.get(tempPathString); File tempFile = PluginFileUtils.createExistFile(tempFilePath); // 将上传的插件拷贝到临时目录 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java index 8a98b45..d286b0d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java @@ -16,6 +16,8 @@ package com.gitee.starblues.utils; +import org.springframework.util.PathMatcher; + import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -98,6 +100,7 @@ public class ClassUtils { } /** + * // TODO 可能某个java版本不生效 * 得到注解修改者 * @param annotation 注解 * @return 修改者集合 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/LogUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/LogUtils.java new file mode 100644 index 0000000..c637552 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/LogUtils.java @@ -0,0 +1,34 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.utils; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; +import org.slf4j.Logger; + +/** + * @author starBlues + * @version 3.0.0 + */ +public class LogUtils { + + private LogUtils(){} + + public static void info(Logger logger, PluginDescriptor pluginDescriptor, String msg){ + logger.info("插件[{}]{}", MsgUtils.getPluginUnique(pluginDescriptor), msg); + } + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java index 37a797e..ed4da06 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/MsgUtils.java @@ -16,8 +16,8 @@ package com.gitee.starblues.utils; + import com.gitee.starblues.core.descriptor.PluginDescriptor; -import org.slf4j.Logger; /** * @author starBlues @@ -46,8 +46,4 @@ public abstract class MsgUtils { return ObjectUtils.isEmpty(message) ? "" : message; } - public static void info(Logger logger, PluginDescriptor pluginDescriptor, String msg){ - logger.info("插件[{}]{}", getPluginUnique(pluginDescriptor), msg); - } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java new file mode 100644 index 0000000..7cc43b1 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java @@ -0,0 +1,68 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.utils; + + +import java.io.File; +import java.util.Comparator; +import java.util.List; +import java.util.function.Function; + +/** + * 通用工具 + * + * @author starBlues + * @version 3.0.0 + */ +public class OrderUtils { + + private OrderUtils(){} + + /** + * list按照int排序. 数字越大, 越排在前面 + * @param list list集合 + * @param orderImpl 排序实现 + * @param T + * @return List + */ + public static List order(List list, Function orderImpl){ + if(list == null){ + return null; + } + list.sort(Comparator.comparing(orderImpl, Comparator.nullsLast(Comparator.reverseOrder()))); + return list; + } + + + /** + * 对 OrderPriority 进行排序操作 + * @param order OrderPriority + * @param 当前操作要被排序的bean + * @return Comparator + */ + public static Comparator orderPriority(final Function order){ + return Comparator.comparing(t -> { + OrderPriority orderPriority = order.apply(t); + if(orderPriority == null){ + orderPriority = OrderPriority.getLowPriority(); + } + return orderPriority.getPriority(); + }, Comparator.nullsLast(Comparator.reverseOrder())); + } + + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java index 63f352c..22bc4a5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginConfigUtils.java @@ -17,6 +17,7 @@ package com.gitee.starblues.utils; import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.integration.IntegrationConfiguration; /** * 插件配置工具类 @@ -87,6 +88,29 @@ public class PluginConfigUtils { return fileNamePrefix + suffix + fileNamePrefixSuffix; } + /** + * 得到插件接口前缀 + * @param configuration 配置 + * @param pluginId 插件id + * @return 接口前缀 + */ + public static String getPluginRestPrefix(IntegrationConfiguration configuration, String pluginId){ + String pathPrefix = configuration.pluginRestPathPrefix(); + if(configuration.enablePluginIdRestPathPrefix()){ + if(pathPrefix != null && !"".equals(pathPrefix)){ + pathPrefix = FilesUtils.restJoiningPath(pathPrefix, pluginId); + } else { + pathPrefix = pluginId; + } + return pathPrefix; + } else { + if(pathPrefix == null || "".equals(pathPrefix)){ + // 不启用插件id作为路径前缀, 并且路径前缀为空, 则直接返回。 + return null; + } + } + return pathPrefix; + } public static class FileNamePack { private final String sourceFileName; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java index d7ef031..3e1423e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/PluginFileUtils.java @@ -32,8 +32,6 @@ import java.nio.file.Paths; import java.security.MessageDigest; import java.util.Enumeration; import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.zip.ZipEntry; @@ -119,22 +117,6 @@ public final class PluginFileUtils { return path.toFile(); } - public static File getExistFile(String pathStr){ - File file = new File(pathStr); - if(file.exists()){ - return file; - } - return null; - } - - public static File getExistFile(String pathStr, Supplier secondPathSupplier){ - File existFile = getExistFile(pathStr); - if(existFile != null){ - return existFile; - } - return getExistFile(secondPathSupplier.get()); - } - /** * 得到文件名称 * @param file 原始文件 @@ -214,7 +196,7 @@ public final class PluginFileUtils { zipEntry = zipEnumeration.nextElement(); String zipEntryName = zipEntry.getName(); String currentZipPath = PackageStructure.resolvePath(zipEntryName); - String currentTargetPath = CommonUtils.joiningFilePath(targetDir, currentZipPath); + String currentTargetPath = FilesUtils.joiningFilePath(targetDir, currentZipPath); //判断路径是否存在,不存在则创建文件路径 if (zipEntry.isDirectory()) { FileUtils.forceMkdir(new File(currentTargetPath)); @@ -238,10 +220,4 @@ public final class PluginFileUtils { } } - public static void main(String[] args) throws IOException { - decompressZip("D:\\etc\\kitte\\ksm\\springboot-plugin-framework-parent\\springboot-plugin-framework-example\\plugin\\example-basic-1-1.0.0-SNAPSHOT_0.zip", - - "D:\\etc\\kitte\\springboot-plugin-framework-parent\\springboot-plugin-framework\\src\\main\\java\\com\\gitee\\starblues\\integration\\operator"); - } - } diff --git a/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/CommonUtilsTest.java b/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/CommonUtilsTest.java deleted file mode 100644 index 19e945f..0000000 --- a/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/CommonUtilsTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gitee.starblues.utils; - -import org.junit.Assert; -import org.junit.Test; - -/** - * @author starBlues - * @version 1.0 - */ -public class CommonUtilsTest { - - @Test - public void testJoin(){ - Assert.assertEquals(CommonUtils.joiningPath("/p1", "p2", "p3"), "/p1/p2/p3"); - Assert.assertEquals(CommonUtils.joiningPath("/p1", "p2", "p3/"), "/p1/p2/p3/"); - Assert.assertEquals(CommonUtils.joiningPath("p1", "p2", "p3/"), "/p1/p2/p3/"); - } - - - -} diff --git a/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/ResourceUtilsTest.java b/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/ResourceUtilsTest.java deleted file mode 100644 index 1f2f6d1..0000000 --- a/springboot-plugin-framework/src/test/java/com/gitee/starblues/utils/ResourceUtilsTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.gitee.starblues.utils; - - -import org.junit.Assert; -import org.junit.Test; - -/** - * @author starBlues - * @version 2.3.4 - * @since 2021-06-01 - */ -public class ResourceUtilsTest { - - @Test - public void test(){ - String locationMatch = "file:C:\\Users\\Desktop\\plugin1-log.xml"; - String matchLocation = ResourceUtils.getMatchLocation(locationMatch); - Assert.assertEquals("C:\\Users\\Desktop\\plugin1-log.xml", - matchLocation); - - locationMatch = "classpath:C:\\Users\\Desktop\\plugin1-log.xml"; - matchLocation = ResourceUtils.getMatchLocation(locationMatch); - Assert.assertEquals("C:\\Users\\Desktop\\plugin1-log.xml", - matchLocation); - - locationMatch = "package:com.test.aa"; - matchLocation = ResourceUtils.getMatchLocation(locationMatch); - Assert.assertEquals("com/test/aa", - matchLocation); - - - } - -} \ No newline at end of file diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java index fdaa348..bb9b90a 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -21,6 +21,7 @@ import com.gitee.starblues.plugin.pack.filter.ExcludeFilter; import com.gitee.starblues.plugin.pack.filter.Include; import com.gitee.starblues.plugin.pack.filter.IncludeFilter; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.maven.artifact.Artifact; @@ -69,10 +70,10 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { for (ArtifactsFilter additionalFilter : additionalFilters) { filters.addFilter(additionalFilter); } - if (!CommonUtils.isEmpty(includes)) { + if (!ObjectUtils.isEmpty(includes)) { filters.addFilter(new IncludeFilter(this.includes)); } - if(CommonUtils.isEmpty(excludes)){ + if(ObjectUtils.isEmpty(excludes)){ excludes = new ArrayList<>(); } // 添加主框架排除 @@ -84,7 +85,7 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { } private void addPluginFrameworkExclude(){ - excludes.add(Exclude.get("com.gitee.starblues", "springboot-plugin-framework")); + excludes.add(CommonUtils.getPluginFrameworkExclude()); } private void addSpringWebEnvExclude(){ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java index 54aaef2..fa13196 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java @@ -49,7 +49,7 @@ public abstract class AbstractPackagerMojo extends AbstractDependencyFilterMojo{ @Parameter(property = "springboot-plugin.skip", defaultValue = "false") private boolean skip; - @Parameter(property = "springboot-plugin.pluginInfo", required = true) + @Parameter(property = "springboot-plugin.pluginInfo") private PluginInfo pluginInfo; @Parameter(property = "springboot-plugin.loadMainResourcePattern", required = false) @@ -65,40 +65,21 @@ public abstract class AbstractPackagerMojo extends AbstractDependencyFilterMojo{ getLog().debug("skipping plugin package."); return; } - checkPluginInfo(); pack(); } + /** + * 打包 + * @throws MojoExecutionException MojoExecutionException + * @throws MojoFailureException MojoFailureException + */ protected abstract void pack() throws MojoExecutionException, MojoFailureException; - public final Set getDependencies() throws MojoExecutionException { + public final Set getFilterDependencies() throws MojoExecutionException { return filterDependencies(project.getArtifacts(), getFilters()); } - private void checkPluginInfo() throws MojoExecutionException { - if(pluginInfo == null){ - throw new MojoExecutionException("configuration.pluginInfo config cannot be empty"); - } - if(CommonUtils.isEmpty(pluginInfo.getId())){ - throw new MojoExecutionException("configuration.pluginInfo.id config cannot be empty"); - } else { - String id = pluginInfo.getId(); - String illegal = PackageStructure.getIllegal(id); - if(illegal != null){ - throw new MojoExecutionException("configuration.pluginInfo.id config can't contain: " + illegal); - } - } - if(CommonUtils.isEmpty(pluginInfo.getBootstrapClass())){ - throw new MojoExecutionException("configuration.pluginInfo.bootstrapClass config cannot be empty"); - } - if(CommonUtils.isEmpty(pluginInfo.getVersion())){ - throw new MojoExecutionException("configuration.pluginInfo.version config cannot be empty"); - } else { - String version = pluginInfo.getVersion(); - String illegal = PackageStructure.getIllegal(version); - if(illegal != null){ - throw new MojoExecutionException("configuration.pluginInfo.version config can't contain: " + illegal); - } - } + public final Set getSourceDependencies() throws MojoExecutionException { + return project.getArtifacts(); } } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index ee4a5ff..c0ecb42 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -17,9 +17,12 @@ package com.gitee.starblues.plugin.pack; import com.gitee.starblues.common.AbstractDependencyPlugin; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.plugin.pack.dev.DevConfig; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; +import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; @@ -38,15 +41,12 @@ import java.util.jar.Manifest; import static com.gitee.starblues.common.PackageStructure.*; import static com.gitee.starblues.common.PluginDescriptorKey.*; -import static com.gitee.starblues.plugin.pack.utils.CommonUtils.isEmpty; -import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; /** * 基础打包 * @author starBlues * @version 3.0.0 */ - public class BasicRepackager implements Repackager{ @Getter @@ -64,6 +64,7 @@ public class BasicRepackager implements Repackager{ @Override public void repackage() throws MojoExecutionException, MojoFailureException { + checkPluginInfo(); rootDir = createRootDir(); relativeManifestPath = getRelativeManifestPath(); relativeResourcesDefinePath = getRelativeResourcesDefinePath(); @@ -76,6 +77,34 @@ public class BasicRepackager implements Repackager{ } } + private void checkPluginInfo() throws MojoExecutionException { + PluginInfo pluginInfo = repackageMojo.getPluginInfo(); + if(pluginInfo == null){ + throw new MojoExecutionException("configuration.pluginInfo config cannot be empty"); + } + if(ObjectUtils.isEmpty(pluginInfo.getId())){ + throw new MojoExecutionException("configuration.pluginInfo.id config cannot be empty"); + } else { + String id = pluginInfo.getId(); + String illegal = PackageStructure.getIllegal(id); + if(illegal != null){ + throw new MojoExecutionException("configuration.pluginInfo.id config can't contain: " + illegal); + } + } + if(ObjectUtils.isEmpty(pluginInfo.getBootstrapClass())){ + throw new MojoExecutionException("configuration.pluginInfo.bootstrapClass config cannot be empty"); + } + if(ObjectUtils.isEmpty(pluginInfo.getVersion())){ + throw new MojoExecutionException("configuration.pluginInfo.version config cannot be empty"); + } else { + String version = pluginInfo.getVersion(); + String illegal = PackageStructure.getIllegal(version); + if(illegal != null){ + throw new MojoExecutionException("configuration.pluginInfo.version config can't contain: " + illegal); + } + } + } + protected String getRelativeManifestPath(){ return MANIFEST; } @@ -91,16 +120,16 @@ public class BasicRepackager implements Repackager{ if(rootDir.mkdir()){ return rootDirPath; } - throw new MojoFailureException("创建插件根目录失败. " + rootDirPath); + throw new MojoFailureException("Failed to create the plugin root directory. " + rootDirPath); } protected String getBasicRootDir(){ File outputDirectory = repackageMojo.getOutputDirectory(); - return joinPath(outputDirectory.getPath(), PackageStructure.META_INF_NAME); + return FilesUtils.joiningFilePath(outputDirectory.getPath(), PackageStructure.META_INF_NAME); } protected void writeManifest(Manifest manifest) throws Exception { - String manifestPath = CommonUtils.joinPath(rootDir, resolvePath(this.relativeManifestPath)); + String manifestPath = FilesUtils.joiningFilePath(rootDir, resolvePath(this.relativeManifestPath)); File file = new File(manifestPath); FileOutputStream outputStream = null; try { @@ -124,38 +153,38 @@ public class BasicRepackager implements Repackager{ PluginInfo pluginInfo = repackageMojo.getPluginInfo(); Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); - attributes.putValue("Manifest-Version", "1.0"); + attributes.putValue(ManifestKey.MANIFEST_VERSION, ManifestKey.MANIFEST_VERSION_1_0); attributes.putValue(PLUGIN_ID, pluginInfo.getId()); attributes.putValue(PLUGIN_BOOTSTRAP_CLASS, pluginInfo.getBootstrapClass()); attributes.putValue(PLUGIN_VERSION, pluginInfo.getVersion()); attributes.putValue(PLUGIN_PATH, getPluginPath()); String resourcesDefineFilePath = writeResourcesDefineFile(); - if(!CommonUtils.isEmpty(resourcesDefineFilePath)){ + if(!ObjectUtils.isEmpty(resourcesDefineFilePath)){ attributes.putValue(PLUGIN_RESOURCES_CONFIG, resourcesDefineFilePath); } String configFileName = pluginInfo.getConfigFileName(); - if(!isEmpty(configFileName)){ + if(!ObjectUtils.isEmpty(configFileName)){ attributes.putValue(PLUGIN_CONFIG_FILE_NAME, configFileName); } String provider = pluginInfo.getProvider(); - if(!isEmpty(provider)){ + if(!ObjectUtils.isEmpty(provider)){ attributes.putValue(PLUGIN_PROVIDER, provider); } String requires = pluginInfo.getRequires(); - if(!isEmpty(requires)){ + if(!ObjectUtils.isEmpty(requires)){ attributes.putValue(PLUGIN_REQUIRES, requires); } String dependencyPlugins = getDependencyPlugin(pluginInfo); - if(!isEmpty(dependencyPlugins)){ + if(!ObjectUtils.isEmpty(dependencyPlugins)){ attributes.putValue(PLUGIN_DEPENDENCIES, dependencyPlugins); } String description = pluginInfo.getDescription(); - if(!isEmpty(description)){ + if(!ObjectUtils.isEmpty(description)){ attributes.putValue(PLUGIN_DESCRIPTION, description); } String license = pluginInfo.getLicense(); - if(!isEmpty(license)){ + if(!ObjectUtils.isEmpty(license)){ attributes.putValue(PLUGIN_LICENSE, license); } return manifest; @@ -168,7 +197,7 @@ public class BasicRepackager implements Repackager{ protected String getPluginPath(){ DevConfig devConfig = repackageMojo.getDevConfig(); - if(devConfig != null && !isEmpty(devConfig.getPluginPath())){ + if(devConfig != null && !ObjectUtils.isEmpty(devConfig.getPluginPath())){ return devConfig.getPluginPath(); } return repackageMojo.getProject().getBuild().getOutputDirectory(); @@ -182,7 +211,7 @@ public class BasicRepackager implements Repackager{ } protected File createResourcesDefineFile() throws IOException { - String path = joinPath(rootDir, resolvePath(relativeResourcesDefinePath)); + String path = FilesUtils.joiningFilePath(rootDir, resolvePath(relativeResourcesDefinePath)); try { File file = new File(path); FileUtils.forceMkdirParent(file); @@ -207,7 +236,7 @@ public class BasicRepackager implements Repackager{ } protected Set getDependenciesIndexSet() throws Exception { - Set dependencies = repackageMojo.getDependencies(); + Set dependencies = repackageMojo.getFilterDependencies(); Set libPaths = new HashSet<>(dependencies.size()); for (Artifact artifact : dependencies) { if(filterArtifact(artifact)){ @@ -224,7 +253,7 @@ public class BasicRepackager implements Repackager{ protected void writeLoadMainResources() throws Exception { String loadMainResources = getLoadMainResources(); - if(CommonUtils.isEmpty(loadMainResources)){ + if(ObjectUtils.isEmpty(loadMainResources)){ return; } FileUtils.write(resourcesDefineFile, loadMainResources, CHARSET_NAME, true); @@ -244,13 +273,13 @@ public class BasicRepackager implements Repackager{ } private void addLoadMainResources(StringBuilder stringBuilder, String header, String[] patterns){ - if(CommonUtils.isEmpty(patterns)){ + if(ObjectUtils.isEmpty(patterns)){ return; } Set patternSet = new HashSet<>(Arrays.asList(patterns)); stringBuilder.append(header).append("\n"); for (String patternStr : patternSet) { - if(CommonUtils.isEmpty(patternStr)){ + if(ObjectUtils.isEmpty(patternStr)){ continue; } stringBuilder.append(resolvePattern(patternStr)).append("\n"); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java index 937ccfe..a605e43 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -28,6 +28,7 @@ public class Constant { public static final String SCOPE_COMPILE = "compile"; public static final String SCOPE_TEST = "test"; + public static final String MODE_MAIN = "main"; public static final String MODE_DEV = "dev"; public static final String MODE_PROD = "prod"; @@ -35,6 +36,10 @@ public class Constant { public static final String PACKAGE_TYPE_ZIP = "zip"; public static final String PACKAGE_TYPE_DIR = "dir"; + public static final String MAIN_PACKAGE_TYPE_JAR_NEST = "jar-nest"; + public static final String MAIN_PACKAGE_TYPE_JAR_OUTER = "jar-outer"; + public static final String MAIN_PACKAGE_TYPE_WAR = "jar-war"; + public static boolean isPom(String packageType){ return PACKAGING_POM.equalsIgnoreCase(packageType); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java index 6ea075e..614828e 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java @@ -16,10 +16,14 @@ package com.gitee.starblues.plugin.pack; +import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.plugin.pack.dev.DevConfig; import com.gitee.starblues.plugin.pack.dev.DevRepackager; +import com.gitee.starblues.plugin.pack.main.MainConfig; +import com.gitee.starblues.plugin.pack.main.MainRepackager; import com.gitee.starblues.plugin.pack.prod.ProdConfig; import com.gitee.starblues.plugin.pack.prod.ProdRepackager; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; import lombok.Getter; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -45,14 +49,18 @@ public class RepackageMojo extends AbstractPackagerMojo { @Parameter(property = "springboot-plugin.prodConfig") private ProdConfig prodConfig; + @Parameter(property = "springboot-plugin.mainConfig") + private MainConfig mainConfig; + @Override protected void pack() throws MojoExecutionException, MojoFailureException { String mode = getMode(); - if(Constant.MODE_PROD.equalsIgnoreCase(mode)){ new ProdRepackager(this).repackage(); } else if(Constant.MODE_DEV.equalsIgnoreCase(mode)){ new DevRepackager(this).repackage(); + } else if(Constant.MODE_MAIN.equalsIgnoreCase(mode)){ + new MainRepackager(this).repackage(); } else { throw new MojoExecutionException(mode +" model not supported, mode support : " + Constant.MODE_DEV + "/" + Constant.MODE_PROD); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java index fb8ab53..cb28cda 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java @@ -19,6 +19,7 @@ package com.gitee.starblues.plugin.pack.dev; import com.gitee.starblues.plugin.pack.BasicRepackager; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; @@ -56,7 +57,7 @@ public class DevRepackager extends BasicRepackager { } String moduleDependencyKey = getModuleDependencyKey(artifact.getGroupId(), artifact.getArtifactId()); Dependency dependency = moduleDependencies.get(moduleDependencyKey); - return dependency != null && !CommonUtils.isEmpty(dependency.getClassesPath()); + return dependency != null && !ObjectUtils.isEmpty(dependency.getClassesPath()); } protected Map getModuleDependencies(DevConfig devConfig) { @@ -64,7 +65,7 @@ public class DevRepackager extends BasicRepackager { return Collections.emptyMap(); } List moduleDependencies = devConfig.getModuleDependencies(); - if(CommonUtils.isEmpty(moduleDependencies)){ + if(ObjectUtils.isEmpty(moduleDependencies)){ return Collections.emptyMap(); } Map moduleDependenciesMap = new HashMap<>(); @@ -80,7 +81,7 @@ public class DevRepackager extends BasicRepackager { } protected String getModuleDependencyKey(String groupId, String artifactId){ - if(CommonUtils.isEmpty(groupId) || CommonUtils.isEmpty(artifactId)){ + if(ObjectUtils.isEmpty(groupId) || ObjectUtils.isEmpty(artifactId)){ return null; } return groupId + artifactId; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java index 3d2daba..0b9405c 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java @@ -17,6 +17,7 @@ package com.gitee.starblues.plugin.pack.filter; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; @@ -40,7 +41,7 @@ public abstract class DependencyFilter extends AbstractArtifactsFilter { @Override public Set filter(Set artifacts) throws ArtifactFilterException { - if(CommonUtils.isEmpty(artifacts)){ + if(ObjectUtils.isEmpty(artifacts)){ return artifacts; } Set result = new HashSet<>(); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java new file mode 100644 index 0000000..254b31a --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java @@ -0,0 +1,122 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.main; + +import com.gitee.starblues.common.Constants; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.plugin.pack.Constant; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.Repackager; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.plugin.pack.utils.PackageJar; +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.io.IOUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.File; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PackageStructure.*; +import static com.gitee.starblues.common.ManifestKey.*; + +/** + * 嵌套jar打包 + * @author starBlues + * @version 3.0.0 + */ +public class JarNestPackager implements Repackager { + + protected final MainConfig mainConfig; + protected final RepackageMojo repackageMojo; + + private PackageJar packageJar; + + public JarNestPackager(MainRepackager mainRepackager) { + this.mainConfig = mainRepackager.getMainConfig(); + this.repackageMojo = mainRepackager.getRepackageMojo(); + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + try { + packageJar = new PackageJar(mainConfig.getOutputDirectory(), mainConfig.getFileName()); + writeClasses(); + writeDependencies(); + writeManifest(); + } catch (Exception e) { + repackageMojo.getLog().error(e.getMessage(), e); + throw new MojoFailureException(e); + } finally { + if(packageJar != null){ + IOUtils.closeQuietly(packageJar); + } + } + } + + protected void writeManifest() throws Exception { + Manifest manifest = getManifest(); + packageJar.putDirEntry(META_INF_NAME + SEPARATOR); + packageJar.write(PROD_MANIFEST_PATH, manifest::write); + } + + protected Manifest getManifest() throws Exception{ + Manifest manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue(MANIFEST_VERSION, MANIFEST_VERSION_1_0); + attributes.putValue(START_CLASS, mainConfig.getMainClass()); + attributes.putValue(MAIN_CLASS, MAIN_CLASS_VALUE); + return manifest; + } + + protected void writeClasses() throws Exception { + String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); + packageJar.copyDirToPackage(new File(buildDir), null); + } + + protected void writeDependencies() throws Exception { + Set dependencies = repackageMojo.getSourceDependencies(); + String libDirEntryName = createLibEntry(); + for (Artifact artifact : dependencies) { + if(filterArtifact(artifact)){ + continue; + } + if(CommonUtils.isPluginFrameworkLoader(artifact)){ + // 本框架依赖 + packageJar.copyZipToPackage(artifact.getFile()); + } else { + packageJar.writeDependency(artifact.getFile(), libDirEntryName); + } + } + } + + protected boolean filterArtifact(Artifact artifact) { + return Constant.scopeFilter(artifact.getScope()); + } + + protected String createLibEntry() throws Exception { + String libDirEntryName = PROD_LIB_PATH; + packageJar.putDirEntry(libDirEntryName); + return libDirEntryName; + } + + + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java new file mode 100644 index 0000000..77bfc87 --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java @@ -0,0 +1,52 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.main; + + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * 主程序打包配置 + * @author starBlues + * @version 3.0.0 + */ +@Data +public class MainConfig { + + /** + * 主启动类 + */ + @Parameter(required = true) + private String mainClass; + + /** + * 打包类型。默认:jar-nest + */ + private String packageType; + + /** + * 文件名称。默认 artifactId-version-repackage + */ + private String fileName; + + /** + * 输出文件目录。默认target + */ + private String outputDirectory; + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java new file mode 100644 index 0000000..0381712 --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java @@ -0,0 +1,79 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.main; + +import com.gitee.starblues.plugin.pack.Constant; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.Repackager; +import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; +import lombok.Getter; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.project.MavenProject; + +/** + * 主程序打包 + * @author starBlues + * @version 3.0.0 + */ +@Getter +public class MainRepackager implements Repackager { + + private final RepackageMojo repackageMojo; + private final MainConfig mainConfig; + + public MainRepackager(RepackageMojo repackageMojo) { + this.repackageMojo = repackageMojo; + this.mainConfig = repackageMojo.getMainConfig(); + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + checkConfig(); + String packageType = mainConfig.getPackageType(); + if(Constant.MAIN_PACKAGE_TYPE_JAR_NEST.equalsIgnoreCase(packageType)){ + new JarNestPackager(this).repackage(); + } else { + throw new MojoFailureException("Not found packageType : " + packageType); + } + } + + private void checkConfig() throws MojoFailureException { + if(mainConfig == null){ + throw new MojoFailureException("configuration.mainConfig config cannot be empty"); + } + if(ObjectUtils.isEmpty(mainConfig.getMainClass())) { + throw new MojoFailureException("configuration.mainConfig.mainClass config cannot be empty"); + } + String fileName = mainConfig.getFileName(); + if(ObjectUtils.isEmpty(fileName)) { + MavenProject project = repackageMojo.getProject(); + mainConfig.setFileName(project.getArtifactId() + "-" + project.getVersion() + "-repackage"); + } + String packageType = mainConfig.getPackageType(); + if(ObjectUtils.isEmpty(packageType)) { + mainConfig.setPackageType(Constant.MAIN_PACKAGE_TYPE_JAR_NEST); + } + String outputDirectory = mainConfig.getOutputDirectory(); + if(ObjectUtils.isEmpty(outputDirectory)){ + mainConfig.setOutputDirectory(repackageMojo.getOutputDirectory().getPath()); + } + } + + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java index a0a474d..835ec1e 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java @@ -21,6 +21,7 @@ import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.dev.DevRepackager; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; @@ -64,7 +65,7 @@ public class DirProdRepackager extends DevRepackager { @Override protected String createRootDir() throws MojoFailureException { String fileName = prodConfig.getFileName(); - String dirPath = CommonUtils.joinPath(prodConfig.getOutputDirectory(), fileName); + String dirPath = FilesUtils.joiningFilePath(prodConfig.getOutputDirectory(), fileName); File dirFile = new File(dirPath); if(dirFile.exists() && dirFile.isFile()){ int i = 0; @@ -86,12 +87,12 @@ public class DirProdRepackager extends DevRepackager { @Override protected String getRelativeManifestPath() { - return CommonUtils.joinPath(META_INF_NAME, MANIFEST); + return FilesUtils.joiningFilePath(META_INF_NAME, MANIFEST); } @Override protected String getRelativeResourcesDefinePath() { - return CommonUtils.joinPath(META_INF_NAME, RESOURCES_DEFINE_NAME); + return FilesUtils.joiningFilePath(META_INF_NAME, RESOURCES_DEFINE_NAME); } @Override @@ -105,7 +106,7 @@ public class DirProdRepackager extends DevRepackager { protected void resolveClasses() throws Exception { String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); - String path = CommonUtils.joinPath(getRootDir(), CLASSES_NAME); + String path = FilesUtils.joiningFilePath(getRootDir(), CLASSES_NAME); File file = new File(path); FileUtils.forceMkdir(file); FileUtils.copyDirectory(new File(buildDir), file); @@ -113,7 +114,7 @@ public class DirProdRepackager extends DevRepackager { @Override protected Set getDependenciesIndexSet() throws Exception { - Set dependencies = repackageMojo.getDependencies(); + Set dependencies = repackageMojo.getFilterDependencies(); String libDir = createLibDir(); Set dependencyIndexNames = new HashSet<>(dependencies.size()); for (Artifact artifact : dependencies) { @@ -121,14 +122,14 @@ public class DirProdRepackager extends DevRepackager { continue; } File artifactFile = artifact.getFile(); - FileUtils.copyFile(artifactFile, new File(CommonUtils.joinPath(libDir, artifactFile.getName()))); + FileUtils.copyFile(artifactFile, new File(FilesUtils.joiningFilePath(libDir, artifactFile.getName()))); dependencyIndexNames.add(PackageStructure.PROD_LIB_PATH + artifactFile.getName()); } return dependencyIndexNames; } protected String createLibDir() throws IOException { - String dir = CommonUtils.joinPath(getRootDir(), PackageStructure.LIB_NAME); + String dir = FilesUtils.joiningFilePath(getRootDir(), PackageStructure.LIB_NAME); File file = new File(dir); if(file.mkdir()){ return dir; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java index 4f022ed..56648b3 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java @@ -17,6 +17,8 @@ package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.utils.PackageJar; +import com.gitee.starblues.plugin.pack.utils.PackageZip; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.jar.JarArchiveEntry; import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream; @@ -44,17 +46,7 @@ public class JarProdRepackager extends ZipProdRepackager { } @Override - protected String getPackageFileSuffix() { - return "jar"; - } - - @Override - protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { - return new JarArchiveOutputStream(new FileOutputStream(packFile)); - } - - @Override - protected ZipArchiveEntry getArchiveEntry(String name) { - return new JarArchiveEntry(name); + protected PackageZip getPackageZip() throws Exception { + return new PackageJar(prodConfig.getOutputDirectory(), prodConfig.getFileName()); } } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java index 76cbd35..5a7bb31 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java @@ -28,7 +28,6 @@ import org.apache.maven.plugins.annotations.Parameter; @Data public class ProdConfig { - /** * 打包类型。默认jar包 */ @@ -36,7 +35,7 @@ public class ProdConfig { private String packageType = "jar"; /** - * 文件名称。默认 pluginId-version.jar + * 文件名称。默认 pluginId-version-repackage */ private String fileName; @@ -45,15 +44,4 @@ public class ProdConfig { */ private String outputDirectory; - /** - * 是否将依赖导入包中. 默认打入 - */ - @Parameter(required = true, defaultValue = "true") - private Boolean includeDependencies = true; - - /** - * 生成环境依赖包的路径。默认 lib - */ - private String libPath; - } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java index cda85fc..2f85566 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java @@ -16,13 +16,13 @@ package com.gitee.starblues.plugin.pack.prod; -import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.PluginInfo; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.Repackager; import com.gitee.starblues.plugin.pack.dev.DevRepackager; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -52,6 +52,7 @@ public class ProdRepackager implements Repackager { this.prodConfig = getProdConfig(repackageMojo); String packageType = prodConfig.getPackageType(); Repackager repackager = null; + if(Constant.PACKAGE_TYPE_ZIP.equalsIgnoreCase(packageType)){ // jar repackager = new ZipProdRepackager(repackageMojo, prodConfig); @@ -60,38 +61,31 @@ public class ProdRepackager implements Repackager { } else if(Constant.PACKAGE_TYPE_DIR.equalsIgnoreCase(packageType)){ repackager = new DirProdRepackager(repackageMojo, prodConfig); } else { - throw new MojoFailureException("Not found packageType:" + packageType); + throw new MojoFailureException("Not found packageType : " + packageType); } repackager.repackage(); } - protected ProdConfig getProdConfig(RepackageMojo repackageMojo){ ProdConfig prodConfig = repackageMojo.getProdConfig(); if(prodConfig == null){ prodConfig = new ProdConfig(); } - if(CommonUtils.isEmpty(prodConfig.getPackageType())){ + if(ObjectUtils.isEmpty(prodConfig.getPackageType())){ prodConfig.setPackageType(Constant.PACKAGE_TYPE_JAR); } String fileName = prodConfig.getFileName(); - if(CommonUtils.isEmpty(fileName)) { + if(ObjectUtils.isEmpty(fileName)) { PluginInfo pluginInfo = repackageMojo.getPluginInfo(); - prodConfig.setFileName(pluginInfo.getId() + "-" + pluginInfo.getVersion()); + prodConfig.setFileName(pluginInfo.getId() + "-" + pluginInfo.getVersion() + "-repackage"); } String outputDirectory = prodConfig.getOutputDirectory(); - if(CommonUtils.isEmpty(outputDirectory)){ + if(ObjectUtils.isEmpty(outputDirectory)){ prodConfig.setOutputDirectory(repackageMojo.getOutputDirectory().getPath()); } - Boolean includeDependencies = prodConfig.getIncludeDependencies(); - if(includeDependencies == null){ - prodConfig.setIncludeDependencies(true); - } - String libPath = prodConfig.getLibPath(); - if(CommonUtils.isEmpty(libPath)){ - prodConfig.setLibPath(PackageStructure.LIB_NAME); - } return prodConfig; } + + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java index ca3fb0f..35432e9 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -22,12 +22,10 @@ import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.dev.Dependency; import com.gitee.starblues.plugin.pack.dev.DevConfig; import com.gitee.starblues.plugin.pack.dev.DevRepackager; -import com.gitee.starblues.plugin.pack.utils.CommonUtils; -import org.apache.commons.compress.archivers.ArchiveEntry; +import com.gitee.starblues.plugin.pack.utils.PackageZip; +import com.gitee.starblues.utils.FilesUtils; +import com.gitee.starblues.utils.ObjectUtils; import org.apache.commons.compress.archivers.ArchiveOutputStream; -import org.apache.commons.compress.archivers.jar.JarArchiveEntry; -import org.apache.commons.compress.archivers.zip.UnixStat; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -35,17 +33,16 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.jar.Attributes; import java.util.jar.Manifest; -import java.util.zip.CRC32; -import java.util.zip.ZipEntry; import static com.gitee.starblues.common.PackageStructure.*; -import static com.gitee.starblues.plugin.pack.Constant.SCOPE_PROVIDED; -import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; /** * zip 打包 @@ -54,13 +51,10 @@ import static com.gitee.starblues.plugin.pack.utils.CommonUtils.joinPath; */ public class ZipProdRepackager extends DevRepackager { - private static final int UNIX_FILE_MODE = UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM; - - private static final int UNIX_DIR_MODE = UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM; protected final ProdConfig prodConfig; - protected ArchiveOutputStream outputStream; + protected PackageZip packageZip; public ZipProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { super(repackageMojo); @@ -69,63 +63,31 @@ public class ZipProdRepackager extends DevRepackager { @Override public void repackage() throws MojoExecutionException, MojoFailureException { - File packageFile = getPackageFile(); try { - outputStream = getOutputStream(packageFile); + packageZip = getPackageZip(); super.repackage(); resolveClasses(); resolveResourcesDefine(); - outputStream.finish(); String rootDir = getRootDir(); try { FileUtils.deleteDirectory(new File(rootDir)); } catch (IOException e) { // 忽略 } - repackageMojo.getLog().info("Success package prod zip file : " + packageFile.getPath()); + repackageMojo.getLog().info("Success package prod zip file : " + + packageZip.getFile().getPath()); } catch (Exception e){ repackageMojo.getLog().error(e.getMessage(), e); throw new MojoFailureException(e); } finally { - if(outputStream != null){ - IOUtils.closeQuietly(outputStream); - } - } - } - - protected File getPackageFile() throws MojoFailureException { - String fileSuffix = getPackageFileSuffix(); - String path = getPackageFilePath(); - File file = new File(path + "." + fileSuffix); - - if(file.exists()){ - int i = 0; - while (true){ - file = new File(path + "_" + i + "." + fileSuffix); - if(file.exists()){ - i = i + 1; - continue; - } - break; + if(packageZip != null){ + IOUtils.closeQuietly(packageZip); } } - try { - if(file.createNewFile()){ - return file; - } - throw new IOException("Create file '" + file.getPath() + "' failure."); - } catch (IOException e) { - repackageMojo.getLog().error(e.getMessage(), e); - throw new MojoFailureException("Create prod package file failure"); - } - } - - protected String getPackageFileSuffix(){ - return "zip"; } - protected String getPackageFilePath(){ - return CommonUtils.joinPath(prodConfig.getOutputDirectory(), prodConfig.getFileName()); + protected PackageZip getPackageZip() throws Exception { + return new PackageZip(prodConfig.getOutputDirectory(), prodConfig.getFileName()); } protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { @@ -135,7 +97,7 @@ public class ZipProdRepackager extends DevRepackager { @Override protected String getBasicRootDir(){ File outputDirectory = repackageMojo.getOutputDirectory(); - return joinPath(outputDirectory.getPath(), UUID.randomUUID().toString()); + return FilesUtils.joiningFilePath(outputDirectory.getPath(), UUID.randomUUID().toString()); } @Override @@ -161,7 +123,7 @@ public class ZipProdRepackager extends DevRepackager { protected void resolveClasses() throws Exception { String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); - copyFileToPackage(new File(buildDir), ""); + packageZip.copyDirToPackage(new File(buildDir), null); } @Override @@ -175,10 +137,8 @@ public class ZipProdRepackager extends DevRepackager { @Override protected void writeManifest(Manifest manifest) throws Exception { - putDirEntry(META_INF_NAME + SEPARATOR); - outputStream.putArchiveEntry(getArchiveEntry(PROD_MANIFEST_PATH)); - manifest.write(outputStream); - outputStream.closeArchiveEntry(); + packageZip.putDirEntry(META_INF_NAME + SEPARATOR); + packageZip.write(PROD_MANIFEST_PATH, manifest::write); } protected void resolveResourcesDefine() throws Exception{ @@ -189,24 +149,24 @@ public class ZipProdRepackager extends DevRepackager { content.append(dependencyIndexName).append("\n"); } String loadMainResources = super.getLoadMainResources(); - if(!CommonUtils.isEmpty(loadMainResources)){ + if(!ObjectUtils.isEmpty(loadMainResources)){ content.append(loadMainResources).append("\n"); } final byte[] bytes = content.toString().getBytes(StandardCharsets.UTF_8); try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)){ - putInputStreamEntry(byteArrayInputStream, PROD_RESOURCES_DEFINE_PATH); + packageZip.putInputStreamEntry(byteArrayInputStream, PROD_RESOURCES_DEFINE_PATH); } } protected Set resolveDependencies() throws Exception { - Set dependencies = repackageMojo.getDependencies(); + Set dependencies = repackageMojo.getFilterDependencies(); String libDirEntryName = createLibEntry(); Set dependencyIndexNames = new HashSet<>(dependencies.size()); for (Artifact artifact : dependencies) { if(filterArtifact(artifact)){ continue; } - String dependencyIndexName = writeDependency(artifact.getFile(), libDirEntryName, outputStream); + String dependencyIndexName = packageZip.writeDependency(artifact.getFile(), libDirEntryName); dependencyIndexNames.add(dependencyIndexName); } return dependencyIndexNames; @@ -214,99 +174,8 @@ public class ZipProdRepackager extends DevRepackager { protected String createLibEntry() throws Exception { String libDirEntryName = PROD_LIB_PATH; - putDirEntry(libDirEntryName); + packageZip.putDirEntry(libDirEntryName); return libDirEntryName; } - protected String writeDependency(File dependencyFile, String libDirEntryName, - ArchiveOutputStream outputStream) throws Exception { - String indexName = libDirEntryName + dependencyFile.getName(); - ZipArchiveEntry entry = getArchiveEntry(indexName); - entry.setTime(System.currentTimeMillis()); - entry.setUnixMode(indexName.endsWith("/") ? UNIX_DIR_MODE : UNIX_FILE_MODE); - entry.getGeneralPurposeBit().useUTF8ForNames(true); - try(FileInputStream inputStream = new FileInputStream(dependencyFile)){ - new CrcAndSize(inputStream).setupStoredEntry(entry); - } - try (FileInputStream inputStream = new FileInputStream(dependencyFile)){ - outputStream.putArchiveEntry(entry); - IOUtils.copy(inputStream, outputStream); - outputStream.closeArchiveEntry(); - } - return indexName; - } - - protected void copyFileToPackage(File file, String rootDir) throws Exception { - if(CommonUtils.isEmpty(rootDir)){ - rootDir = file.getName(); - } - if (file.isDirectory()) { - File[] childFiles = file.listFiles(); - rootDir = rootDir + "/"; - putDirEntry(rootDir); - if(childFiles == null){ - return; - } - for (File childFile : childFiles) { - copyFileToPackage(childFile, rootDir + childFile.getName()); - } - } else { - putFileEntry(file, rootDir); - } - } - - protected void putFileEntry(File destFile, String rootDir) throws Exception { - if(!destFile.exists()){ - throw new FileNotFoundException("Not found file : " + destFile.getPath()); - } - outputStream.putArchiveEntry(getArchiveEntry(rootDir)); - FileUtils.copyFile(destFile, outputStream); - outputStream.closeArchiveEntry(); - } - - protected void putInputStreamEntry(InputStream inputStream, String name) throws Exception { - outputStream.putArchiveEntry(getArchiveEntry(name)); - IOUtils.copy(inputStream, outputStream); - outputStream.closeArchiveEntry(); - } - - protected void putDirEntry(String dir) throws IOException { - outputStream.putArchiveEntry(getArchiveEntry(dir)); - outputStream.closeArchiveEntry(); - } - - protected ZipArchiveEntry getArchiveEntry(String name){ - return new ZipArchiveEntry(name); - } - - private static class CrcAndSize { - - private static final int BUFFER_SIZE = 32 * 1024; - - private final CRC32 crc = new CRC32(); - - private long size; - - CrcAndSize(InputStream inputStream) throws IOException { - load(inputStream); - } - - private void load(InputStream inputStream) throws IOException { - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead; - while ((bytesRead = inputStream.read(buffer)) != -1) { - this.crc.update(buffer, 0, bytesRead); - this.size += bytesRead; - } - } - - void setupStoredEntry(ZipArchiveEntry entry) { - entry.setSize(this.size); - entry.setCompressedSize(this.size); - entry.setCrc(this.crc.getValue()); - entry.setMethod(ZipEntry.STORED); - } - - } - } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java index 295f635..f9d7229 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/CommonUtils.java @@ -16,12 +16,10 @@ package com.gitee.starblues.plugin.pack.utils; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.Map; -import java.util.Optional; +import com.gitee.starblues.plugin.pack.filter.Exclude; +import org.apache.maven.artifact.Artifact; + +import java.util.Objects; /** * Object 工具类 @@ -30,85 +28,24 @@ import java.util.Optional; */ public class CommonUtils { + public final static String PLUGIN_FRAMEWORK_GROUP_ID = "com.gitee.starblues"; + public final static String PLUGIN_FRAMEWORK_ARTIFACT_ID = "springboot-plugin-framework"; - private CommonUtils(){} - + public final static String PLUGIN_FRAMEWORK_LOADER_ARTIFACT_ID = "springboot-plugin-framework-loader"; - public static boolean isEmpty(CharSequence cs) { - return cs == null || cs.length() == 0; - } - - public static boolean isEmpty(Object obj) { - if (obj == null) { - return true; - } - - if (obj instanceof Optional) { - return !((Optional) obj).isPresent(); - } - if (obj instanceof CharSequence) { - return ((CharSequence) obj).length() == 0; - } - if (obj.getClass().isArray()) { - return Array.getLength(obj) == 0; - } - if (obj instanceof Collection) { - return ((Collection) obj).isEmpty(); - } - if (obj instanceof Map) { - return ((Map) obj).isEmpty(); - } - return false; - } - - public static boolean hasText(CharSequence str) { - return (str != null && str.length() > 0 && containsText(str)); - } + private CommonUtils(){} - public static boolean hasLength(String str) { - return (str != null && !str.isEmpty()); + public static Exclude getPluginFrameworkExclude(){ + return Exclude.get(PLUGIN_FRAMEWORK_GROUP_ID, PLUGIN_FRAMEWORK_ARTIFACT_ID); } - /** - * 拼接file路径 - * @param paths 拼接的路径 - * @return 拼接的路径 - */ - public static String joinPath(String ...paths){ - if(paths == null || paths.length == 0){ - return ""; - } - StringBuilder stringBuilder = new StringBuilder(); - int length = paths.length; - for (int i = 0; i < length; i++) { - String path = paths[i]; - if(isEmpty(path)) { - continue; - } - if(i > 0){ - if(path.startsWith(File.separator) || path.startsWith("/") || - path.startsWith("\\") || path.startsWith("//")){ - stringBuilder.append(path); - } else { - stringBuilder.append(File.separator).append(path); - } - } else { - stringBuilder.append(path); - } - } - - return stringBuilder.toString(); + public static boolean isPluginFramework(Artifact artifact){ + return Objects.equals(artifact.getGroupId(), PLUGIN_FRAMEWORK_GROUP_ID) + && Objects.equals(artifact.getArtifactId(), PLUGIN_FRAMEWORK_ARTIFACT_ID); } - - 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; + public static boolean isPluginFrameworkLoader(Artifact artifact){ + return Objects.equals(artifact.getGroupId(), PLUGIN_FRAMEWORK_GROUP_ID) + && Objects.equals(artifact.getArtifactId(), PLUGIN_FRAMEWORK_LOADER_ARTIFACT_ID); } - } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageJar.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageJar.java new file mode 100644 index 0000000..d82a8f3 --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageJar.java @@ -0,0 +1,55 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.utils; + +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.compress.archivers.jar.JarArchiveEntry; +import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; + +import java.io.File; +import java.io.FileOutputStream; + +/** + * jar 打包工具 + * @author starBlues + * @version 3.0.0 + */ +public class PackageJar extends PackageZip{ + public PackageJar(File file) throws Exception { + super(file); + } + + public PackageJar(String outputDirectory, String packageName) throws Exception { + super(outputDirectory, packageName); + } + + @Override + protected String getPackageFileSuffix() { + return "jar"; + } + + @Override + protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { + return new JarArchiveOutputStream(new FileOutputStream(packFile)); + } + + @Override + protected ZipArchiveEntry getArchiveEntry(String name) { + return new JarArchiveEntry(name); + } +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java new file mode 100644 index 0000000..154ac4f --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java @@ -0,0 +1,227 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.utils; + +import com.gitee.starblues.utils.FilesUtils; +import com.gitee.starblues.utils.ObjectUtils; +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.util.Enumeration; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; + +/** + * zip 打包工具 + * @author starBlues + * @version 3.0.0 + */ +public class PackageZip implements Closeable{ + + + private static final int UNIX_FILE_MODE = UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM; + + private static final int UNIX_DIR_MODE = UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM; + + private final File file; + private final ArchiveOutputStream outputStream; + + + public PackageZip(File file) throws Exception { + this.file = file; + this.outputStream = getOutputStream(file); + } + + public PackageZip(String outputDirectory, String packageName) throws Exception{ + String rootPath = FilesUtils.joiningFilePath(outputDirectory, packageName); + this.file = getPackageFile(rootPath); + this.outputStream = getOutputStream(file); + + } + + public File getFile(){ + return file; + } + + protected File getPackageFile(String rootPath) throws Exception { + String fileSuffix = getPackageFileSuffix(); + File file = new File(rootPath + "." + fileSuffix); + + if(file.exists()){ + int i = 0; + while (true){ + file = new File(rootPath + "_" + i + "." + fileSuffix); + if(file.exists()){ + i = i + 1; + continue; + } + break; + } + } + if(file.createNewFile()){ + return file; + } + throw new IOException("Create file '" + file.getPath() + "' failure."); + } + + protected String getPackageFileSuffix(){ + return "zip"; + } + + protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { + return new ZipArchiveOutputStream(new FileOutputStream(packFile)); + } + + public void copyDirToPackage(File rootDir, String packageDir) throws Exception { + if(packageDir == null){ + packageDir = rootDir.getName(); + } + if (rootDir.isDirectory()) { + File[] childFiles = rootDir.listFiles(); + if(ObjectUtils.isEmpty(packageDir)){ + packageDir = ""; + } else { + packageDir = packageDir + "/"; + putDirEntry(packageDir); + } + if(childFiles == null){ + return; + } + for (File childFile : childFiles) { + copyDirToPackage(childFile, packageDir + childFile.getName()); + } + } else { + putFileEntry(rootDir, packageDir); + } + } + + public void copyZipToPackage(File sourceZipFile) throws Exception { + if(sourceZipFile == null || !sourceZipFile.exists()){ + return; + } + try (ZipFile zipFile = new ZipFile(sourceZipFile)){ + Enumeration entries = zipFile.getEntries(); + while (entries.hasMoreElements()){ + ZipArchiveEntry zipArchiveEntry = entries.nextElement(); + String name = zipArchiveEntry.getName(); + if(zipArchiveEntry.isDirectory()){ + putDirEntry(name); + } else { + try (InputStream inputStream = zipFile.getInputStream(zipArchiveEntry)){ + putInputStreamEntry(inputStream, name); + } + } + } + } + } + + public String writeDependency(File dependencyFile, String libDirEntryName) throws Exception { + String indexName = libDirEntryName + dependencyFile.getName(); + ZipArchiveEntry entry = getArchiveEntry(indexName); + entry.setTime(System.currentTimeMillis()); + entry.setUnixMode(indexName.endsWith("/") ? UNIX_DIR_MODE : UNIX_FILE_MODE); + entry.getGeneralPurposeBit().useUTF8ForNames(true); + try(FileInputStream inputStream = new FileInputStream(dependencyFile)){ + new CrcAndSize(inputStream).setupStoredEntry(entry); + } + try (FileInputStream inputStream = new FileInputStream(dependencyFile)){ + outputStream.putArchiveEntry(entry); + IOUtils.copy(inputStream, outputStream); + outputStream.closeArchiveEntry(); + } + return indexName; + } + + public void putFileEntry(File destFile, String rootDir) throws Exception { + if(!destFile.exists()){ + throw new FileNotFoundException("Not found file : " + destFile.getPath()); + } + outputStream.putArchiveEntry(getArchiveEntry(rootDir)); + FileUtils.copyFile(destFile, outputStream); + outputStream.closeArchiveEntry(); + } + + public void putInputStreamEntry(InputStream inputStream, String name) throws Exception { + outputStream.putArchiveEntry(getArchiveEntry(name)); + IOUtils.copy(inputStream, outputStream); + outputStream.closeArchiveEntry(); + } + + public void write(String name, Writer writer) throws Exception { + outputStream.putArchiveEntry(getArchiveEntry(name)); + writer.write(outputStream); + outputStream.closeArchiveEntry(); + } + + public void putDirEntry(String dir) throws IOException { + outputStream.putArchiveEntry(getArchiveEntry(dir)); + outputStream.closeArchiveEntry(); + } + + protected ZipArchiveEntry getArchiveEntry(String name){ + return new ZipArchiveEntry(name); + } + + + @Override + public void close() throws IOException { + outputStream.finish(); + outputStream.close(); + } + + private static class CrcAndSize { + + private static final int BUFFER_SIZE = 32 * 1024; + + private final CRC32 crc = new CRC32(); + + private long size; + + CrcAndSize(InputStream inputStream) throws IOException { + load(inputStream); + } + + private void load(InputStream inputStream) throws IOException { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + this.crc.update(buffer, 0, bytesRead); + this.size += bytesRead; + } + } + + void setupStoredEntry(ZipArchiveEntry entry) { + entry.setSize(this.size); + entry.setCompressedSize(this.size); + entry.setCrc(this.crc.getValue()); + entry.setMethod(ZipEntry.STORED); + } + + } + + @FunctionalInterface + public interface Writer{ + void write(ArchiveOutputStream outputStream) throws Exception; + } + +} diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml index 10a23f2..a60b0ff 100644 --- a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml @@ -117,6 +117,14 @@ true prod打包模式配置 + + mainConfig + com.gitee.starblues.plugin.pack.main.MainConfig + 3.0.0 + false + true + main打包模式配置 + @@ -129,6 +137,7 @@ ${springboot-plugin.excludes} + diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml index 10a23f2..a60b0ff 100644 --- a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml @@ -117,6 +117,14 @@ true prod打包模式配置 + + mainConfig + com.gitee.starblues.plugin.pack.main.MainConfig + 3.0.0 + false + true + main打包模式配置 + @@ -129,6 +137,7 @@ ${springboot-plugin.excludes} + -- Gitee From 6196c421cf6dc454d4fdf5eb49f0dd3bf662d43a Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sat, 19 Feb 2022 17:33:54 +0800 Subject: [PATCH 30/37] main jar in jar --- .../classloader/AbstractResourceLoader.java | 26 +++++- .../loader/classloader/ClassPathLoader.java | 17 +++- .../classloader/JarFileResourceLoader.java | 85 ------------------- .../loader/classloader/JarResourceLoader.java | 44 ++++++---- .../classloader/ResourceLoaderFactory.java | 12 +-- .../classloader/filter/ExcludeResource.java | 7 +- .../classloader/filter/IncludeResource.java | 20 +++++ .../loader/launcher/AbstractLauncher.java | 1 - .../launcher/MainJarProgramLauncher.java | 33 ++++--- .../loader/launcher/SpringMainBootstrap.java | 2 + .../launcher/SpringMainProdBootstrap.java | 1 + .../starblues/loader/utils/ResourceUtils.java | 11 +++ .../NestedPluginJarResourceLoader.java | 3 +- .../plugin/pack/main/JarNestPackager.java | 2 +- .../plugin/pack/utils/PackageZip.java | 5 ++ 15 files changed, 139 insertions(+), 130 deletions(-) delete mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java index 4d13a67..4ff1cf9 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java @@ -25,6 +25,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; /** * 抽象的资源加载者 @@ -35,6 +36,8 @@ public abstract class AbstractResourceLoader { private static final String CLASS_FILE_EXTENSION = ".class"; + private boolean isInit = false; + protected final URL baseUrl; private final Map resourceCache = new ConcurrentHashMap<>(); @@ -53,12 +56,27 @@ public abstract class AbstractResourceLoader { * 初始化 resource * @throws Exception 初始异常 */ - public void init() throws Exception{ - // 添加root 路径 - Resource rootResource = new Resource("root", baseUrl, baseUrl); - resourceCache.put("/", rootResource); + public final synchronized void init() throws Exception{ + if(isInit){ + throw new Exception(this.getClass().getName()+": 已经初始化了, 不能再初始化!"); + } + try { + // 添加root 路径 + Resource rootResource = new Resource("root", baseUrl, baseUrl); + resourceCache.put("/", rootResource); + initOfChild(); + } finally { + isInit = true; + } } + /** + * 子类初始化实现 + * @throws Exception 初始异常 + */ + protected void initOfChild() throws Exception{}; + + protected boolean existResource(String name){ return resourceCache.containsKey(name); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java index 3cff944..14277bd 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java @@ -18,7 +18,9 @@ package com.gitee.starblues.loader.classloader; import java.io.File; import java.io.FileInputStream; +import java.net.MalformedURLException; import java.net.URL; +import java.nio.file.Path; import java.util.Objects; /** @@ -28,8 +30,6 @@ import java.util.Objects; */ public class ClassPathLoader extends AbstractResourceLoader{ - - private final URL url; public ClassPathLoader(URL url) { @@ -37,9 +37,18 @@ public class ClassPathLoader extends AbstractResourceLoader{ this.url = Objects.requireNonNull(url, "url 不能为空"); } + public ClassPathLoader(File file) throws MalformedURLException { + this(file.toPath()); + } + + public ClassPathLoader(Path path) throws MalformedURLException { + super(path.toUri().toURL()); + this.url = super.baseUrl; + } + + @Override - public void init() throws Exception { - super.init(); + protected void initOfChild() throws Exception { File file = new File(url.toURI()); load(file, null); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java deleted file mode 100644 index 631c72c..0000000 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarFileResourceLoader.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright [2019-2022] [starBlues] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.gitee.starblues.loader.classloader; - -import com.gitee.starblues.loader.classloader.filter.ExcludeResource; - - -import java.net.URL; -import java.util.function.Function; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; - -/** - * jar 资源加载者 - * @author starBlues - * @version 3.0.0 - */ -public class JarFileResourceLoader extends AbstractResourceLoader{ - - private final JarInputStream jarInputStream; - - private ExcludeResource excludeResource = (name)->false; - - private Function function = name->name; - - public JarFileResourceLoader(URL url) throws Exception{ - super(url); - this.jarInputStream = new JarInputStream(url.openStream()); - } - - public JarFileResourceLoader(URL url, JarInputStream jarInputStream) throws Exception{ - super(url); - this.jarInputStream = jarInputStream; - } - - public void setExcludeResource(ExcludeResource excludeResource) { - if(excludeResource == null){ - return; - } - this.excludeResource = excludeResource; - } - - public void setFunction(Function function) { - this.function = function; - } - - @Override - public void init() throws Exception { - super.init(); - // 解析 - try { - JarEntry jarEntry = null; - while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { - String name = jarEntry.getName(); - name = function.apply(name); - if(excludeResource.exclude(name)){ - continue; - } - URL url = new URL(baseUrl.toString() + name); - Resource resource = new Resource(name, baseUrl, url); - resource.setBytes(getClassBytes(name, jarInputStream, false)); - addResource(name, resource); - jarInputStream.closeEntry(); - } - } finally { - jarInputStream.close(); - } - } - - -} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java index d610d8a..f3fa0ba 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java @@ -17,7 +17,9 @@ package com.gitee.starblues.loader.classloader; import com.gitee.starblues.loader.classloader.filter.ExcludeResource; +import com.gitee.starblues.loader.classloader.filter.IncludeResource; +import java.io.File; import java.net.URL; import java.util.function.Function; import java.util.jar.JarEntry; @@ -32,13 +34,17 @@ public class JarResourceLoader extends AbstractResourceLoader{ private final JarInputStream jarInputStream; - private ExcludeResource excludeResource = (name)->false; + private ExcludeResource excludeResource = (jarEntry)->false; + private IncludeResource includeResource = (jarEntry)->true; - - private Function function = name->name; + public JarResourceLoader(File file) throws Exception{ + super(new URL("jar:" + file.toURI().toURL() + "!/")); + URL url = file.toURI().toURL(); + this.jarInputStream = new JarInputStream(url.openStream()); + } public JarResourceLoader(URL url) throws Exception{ - super(new URL("jar:" + url.toString() + "!/")); + super(url); this.jarInputStream = new JarInputStream(url.openStream()); } @@ -54,32 +60,38 @@ public class JarResourceLoader extends AbstractResourceLoader{ this.excludeResource = excludeResource; } - public void setFunction(Function function) { - this.function = function; + public void setIncludeResource(IncludeResource includeResource) { + if(includeResource == null){ + return; + } + this.includeResource = includeResource; } @Override - public void init() throws Exception { - super.init(); + protected void initOfChild() throws Exception { // 解析 try { JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { - String name = jarEntry.getName(); - name = function.apply(name); - if(excludeResource.exclude(name)){ + if(excludeResource.exclude(jarEntry)){ continue; } - URL url = new URL(baseUrl.toString() + name); - Resource resource = new Resource(name, baseUrl, url); - resource.setBytes(getClassBytes(name, jarInputStream, false)); - addResource(name, resource); - jarInputStream.closeEntry(); + if(includeResource.include(jarEntry)){ + String name = resolveName(jarEntry.getName()); + URL url = new URL(baseUrl.toString() + name); + Resource resource = new Resource(name, baseUrl, url); + resource.setBytes(getClassBytes(name, jarInputStream, false)); + addResource(name, resource); + jarInputStream.closeEntry(); + } } } finally { jarInputStream.close(); } } + protected String resolveName(String name){ + return name; + } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java index de1dd30..b41b979 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java @@ -68,20 +68,22 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { if(!Files.exists(path)){ return; } - URL url = path.toUri().toURL(); - addResource(url); + addResource(path.toUri().toURL()); } public void addResource(URL url) throws Exception{ AbstractResourceLoader resourceLoader = null; if(ResourceUtils.isJarFileUrl(url)) { - resourceLoader = new JarResourceLoader(url); + if(ResourceUtils.isJarProtocolUrl(url)){ + resourceLoader = new JarResourceLoader(url); + } else { + resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile()); + } } else if(ResourceUtils.isFileUrl(url)){ resourceLoader = new ClassPathLoader(url); } if(resourceLoader != null){ - resourceLoader.init(); - resourceLoaders.add(resourceLoader); + addResource(resourceLoader); } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java index cfd592e..06809bf 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java @@ -1,6 +1,9 @@ package com.gitee.starblues.loader.classloader.filter; +import java.util.jar.JarEntry; + /** + * 排除资源 * @author starBlues * @version 3.0.0 */ @@ -9,9 +12,9 @@ public interface ExcludeResource { /** * 过滤排除 - * @param name 资源名称 + * @param jarEntry jarEntry * @return boolean */ - boolean exclude(String name); + boolean exclude(JarEntry jarEntry); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java new file mode 100644 index 0000000..c46d8db --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java @@ -0,0 +1,20 @@ +package com.gitee.starblues.loader.classloader.filter; + +import java.util.jar.JarEntry; + +/** + * 包含资源 + * @author starBlues + * @version 3.0.0 + */ +@FunctionalInterface +public interface IncludeResource { + + /** + * 过滤排除 + * @param jarEntry jarEntry + * @return boolean + */ + boolean include(JarEntry jarEntry); + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java index 55a0ed0..a4853d0 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java @@ -32,7 +32,6 @@ public abstract class AbstractLauncher implements Launcher { ClassLoader oldClassLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); - JarFile.registerUrlProtocolHandler(); return launch(classLoader, args); } finally { thread.setContextClassLoader(oldClassLoader); diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java index 02477d4..942855a 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java @@ -20,12 +20,12 @@ import com.gitee.starblues.loader.archive.Archive; import com.gitee.starblues.loader.archive.ExplodedArchive; import com.gitee.starblues.loader.archive.JarFileArchive; import com.gitee.starblues.loader.classloader.GenericClassLoader; -import com.gitee.starblues.loader.classloader.JarFileResourceLoader; +import com.gitee.starblues.loader.classloader.JarResourceLoader; +import com.gitee.starblues.loader.classloader.ResourceLoaderFactory; import com.gitee.starblues.loader.launcher.runner.MethodRunner; import java.io.File; import java.io.IOException; -import java.net.URISyntaxException; import java.net.URL; import java.util.Iterator; import java.util.Objects; @@ -38,6 +38,7 @@ import java.util.Objects; public class MainJarProgramLauncher extends MainProgramLauncher{ private static final String PROD_CLASSES_PATH = "classes/"; + private static final String PROD_CLASSES_URL_SIGN = "/classes!/"; private static final String PROD_LIB_PATH = "lib/"; @@ -77,16 +78,28 @@ public class MainJarProgramLauncher extends MainProgramLauncher{ Archive archive = archives.next(); URL url = archive.getUrl(); String path = url.getPath(); - if(path.contains("/classes!/")){ - JarFileResourceLoader jarResourceLoader = new JarFileResourceLoader(url); - jarResourceLoader.setFunction(name->{ - return name.replace("classes/", ""); - }); - classLoader.getResourceLoaderFactory().addResource(jarResourceLoader); + ResourceLoaderFactory resourceLoaderFactory = classLoader.getResourceLoaderFactory(); + if(path.contains(PROD_CLASSES_URL_SIGN)){ + MainJarResourceLoader jarResourceLoader = new MainJarResourceLoader(url); + resourceLoaderFactory.addResource(jarResourceLoader); } else { - JarFileResourceLoader jarResourceLoader = new JarFileResourceLoader(archive.getUrl()); - classLoader.getResourceLoaderFactory().addResource(jarResourceLoader); + JarResourceLoader jarResourceLoader = new JarResourceLoader(url); + resourceLoaderFactory.addResource(jarResourceLoader); } } } + + private static class MainJarResourceLoader extends JarResourceLoader { + + public MainJarResourceLoader(URL url) throws Exception { + super(url); + } + + @Override + protected String resolveName(String name) { + return name.replace(PROD_CLASSES_PATH, ""); + } + } + + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java index 2b56a09..42f709c 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java @@ -16,6 +16,7 @@ package com.gitee.starblues.loader.launcher; +import com.gitee.starblues.loader.jar.JarFile; import com.gitee.starblues.loader.launcher.runner.MainMethodRunner; import com.gitee.starblues.loader.launcher.runner.MethodRunner; @@ -50,6 +51,7 @@ public class SpringMainBootstrap { SpringMainBootstrap.springBootstrap = Objects.requireNonNull(springBootstrap, "springBootBootstrap 不能为空"); MainMethodRunner mainMethodRunner = new MainMethodRunner(SpringMainBootstrap.class.getName(), MAIN_RUN_METHOD, args); + JarFile.registerUrlProtocolHandler(); Thread launchThread = new Thread(new Runner(mainMethodRunner)); launchThread.start(); try { diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java index c7c40cf..2a276b4 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java @@ -36,6 +36,7 @@ public class SpringMainProdBootstrap { private static final String START_CLASS = "Start-Class"; public static void main(String[] args) throws Exception { + JarFile.registerUrlProtocolHandler(); new SpringMainProdBootstrap().run(args); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java index 3ddf9ec..8feb952 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java @@ -30,6 +30,16 @@ public class ResourceUtils { || (URL_PROTOCOL_JAR_FILE.equals(protocol) || extensionIsJar); } + /** + * 是否为jar协议的文件 + * @param url url + * @return boolean + */ + public static boolean isJarProtocolUrl(URL url) { + return URL_PROTOCOL_JAR_FILE.equals(url.getProtocol()); + } + + /** * 是否为普通文件 * @param url url @@ -40,4 +50,5 @@ public class ResourceUtils { return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) || URL_PROTOCOL_VFS.equals(protocol)); } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java index e6cd34b..75fc7c5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java @@ -51,8 +51,7 @@ public class NestedPluginJarResourceLoader extends AbstractResourceLoader { } @Override - public void init() throws Exception { - super.init(); + protected void initOfChild() throws Exception { try (JarFile jarFile = new JarFile(pluginDescriptor.getInsidePluginPath().toFile())) { addClassPath(jarFile); addLib(jarFile); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java index 254b31a..464f739 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java @@ -99,7 +99,7 @@ public class JarNestPackager implements Repackager { continue; } if(CommonUtils.isPluginFrameworkLoader(artifact)){ - // 本框架依赖 + // 本框架loader依赖 packageJar.copyZipToPackage(artifact.getFile()); } else { packageJar.writeDependency(artifact.getFile(), libDirEntryName); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java index 154ac4f..de9e06c 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.utils; +import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; import org.apache.commons.compress.archivers.ArchiveOutputStream; @@ -124,6 +125,10 @@ public class PackageZip implements Closeable{ while (entries.hasMoreElements()){ ZipArchiveEntry zipArchiveEntry = entries.nextElement(); String name = zipArchiveEntry.getName(); + if(name.contains(PackageStructure.META_INF_NAME)){ + // 不拷贝 mate-inf + continue; + } if(zipArchiveEntry.isDirectory()){ putDirEntry(name); } else { -- Gitee From 55ca89a032db995a1cd307d895c83de202f7757e Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sun, 27 Feb 2022 07:38:31 +0800 Subject: [PATCH 31/37] main jar in jar --- .../common/AbstractDependencyPlugin.java | 20 +++ .../com/gitee/starblues/common/Constants.java | 20 +++ .../starblues/common/DependencyPlugin.java | 20 +++ .../gitee/starblues/common/ManifestKey.java | 7 +- .../starblues/common/PackageStructure.java | 17 ++ .../gitee/starblues/common/PackageType.java | 36 ++++ .../starblues/common/PluginDescriptorKey.java | 19 +++ .../com/gitee/starblues/utils/Assert.java | 1 + .../utils/CompareClassTypeUtils.java | 1 + .../gitee/starblues/utils/FieldFilter.java | 2 + .../com/gitee/starblues/utils/FilesUtils.java | 34 +++- .../gitee/starblues/utils/ManifestUtils.java | 35 +++- .../gitee/starblues/utils/ObjectUtils.java | 84 ++++++++- .../starblues/utils/ReflectionUtils.java | 1 + .../gitee/starblues/utils/StringUtils.java | 20 ++- .../bootstrap/ConfigurePluginEnvironment.java | 5 + .../bootstrap/DefaultSpringPluginHook.java | 21 ++- .../realize/PluginCloseListener.java | 34 ++++ .../loader/PluginResourceStorage.java | 41 +++-- .../starblues/loader/archive/Archive.java | 54 +++--- .../loader/archive/ExplodedArchive.java | 33 +++- .../loader/archive/JarFileArchive.java | 30 +++- .../classloader/GenericClassLoader.java | 107 +++++------- .../classloader/filter/ExcludeResource.java | 16 ++ .../classloader/filter/IncludeResource.java | 16 ++ .../loader/classloader/resource/Resource.java | 61 +++++++ .../ResourceByteGetter.java} | 21 ++- .../loader}/AbstractResourceLoader.java | 61 ++++--- .../loader}/ClassPathLoader.java | 37 ++-- .../loader/DefaultResource.java} | 42 ++--- .../loader/DefaultResourceLoaderFactory.java} | 111 +++++++----- .../loader}/JarResourceLoader.java | 26 +-- .../resource/loader/ResourceLoader.java | 43 +++++ .../loader/ResourceLoaderFactory.java | 32 ++++ .../resource/loader/ResourceLoaderGetter.java | 32 ++++ .../storage/CacheResourceStorage.java | 71 ++++++++ .../storage/DefaultResourceStorage.java | 80 +++++++++ .../resource/storage/ResourceStorage.java | 71 ++++++++ .../storage/ShareResourceStorage.java | 160 ++++++++++++++++++ .../starblues/loader/jar/AbstractJarFile.java | 31 +++- .../starblues/loader/jar/AsciiBytes.java | 25 ++- .../com/gitee/starblues/loader/jar/Bytes.java | 16 ++ .../loader/jar/CentralDirectoryEndRecord.java | 19 ++- .../jar/CentralDirectoryFileHeader.java | 16 ++ .../loader/jar/CentralDirectoryParser.java | 16 ++ .../loader/jar/CentralDirectoryVisitor.java | 16 ++ .../starblues/loader/jar/FileHeader.java | 16 ++ .../gitee/starblues/loader/jar/Handler.java | 60 ++++--- .../gitee/starblues/loader/jar/JarEntry.java | 16 ++ .../loader/jar/JarEntryCertification.java | 16 ++ .../starblues/loader/jar/JarEntryFilter.java | 16 ++ .../gitee/starblues/loader/jar/JarFile.java | 31 ++-- .../starblues/loader/jar/JarFileEntries.java | 25 ++- .../starblues/loader/jar/JarFileWrapper.java | 16 ++ .../loader/jar/JarURLConnection.java | 22 ++- .../loader/jar/RandomAccessData.java | 16 ++ .../loader/jar/RandomAccessDataFile.java | 19 ++- .../starblues/loader/jar/StringSequence.java | 16 ++ .../loader/jar/ZipInflaterInputStream.java | 22 ++- .../loader/launcher/AbstractLauncher.java | 6 +- .../launcher/MainJarProgramLauncher.java | 16 +- .../loader/launcher/MainProgramLauncher.java | 12 +- .../launcher/ResourceLoaderFactoryGetter.java | 107 ++++++++++++ .../launcher/SpringMainProdBootstrap.java | 1 + .../launcher/runner/SpringBootRunner.java | 30 ---- .../loader/utils/CompareClassTypeUtils.java | 18 ++ .../gitee/starblues/loader/utils/IOUtils.java | 8 +- .../starblues/loader/utils/ObjectUtils.java | 18 ++ .../starblues/loader/utils/ResourceUtils.java | 16 ++ .../core/DefaultPluginInsideInfo.java | 31 +++- .../starblues/core/DefaultPluginManager.java | 2 +- .../com/gitee/starblues/core/PluginInfo.java | 15 ++ .../gitee/starblues/core/PluginInfoFace.java | 17 ++ .../NestedPluginJarResourceLoader.java | 52 +++--- .../core/classloader/PluginClassLoader.java | 62 +++++-- .../PluginResourceLoaderFactory.java | 70 -------- .../AbstractPluginDescriptorLoader.java | 42 ++++- .../DefaultInsidePluginDescriptor.java | 45 +++-- .../descriptor/InsidePluginDescriptor.java | 13 +- .../core/descriptor/PluginDescriptor.java | 1 - .../core/descriptor/PluginLibInfo.java | 38 +++++ .../starblues/core/descriptor/PluginType.java | 10 ++ .../ProdDirPluginDescriptorLoader.java | 5 +- .../ProdPackagePluginDescriptorLoader.java | 11 +- .../core/launcher/plugin/PluginLauncher.java | 19 ++- .../PluginMainResourcePatternDefiner.java | 23 +++ .../com/gitee/starblues/utils/ClassUtils.java | 51 +++--- .../pack/AbstractDependencyFilterMojo.java | 1 + .../plugin/pack/AbstractPackagerMojo.java | 3 +- .../plugin/pack/BasicRepackager.java | 9 +- .../gitee/starblues/plugin/pack/Constant.java | 9 - .../starblues/plugin/pack/Dependency.java | 36 ++++ .../starblues/plugin/pack/LoadToMain.java | 33 ++++ .../starblues/plugin/pack/PluginInfo.java | 9 +- .../starblues/plugin/pack/RepackageMojo.java | 39 ++++- .../starblues/plugin/pack/Repackager.java | 2 +- .../starblues/plugin/pack/dev/Dependency.java | 3 +- .../plugin/pack/main/JarNestPackager.java | 6 +- .../plugin/pack/main/JarOuterPackager.java | 111 ++++++++++++ .../plugin/pack/main/MainConfig.java | 7 +- .../plugin/pack/main/MainRepackager.java | 9 +- .../plugin/pack/prod/DirProdRepackager.java | 7 +- ...ager.java => JarNestedProdRepackager.java} | 20 ++- .../pack/prod/JarOuterProdRepackager.java | 52 ++++++ .../plugin/pack/prod/ProdConfig.java | 6 + .../plugin/pack/prod/ProdRepackager.java | 17 +- .../pack/prod/ZipOuterProdRepackager.java | 96 +++++++++++ .../plugin/pack/prod/ZipProdRepackager.java | 13 +- .../plugin/pack/utils/PackageZip.java | 25 ++- .../plugin-help.xml | 9 + .../main/resources/META-INF/maven/plugin.xml | 9 + 111 files changed, 2612 insertions(+), 610 deletions(-) create mode 100644 spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java create mode 100644 springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/PluginCloseListener.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/Resource.java rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/{AbstractPluginClassLoader.java => resource/ResourceByteGetter.java} (70%) rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/{ => resource/loader}/AbstractResourceLoader.java (71%) rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/{ => resource/loader}/ClassPathLoader.java (68%) rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/{Resource.java => resource/loader/DefaultResource.java} (61%) rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/{ResourceLoaderFactory.java => resource/loader/DefaultResourceLoaderFactory.java} (53%) rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/{ => resource/loader}/JarResourceLoader.java (75%) create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java create mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java delete mode 100644 springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java delete mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java create mode 100644 springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Dependency.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadToMain.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java rename springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/{JarProdRepackager.java => JarNestedProdRepackager.java} (68%) create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java create mode 100644 springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java index 465a41e..4052ff7 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/AbstractDependencyPlugin.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.common; import java.util.ArrayList; @@ -7,6 +23,7 @@ import java.util.function.Supplier; /** * 依赖的插件 + * * @author starBlues * @version 3.0.0 */ @@ -18,18 +35,21 @@ public abstract class AbstractDependencyPlugin implements DependencyPlugin{ /** * set依赖插件id + * * @param id 插件id */ public abstract void setId(String id); /** * set依赖插件版本 + * * @param version 插件版本 */ public abstract void setVersion(String version); /** * set optional + * * @param optional 是否可选 */ public abstract void setOptional(Boolean optional); diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java index 53fe8ec..c6bec80 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.common; /** @@ -20,6 +36,10 @@ public abstract class Constants { */ public final static String ALLOW_VERSION = "0.0.0"; + /** + * 加载到主程序依赖的标志 + */ + public final static String LOAD_TO_MAIN_SIGN = "@LOAD_TO_MAIN"; } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java index e269863..cb306a9 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/DependencyPlugin.java @@ -1,7 +1,24 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.common; /** * 依赖的插件 + * * @author starBlues * @version 3.0.0 */ @@ -9,18 +26,21 @@ public interface DependencyPlugin { /** * 依赖插件id + * * @return String */ String getId(); /** * 依赖插件版本. 如果设置为: 0.0.0 表示支持任意版本依赖 + * * @return String */ String getVersion(); /** * 是否为必须依赖. 默认: false + * * @return boolean */ Boolean getOptional(); diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java index aacf013..6e2cafd 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java @@ -17,6 +17,8 @@ package com.gitee.starblues.common; /** + * Manifest-Key + * * @author starBlues * @version 3.0.0 */ @@ -48,6 +50,9 @@ public class ManifestKey { */ public static final String START_CLASS = "Start-Class"; - + /** + * jar class path + */ + public static final String CLASS_PATH = "Class-Path"; } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java index 34365ba..b83fc0c 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.common; @@ -8,6 +24,7 @@ import java.util.regex.Matcher; /** * 插件打包结构 + * * @author starBlues * @version 3.0.0 */ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java new file mode 100644 index 0000000..aa72ea3 --- /dev/null +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java @@ -0,0 +1,36 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.common; + +/** + * 打包类型 + * + * @author starBlues + * @version 3.0.0 + */ +public class PackageType { + + public static final String PLUGIN_PACKAGE_TYPE_JAR = "jar"; + public static final String PLUGIN_PACKAGE_TYPE_JAR_OUTER = "jar-outer"; + public static final String PLUGIN_PACKAGE_TYPE_ZIP = "zip"; + public static final String PLUGIN_PACKAGE_TYPE_ZIP_OUTER = "zip-outer"; + public static final String PLUGIN_PACKAGE_TYPE_DIR = "dir"; + + public static final String MAIN_PACKAGE_TYPE_JAR = "jar"; + public static final String MAIN_PACKAGE_TYPE_JAR_OUTER = "jar-outer"; + +} diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java index 140cd43..4a66ba9 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java @@ -1,7 +1,24 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.common; /** * 插件描述文件配置key + * * @author starBlues * @version 3.0.0 */ @@ -21,10 +38,12 @@ public class PluginDescriptorKey { public static final String PLUGIN_REQUIRES = "Plugin-Requires"; public static final String PLUGIN_LICENSE = "Plugin-License"; public static final String PLUGIN_CONFIG_FILE_NAME = "Plugin-Config-Filename"; + public static final String PLUGIN_CONFIG_FILE_LOCATION = "Plugin-Config-File-Location"; /** System create prop **/ public static final String PLUGIN_PATH = "Plugin-Path"; public static final String PLUGIN_RESOURCES_CONFIG = "Plugin-Resources-Config"; + public static final String PLUGIN_PACKAGE_TYPE = "Plugin-Package-Type"; } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/Assert.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/Assert.java index 546bcc7..839a8ba 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/Assert.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/Assert.java @@ -21,6 +21,7 @@ import java.util.function.Supplier; /** * 参数校验工具类 + * * @author starBlues * @version 3.0.0 */ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java index fe03645..1901f57 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/CompareClassTypeUtils.java @@ -18,6 +18,7 @@ package com.gitee.starblues.utils; /** * 比较两个类类型 + * * @author starBlues * @version 3.0.0 */ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FieldFilter.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FieldFilter.java index 5f421b6..915882f 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FieldFilter.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FieldFilter.java @@ -20,6 +20,7 @@ import java.lang.reflect.Field; /** * 文过滤接口 + * * @author starBlues * @version 3.0.0 */ @@ -28,6 +29,7 @@ public interface FieldFilter { /** * 过滤 + * * @param field 当前字段 * @return true 允许, false 不允许 */ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java index decc412..4b898d1 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java @@ -1,14 +1,38 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.io.File; import java.util.function.Supplier; /** + * 文件工具类 + * * @author starBlues * @version 3.0.0 */ public class FilesUtils { + /** + * 获取存在的文件 + * + * @param pathStr 文件路径 + * @return File + */ public static File getExistFile(String pathStr){ File file = new File(pathStr); if(file.exists()){ @@ -17,16 +41,10 @@ public class FilesUtils { return null; } - public static File getExistFile(String pathStr, Supplier secondPathSupplier){ - File existFile = getExistFile(pathStr); - if(existFile != null){ - return existFile; - } - return getExistFile(secondPathSupplier.get()); - } /** * rest接口拼接路径 + * * @param path1 路径1 * @param path2 路径2 * @return 拼接的路径 @@ -52,6 +70,7 @@ public class FilesUtils { /** * 拼接url路径 + * * @param paths 拼接的路径 * @return 拼接的路径 */ @@ -81,6 +100,7 @@ public class FilesUtils { /** * 拼接file路径 + * * @param paths 拼接的路径 * @return 拼接的路径 */ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java index acc5613..568ada3 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java @@ -1,19 +1,52 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.util.jar.Attributes; /** + * 操作 Manifest 工具类 + * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public abstract class ManifestUtils { private ManifestUtils(){} + /** + * 获取值 + * + * @param attributes attributes + * @param key 获取的key + * @return 获取的值或者null + */ public static String getValue(Attributes attributes, String key){ return getValue(attributes, key, true); } + /** + * 获取值 + * + * @param attributes attributes + * @param key 获取的key + * @param notExitsThrowException 如果不存在是否抛出异常 + * @return 获取的值 + */ public static String getValue(Attributes attributes, String key, boolean notExitsThrowException){ boolean throwException = false; String value = null; diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java index 32b623f..4ec35ae 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ObjectUtils.java @@ -22,6 +22,7 @@ import java.util.*; /** * Object 工具类 + * * @author starBlues * @version 3.0.0 */ @@ -41,11 +42,22 @@ public class ObjectUtils { private ObjectUtils(){} - - public static boolean isEmpty(CharSequence cs) { - return cs == null || cs.length() == 0; + /** + * 字符串是否为空 + * + * @param charSequence 字符串 + * @return true 为空, false 不为空 + */ + public static boolean isEmpty(CharSequence charSequence) { + return charSequence == null || charSequence.length() == 0; } + /** + * 对象是否为空 + * + * @param obj 对象 + * @return true 为空, false 不为空 + */ public static boolean isEmpty(Object obj) { if (obj == null) { return true; @@ -69,10 +81,22 @@ public class ObjectUtils { return false; } + /** + * 是否存在字符 + * + * @param str str + * @return true 存在, false 不存在 + */ public static boolean hasText(CharSequence str) { return (str != null && str.length() > 0 && containsText(str)); } + /** + * 设置数组字符的空格 + * + * @param array array + * @return result array + */ public static String[] trimArrayElements(String[] array) { if (isEmpty(array)) { return array; @@ -87,14 +111,35 @@ public class ObjectUtils { } + /** + * 将逗号分割的字符串转换为字符转租 + * + * @param str 逗号分割的字符 + * @return 字符数组 + */ public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } + /** + * 自定义符号分割的字符串转换为字符转租 + * + * @param str 待处理字符串 + * @param delimiter 分割符号 + * @return 字符数组 + */ public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, null); } + /** + * 自定义符号分割的字符串转换为字符转租 + * + * @param str 待处理字符串 + * @param delimiter 分割符号 + * @param charsToDelete 要删除的字符 + * @return 字符数组 + */ public static String[] delimitedListToStringArray( String str, String delimiter, String charsToDelete) { @@ -126,11 +171,23 @@ public class ObjectUtils { return toStringArray(result); } + /** + * 将集合字符串转换为数组字符串 + * + * @param collection 集合 + * @return 数字字符串 + */ public static String[] toStringArray(Collection collection) { return (!isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); } - + /** + * 从字符串中删除某个字符字符 + * + * @param inString 待处理字符串 + * @param charsToDelete 要删除的字符 + * @return 处理后的字符串 + */ public static String deleteAny(String inString, String charsToDelete) { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; @@ -150,14 +207,33 @@ public class ObjectUtils { return new String(result, 0, lastCharIndex); } + /** + * 字符串是否存在长度 + * + * @param str 字符串 + * @return true 存在长度, false 不存在长度 + */ public static boolean hasLength(String str) { return (str != null && !str.isEmpty()); } + /** + * 将集合字转换为逗号分割的字符串 + * + * @param coll 集合 + * @return 字符串 + */ public static String collectionToCommaDelimitedString(Collection coll) { return collectionToDelimitedString(coll, ","); } + /** + * 将集合字转换为逗号分割的字符串 + * + * @param coll 集合 + * @param delim 分割符号 + * @return 字符串 + */ public static String collectionToDelimitedString(Collection coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java index f23ad88..a087e07 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ReflectionUtils.java @@ -23,6 +23,7 @@ import java.util.*; /** * 反射工具类 + * * @author starBlues * @version 3.0.0 */ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java index 825b520..fc2abbb 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/StringUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.utils; import java.util.ArrayList; @@ -6,8 +22,10 @@ import java.util.List; import java.util.StringTokenizer; /** + * String 工具类 + * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class StringUtils { diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 33083b1..4cd4505 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -38,6 +38,7 @@ class ConfigurePluginEnvironment { private final static String PLUGIN_PROPERTY_NAME = "pluginPropertySources"; private final static String SPRING_CONFIG_NAME = "spring.config.name"; + private final static String SPRING_CONFIG_LOCATION = "spring.config.location"; private final static String SPRING_JMX_UNIQUE_NAMES = "spring.jmx.unique-names"; private final static String SPRING_ADMIN_JMX_NAME = "spring.application.admin.jmx-name"; @@ -62,6 +63,10 @@ class ConfigurePluginEnvironment { if(!ObjectUtils.isEmpty(configFileName)){ env.put(SPRING_CONFIG_NAME, PluginFileUtils.getFileName(configFileName)); } + String configFileLocation = pluginDescriptor.getConfigFileLocation(); + if(!ObjectUtils.isEmpty(configFileLocation)){ + env.put(SPRING_CONFIG_LOCATION, configFileLocation); + } env.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); env.put(SPRING_JMX_UNIQUE_NAMES, true); env.put(SPRING_ADMIN_JMX_NAME, SPRING_ADMIN_JMX_VALUE + pluginId); diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java index e11e6dd..7e47ff4 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/DefaultSpringPluginHook.java @@ -19,6 +19,7 @@ package com.gitee.starblues.bootstrap; import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.bootstrap.processor.SpringPluginProcessor; import com.gitee.starblues.bootstrap.processor.web.thymeleaf.PluginThymeleafProcessor; +import com.gitee.starblues.bootstrap.realize.PluginCloseListener; import com.gitee.starblues.bootstrap.realize.StopValidator; import com.gitee.starblues.bootstrap.utils.DestroyUtils; import com.gitee.starblues.bootstrap.utils.SpringBeanUtils; @@ -31,6 +32,7 @@ import com.gitee.starblues.spring.web.thymeleaf.ThymeleafConfig; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.support.SpringFactoriesLoader; +import java.util.List; import java.util.Map; /** @@ -76,8 +78,9 @@ public class DefaultSpringPluginHook implements SpringPluginHook { @Override public void close() throws Exception{ try { - pluginProcessor.close(processorContext); GenericApplicationContext applicationContext = processorContext.getApplicationContext(); + callPluginCloseListener(applicationContext); + pluginProcessor.close(processorContext); if(applicationContext != null){ applicationContext.close(); } @@ -102,4 +105,20 @@ public class DefaultSpringPluginHook implements SpringPluginHook { public ThymeleafConfig getThymeleafConfig() { return processorContext.getRegistryInfo(PluginThymeleafProcessor.CONFIG_KEY); } + + private void callPluginCloseListener(GenericApplicationContext applicationContext){ + List pluginCloseListeners = SpringBeanUtils.getBeans( + applicationContext, PluginCloseListener.class); + if(pluginCloseListeners.isEmpty()){ + return; + } + for (PluginCloseListener pluginCloseListener : pluginCloseListeners) { + try { + pluginCloseListener.close(processorContext.getPluginDescriptor()); + } catch (Exception e){ + e.printStackTrace(); + } + } + } + } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/PluginCloseListener.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/PluginCloseListener.java new file mode 100644 index 0000000..dfdfd66 --- /dev/null +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/realize/PluginCloseListener.java @@ -0,0 +1,34 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.bootstrap.realize; + +import com.gitee.starblues.core.descriptor.PluginDescriptor; + +/** + * 插件被停止监听者。用于自定义关闭资源 + * @author starBlues + * @version 3.0.0 + */ +public interface PluginCloseListener { + + /** + * 关闭时调用 + * @param descriptor 当前插件描述者 + */ + void close(PluginDescriptor descriptor); + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java index 0d25864..056596a 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/PluginResourceStorage.java @@ -36,40 +36,61 @@ import java.util.concurrent.ConcurrentHashMap; */ public class PluginResourceStorage { - public final static Map STORAGES = new ConcurrentHashMap<>(); - + public final static Map STORAGE_MAP = new ConcurrentHashMap<>(); + /** + * 添加插件资源 + * @param pluginId 插件id + * @param pluginFileName 插件文件名称 + */ public static void addPlugin(String pluginId, String pluginFileName){ - if(STORAGES.containsKey(pluginId)){ + if(STORAGE_MAP.containsKey(pluginId)){ return; } - STORAGES.put(pluginId, new Storage(pluginFileName)); + STORAGE_MAP.put(pluginId, new Storage(pluginFileName)); } - + /** + * 移除插件 + * @param pluginId 插件 + */ public static void removePlugin(String pluginId){ - Storage storage = STORAGES.get(pluginId); + Storage storage = STORAGE_MAP.get(pluginId); if(storage == null){ return; } IOUtils.closeQuietly(storage); - STORAGES.remove(pluginId); + STORAGE_MAP.remove(pluginId); } + /** + * 添加插件jar文件 + * @param jarFile jar插件文件 + */ public static void addJarFile(AbstractJarFile jarFile){ - STORAGES.forEach((k,v)->{ + STORAGE_MAP.forEach((k,v)->{ v.addJarFile(jarFile.getName(), jarFile); }); } + /** + * 添加插件根的jar文件 + * @param file 插件文件 + * @param jarFile 插件jar文件 + */ public static void addRootJarFile(File file, JarFile jarFile){ - STORAGES.forEach((k,v)->{ + STORAGE_MAP.forEach((k,v)->{ v.addRootJarFile(file, jarFile); }); } + /** + * 通过插件文件获取插件jar文件 + * @param file 插件文件 + * @return 插件jar文件 + */ public static JarFile getRootJarFile(File file){ - for (Storage value : STORAGES.values()) { + for (Storage value : STORAGE_MAP.values()) { JarFile jarFile = value.getRootJarFile(file); if(jarFile != null){ return jarFile; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java index 639e3b8..50bdc2c 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/Archive.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.archive; import java.io.IOException; @@ -35,48 +51,22 @@ public interface Archive extends Iterable, AutoCloseable { * @param includeFilter filter used to determine which entries should be included in * the result or {@code null} if all entries should be included * @return the nested archives - * @throws IOException on IO error + * @throws IOException io exception * @since 2.3.0 */ - default Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) - throws IOException { - EntryFilter combinedFilter = (entry) -> (searchFilter == null || searchFilter.matches(entry)) - && (includeFilter == null || includeFilter.matches(entry)); - List nestedArchives = getNestedArchives(combinedFilter); - return nestedArchives.iterator(); - } - - /** - * Returns nested {@link Archive}s for entries that match the specified filter. - * @param filter the filter used to limit entries - * @return nested archives - * @throws IOException if nested archives cannot be read - * @deprecated since 2.3.0 for removal in 2.5.0 in favor of - * {@link #getNestedArchives(EntryFilter, EntryFilter)} - */ - @Deprecated - default List getNestedArchives(EntryFilter filter) throws IOException { - throw new IllegalStateException("Unexpected call to getNestedArchives(filter)"); - } + Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException; /** * Return a new iterator for the archive entries. - * @see java.lang.Iterable#iterator() - * @deprecated since 2.3.0 for removal in 2.5.0 in favor of using - * {@link org.springframework.boot.loader.jar.JarFile} to access entries and - * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. + * @return {@link Iterable} */ - @Deprecated @Override Iterator iterator(); /** * Performs the given action for each element of the {@code Iterable} until all * elements have been processed or the action throws an exception. - * @see Iterable#forEach - * @deprecated since 2.3.0 for removal in 2.5.0 in favor of using - * {@link org.springframework.boot.loader.jar.JarFile} to access entries and - * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. + * @param action consumer entry */ @Override default void forEach(Consumer action) { @@ -89,9 +79,7 @@ public interface Archive extends Iterable, AutoCloseable { /** * Creates a {@link Spliterator} over the elements described by this {@code Iterable}. * @see Iterable#spliterator - * @deprecated since 2.3.0 for removal in 2.5.0 in favor of using - * {@link org.springframework.boot.loader.jar.JarFile} to access entries and - * {@link #getNestedArchives(EntryFilter, EntryFilter)} for accessing nested archives. + * @return {@link Spliterator} */ @Override default Spliterator spliterator() { diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java index 0047be3..284a270 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/ExplodedArchive.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.archive; import java.io.File; @@ -22,7 +38,7 @@ public class ExplodedArchive implements Archive { private final boolean recursive; - private File manifestFile; + private final File manifestFile; private Manifest manifest; @@ -76,7 +92,6 @@ public class ExplodedArchive implements Archive { } @Override - @Deprecated public Iterator iterator() { return new EntryIterator(this.root, this.recursive, null, null); } @@ -106,7 +121,7 @@ public class ExplodedArchive implements Archive { */ private abstract static class AbstractIterator implements Iterator { - private static final Comparator entryComparator = Comparator.comparing(File::getAbsolutePath); + private static final Comparator ENTRY_COMPARATOR = Comparator.comparing(File::getAbsolutePath); private final File root; @@ -120,7 +135,7 @@ public class ExplodedArchive implements Archive { private FileEntry current; - private String rootUrl; + private final String rootUrl; AbstractIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { this.root = root; @@ -149,8 +164,12 @@ public class ExplodedArchive implements Archive { private FileEntry poll() { while (!this.stack.isEmpty()) { - while (this.stack.peek().hasNext()) { - File file = this.stack.peek().next(); + Iterator peek = this.stack.peek(); + if(peek == null){ + continue; + } + while (peek.hasNext()) { + File file = peek.next(); if (SKIPPED_NAMES.contains(file.getName())) { continue; } @@ -189,7 +208,7 @@ public class ExplodedArchive implements Archive { if (files == null) { return Collections.emptyIterator(); } - Arrays.sort(files, entryComparator); + Arrays.sort(files, ENTRY_COMPARATOR); return Arrays.asList(files).iterator(); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java index 3f363af..8698a2e 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/archive/JarFileArchive.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.archive; import com.gitee.starblues.loader.jar.JarFile; @@ -75,7 +91,6 @@ public class JarFileArchive implements Archive { } @Override - @Deprecated public Iterator iterator() { return new EntryIterator(this.jarFile.iterator(), null, null); } @@ -93,8 +108,7 @@ public class JarFileArchive implements Archive { try { JarFile jarFile = this.jarFile.getNestedJarFile(jarEntry); return new JarFileArchive(jarFile); - } - catch (Exception ex) { + } catch (Exception ex) { throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex); } } @@ -127,8 +141,8 @@ public class JarFileArchive implements Archive { try { createDirectory(unpackDirectory); return unpackDirectory; - } - catch (IOException ex) { + } catch (IOException ex) { + // ignore } } throw new IllegalStateException("Failed to create unpack directory in directory '" + parent + "'"); @@ -168,8 +182,7 @@ public class JarFileArchive implements Archive { public String toString() { try { return getUrl().toString(); - } - catch (Exception ex) { + } catch (Exception ex) { return "jar archive"; } } @@ -250,8 +263,7 @@ public class JarFileArchive implements Archive { protected Archive adapt(Entry entry) { try { return getNestedArchive(entry); - } - catch (IOException ex) { + } catch (IOException ex) { throw new IllegalStateException(ex); } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java index bd1ee33..ac3530e 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java @@ -17,6 +17,11 @@ package com.gitee.starblues.loader.classloader; +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoader; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderGetter; +import com.gitee.starblues.loader.utils.Assert; import com.gitee.starblues.loader.utils.IOUtils; import com.gitee.starblues.loader.utils.ObjectUtils; @@ -44,26 +49,16 @@ public class GenericClassLoader extends URLClassLoader { private final Map> pluginClassCache = new ConcurrentHashMap<>(); - public GenericClassLoader(String name) { - this(name, null); + public GenericClassLoader(String name, ResourceLoaderFactory resourceLoaderFactory) { + this(name, null, resourceLoaderFactory); } - public GenericClassLoader(String name, ClassLoader parent) { - this(name, parent, null); - } - - public GenericClassLoader(String name, ClassLoader parent, ResourceLoaderFactory loaderFactory) { + public GenericClassLoader(String name, ClassLoader parent, ResourceLoaderFactory resourceLoaderFactory) { super(new URL[]{}, null); - if(ObjectUtils.isEmpty(name)){ - throw new IllegalArgumentException("参数 name 不能为空"); - } - this.name = name; + this.name = Assert.isNotEmpty(name, "name 不能为空"); + this.resourceLoaderFactory = Assert.isNotNull(resourceLoaderFactory, "resourceLoaderFactory 不能为空"); this.parent = parent; - if(loaderFactory == null){ - resourceLoaderFactory = new ResourceLoaderFactory(); - } else { - resourceLoaderFactory = loaderFactory; - } + } public String getName() { @@ -87,8 +82,12 @@ public class GenericClassLoader extends URLClassLoader { resourceLoaderFactory.addResource(url); } - public ResourceLoaderFactory getResourceLoaderFactory(){ - return resourceLoaderFactory; + public void addResource(ResourceLoader resourceLoader) throws Exception{ + resourceLoaderFactory.addResource(resourceLoader); + } + + public ClassLoader getParentClassLoader(){ + return parent; } @Override @@ -127,37 +126,35 @@ public class GenericClassLoader extends URLClassLoader { } protected Class findClassFromLocal(String name) { - synchronized (pluginClassCache){ - Class aClass; - String formatClassName = formatClassName(name); - aClass = pluginClassCache.get(formatClassName); - if (aClass != null) { - return aClass; - } - Resource resource = resourceLoaderFactory.findResource(formatClassName); - byte[] bytes = null; - if(resource != null){ - bytes = resource.getBytes(); - } - if(bytes == null || bytes.length == 0){ - bytes = getClassByte(formatClassName); - } - if(bytes == null || bytes.length == 0){ - return null; - } - aClass = defineClass(name, bytes, 0, bytes.length ); - if(aClass == null) { - return null; - } - if (aClass.getPackage() == null) { - int lastDotIndex = name.lastIndexOf( '.' ); - String packageName = (lastDotIndex >= 0) ? name.substring( 0, lastDotIndex) : ""; - definePackage(packageName, null, null, null, - null, null, null, null ); - } - pluginClassCache.put(name, aClass); + Class aClass; + String formatClassName = formatClassName(name); + aClass = pluginClassCache.get(formatClassName); + if (aClass != null) { return aClass; } + Resource resource = resourceLoaderFactory.findResource(formatClassName); + byte[] bytes = null; + if(resource != null){ + bytes = resource.getBytes(); + } + if(bytes == null || bytes.length == 0){ + bytes = getClassByte(formatClassName); + } + if(bytes == null || bytes.length == 0){ + return null; + } + aClass = defineClass(name, bytes, 0, bytes.length ); + if(aClass == null) { + return null; + } + if (aClass.getPackage() == null) { + int lastDotIndex = name.lastIndexOf( '.' ); + String packageName = (lastDotIndex >= 0) ? name.substring( 0, lastDotIndex) : ""; + definePackage(packageName, null, null, null, + null, null, null, null ); + } + pluginClassCache.put(name, aClass); + return aClass; } private byte[] getClassByte(String formatClassName){ @@ -165,25 +162,13 @@ public class GenericClassLoader extends URLClassLoader { if(inputStream == null){ return null; } - ByteArrayOutputStream byteArrayOutputStream = null; - byte[] bytes = null; try { - if(inputStream instanceof ByteArrayInputStream){ - bytes = IOUtils.read(inputStream); - } else { - byteArrayOutputStream = new ByteArrayOutputStream(); - IOUtils.copy(inputStream, byteArrayOutputStream); - bytes = byteArrayOutputStream.toByteArray(); - } - return bytes; + return IOUtils.read(inputStream); } catch (Exception e){ e.printStackTrace(); return null; } finally { IOUtils.closeQuietly(inputStream); - if(byteArrayOutputStream != null){ - IOUtils.closeQuietly(byteArrayOutputStream); - } } } @@ -319,7 +304,7 @@ public class GenericClassLoader extends URLClassLoader { public void close() throws IOException { synchronized (pluginClassCache){ pluginClassCache.clear(); - resourceLoaderFactory.clear(); + IOUtils.closeQuietly(resourceLoaderFactory); } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java index 06809bf..237c4de 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/ExcludeResource.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.classloader.filter; import java.util.jar.JarEntry; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java index c46d8db..e009123 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/filter/IncludeResource.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.classloader.filter; import java.util.jar.JarEntry; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/Resource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/Resource.java new file mode 100644 index 0000000..59ea855 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/Resource.java @@ -0,0 +1,61 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource; + +import java.net.URL; + +/** + * 资源信息 + * @author starBlues + * @version 3.0.0 + */ +public interface Resource extends AutoCloseable{ + + String PACKAGE_SPLIT = "/"; + + /** + * 得到资源名称 + * @return 全局唯一的资源名称 + */ + String getName(); + + /** + * 得到根URL地址 + * @return URL + */ + URL getBaseUrl(); + + /** + * 得到完整URL地址 + * @return URL + */ + URL getUrl(); + + /** + * 得到资源字节数组 + * @return byte[] + */ + byte[] getBytes(); + + /** + * 设置字节数 + * @param byteGetter byteGetter + */ + void setBytes(ResourceByteGetter byteGetter) throws Exception; + + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractPluginClassLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/ResourceByteGetter.java similarity index 70% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractPluginClassLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/ResourceByteGetter.java index 2915e5c..e8b78f8 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractPluginClassLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/ResourceByteGetter.java @@ -14,18 +14,21 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader; - -import java.net.URL; -import java.net.URLClassLoader; +package com.gitee.starblues.loader.classloader.resource; /** - * 插件 ClassLoader + * 资源 byte 得到者 + * * @author starBlues * @version 3.0.0 */ -public abstract class AbstractPluginClassLoader extends URLClassLoader { - public AbstractPluginClassLoader() { - super(new URL[]{}, null); - } +public interface ResourceByteGetter { + + /** + * 得到 byte + * @return byte[] + * @throws Exception Exception + */ + byte[] get() throws Exception; + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java similarity index 71% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java index 4ff1cf9..113c8ab 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/AbstractResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java @@ -14,9 +14,11 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader; +package com.gitee.starblues.loader.classloader.resource.loader; +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; import com.gitee.starblues.loader.utils.IOUtils; import java.io.*; @@ -25,48 +27,47 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; /** * 抽象的资源加载者 * @author starBlues * @version 3.0.0 */ -public abstract class AbstractResourceLoader { +public abstract class AbstractResourceLoader implements ResourceLoader{ private static final String CLASS_FILE_EXTENSION = ".class"; - private boolean isInit = false; + private boolean loaded = false; protected final URL baseUrl; - private final Map resourceCache = new ConcurrentHashMap<>(); - protected AbstractResourceLoader(URL baseUrl) { + protected final ResourceStorage resourceStorage; + + protected AbstractResourceLoader(URL baseUrl, ResourceStorage resourceStorage) { this.baseUrl = baseUrl; + this.resourceStorage = resourceStorage; } - protected void addResource(String name, Resource resource) { - if(resourceCache.containsKey(name)){ - return; - } - resourceCache.put(name, resource); + @Override + public URL getBaseUrl() { + return baseUrl; } /** * 初始化 resource * @throws Exception 初始异常 */ - public final synchronized void init() throws Exception{ - if(isInit){ + @Override + public final synchronized void load() throws Exception{ + if(loaded){ throw new Exception(this.getClass().getName()+": 已经初始化了, 不能再初始化!"); } try { // 添加root 路径 - Resource rootResource = new Resource("root", baseUrl, baseUrl); - resourceCache.put("/", rootResource); - initOfChild(); + resourceStorage.add("/", baseUrl, baseUrl); + loadOfChild(); } finally { - isInit = true; + loaded = true; } } @@ -74,24 +75,20 @@ public abstract class AbstractResourceLoader { * 子类初始化实现 * @throws Exception 初始异常 */ - protected void initOfChild() throws Exception{}; - - - protected boolean existResource(String name){ - return resourceCache.containsKey(name); - } + protected void loadOfChild() throws Exception{}; + @Override public Resource findResource(final String name) { - return resourceCache.get(name); + return resourceStorage.get(name); } + @Override public InputStream getInputStream(final String name) { - Resource resourceInfo = resourceCache.get(name); + Resource resourceInfo = resourceStorage.get(name); if (resourceInfo != null) { try (InputStream inputStream = resourceInfo.getUrl().openStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){ IOUtils.copy(inputStream, byteArrayOutputStream); - return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } catch (Exception e){ e.printStackTrace(); @@ -102,12 +99,9 @@ public abstract class AbstractResourceLoader { } } + @Override public List getResources(){ - return new ArrayList<>(resourceCache.values()); - } - - public void clear() { - resourceCache.clear(); + return resourceStorage.getAll(); } protected byte[] getClassBytes(String path, InputStream inputStream, boolean isClose) throws Exception{ @@ -126,6 +120,11 @@ public abstract class AbstractResourceLoader { } } + @Override + public void close() throws Exception { + resourceStorage.close(); + } + private static boolean isClass(String path){ if(path == null || "".equals(path)){ return false; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java similarity index 68% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java index 14277bd..0aff14d 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ClassPathLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java @@ -14,7 +14,9 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader; +package com.gitee.starblues.loader.classloader.resource.loader; +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; import java.io.File; import java.io.FileInputStream; @@ -28,27 +30,26 @@ import java.util.Objects; * @author starBlues * @version 3.0.0 */ -public class ClassPathLoader extends AbstractResourceLoader{ +public class ClassPathLoader extends AbstractResourceLoader { private final URL url; - public ClassPathLoader(URL url) { - super(url); + public ClassPathLoader(URL url, ResourceStorage resourceStorage) { + super(url, resourceStorage); this.url = Objects.requireNonNull(url, "url 不能为空"); } - public ClassPathLoader(File file) throws MalformedURLException { - this(file.toPath()); + public ClassPathLoader(File file, ResourceStorage resourceStorage) throws MalformedURLException { + this(file.toPath(), resourceStorage); } - public ClassPathLoader(Path path) throws MalformedURLException { - super(path.toUri().toURL()); + public ClassPathLoader(Path path, ResourceStorage resourceStorage) throws MalformedURLException { + super(path.toUri().toURL(), resourceStorage); this.url = super.baseUrl; } - @Override - protected void initOfChild() throws Exception { + protected void loadOfChild() throws Exception { File file = new File(url.toURI()); load(file, null); } @@ -85,16 +86,14 @@ public class ClassPathLoader extends AbstractResourceLoader{ } private void addResource(File file, String packageName) throws Exception { - Resource resource = new Resource( - file.getName(), url, new URL(url.toString() + packageName) - ); - if(file.exists() && file.isFile()){ - resource.setBytes(getClassBytes(file.getPath(), new FileInputStream(file), true)); - } - addResource(packageName, resource); + resourceStorage.add(packageName, url, new URL(url.toString() + packageName), ()->{ + if(file.exists() && file.isFile()){ + return getClassBytes(file.getPath(), new FileInputStream(file), true); + } else { + return null; + } + }); } - - } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/Resource.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResource.java similarity index 61% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/Resource.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResource.java index fa5547f..d8f53f9 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/Resource.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResource.java @@ -14,63 +14,57 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader; +package com.gitee.starblues.loader.classloader.resource.loader; + +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; import java.net.URL; -import java.nio.file.Paths; /** - * 资源信息 + * 默认的资源信息 * @author starBlues * @version 3.0.0 */ -public class Resource { - - public static final String PACKAGE_SPLIT = "/"; +public class DefaultResource implements Resource { private final String name; private final URL baseUrl; private final URL url; - private byte[] bytes; - - public Resource(String name, URL baseUrl, URL url) { + public DefaultResource(String name, URL baseUrl, URL url) { this.name = name; this.baseUrl = baseUrl; this.url = url; } + @Override public String getName() { return name; } + @Override public URL getBaseUrl() { return baseUrl; } + @Override public URL getUrl() { return url; } + @Override public byte[] getBytes() { - return bytes; + return null; } - public void setBytes(byte[] bytes) { - this.bytes = bytes; + @Override + public void setBytes(ResourceByteGetter byteGetter) throws Exception{ + // 忽略 } - void tryCloseUrlSystemFile(){ - try { - Paths.get(baseUrl.toURI()).getFileSystem().close(); - } catch (Exception e) { - e.printStackTrace(); - } - try { - Paths.get(url.toURI()).getFileSystem().close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + @Override + public void close() throws Exception { + } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java similarity index 53% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java index b41b979..77b1351 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java @@ -14,9 +14,11 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader; - +package com.gitee.starblues.loader.classloader.resource.loader; +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.launcher.ResourceLoaderFactoryGetter; +import com.gitee.starblues.loader.utils.IOUtils; import com.gitee.starblues.loader.utils.ResourceUtils; import java.io.File; @@ -27,26 +29,27 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** - * 资源加载工厂 + * 默认的资源加载工厂 + * * @author starBlues * @version 3.0.0 */ -public class ResourceLoaderFactory extends AbstractResourceLoader { +public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ - private final List resourceLoaders = new ArrayList<>(); + private final Map resourceLoaderMap = new ConcurrentHashMap<>(); - public ResourceLoaderFactory() { - super(null); - } + private final String classLoaderName; - public void addResourceLoader(AbstractResourceLoader resourceLoader){ - if(resourceLoader != null){ - resourceLoaders.add(resourceLoader); - } + public DefaultResourceLoaderFactory(String classLoaderName) { + this.classLoaderName = classLoaderName; } + + @Override public void addResource(String path) throws Exception{ if(path == null || "".equals(path)){ return; @@ -54,6 +57,7 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { addResource(Paths.get(path)); } + @Override public void addResource(File file) throws Exception{ if(file == null){ return; @@ -61,6 +65,7 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { addResource(file.toPath()); } + @Override public void addResource(Path path) throws Exception{ if(path == null){ return; @@ -71,39 +76,63 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { addResource(path.toUri().toURL()); } + @Override public void addResource(URL url) throws Exception{ AbstractResourceLoader resourceLoader = null; if(ResourceUtils.isJarFileUrl(url)) { if(ResourceUtils.isJarProtocolUrl(url)){ - resourceLoader = new JarResourceLoader(url); + resourceLoader = new JarResourceLoader(url, + ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName)); } else { - resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile()); + resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile(), + ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName)); } } else if(ResourceUtils.isFileUrl(url)){ - resourceLoader = new ClassPathLoader(url); + resourceLoader = new ClassPathLoader(url, + ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName)); } if(resourceLoader != null){ addResource(resourceLoader); } } - public void addResource(AbstractResourceLoader resourceLoader) throws Exception { - resourceLoader.init(); - resourceLoaders.add(resourceLoader); + @Override + public void addResource(ResourceLoader resourceLoader) throws Exception { + if(resourceLoader == null){ + return; + } + if (resourceLoaderMap.containsKey(resourceLoader.getBaseUrl())) { + return; + } + resourceLoader.load(); + resourceLoaderMap.put(resourceLoader.getBaseUrl(), resourceLoader); } @Override - public List getResources() { + public List findResources(String name) { List resources = new ArrayList<>(); - for (AbstractResourceLoader resourceLoader : resourceLoaders) { - resources.addAll(resourceLoader.getResources()); + for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { + Resource resource = resourceLoader.findResource(name); + if(resource != null){ + resources.add(resource); + } } return resources; } @Override - public synchronized Resource findResource(String name) { - for (AbstractResourceLoader resourceLoader : resourceLoaders) { + public URL getBaseUrl() { + return null; + } + + @Override + public void load() throws Exception { + // 忽略 + } + + @Override + public Resource findResource(String name) { + for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { Resource resourceInfo = resourceLoader.findResource(name); if(resourceInfo != null){ return resourceInfo; @@ -112,20 +141,9 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { return null; } - public synchronized List findResources(String name) { - List resourceInfos = new ArrayList<>(); - for (AbstractResourceLoader resourceLoader : resourceLoaders) { - Resource resource = resourceLoader.findResource(name); - if(resource != null){ - resourceInfos.add(resource); - } - } - return resourceInfos; - } - @Override - public synchronized InputStream getInputStream(String name) { - for (AbstractResourceLoader resourceLoader : resourceLoaders) { + public InputStream getInputStream(String name) { + for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { InputStream inputStream = resourceLoader.getInputStream(name); if(inputStream != null){ return inputStream; @@ -135,14 +153,19 @@ public class ResourceLoaderFactory extends AbstractResourceLoader { } @Override - public synchronized void clear() { - for (AbstractResourceLoader resourceLoader : resourceLoaders) { - try { - resourceLoader.clear(); - } catch (Exception e){ - // 忽略 - } + public List getResources() { + List resources = new ArrayList<>(); + for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { + resources.addAll(resourceLoader.getResources()); + } + return resources; + } + + @Override + public void close() throws Exception { + for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { + IOUtils.closeQuietly(resourceLoader); } - resourceLoaders.clear(); + resourceLoaderMap.clear(); } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java similarity index 75% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java index f3fa0ba..08af3fa 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/JarResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java @@ -14,14 +14,14 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader; +package com.gitee.starblues.loader.classloader.resource.loader; import com.gitee.starblues.loader.classloader.filter.ExcludeResource; import com.gitee.starblues.loader.classloader.filter.IncludeResource; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; import java.io.File; import java.net.URL; -import java.util.function.Function; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; @@ -30,26 +30,26 @@ import java.util.jar.JarInputStream; * @author starBlues * @version 3.0.0 */ -public class JarResourceLoader extends AbstractResourceLoader{ +public class JarResourceLoader extends AbstractResourceLoader { private final JarInputStream jarInputStream; private ExcludeResource excludeResource = (jarEntry)->false; private IncludeResource includeResource = (jarEntry)->true; - public JarResourceLoader(File file) throws Exception{ - super(new URL("jar:" + file.toURI().toURL() + "!/")); + public JarResourceLoader(File file, ResourceStorage resourceStorage) throws Exception{ + super(new URL("jar:" + file.toURI().toURL() + "!/"), resourceStorage); URL url = file.toURI().toURL(); this.jarInputStream = new JarInputStream(url.openStream()); } - public JarResourceLoader(URL url) throws Exception{ - super(url); + public JarResourceLoader(URL url, ResourceStorage resourceStorage) throws Exception{ + super(url, resourceStorage); this.jarInputStream = new JarInputStream(url.openStream()); } - public JarResourceLoader(URL url, JarInputStream jarInputStream) throws Exception{ - super(url); + public JarResourceLoader(URL url, JarInputStream jarInputStream, ResourceStorage resourceStorage) throws Exception{ + super(url, resourceStorage); this.jarInputStream = jarInputStream; } @@ -68,7 +68,7 @@ public class JarResourceLoader extends AbstractResourceLoader{ } @Override - protected void initOfChild() throws Exception { + protected void loadOfChild() throws Exception { // 解析 try { JarEntry jarEntry = null; @@ -79,9 +79,9 @@ public class JarResourceLoader extends AbstractResourceLoader{ if(includeResource.include(jarEntry)){ String name = resolveName(jarEntry.getName()); URL url = new URL(baseUrl.toString() + name); - Resource resource = new Resource(name, baseUrl, url); - resource.setBytes(getClassBytes(name, jarInputStream, false)); - addResource(name, resource); + resourceStorage.add(name, baseUrl, url, ()->{ + return getClassBytes(name, jarInputStream, false); + }); jarInputStream.closeEntry(); } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java new file mode 100644 index 0000000..d7112ca --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java @@ -0,0 +1,43 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource.loader; + +import com.gitee.starblues.loader.classloader.resource.Resource; + +import java.io.InputStream; +import java.net.URL; +import java.util.List; + +/** + * 资源加载者 + * + * @author starBlues + * @version 3.0.0 + */ +public interface ResourceLoader extends AutoCloseable{ + + URL getBaseUrl(); + + void load() throws Exception; + + Resource findResource(String name); + + InputStream getInputStream(String name); + + List getResources(); + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java new file mode 100644 index 0000000..ebd592d --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java @@ -0,0 +1,32 @@ +package com.gitee.starblues.loader.classloader.resource.loader; + +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; + +import java.io.File; +import java.net.URL; +import java.nio.file.Path; +import java.util.List; + +/** + * 资源加载工厂 + * + * @author starBlues + * @version 3.0.0 + */ +public interface ResourceLoaderFactory extends ResourceLoader{ + + + void addResource(String path) throws Exception; + + void addResource(File file) throws Exception; + + void addResource(Path path) throws Exception; + + void addResource(URL url) throws Exception; + + void addResource(ResourceLoader resourceLoader) throws Exception; + + List findResources(String name); + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java new file mode 100644 index 0000000..c25b2d5 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java @@ -0,0 +1,32 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource.loader; + +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; + +/** + * 资源加载获取者 + * + * @author starBlues + * @version 3.0.0 + */ +@FunctionalInterface +public interface ResourceLoaderGetter { + + ResourceLoader get(ResourceStorage resourceStorage) throws Exception; + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java new file mode 100644 index 0000000..7dfcd0c --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java @@ -0,0 +1,71 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource.storage; + +import com.gitee.starblues.loader.classloader.resource.loader.DefaultResource; +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; + +import java.net.URL; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 可缓存的资源存储者 + * + * @author starBlues + * @version 3.0.0 + */ +public class CacheResourceStorage extends DefaultResourceStorage{ + + protected final Map resourceStorage = new ConcurrentHashMap<>(); + + @Override + public void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception{ + if(resourceStorage.containsKey(name)){ + return; + } + CacheResource cacheResource = new CacheResource(name, baseUrl, url); + cacheResource.setBytes(byteGetter); + addResource(name, cacheResource); + } + + private static class CacheResource extends DefaultResource { + + private byte[] bytes; + + public CacheResource(String name, URL baseUrl, URL url) { + super(name, baseUrl, url); + } + + @Override + public void setBytes(ResourceByteGetter byteGetter) throws Exception{ + if(byteGetter == null){ + return; + } + // 忽略 + bytes = byteGetter.get(); + } + + @Override + public byte[] getBytes() { + return bytes; + } + } + + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java new file mode 100644 index 0000000..195df1f --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java @@ -0,0 +1,80 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource.storage; + +import com.gitee.starblues.loader.classloader.resource.loader.DefaultResource; +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; +import com.gitee.starblues.loader.utils.IOUtils; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 默认的资源存储者 + * + * @author starBlues + * @version 3.0.0 + */ +public class DefaultResourceStorage implements ResourceStorage{ + + protected final Map resourceStorage = new ConcurrentHashMap<>(); + + @Override + public void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception{ + if(resourceStorage.containsKey(name)){ + return; + } + DefaultResource defaultResource = new DefaultResource(name, baseUrl, url); + addResource(name, defaultResource); + } + + @Override + public void add(String name, URL baseUrl, URL url) throws Exception{ + this.add(name, baseUrl, url, null); + } + + @Override + public boolean exist(String name) { + return resourceStorage.containsKey(name); + } + + protected void addResource(String name, Resource resource){ + resourceStorage.put(name, resource); + } + + @Override + public Resource get(String name) { + return resourceStorage.get(name); + } + + @Override + public List getAll() { + return new ArrayList<>(resourceStorage.values()); + } + + @Override + public void close() throws Exception { + for (Resource resource : resourceStorage.values()) { + IOUtils.closeQuietly(resource); + } + resourceStorage.clear(); + } +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java new file mode 100644 index 0000000..fd328a1 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java @@ -0,0 +1,71 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource.storage; + +import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; + +import java.net.URL; +import java.util.List; + +/** + * 资源存储者 + * + * @author starBlues + * @version 3.0.0 + */ +public interface ResourceStorage extends AutoCloseable{ + + /** + * 添加资源 + * @param name 资源名称 + * @param baseUrl 资源根URL + * @param url 资源url + * @param byteGetter 资源字节获取者 + */ + void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception; + + /** + * 添加资源 + * @param name 资源名称 + * @param baseUrl 资源根URL + * @param url 资源url + */ + void add(String name, URL baseUrl, URL url) throws Exception; + + /** + * 存在资源 + * @param name 资源名称 + * @return 存在 true, 不存在 false + */ + boolean exist(String name); + + /** + * 获取资源 + * @param name 资源名称 + * @return Resource + */ + Resource get(String name); + + /** + * 得到全部资源 + * @return 全部资源列表 + */ + List getAll(); + + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java new file mode 100644 index 0000000..a4b6a41 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java @@ -0,0 +1,160 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.classloader.resource.storage; + +import com.gitee.starblues.loader.classloader.resource.loader.DefaultResource; +import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; +import com.gitee.starblues.loader.utils.Assert; + +import java.net.URL; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 共享资源存储者 + * + * @author starBlues + * @version 3.0.0 + */ +public class ShareResourceStorage extends DefaultResourceStorage{ + + private final String key; + + public ShareResourceStorage(String key) { + this.key = key; + } + + @Override + public void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception{ + if(resourceStorage.containsKey(name)){ + return; + } + ShareResource shareResource = new ShareResource(key, name, baseUrl, url); + shareResource.setBytes(byteGetter); + super.addResource(name, shareResource); + } + + private static class ShareResource extends DefaultResource { + + private final static Map BYTE_STORE_MAP = new ConcurrentHashMap<>(); + private final String key; + + public ShareResource(String key, String name, URL baseUrl, URL url) { + super(name, baseUrl, url); + this.key = key; + } + + @Override + public void setBytes(ResourceByteGetter byteGetter) throws Exception{ + if(byteGetter == null){ + return; + } + byte[] bytes = byteGetter.get(); + String name = getName(); + ByteStore byteStore = BYTE_STORE_MAP.get(name); + if(byteStore == null){ + byteStore = new ByteStore(name); + byteStore.addByte(key, bytes); + BYTE_STORE_MAP.put(getName(), byteStore); + } else { + byteStore.addByte(key, bytes); + } + } + + @Override + public byte[] getBytes() { + String name = getName(); + ByteStore byteStore = BYTE_STORE_MAP.get(name); + if(byteStore == null){ + return null; + } + return byteStore.getByte(key); + } + + @Override + public void close() throws Exception { + String name = getName(); + ByteStore byteStore = BYTE_STORE_MAP.get(name); + if(byteStore == null){ + return; + } + if(byteStore.remove(key)){ + BYTE_STORE_MAP.remove(name); + } + } + } + + private static class ByteStore{ + + private final String resourceName; + + private final String commonByteKey; + + private final Map bytesMap = new HashMap<>(); + + private ByteStore(String resourceName) { + this.resourceName = resourceName; + this.commonByteKey = resourceName + "_ByteStoreCommon"; + } + + public String getResourceName() { + return resourceName; + } + + public synchronized void addByte(String key, byte[] bytes){ + Assert.isNotEmpty(key, "classLoaderName 不能为空"); + if(bytes == null || bytes.length == 0){ + return; + } + byte[] bytesOfMap = bytesMap.get(commonByteKey); + if(bytesOfMap != null && bytesOfMap.length > 0){ + if(Arrays.equals(bytesOfMap, bytes)){ + bytesMap.put(key, new byte[]{}); + } else { + bytesMap.put(key, bytes); + } + return; + } + // common 不存在, 则往 common 存储一份 + bytesMap.put(commonByteKey, bytes); + bytesMap.put(key, new byte[]{}); + } + + public synchronized byte[] getByte(String classLoaderName){ + byte[] bytes = bytesMap.get(classLoaderName); + if(bytes == null || bytes.length == 0){ + bytes = bytesMap.get(commonByteKey); + } + return bytes; + } + + public boolean remove(String classLoaderName){ + bytesMap.remove(classLoaderName); + if(bytesMap.size() == 1 && bytesMap.containsKey(commonByteKey)){ + // 只存在一个common + bytesMap.clear(); + return true; + } else { + return false; + } + } + + } + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java index 38b0aa9..ae88cdd 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AbstractJarFile.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.io.File; @@ -55,7 +71,20 @@ public abstract class AbstractJarFile extends java.util.jar.JarFile{ */ enum JarFileType { - DIRECT, NESTED_DIRECTORY, NESTED_JAR + /** + * DIRECT + */ + DIRECT, + + /** + * NESTED_DIRECTORY + */ + NESTED_DIRECTORY, + + /** + * NESTED_JAR + */ + NESTED_JAR } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java index 22d65d3..be75721 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/AsciiBytes.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.nio.charset.StandardCharsets; @@ -122,8 +138,7 @@ public class AsciiBytes { if (c != b) { return false; } - } - else { + } else { if (c != ((b >> 0xA) + 0xD7C0)) { return false; } @@ -193,8 +208,7 @@ public class AsciiBytes { } if (b <= 0xFFFF) { hash = 31 * hash + b; - } - else { + } else { hash = 31 * hash + ((b >> 0xA) + 0xD7C0); hash = 31 * hash + ((b & 0x3FF) + 0xDC00); } @@ -209,8 +223,7 @@ public class AsciiBytes { if (this.string == null) { if (this.length == 0) { this.string = EMPTY_STRING; - } - else { + } else { this.string = new String(this.bytes, this.offset, this.length, StandardCharsets.UTF_8); } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java index 13e46ab..6b19352 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Bytes.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; /** diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java index f9ef4a3..3e941a3 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryEndRecord.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.io.IOException; @@ -63,7 +79,8 @@ public class CentralDirectoryEndRecord { } private boolean isValid() { - if (this.block.length < MINIMUM_SIZE || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { + if (this.block.length < MINIMUM_SIZE || + Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { return false; } // Total size must be the structure size + comment diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java index 62c00ce..be3a473 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryFileHeader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.io.IOException; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java index 72d91bd..e589c37 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryParser.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.io.IOException; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java index 62cc7e9..046120c 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/CentralDirectoryVisitor.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; /** diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java index 64b93d7..7c500e4 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/FileHeader.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.util.zip.ZipEntry; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java index 4e00ad2..558bb1b 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/Handler.java @@ -1,5 +1,20 @@ -package com.gitee.starblues.loader.jar; +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitee.starblues.loader.jar; import com.gitee.starblues.loader.PluginResourceStorage; @@ -119,8 +134,8 @@ public class Handler extends URLStreamHandler { URLConnection connection = openConnection(new URL("jar:file:" + file)); connection.getInputStream().close(); return connection; - } - catch (IOException ex) { + } catch (IOException ex) { + // ignore } } return null; @@ -133,8 +148,8 @@ public class Handler extends URLStreamHandler { if (connection.getClass().getName().startsWith("org.apache.catalina")) { return true; } - } - catch (Exception ex) { + } catch (Exception ex) { + // ignore } } return false; @@ -154,6 +169,7 @@ public class Handler extends URLStreamHandler { return new URL(jarContextUrl, url.toExternalForm()).openConnection(); } } catch (Exception ex) { + // ignore } return null; } @@ -179,8 +195,7 @@ public class Handler extends URLStreamHandler { Class handlerClass = Class.forName(handlerClassName); this.fallbackHandler = (URLStreamHandler) handlerClass.getDeclaredConstructor().newInstance(); return this.fallbackHandler; - } - catch (Exception ex) { + } catch (Exception ex) { // Ignore } } @@ -191,8 +206,7 @@ public class Handler extends URLStreamHandler { try { Level level = warning ? Level.WARNING : Level.FINEST; Logger.getLogger(getClass().getName()).log(level, message, cause); - } - catch (Exception ex) { + } catch (Exception ex) { if (warning) { System.err.println("WARNING: " + message); } @@ -203,8 +217,7 @@ public class Handler extends URLStreamHandler { protected void parseURL(URL context, String spec, int start, int limit) { if (spec.regionMatches(true, 0, JAR_PROTOCOL, 0, JAR_PROTOCOL.length())) { setFile(context, getFileFromSpec(spec.substring(start, limit))); - } - else { + } else { setFile(context, getFileFromContext(context, spec.substring(start, limit))); } } @@ -217,8 +230,7 @@ public class Handler extends URLStreamHandler { try { new URL(spec.substring(0, separatorIndex)); return spec; - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { throw new IllegalArgumentException("Invalid spec URL '" + spec + "'", ex); } } @@ -274,8 +286,7 @@ public class Handler extends URLStreamHandler { int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1); if (precedingSlashIndex >= 0) { file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3); - } - else { + } else { file = file.substring(parentDirIndex + 4); } } @@ -301,8 +312,7 @@ public class Handler extends URLStreamHandler { String entry = canonicalize(file.substring(separatorIndex + 2)); try { result += new URL(source).hashCode(); - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { result += source.hashCode(); } result += entry.hashCode(); @@ -332,8 +342,7 @@ public class Handler extends URLStreamHandler { String root2 = u2.getFile().substring(0, separator2); try { return super.sameFile(new URL(root1), new URL(root2)); - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { // Continue } return super.sameFile(u1, u2); @@ -401,15 +410,13 @@ public class Handler extends URLStreamHandler { if (connection instanceof JarURLConnection) { jarContextUrl = null; } + } catch (Exception ex) { + // ignore } - catch (Exception ex) { - } - } - finally { + } finally { if (handlers == null) { System.clearProperty(PROTOCOL_HANDLER); - } - else { + } else { System.setProperty(PROTOCOL_HANDLER, handlers); } } @@ -421,8 +428,7 @@ public class Handler extends URLStreamHandler { try { resetCachedUrlHandlers(); return true; - } - catch (Error ex) { + } catch (Error ex) { return false; } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java index 0d68445..b5c0a7c 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntry.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.io.IOException; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java index c4b1d5e..2313ef8 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryCertification.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.security.CodeSigner; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java index 54cb294..defa225 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarEntryFilter.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; /** diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java index 841b1b1..e22c64d 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/jar/JarFile.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.jar; import java.io.File; @@ -108,8 +124,7 @@ public class JarFile extends AbstractJarFile implements Iterable(manifest); @@ -360,8 +373,7 @@ public class JarFile extends AbstractJarFile implements Iterable 65536) ? 8192 : size; size = (size <= 0) ? 4096 : size; return (int) size; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java index a4853d0..573ce90 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/AbstractLauncher.java @@ -16,8 +16,6 @@ package com.gitee.starblues.loader.launcher; -import com.gitee.starblues.loader.jar.JarFile; - /** * 抽象的启动引导者 * @author starBlues @@ -27,7 +25,7 @@ public abstract class AbstractLauncher implements Launcher { @Override public R run(String... args) throws Exception { - ClassLoader classLoader = createClassLoader(); + ClassLoader classLoader = createClassLoader(args); Thread thread = Thread.currentThread(); ClassLoader oldClassLoader = thread.getContextClassLoader(); try { @@ -43,7 +41,7 @@ public abstract class AbstractLauncher implements Launcher { * @return ClassLoader * @throws Exception 创建异常 */ - protected abstract ClassLoader createClassLoader() throws Exception; + protected abstract ClassLoader createClassLoader(String... args) throws Exception; /** * 子类实现具体的启动方法 diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java index 942855a..d0f8649 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java @@ -20,8 +20,8 @@ import com.gitee.starblues.loader.archive.Archive; import com.gitee.starblues.loader.archive.ExplodedArchive; import com.gitee.starblues.loader.archive.JarFileArchive; import com.gitee.starblues.loader.classloader.GenericClassLoader; -import com.gitee.starblues.loader.classloader.JarResourceLoader; -import com.gitee.starblues.loader.classloader.ResourceLoaderFactory; +import com.gitee.starblues.loader.classloader.resource.loader.JarResourceLoader; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; import com.gitee.starblues.loader.launcher.runner.MethodRunner; import java.io.File; @@ -78,21 +78,19 @@ public class MainJarProgramLauncher extends MainProgramLauncher{ Archive archive = archives.next(); URL url = archive.getUrl(); String path = url.getPath(); - ResourceLoaderFactory resourceLoaderFactory = classLoader.getResourceLoaderFactory(); + ResourceStorage resourceStorage = ResourceLoaderFactoryGetter.getMainResourceStorage(); if(path.contains(PROD_CLASSES_URL_SIGN)){ - MainJarResourceLoader jarResourceLoader = new MainJarResourceLoader(url); - resourceLoaderFactory.addResource(jarResourceLoader); + classLoader.addResource(new MainJarResourceLoader(url, resourceStorage)); } else { - JarResourceLoader jarResourceLoader = new JarResourceLoader(url); - resourceLoaderFactory.addResource(jarResourceLoader); + classLoader.addResource(new JarResourceLoader(url, resourceStorage)); } } } private static class MainJarResourceLoader extends JarResourceLoader { - public MainJarResourceLoader(URL url) throws Exception { - super(url); + public MainJarResourceLoader(URL url, ResourceStorage resourceStorage) throws Exception { + super(url, resourceStorage); } @Override diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java index 472b308..0d62b0c 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java @@ -17,6 +17,7 @@ package com.gitee.starblues.loader.launcher; import com.gitee.starblues.loader.classloader.GenericClassLoader; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; import com.gitee.starblues.loader.launcher.runner.MethodRunner; import com.gitee.starblues.loader.utils.ObjectUtils; @@ -32,7 +33,7 @@ import java.net.URLClassLoader; */ public class MainProgramLauncher extends AbstractLauncher{ - private static final String MAIN_CLASS_LOADER_NAME = "MainProgramLauncherClassLoader"; + public static final String MAIN_CLASS_LOADER_NAME = "MainProgramLauncherClassLoader"; private final MethodRunner methodRunner; @@ -41,8 +42,9 @@ public class MainProgramLauncher extends AbstractLauncher{ } @Override - protected ClassLoader createClassLoader() throws Exception { - GenericClassLoader classLoader = new GenericClassLoader(MAIN_CLASS_LOADER_NAME, getParentClassLoader()); + protected ClassLoader createClassLoader(String... args) throws Exception { + GenericClassLoader classLoader = new GenericClassLoader(MAIN_CLASS_LOADER_NAME, getParentClassLoader(), + getResourceLoaderFactory()); addResource(classLoader); return classLoader; } @@ -53,6 +55,10 @@ public class MainProgramLauncher extends AbstractLauncher{ return classLoader; } + protected ResourceLoaderFactory getResourceLoaderFactory(String... args){ + return ResourceLoaderFactoryGetter.create(MAIN_CLASS_LOADER_NAME, args); + } + protected ClassLoader getParentClassLoader(){ return MainProgramLauncher.class.getClassLoader(); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java new file mode 100644 index 0000000..417f2e9 --- /dev/null +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java @@ -0,0 +1,107 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.loader.launcher; + +import com.gitee.starblues.loader.classloader.resource.loader.DefaultResourceLoaderFactory; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; +import com.gitee.starblues.loader.classloader.resource.storage.CacheResourceStorage; +import com.gitee.starblues.loader.classloader.resource.storage.DefaultResourceStorage; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; +import com.gitee.starblues.loader.classloader.resource.storage.ShareResourceStorage; + +import java.util.Objects; + +/** + * 获取ResourceLoaderFactory + * + * @author starBlues + * @version 3.0.0 + */ +public class ResourceLoaderFactoryGetter { + + private static final String PARAMS_KEY = "--resource.store.mode"; + + + /** + * 资源模式--缓存隔离模式 + */ + private static final String RESOURCE_MODE_CACHE_ISOLATION = "cache-isolation"; + + + /** + * 资源模式--缓存共享模式 + */ + private static final String RESOURCE_MODE_CACHE_SHARE = "cache-share"; + + + /** + * 资源模式--不缓存模式 + */ + private static final String RESOURCE_MODE_NO_CACHE = "no-cache"; + + private static volatile String resourceMode; + + + public static ResourceLoaderFactory create(String classLoaderName, String... args){ + if(resourceMode == null){ + synchronized (ResourceLoaderFactory.class){ + if(resourceMode == null){ + resourceMode = parseArg(args); + } + } + } + return instant(classLoaderName); + } + + public static synchronized ResourceLoaderFactory get(String classLoaderName){ + return instant(classLoaderName); + } + + private static String parseArg(String... args){ + for (String arg : args) { + if(arg.startsWith(PARAMS_KEY)){ + String[] split = arg.split("="); + if(split.length != 2){ + return null; + } + return split[1]; + } + } + return null; + } + + public static ResourceStorage getResourceStorage(String key){ + ResourceStorage resourceStorage = null; + if(Objects.equals(resourceMode, RESOURCE_MODE_NO_CACHE)){ + resourceStorage = new DefaultResourceStorage(); + } else if(Objects.equals(resourceMode, RESOURCE_MODE_CACHE_SHARE)){ + resourceStorage = new ShareResourceStorage(key); + } else { + resourceStorage = new CacheResourceStorage(); + } + return resourceStorage; + } + + public static ResourceStorage getMainResourceStorage(){ + return getResourceStorage(MainProgramLauncher.MAIN_CLASS_LOADER_NAME); + } + + private static ResourceLoaderFactory instant(String classLoaderName){ + return new DefaultResourceLoaderFactory(classLoaderName); + } + +} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java index 2a276b4..5e79f5a 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainProdBootstrap.java @@ -28,6 +28,7 @@ import java.security.ProtectionDomain; import java.util.jar.Manifest; /** + * 主程序生成环境启动引导器 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java deleted file mode 100644 index 9786bd1..0000000 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/SpringBootRunner.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.starblues.loader.launcher.runner; - -import java.util.concurrent.CountDownLatch; - -/** - * @author starBlues - * @version 3.0.0 - */ -public class SpringBootRunner implements Runnable{ - - private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1); - - private final MethodRunner methodRunner; - - public SpringBootRunner(MethodRunner methodRunner) { - this.methodRunner = methodRunner; - } - - @Override - public void run() { - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - try { - methodRunner.run(contextClassLoader); - } catch (Exception e) { - e.printStackTrace(); - } finally { - COUNT_DOWN_LATCH.countDown(); - } - } -} diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java index 13e8ba5..2b0d746 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/CompareClassTypeUtils.java @@ -1,6 +1,24 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.utils; /** + * 比较两个类类型 + * * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java index 6947e01..483cda5 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/IOUtils.java @@ -19,6 +19,8 @@ import java.io.*; import java.util.function.Consumer; /** + * io utils + * * @author starBlues * @version 3.0.0 */ @@ -54,15 +56,15 @@ public class IOUtils { return output.toByteArray(); } - public static void closeQuietly(final Closeable closeable) { + public static void closeQuietly(final AutoCloseable closeable) { closeQuietly(closeable, null); } - public static void closeQuietly(final Closeable closeable, final Consumer consumer) { + public static void closeQuietly(final AutoCloseable closeable, final Consumer consumer) { if (closeable != null) { try { closeable.close(); - } catch (final IOException e) { + } catch (final Exception e) { if (consumer != null) { consumer.accept(e); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java index 817ad6f..8490c72 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ObjectUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.utils; import java.lang.reflect.Array; @@ -6,6 +22,8 @@ import java.util.Map; import java.util.Optional; /** + * object utils + * * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java index 8feb952..0b4297c 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.utils; import java.net.URL; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java index 26ecd30..f0b90e5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java @@ -17,6 +17,9 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.utils.Assert; + +import java.util.Date; /** * 默认的内部PluginWrapperInside实现 @@ -30,6 +33,9 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { private PluginState pluginState; private boolean isFollowInitial = false; + private Date startTime; + private Date stopTime; + public DefaultPluginInsideInfo(InsidePluginDescriptor pluginDescriptor) { this.pluginId = pluginDescriptor.getPluginId(); this.pluginDescriptor = pluginDescriptor; @@ -37,7 +43,8 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { @Override public void setPluginState(PluginState pluginState) { - this.pluginState = pluginState; + this.pluginState = Assert.isNotNull(pluginState, "pluginState 不能为空"); + resolveTime(pluginState); } @Override @@ -70,10 +77,32 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { return pluginState; } + @Override + public Date startTime() { + return startTime; + } + + @Override + public Date stopTime() { + return stopTime; + } + @Override public boolean isFollowSystem() { return isFollowInitial; } + private void resolveTime(PluginState pluginState){ + if(pluginState == PluginState.STARTED){ + startTime = new Date(); + stopTime = null; + } if(pluginState == PluginState.STOPPED){ + stopTime = new Date(); + startTime = null; + } else { + startTime = null; + stopTime = null; + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index c170cc8..a4bd063 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -242,7 +242,7 @@ public class DefaultPluginManager implements PluginManager{ } PluginException pluginException = PluginException.getPluginException(e, ()-> { unLoad(loadPluginInfo.getPluginId()); - throw new PluginException("插件包安装失败: " + pluginPath); + throw new PluginException("插件包[ " + pluginPath + " ]安装失败: " + e.getMessage(), e); }); pluginListenerFactory.startFailure(pluginInfo, pluginException); throw pluginException; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java index b451512..edc51f2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java @@ -18,6 +18,8 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; +import java.util.Date; + /** * 插件信息 * @author starBlues @@ -49,6 +51,19 @@ public interface PluginInfo { */ PluginState getPluginState(); + /** + * 启动时间. 只有启动状态 {@link PluginState#STARTED} 才有值。 + * @return Date + */ + Date startTime(); + + /** + * 停止时间. 只有停止状态 {@link PluginState#STOPPED} 才有值。 + * @return Date + */ + Date stopTime(); + + /** * 是否跟随系统启动而加载的插件 * @return true: 是, false: 否 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java index ad7b0d9..6873ea7 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java @@ -19,6 +19,8 @@ package com.gitee.starblues.core; import com.gitee.starblues.core.descriptor.PluginDescriptor; import com.gitee.starblues.utils.Assert; +import java.util.Date; + /** * 外部 PluginWrapperFace * @author starBlues @@ -30,11 +32,16 @@ public class PluginInfoFace implements PluginInfo { private final PluginState pluginState; private final boolean followSystem; + private final Date startTime; + private final Date stopTime; + public PluginInfoFace(PluginInsideInfo pluginInsideInfo) { Assert.isNotNull(pluginInsideInfo, "参数 pluginWrapperInside 不能为空"); this.pluginDescriptor = pluginInsideInfo.getPluginDescriptor().toPluginDescriptor(); this.pluginState = pluginInsideInfo.getPluginState(); this.followSystem = pluginInsideInfo.isFollowSystem(); + this.startTime = pluginInsideInfo.startTime(); + this.stopTime = pluginInsideInfo.stopTime(); } @Override @@ -57,6 +64,16 @@ public class PluginInfoFace implements PluginInfo { return pluginState; } + @Override + public Date startTime() { + return startTime; + } + + @Override + public Date stopTime() { + return stopTime; + } + @Override public boolean isFollowSystem() { return followSystem; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java index 75fc7c5..eef2c2c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java @@ -17,12 +17,13 @@ package com.gitee.starblues.core.classloader; +import com.gitee.starblues.core.descriptor.PluginLibInfo; import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.loader.classloader.AbstractResourceLoader; -import com.gitee.starblues.loader.classloader.JarResourceLoader; -import com.gitee.starblues.loader.classloader.Resource; -import com.gitee.starblues.loader.classloader.ResourceLoaderFactory; +import com.gitee.starblues.loader.classloader.*; +import com.gitee.starblues.loader.classloader.resource.loader.*; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; +import com.gitee.starblues.loader.launcher.ResourceLoaderFactoryGetter; import java.io.InputStream; import java.net.URL; @@ -41,17 +42,18 @@ import java.util.zip.ZipEntry; public class NestedPluginJarResourceLoader extends AbstractResourceLoader { private final InsidePluginDescriptor pluginDescriptor; - private final ResourceLoaderFactory resourceLoaderFactory; + private final GenericClassLoader parentClassLoader; public NestedPluginJarResourceLoader(InsidePluginDescriptor pluginDescriptor, - ResourceLoaderFactory resourceLoaderFactory) throws Exception { - super(new URL("jar:" + pluginDescriptor.getInsidePluginPath().toUri().toURL() + "!/")); + GenericClassLoader parentClassLoader) throws Exception { + super(new URL("jar:" + pluginDescriptor.getInsidePluginPath().toUri().toURL() + "!/"), + ResourceLoaderFactoryGetter.getResourceStorage(pluginDescriptor.getPluginId())); this.pluginDescriptor = pluginDescriptor; - this.resourceLoaderFactory = resourceLoaderFactory; + this.parentClassLoader = parentClassLoader; } @Override - protected void initOfChild() throws Exception { + protected void loadOfChild() throws Exception { try (JarFile jarFile = new JarFile(pluginDescriptor.getInsidePluginPath().toFile())) { addClassPath(jarFile); addLib(jarFile); @@ -61,38 +63,38 @@ public class NestedPluginJarResourceLoader extends AbstractResourceLoader { private void addClassPath(JarFile jarFile) throws Exception{ String classesPath = pluginDescriptor.getPluginClassPath(); Enumeration entries = jarFile.entries(); - JarEntry jarEntry; while (entries.hasMoreElements()){ - jarEntry = entries.nextElement(); + JarEntry jarEntry = entries.nextElement(); if(!jarEntry.getName().startsWith(classesPath)){ continue; } String realName = jarEntry.getName().replace(classesPath, ""); URL url = new URL(baseUrl.toString() + jarEntry.getName()); - Resource resource = new Resource(realName, baseUrl, url); - resource.setBytes(getClassBytes(realName, jarFile.getInputStream(jarEntry), true)); - addResource(realName, resource); + super.resourceStorage.add(realName, baseUrl, url, ()->{ + return getClassBytes(realName, jarFile.getInputStream(jarEntry), true); + }); } } private void addLib(JarFile jarFile) throws Exception { JarEntry jarEntry = null; - Set pluginLibPaths = pluginDescriptor.getPluginLibPaths(); - for (String pluginLibPath : pluginLibPaths) { - jarEntry = jarFile.getJarEntry(pluginLibPath); + Set pluginLibInfos = pluginDescriptor.getPluginLibInfo(); + for (PluginLibInfo pluginLibInfo : pluginLibInfos) { + jarEntry = jarFile.getJarEntry(pluginLibInfo.getPath()); if (jarEntry.getMethod() != ZipEntry.STORED) { throw new PluginException("插件依赖压缩方式错误, 必须是: 存储(stored)压缩方式"); } InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); - URL url = new URL(baseUrl.toString() + pluginLibPath + "!/"); - JarResourceLoader jarResourceLoader = new JarResourceLoader(url, new JarInputStream(jarFileInputStream)); - jarResourceLoader.init(); - resourceLoaderFactory.addResourceLoader(jarResourceLoader); + URL url = new URL(baseUrl.toString() + pluginLibInfo.getPath() + "!/"); + if(pluginLibInfo.isLoadToMain()){ + parentClassLoader.addResource(new JarResourceLoader(url, new JarInputStream(jarFileInputStream), + ResourceLoaderFactoryGetter.getMainResourceStorage())); + } else { + JarResourceLoader jarResourceLoader = new JarResourceLoader(url, + new JarInputStream(jarFileInputStream), resourceStorage); + jarResourceLoader.load(); + } } } - @Override - public void clear() { - super.clear(); - } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index 74f66f0..d254fe8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -17,13 +17,20 @@ package com.gitee.starblues.core.classloader; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; +import com.gitee.starblues.core.descriptor.PluginLibInfo; +import com.gitee.starblues.core.descriptor.PluginType; import com.gitee.starblues.loader.classloader.*; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.FilesUtils; +import com.gitee.starblues.utils.ObjectUtils; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; +import java.util.Set; /** * 插件 classLoader @@ -32,31 +39,60 @@ import java.util.Enumeration; */ public class PluginClassLoader extends GenericClassLoader { + private final GenericClassLoader parentClassLoader; private MainResourceMatcher mainResourceMatcher; - public PluginClassLoader(String name) { - this(name, null); + public PluginClassLoader(String name, GenericClassLoader parentClassLoader, MainResourcePatternDefiner patternDefiner, + ResourceLoaderFactory resourceLoaderFactory) { + super(name, parentClassLoader, resourceLoaderFactory); + this.parentClassLoader = parentClassLoader; + if(patternDefiner != null){ + setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); + } else { + setMainResourceMatcher(new ProhibitMainResourceMatcher()); + } } - public PluginClassLoader(String name, ClassLoader parentClassLoader) { - this(name, parentClassLoader, null); + public void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ + this.mainResourceMatcher = Assert.isNotNull(mainResourceMatcher, "参数 mainResourceMatcher 不能为空"); } - public PluginClassLoader(String name, ClassLoader parentClassLoader, MainResourcePatternDefiner patternDefiner) { - super(name, parentClassLoader, new PluginResourceLoaderFactory()); - if(patternDefiner != null){ - setMainResourceMatcher(new CacheMainResourceMatcher(patternDefiner)); + public void addResource(InsidePluginDescriptor descriptor) throws Exception { + PluginType pluginType = descriptor.getType(); + if(pluginType == PluginType.JAR || pluginType == PluginType.ZIP){ + NestedPluginJarResourceLoader resourceLoader = + new NestedPluginJarResourceLoader(descriptor, parentClassLoader); + resourceLoaderFactory.addResource(resourceLoader); } else { - setMainResourceMatcher(new ProhibitMainResourceMatcher()); + addClasspath(descriptor); + addLibFile(descriptor); } } - public void addResource(InsidePluginDescriptor pluginDescriptor) throws Exception { - ((PluginResourceLoaderFactory) resourceLoaderFactory).addResource(pluginDescriptor); + private void addClasspath(InsidePluginDescriptor pluginDescriptor) throws Exception { + String pluginClassPath = pluginDescriptor.getPluginClassPath(); + File existFile = FilesUtils.getExistFile(pluginClassPath); + if(existFile != null){ + addResource(existFile); + } } - public void setMainResourceMatcher(MainResourceMatcher mainResourceMatcher){ - this.mainResourceMatcher = Assert.isNotNull(mainResourceMatcher, "参数 mainResourceMatcher 不能为空"); + private void addLibFile(InsidePluginDescriptor pluginDescriptor) throws Exception { + Set pluginLibInfos = pluginDescriptor.getPluginLibInfo(); + if(ObjectUtils.isEmpty(pluginLibInfos)){ + return; + } + for (PluginLibInfo pluginLibInfo : pluginLibInfos) { + File existFile = FilesUtils.getExistFile(pluginLibInfo.getPath()); + if(existFile != null){ + if(pluginLibInfo.isLoadToMain()){ + // 加载到主程序中 + parentClassLoader.addResource(existFile); + } else { + addResource(existFile); + } + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java deleted file mode 100644 index f3375c8..0000000 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginResourceLoaderFactory.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright [2019-2022] [starBlues] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.gitee.starblues.core.classloader; - -import com.gitee.starblues.core.descriptor.PluginType; -import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; -import com.gitee.starblues.loader.classloader.ResourceLoaderFactory; -import com.gitee.starblues.utils.FilesUtils; -import com.gitee.starblues.utils.ObjectUtils; - -import java.io.File; -import java.util.Set; - -/** - * 插件资源加载者工厂 - * @author starBlues - * @version 3.0.0 - */ -public class PluginResourceLoaderFactory extends ResourceLoaderFactory { - - - public synchronized void addResource(InsidePluginDescriptor descriptor) throws Exception{ - PluginType pluginType = descriptor.getType(); - if(pluginType == PluginType.JAR || pluginType == PluginType.ZIP){ - NestedPluginJarResourceLoader resourceLoader = - new NestedPluginJarResourceLoader(descriptor, this); - resourceLoader.init(); - addResourceLoader(resourceLoader); - } else if(pluginType == PluginType.DIR || pluginType == PluginType.DEV){ - addClasspath(descriptor); - addLibFile(descriptor); - } - } - - private void addClasspath(InsidePluginDescriptor pluginDescriptor) throws Exception { - String pluginClassPath = pluginDescriptor.getPluginClassPath(); - File existFile = FilesUtils.getExistFile(pluginClassPath); - if(existFile != null){ - addResource(existFile); - } - } - - private void addLibFile(InsidePluginDescriptor pluginDescriptor) throws Exception { - Set pluginLibPaths = pluginDescriptor.getPluginLibPaths(); - if(ObjectUtils.isEmpty(pluginLibPaths)){ - return; - } - for (String pluginLibPath : pluginLibPaths) { - File existFile = FilesUtils.getExistFile(pluginLibPath); - if(existFile != null){ - addResource(existFile); - } - } - } - -} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index c0c21ab..a386698 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -17,10 +17,10 @@ package com.gitee.starblues.core.descriptor; -import com.gitee.starblues.common.AbstractDependencyPlugin; -import com.gitee.starblues.common.DependencyPlugin; +import com.gitee.starblues.common.*; import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.utils.FilesUtils; +import com.gitee.starblues.utils.ManifestUtils; import com.gitee.starblues.utils.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,7 +30,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.util.List; +import java.util.*; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -87,7 +87,7 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor ); PluginResourcesConfig pluginResourcesConfig = getPluginResourcesConfig(path, attributes); - descriptor.setPluginLibPath(pluginResourcesConfig.getDependenciesIndex()); + descriptor.setPluginLibInfo(getPluginLibInfo(pluginResourcesConfig.getDependenciesIndex())); descriptor.setIncludeMainResourcePatterns(pluginResourcesConfig.getLoadMainResourceIncludes()); descriptor.setExcludeMainResourcePatterns(pluginResourcesConfig.getLoadMainResourceExcludes()); @@ -98,11 +98,29 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor descriptor.setProvider(getValue(attributes, PLUGIN_PROVIDER, false)); descriptor.setLicense(getValue(attributes, PLUGIN_LICENSE, false)); descriptor.setConfigFileName(getValue(attributes, PLUGIN_CONFIG_FILE_NAME, false)); + descriptor.setConfigFileLocation(getValue(attributes, PLUGIN_CONFIG_FILE_LOCATION, false)); + + descriptor.setType(getPluginType(attributes)); descriptor.setDependencyPlugins(getPluginDependency(attributes)); return descriptor; } + protected PluginType getPluginType(Attributes attributes){ + String packageType = ManifestUtils.getValue(attributes, PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, false); + if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_JAR)){ + return PluginType.JAR; + } else if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_JAR_OUTER)){ + return PluginType.JAR_OUTER; + } else if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_ZIP)){ + return PluginType.ZIP; + } else if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER)){ + return PluginType.ZIP_OUTER; + } else { + return null; + } + } + protected List getPluginDependency(Attributes attributes){ return AbstractDependencyPlugin.toList(getValue(attributes, PLUGIN_DEPENDENCIES, false), DefaultDependencyPlugin::new); @@ -132,6 +150,22 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor } } + protected Set getPluginLibInfo(Set dependenciesIndex){ + if(ObjectUtils.isEmpty(dependenciesIndex)){ + return Collections.emptySet(); + } + Set pluginLibInfos = new HashSet<>(dependenciesIndex.size()); + for (String index : dependenciesIndex) { + if(index.endsWith(Constants.LOAD_TO_MAIN_SIGN)){ + String path = index.substring(0, index.lastIndexOf(Constants.LOAD_TO_MAIN_SIGN)); + pluginLibInfos.add(new PluginLibInfo(path, true)); + } else { + pluginLibInfos.add(new PluginLibInfo(index, false)); + } + } + return pluginLibInfos; + } + protected Manifest getManifest(InputStream inputStream) throws Exception{ Manifest manifest = new Manifest(); try { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java index e6ab6c9..04900f2 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -16,6 +16,9 @@ package com.gitee.starblues.core.descriptor; +import lombok.Data; +import lombok.Setter; + import java.nio.file.Path; import java.util.Set; import java.util.jar.Manifest; @@ -30,11 +33,19 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple private final Path pluginPath; private final String pluginFileName; + @Setter private String pluginClassPath; + @Setter private Manifest manifest; + @Setter private String configFileName; - private Set pluginLibPaths; + @Setter + private String configFileLocation; + @Setter + private Set pluginLibInfo; + @Setter private Set includeMainResourcePatterns; + @Setter private Set excludeMainResourcePatterns; public DefaultInsidePluginDescriptor(String pluginId, String pluginVersion, String pluginClass, Path pluginPath) { @@ -43,29 +54,6 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple this.pluginFileName = pluginPath.toFile().getName(); } - public void setPluginClassPath(String pluginClassPath) { - this.pluginClassPath = pluginClassPath; - } - - public void setManifest(Manifest manifest){ - this.manifest = manifest; - } - - public void setConfigFileName(String configFileName) { - this.configFileName = configFileName; - } - - public void setPluginLibPath(Set pluginLibPaths) { - this.pluginLibPaths = pluginLibPaths; - } - - public void setIncludeMainResourcePatterns(Set includeMainResourcePatterns) { - this.includeMainResourcePatterns = includeMainResourcePatterns; - } - - public void setExcludeMainResourcePatterns(Set excludeMainResourcePatterns) { - this.excludeMainResourcePatterns = excludeMainResourcePatterns; - } @Override public String getPluginClassPath() { @@ -73,8 +61,8 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple } @Override - public Set getPluginLibPaths() { - return pluginLibPaths; + public Set getPluginLibInfo() { + return pluginLibInfo; } @Override @@ -92,6 +80,11 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple return configFileName; } + @Override + public String getConfigFileLocation() { + return configFileLocation; + } + @Override public Path getInsidePluginPath() { return pluginPath; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java index 876f83b..134f8d5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java @@ -33,13 +33,20 @@ public interface InsidePluginDescriptor extends PluginDescriptor{ */ Manifest getManifest(); - /** - * 获取插件配置文件名称 + * 获取插件配置文件名称。 + * 和 getConfigFileLocation 配置二选一, 如果都有值则默认使用 getConfigFileName * @return String */ String getConfigFileName(); + /** + * 获取插件配置文件路径。 + * 和 getConfigFileName 配置二选一, 如果都有值则默认使用 getConfigFileName + * @return String + */ + String getConfigFileLocation(); + /** * 得到内部的插件路径 * @return Path @@ -63,7 +70,7 @@ public interface InsidePluginDescriptor extends PluginDescriptor{ * 获取插件依赖的路径 * @return String */ - Set getPluginLibPaths(); + Set getPluginLibInfo(); /** * 设置当前插件包含主程序加载资源的匹配 diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java index 03919dc..4e125bb 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginDescriptor.java @@ -17,7 +17,6 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.DependencyPlugin; -import com.gitee.starblues.core.descriptor.PluginType; import java.util.List; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java new file mode 100644 index 0000000..e693592 --- /dev/null +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java @@ -0,0 +1,38 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.core.descriptor; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; + +/** + * 插件依赖包信息 + * @author starBlues + * @version 3.0.0 + */ +@AllArgsConstructor +@Getter +@EqualsAndHashCode +@ToString +public class PluginLibInfo { + + private final String path; + private final boolean loadToMain; + +} diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java index 24bd2ce..d45c238 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java @@ -11,11 +11,21 @@ public enum PluginType { */ JAR, + /** + * jar-outer 文件 + */ + JAR_OUTER, + /** * zip 文件 */ ZIP, + /** + * zip-outer 文件 + */ + ZIP_OUTER, + /** * 生产模式目录 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java index 1b9ffcd..04a4495 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -38,6 +38,7 @@ import static com.gitee.starblues.common.PackageStructure.*; /** * 生产环境目录式插件 PluginDescriptorLoader 加载者 + * 解析生产的dir * @author starBlues * @version 3.0.0 */ @@ -59,12 +60,10 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade @Override protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); - descriptor.setType(PluginType.DIR); String pathStr = path.toFile().getPath(); descriptor.setPluginClassPath(FilesUtils.joiningFilePath( - pathStr, CLASSES_NAME + pathStr, descriptor.getPluginClassPath() )); - System.out.println(descriptor.getPluginClassPath()); return descriptor; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java index 84bb572..7b22ce5 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -18,6 +18,9 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PackageType; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.utils.ManifestUtils; import com.gitee.starblues.utils.ObjectUtils; import org.apache.commons.io.IOUtils; @@ -25,6 +28,7 @@ import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.nio.file.Path; import java.util.List; +import java.util.Objects; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -35,6 +39,7 @@ import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_RESOURCES_CO /** * 生产环境打包好的插件 PluginDescriptorLoader 加载者 + * 解析 jar、zip * @author starBlues * @version 3.0.0 */ @@ -64,7 +69,11 @@ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorL @Override protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); - descriptor.setType(type); + PluginType manifestPluginType = descriptor.getType(); + if(manifestPluginType == null){ + descriptor.setType(type); + return descriptor; + } return descriptor; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index 7537524..dccfa2d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -19,7 +19,9 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; +import com.gitee.starblues.loader.classloader.GenericClassLoader; import com.gitee.starblues.loader.launcher.AbstractLauncher; +import com.gitee.starblues.loader.launcher.ResourceLoaderFactoryGetter; import com.gitee.starblues.spring.SpringPluginHook; import java.util.Map; @@ -49,27 +51,34 @@ public class PluginLauncher extends AbstractLauncher { } @Override - protected ClassLoader createClassLoader() throws Exception { + protected ClassLoader createClassLoader(String... args) throws Exception { PluginClassLoader pluginClassLoader = getPluginClassLoader(); pluginClassLoader.addResource(pluginDescriptor); return pluginClassLoader; } - protected synchronized PluginClassLoader getPluginClassLoader(){ + protected synchronized PluginClassLoader getPluginClassLoader() throws Exception { String pluginId = pluginDescriptor.getPluginId(); PluginClassLoader classLoader = CLASS_LOADER_CACHE.get(pluginId); if(classLoader != null){ return classLoader; } PluginClassLoader pluginClassLoader = new PluginClassLoader( - pluginId, getParentClassLoader(), mainResourcePatternDefiner + pluginId, getParentClassLoader(), mainResourcePatternDefiner, + ResourceLoaderFactoryGetter.get(pluginId) ); CLASS_LOADER_CACHE.put(pluginId, pluginClassLoader); return pluginClassLoader; } - protected ClassLoader getParentClassLoader(){ - return PluginLauncher.class.getClassLoader(); + + protected GenericClassLoader getParentClassLoader() throws Exception { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + if(contextClassLoader instanceof GenericClassLoader){ + return (GenericClassLoader) contextClassLoader; + } else { + throw new Exception("非法父类加载器: " + contextClassLoader.getClass().getName()); + } } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java index ac848cc..e998516 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMainResourcePatternDefiner.java @@ -109,7 +109,30 @@ public class PluginMainResourcePatternDefiner extends JavaMainResourcePatternDef } protected void addDbDriver(Set patterns){ + // mysql patterns.add("com/mysql/**"); + // oracle + patterns.add("oracle/jdbc/**"); + // sqlserver + patterns.add("com/microsoft/jdbc/sqlserver/**"); + // DB2 + patterns.add("com/ibm/db2/jdbc/**"); + // DB2/AS400 + patterns.add("com/ibm/as400/**"); + // Informix + patterns.add("com/informix/jdbc/**"); + // Hypersonic + patterns.add("org/hsql/**"); + // MS SQL + patterns.add("com/microsoft/jdbc/**"); + // Postgres + patterns.add("org/postgresql/**"); + // Sybase + patterns.add("com/sybase/jdbc2/**"); + // Weblogic + patterns.add("weblogic/jdbc/**"); + // h2 + patterns.add("jdbc/h2/**"); } /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java index d286b0d..a1fe7a1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/ClassUtils.java @@ -1,23 +1,21 @@ /** * Copyright [2019-2022] [starBlues] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.gitee.starblues.utils; -import org.springframework.util.PathMatcher; - import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -28,18 +26,19 @@ import java.util.Map; /** * 类工具类 + * * @author starBlues * @version 2.4.0 */ public class ClassUtils { - private ClassUtils(){ + private ClassUtils() { } public static List getAllFields(Class clazz) { List fieldList = new ArrayList<>(); - while (clazz != null){ + while (clazz != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } @@ -48,6 +47,7 @@ public class ClassUtils { /** * 通过反射获取字段 + * * @param o 对象 * @param fieldName 字段名称 * @param 字段类型 @@ -55,7 +55,7 @@ public class ClassUtils { * @throws IllegalAccessException 异常信息 */ public static T getReflectionField(Object o, String fieldName) throws IllegalAccessException { - if(o == null){ + if (o == null) { return null; } @@ -66,6 +66,7 @@ public class ClassUtils { /** * 通过反射获取字段 + * * @param o 对象 * @param fieldName 字段名称 * @param fieldClassType 字段类型 @@ -74,7 +75,7 @@ public class ClassUtils { * @throws IllegalAccessException 异常信息 */ public static T getReflectionField(Object o, String fieldName, Class fieldClassType) throws IllegalAccessException { - if(o == null){ + if (o == null) { return null; } Field templateResolversField = ReflectionUtils.findField(o.getClass(), @@ -84,6 +85,7 @@ public class ClassUtils { /** * 通过反射Field获取字段 + * * @param field Field字段 * @param o 当前对象 * @param 字段类型 @@ -100,8 +102,9 @@ public class ClassUtils { } /** - * // TODO 可能某个java版本不生效 * 得到注解修改者 + * + * TODO 可能某个java版本不生效 * @param annotation 注解 * @return 修改者集合 * @throws Exception 异常 @@ -110,22 +113,22 @@ public class ClassUtils { public static Map getAnnotationsUpdater(Object annotation) throws Exception { InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); Field field = getAnnotationsUpdaterField(invocationHandler); - if(field == null){ + if (field == null) { return null; } return (Map) field.get(invocationHandler); } - private static Field getAnnotationsUpdaterField(InvocationHandler invocationHandler){ + private static Field getAnnotationsUpdaterField(InvocationHandler invocationHandler) { Class aClass = invocationHandler.getClass(); Field field = ReflectionUtils.findField(aClass, "memberValues", Map.class); - if(field == null){ + if (field == null) { field = ReflectionUtils.findField(aClass, "valueCache", Map.class); } - if(field == null){ + if (field == null) { field = ReflectionUtils.findField(aClass, Map.class); } - if(field != null){ + if (field != null) { field.setAccessible(true); return field; } else { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java index bb9b90a..8342027 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractDependencyFilterMojo.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Set; /** + * 抽象可过滤依赖的 mojo * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java index fa13196..5b8b2f0 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/AbstractPackagerMojo.java @@ -16,8 +16,6 @@ package com.gitee.starblues.plugin.pack; -import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.plugin.pack.utils.CommonUtils; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.maven.artifact.Artifact; @@ -30,6 +28,7 @@ import java.io.File; import java.util.Set; /** + * 抽象的重新打包 mojo * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index c0ecb42..60e9166 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -54,7 +54,7 @@ public class BasicRepackager implements Repackager{ private String relativeManifestPath; private String relativeResourcesDefinePath; - private File resourcesDefineFile; + protected File resourcesDefineFile; protected final RepackageMojo repackageMojo; @@ -167,6 +167,10 @@ public class BasicRepackager implements Repackager{ if(!ObjectUtils.isEmpty(configFileName)){ attributes.putValue(PLUGIN_CONFIG_FILE_NAME, configFileName); } + String configFileLocation = pluginInfo.getConfigFileLocation(); + if(!ObjectUtils.isEmpty(configFileLocation)){ + attributes.putValue(PLUGIN_CONFIG_FILE_LOCATION, configFileLocation); + } String provider = pluginInfo.getProvider(); if(!ObjectUtils.isEmpty(provider)){ attributes.putValue(PLUGIN_PROVIDER, provider); @@ -248,7 +252,7 @@ public class BasicRepackager implements Repackager{ } protected String getLibIndex(Artifact artifact){ - return artifact.getFile().getPath(); + return artifact.getFile().getPath() + repackageMojo.resolveLoadToMain(artifact); } protected void writeLoadMainResources() throws Exception { @@ -300,4 +304,5 @@ public class BasicRepackager implements Repackager{ } + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java index a605e43..afae975 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -32,15 +32,6 @@ public class Constant { public static final String MODE_DEV = "dev"; public static final String MODE_PROD = "prod"; - public static final String PACKAGE_TYPE_JAR = "jar"; - public static final String PACKAGE_TYPE_ZIP = "zip"; - public static final String PACKAGE_TYPE_DIR = "dir"; - - public static final String MAIN_PACKAGE_TYPE_JAR_NEST = "jar-nest"; - public static final String MAIN_PACKAGE_TYPE_JAR_OUTER = "jar-outer"; - public static final String MAIN_PACKAGE_TYPE_WAR = "jar-war"; - - public static boolean isPom(String packageType){ return PACKAGING_POM.equalsIgnoreCase(packageType); } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Dependency.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Dependency.java new file mode 100644 index 0000000..109a27e --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Dependency.java @@ -0,0 +1,36 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * 依赖Bean + * @author starBlues + * @version 3.0.0 + */ +@Data +public class Dependency { + + @Parameter(required = true) + private String groupId; + + @Parameter(required = true) + private String artifactId; + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadToMain.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadToMain.java new file mode 100644 index 0000000..2cc7e26 --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/LoadToMain.java @@ -0,0 +1,33 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack; + +import lombok.Data; + +import java.util.List; + +/** + * 定义依赖加载到主程序中 + * @author starBlues + * @version 3.0.0 + */ +@Data +public class LoadToMain { + + private List dependencies; + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java index 35b7828..5f60b08 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -48,10 +48,17 @@ public class PluginInfo { private String version; /** - * 插件配置文件名称 + * 插件配置文件名称。 + * 和 configFileLocation 配置二选一, 如果都有值则默认使用 getConfigFileName */ private String configFileName; + /** + * 插件配置文件路径 + * 和 configFileName 配置二选一, 如果都有值则默认使用 getConfigFileName + */ + private String configFileLocation; + /** * 插件描述 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java index 614828e..806bf5e 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/RepackageMojo.java @@ -16,15 +16,16 @@ package com.gitee.starblues.plugin.pack; -import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.Constants; import com.gitee.starblues.plugin.pack.dev.DevConfig; import com.gitee.starblues.plugin.pack.dev.DevRepackager; import com.gitee.starblues.plugin.pack.main.MainConfig; import com.gitee.starblues.plugin.pack.main.MainRepackager; import com.gitee.starblues.plugin.pack.prod.ProdConfig; import com.gitee.starblues.plugin.pack.prod.ProdRepackager; -import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; +import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -32,7 +33,12 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** + * 重新打包 mojo * @author starBlues * @version 3.0.0 */ @@ -52,8 +58,14 @@ public class RepackageMojo extends AbstractPackagerMojo { @Parameter(property = "springboot-plugin.mainConfig") private MainConfig mainConfig; + @Parameter(property = "springboot-plugin.mainLoad") + private LoadToMain loadToMain; + + private final Set loadToMainSet = new HashSet<>(); + @Override protected void pack() throws MojoExecutionException, MojoFailureException { + initLoadToMainSet(); String mode = getMode(); if(Constant.MODE_PROD.equalsIgnoreCase(mode)){ new ProdRepackager(this).repackage(); @@ -67,4 +79,27 @@ public class RepackageMojo extends AbstractPackagerMojo { } } + public String resolveLoadToMain(Artifact artifact){ + if(artifact == null){ + return ""; + } + if(loadToMainSet.contains(artifact.getGroupId() + artifact.getArtifactId())){ + return Constants.LOAD_TO_MAIN_SIGN; + } + return ""; + } + + private void initLoadToMainSet(){ + if(loadToMain == null){ + return; + } + List dependencies = loadToMain.getDependencies(); + if(ObjectUtils.isEmpty(dependencies)){ + return; + } + for (Dependency dependency : dependencies) { + loadToMainSet.add(dependency.getGroupId() + dependency.getArtifactId()); + } + } + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java index 0da4a27..d1ea896 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Repackager.java @@ -20,7 +20,7 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** - * 重新打包者 + * 重新打包j接口 * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java index b0126d4..4e61d92 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/Dependency.java @@ -20,8 +20,9 @@ import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; /** + * 开发环境下配置本地依赖的Bean * @author starBlues - * @version 1.0 + * @version 3.0.0 */ @Data public class Dependency { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java index 464f739..429c4b5 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarNestPackager.java @@ -16,14 +16,12 @@ package com.gitee.starblues.plugin.pack.main; -import com.gitee.starblues.common.Constants; -import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.Repackager; import com.gitee.starblues.plugin.pack.utils.CommonUtils; import com.gitee.starblues.plugin.pack.utils.PackageJar; -import org.apache.commons.compress.archivers.ArchiveOutputStream; +import com.gitee.starblues.utils.ObjectUtils; import org.apache.commons.io.IOUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; @@ -47,7 +45,7 @@ public class JarNestPackager implements Repackager { protected final MainConfig mainConfig; protected final RepackageMojo repackageMojo; - private PackageJar packageJar; + protected PackageJar packageJar; public JarNestPackager(MainRepackager mainRepackager) { this.mainConfig = mainRepackager.getMainConfig(); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java new file mode 100644 index 0000000..ef03650 --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java @@ -0,0 +1,111 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.main; + +import com.gitee.starblues.common.ManifestKey; +import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.utils.FilesUtils; +import org.apache.commons.io.FileUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.ManifestKey.*; +import static com.gitee.starblues.common.ManifestKey.MANIFEST_VERSION_1_0; + +/** + * jar 外置包 + * @author starBlues + * @version 3.0.0 + */ +public class JarOuterPackager extends JarNestPackager { + + private final List dependenciesName = new ArrayList<>(); + + public JarOuterPackager(MainRepackager mainRepackager) { + super(mainRepackager); + } + + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + // 生成依赖文件夹 + String rootDir = createRootDir(); + mainConfig.setOutputDirectory(rootDir); + super.repackage(); + } + + @Override + protected void writeClasses() throws Exception { + String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); + packageJar.copyDirToPackage(new File(buildDir), ""); + } + + private String createRootDir() throws MojoFailureException{ + String outputDirectory = mainConfig.getOutputDirectory(); + String fileName = mainConfig.getFileName(); + String rootDirPath = FilesUtils.joiningFilePath(outputDirectory, fileName); + File rootFile = new File(rootDirPath); + if(rootFile.exists()){ + rootFile.deleteOnExit(); + } + if(rootFile.mkdirs()){ + return rootDirPath; + } else { + throw new MojoFailureException("Create dir failure : " + rootDirPath); + } + } + + @Override + protected Manifest getManifest() throws Exception { + Manifest manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue(MANIFEST_VERSION, MANIFEST_VERSION_1_0); + attributes.remove(START_CLASS); + attributes.putValue(MAIN_CLASS, mainConfig.getMainClass()); + if(dependenciesName.isEmpty()){ + return manifest; + } + String classPathStr = String.join(" ", dependenciesName); + attributes.putValue(ManifestKey.CLASS_PATH, classPathStr); + return manifest; + } + + @Override + protected void writeDependencies() throws Exception { + Set dependencies = repackageMojo.getSourceDependencies(); + for (Artifact artifact : dependencies) { + if(filterArtifact(artifact)){ + continue; + } + File artifactFile = artifact.getFile(); + String targetFilePath = FilesUtils.joiningFilePath( + mainConfig.getOutputDirectory(), PackageStructure.LIB_NAME, artifactFile.getName()); + + FileUtils.copyFile(artifactFile, new File(targetFilePath)); + dependenciesName.add(PackageStructure.LIB_NAME + "/" + artifactFile.getName()); + } + } + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java index 77bfc87..8c5e58b 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainConfig.java @@ -19,6 +19,7 @@ package com.gitee.starblues.plugin.pack.main; import lombok.Data; import org.apache.maven.plugins.annotations.Parameter; +import com.gitee.starblues.plugin.pack.Constant; /** * 主程序打包配置 @@ -35,7 +36,10 @@ public class MainConfig { private String mainClass; /** - * 打包类型。默认:jar-nest + * 打包类型。默认:jar + * + * {@link com.gitee.starblues.common.PackageType#MAIN_PACKAGE_TYPE_JAR} + * {@link com.gitee.starblues.common.PackageType#MAIN_PACKAGE_TYPE_JAR_OUTER} */ private String packageType; @@ -49,4 +53,5 @@ public class MainConfig { */ private String outputDirectory; + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java index 0381712..a32d278 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/MainRepackager.java @@ -16,10 +16,9 @@ package com.gitee.starblues.plugin.pack.main; -import com.gitee.starblues.plugin.pack.Constant; +import com.gitee.starblues.common.PackageType; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.Repackager; -import com.gitee.starblues.plugin.pack.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; import org.apache.maven.plugin.MojoExecutionException; @@ -46,8 +45,10 @@ public class MainRepackager implements Repackager { public void repackage() throws MojoExecutionException, MojoFailureException { checkConfig(); String packageType = mainConfig.getPackageType(); - if(Constant.MAIN_PACKAGE_TYPE_JAR_NEST.equalsIgnoreCase(packageType)){ + if(PackageType.MAIN_PACKAGE_TYPE_JAR.equalsIgnoreCase(packageType)){ new JarNestPackager(this).repackage(); + } else if(PackageType.MAIN_PACKAGE_TYPE_JAR_OUTER.equalsIgnoreCase(packageType)){ + new JarOuterPackager(this).repackage(); } else { throw new MojoFailureException("Not found packageType : " + packageType); } @@ -67,7 +68,7 @@ public class MainRepackager implements Repackager { } String packageType = mainConfig.getPackageType(); if(ObjectUtils.isEmpty(packageType)) { - mainConfig.setPackageType(Constant.MAIN_PACKAGE_TYPE_JAR_NEST); + mainConfig.setPackageType(PackageType.MAIN_PACKAGE_TYPE_JAR); } String outputDirectory = mainConfig.getOutputDirectory(); if(ObjectUtils.isEmpty(outputDirectory)){ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java index 835ec1e..8e33d90 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java @@ -17,6 +17,7 @@ package com.gitee.starblues.plugin.pack.prod; import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.dev.DevRepackager; @@ -43,7 +44,7 @@ import static com.gitee.starblues.common.PackageStructure.*; */ public class DirProdRepackager extends DevRepackager { - private final ProdConfig prodConfig; + protected final ProdConfig prodConfig; public DirProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { @@ -101,6 +102,7 @@ public class DirProdRepackager extends DevRepackager { Attributes attributes = manifest.getMainAttributes(); attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, CLASSES_NAME); attributes.putValue(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); + attributes.putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_DIR); return manifest; } @@ -123,7 +125,8 @@ public class DirProdRepackager extends DevRepackager { } File artifactFile = artifact.getFile(); FileUtils.copyFile(artifactFile, new File(FilesUtils.joiningFilePath(libDir, artifactFile.getName()))); - dependencyIndexNames.add(PackageStructure.PROD_LIB_PATH + artifactFile.getName()); + dependencyIndexNames.add(PackageStructure.PROD_LIB_PATH + artifactFile.getName() + + repackageMojo.resolveLoadToMain(artifact)); } return dependencyIndexNames; } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java similarity index 68% rename from springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java rename to springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java index 56648b3..5df5b5f 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java @@ -16,6 +16,8 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.PackageType; +import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.utils.PackageJar; import com.gitee.starblues.plugin.pack.utils.PackageZip; @@ -27,16 +29,21 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.*; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PackageStructure.PROD_CLASSES_PATH; +import static com.gitee.starblues.common.PackageStructure.PROD_RESOURCES_DEFINE_PATH; /** * jar包生成 * @author starBlues * @version 3.0.0 */ -public class JarProdRepackager extends ZipProdRepackager { +public class JarNestedProdRepackager extends ZipProdRepackager { - public JarProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { + public JarNestedProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { super(repackageMojo, prodConfig); } @@ -49,4 +56,13 @@ public class JarProdRepackager extends ZipProdRepackager { protected PackageZip getPackageZip() throws Exception { return new PackageJar(prodConfig.getOutputDirectory(), prodConfig.getFileName()); } + + @Override + protected Manifest getManifest() throws Exception { + Manifest manifest = super.getManifest(); + manifest.getMainAttributes().putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_JAR); + return manifest; + } + + } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java new file mode 100644 index 0000000..c525826 --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java @@ -0,0 +1,52 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.prod; + +import com.gitee.starblues.common.PackageType; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.utils.PackageJar; +import com.gitee.starblues.plugin.pack.utils.PackageZip; + +import java.util.jar.Manifest; + +/** + * jar-outer包生成 + * @author starBlues + * @version 3.0.0 + */ +public class JarOuterProdRepackager extends ZipOuterProdRepackager { + + + public JarOuterProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { + super(repackageMojo, prodConfig); + } + + @Override + protected PackageZip getPackageZip(String rootDir) throws Exception { + return new PackageJar(rootDir, super.prodConfig.getFileName()); + } + + @Override + protected Manifest getManifest() throws Exception { + Manifest manifest = super.getManifest(); + manifest.getMainAttributes().putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, + PackageType.PLUGIN_PACKAGE_TYPE_JAR_OUTER); + return manifest; + } + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java index 5a7bb31..3943b38 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdConfig.java @@ -30,6 +30,12 @@ public class ProdConfig { /** * 打包类型。默认jar包 + * + * {@link com.gitee.starblues.common.PackageType#PLUGIN_PACKAGE_TYPE_JAR} + * {@link com.gitee.starblues.common.PackageType#PLUGIN_PACKAGE_TYPE_JAR_OUTER} + * {@link com.gitee.starblues.common.PackageType#PLUGIN_PACKAGE_TYPE_ZIP} + * {@link com.gitee.starblues.common.PackageType#PLUGIN_PACKAGE_TYPE_ZIP_OUTER} + * {@link com.gitee.starblues.common.PackageType#PLUGIN_PACKAGE_TYPE_DIR} */ @Parameter(required = true, defaultValue = "jar") private String packageType = "jar"; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java index 2f85566..9db3b18 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ProdRepackager.java @@ -16,12 +16,12 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.PackageType; import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.PluginInfo; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.Repackager; import com.gitee.starblues.plugin.pack.dev.DevRepackager; -import com.gitee.starblues.plugin.pack.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; import org.apache.maven.plugin.MojoExecutionException; @@ -53,12 +53,15 @@ public class ProdRepackager implements Repackager { String packageType = prodConfig.getPackageType(); Repackager repackager = null; - if(Constant.PACKAGE_TYPE_ZIP.equalsIgnoreCase(packageType)){ - // jar + if(PackageType.PLUGIN_PACKAGE_TYPE_ZIP.equalsIgnoreCase(packageType)){ repackager = new ZipProdRepackager(repackageMojo, prodConfig); - } else if(Constant.PACKAGE_TYPE_JAR.equalsIgnoreCase(packageType)){ - repackager = new JarProdRepackager(repackageMojo, prodConfig); - } else if(Constant.PACKAGE_TYPE_DIR.equalsIgnoreCase(packageType)){ + } else if(PackageType.PLUGIN_PACKAGE_TYPE_JAR.equalsIgnoreCase(packageType)){ + repackager = new JarNestedProdRepackager(repackageMojo, prodConfig); + } else if(PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER.equalsIgnoreCase(packageType)){ + repackager = new ZipOuterProdRepackager(repackageMojo, prodConfig); + } else if(PackageType.PLUGIN_PACKAGE_TYPE_JAR_OUTER.equalsIgnoreCase(packageType)){ + repackager = new JarOuterProdRepackager(repackageMojo, prodConfig); + } else if(PackageType.PLUGIN_PACKAGE_TYPE_DIR.equalsIgnoreCase(packageType)){ repackager = new DirProdRepackager(repackageMojo, prodConfig); } else { throw new MojoFailureException("Not found packageType : " + packageType); @@ -72,7 +75,7 @@ public class ProdRepackager implements Repackager { prodConfig = new ProdConfig(); } if(ObjectUtils.isEmpty(prodConfig.getPackageType())){ - prodConfig.setPackageType(Constant.PACKAGE_TYPE_JAR); + prodConfig.setPackageType(PackageType.PLUGIN_PACKAGE_TYPE_JAR); } String fileName = prodConfig.getFileName(); if(ObjectUtils.isEmpty(fileName)) { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java new file mode 100644 index 0000000..5d3e5bf --- /dev/null +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java @@ -0,0 +1,96 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.starblues.plugin.pack.prod; + +import com.gitee.starblues.common.PackageType; +import com.gitee.starblues.common.PluginDescriptorKey; +import com.gitee.starblues.plugin.pack.RepackageMojo; +import com.gitee.starblues.plugin.pack.utils.PackageJar; +import com.gitee.starblues.plugin.pack.utils.PackageZip; +import com.gitee.starblues.utils.FilesUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.gitee.starblues.common.PackageStructure.CLASSES_NAME; +import static com.gitee.starblues.common.PackageStructure.PROD_RESOURCES_DEFINE_PATH; + +/** + * zip-outer 包生成 + * @author starBlues + * @version 3.0.0 + */ +public class ZipOuterProdRepackager extends DirProdRepackager { + + protected PackageZip packageZip; + + public ZipOuterProdRepackager(RepackageMojo repackageMojo, ProdConfig prodConfig) { + super(repackageMojo, prodConfig); + } + + @Override + public void repackage() throws MojoExecutionException, MojoFailureException { + try { + super.repackage(); + } catch (Exception e){ + throw new MojoFailureException(e); + } finally { + if(packageZip != null){ + IOUtils.closeQuietly(packageZip); + } + } + } + + @Override + protected String createRootDir() throws MojoFailureException { + String rootDir = super.createRootDir(); + try { + packageZip = getPackageZip(rootDir); + return rootDir; + } catch (Exception e) { + throw new MojoFailureException(e); + } + } + + protected PackageZip getPackageZip(String rootDir) throws Exception { + return new PackageZip(rootDir, super.prodConfig.getFileName()); + } + + @Override + protected void resolveClasses() throws Exception { + String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); + packageZip.copyDirToPackage(new File(buildDir), ""); + } + + @Override + protected Manifest getManifest() throws Exception { + Manifest manifest = super.getManifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER); + attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, packageZip.getFileName()); + return manifest; + } + +} diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java index 35432e9..3140d0e 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.RepackageMojo; @@ -90,10 +91,6 @@ public class ZipProdRepackager extends DevRepackager { return new PackageZip(prodConfig.getOutputDirectory(), prodConfig.getFileName()); } - protected ArchiveOutputStream getOutputStream(File packFile) throws Exception { - return new ZipArchiveOutputStream(new FileOutputStream(packFile)); - } - @Override protected String getBasicRootDir(){ File outputDirectory = repackageMojo.getOutputDirectory(); @@ -113,7 +110,7 @@ public class ZipProdRepackager extends DevRepackager { @Override protected String getLibIndex(Artifact artifact){ - return PROD_LIB_PATH + artifact.getFile().getName(); + return PROD_LIB_PATH + artifact.getFile().getName() + repackageMojo.resolveLoadToMain(artifact); } @Override @@ -132,13 +129,13 @@ public class ZipProdRepackager extends DevRepackager { Attributes attributes = manifest.getMainAttributes(); attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, PROD_CLASSES_PATH); attributes.putValue(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); + attributes.putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP); return manifest; } @Override protected void writeManifest(Manifest manifest) throws Exception { - packageZip.putDirEntry(META_INF_NAME + SEPARATOR); - packageZip.write(PROD_MANIFEST_PATH, manifest::write); + packageZip.writeManifest(manifest); } protected void resolveResourcesDefine() throws Exception{ @@ -154,7 +151,7 @@ public class ZipProdRepackager extends DevRepackager { } final byte[] bytes = content.toString().getBytes(StandardCharsets.UTF_8); try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)){ - packageZip.putInputStreamEntry(byteArrayInputStream, PROD_RESOURCES_DEFINE_PATH); + packageZip.putInputStreamEntry(PROD_RESOURCES_DEFINE_PATH, byteArrayInputStream); } } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java index de9e06c..20d3931 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/utils/PackageZip.java @@ -29,9 +29,12 @@ import org.apache.commons.io.IOUtils; import java.io.*; import java.util.Enumeration; +import java.util.jar.Manifest; import java.util.zip.CRC32; import java.util.zip.ZipEntry; +import static com.gitee.starblues.common.PackageStructure.*; + /** * zip 打包工具 * @author starBlues @@ -57,13 +60,16 @@ public class PackageZip implements Closeable{ String rootPath = FilesUtils.joiningFilePath(outputDirectory, packageName); this.file = getPackageFile(rootPath); this.outputStream = getOutputStream(file); - } public File getFile(){ return file; } + public String getFileName(){ + return file.getName(); + } + protected File getPackageFile(String rootPath) throws Exception { String fileSuffix = getPackageFileSuffix(); File file = new File(rootPath + "." + fileSuffix); @@ -133,7 +139,7 @@ public class PackageZip implements Closeable{ putDirEntry(name); } else { try (InputStream inputStream = zipFile.getInputStream(zipArchiveEntry)){ - putInputStreamEntry(inputStream, name); + putInputStreamEntry(name, inputStream); } } } @@ -166,7 +172,7 @@ public class PackageZip implements Closeable{ outputStream.closeArchiveEntry(); } - public void putInputStreamEntry(InputStream inputStream, String name) throws Exception { + public void putInputStreamEntry(String name, InputStream inputStream) throws Exception { outputStream.putArchiveEntry(getArchiveEntry(name)); IOUtils.copy(inputStream, outputStream); outputStream.closeArchiveEntry(); @@ -178,6 +184,19 @@ public class PackageZip implements Closeable{ outputStream.closeArchiveEntry(); } + public void write(String name, File file) throws Exception { + outputStream.putArchiveEntry(getArchiveEntry(name)); + try (FileInputStream fileInputStream = new FileInputStream(file)){ + IOUtils.copy(fileInputStream, outputStream); + outputStream.closeArchiveEntry(); + } + } + + public void writeManifest(Manifest manifest) throws Exception { + putDirEntry(META_INF_NAME + SEPARATOR); + write(PROD_MANIFEST_PATH, manifest::write); + } + public void putDirEntry(String dir) throws IOException { outputStream.putArchiveEntry(getArchiveEntry(dir)); outputStream.closeArchiveEntry(); diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml index a60b0ff..9a06007 100644 --- a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/com.gitee.starblues.springboot-plugin-maven-packager/plugin-help.xml @@ -125,6 +125,14 @@ true main打包模式配置 + + loadToMain + com.gitee.starblues.plugin.pack.LoadToMain + 3.0.0 + false + true + 加载到主程序的依赖 + @@ -138,6 +146,7 @@ + diff --git a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml index a60b0ff..9a06007 100644 --- a/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml +++ b/springboot-plugin-maven-packager/src/main/resources/META-INF/maven/plugin.xml @@ -125,6 +125,14 @@ true main打包模式配置 + + loadToMain + com.gitee.starblues.plugin.pack.LoadToMain + 3.0.0 + false + true + 加载到主程序的依赖 + @@ -138,6 +146,7 @@ + -- Gitee From 9db9d7466ead0bcfe5550238f50944000c2eadd0 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Sun, 27 Feb 2022 19:07:15 +0800 Subject: [PATCH 32/37] add resource loader --- .../loader/AbstractResourceLoader.java | 42 +++------------- .../resource/loader/ClassPathLoader.java | 30 ++++++------ .../loader/DefaultResourceLoaderFactory.java | 48 ++++++++----------- .../resource/loader/JarResourceLoader.java | 14 +++--- .../resource/loader/ResourceLoader.java | 12 +---- .../loader/ResourceLoaderFactory.java | 9 +++- .../storage/DefaultResourceStorage.java | 25 ++++++++++ .../resource/storage/ResourceStorage.java | 14 ++++++ .../launcher/MainJarProgramLauncher.java | 9 ++-- .../loader/launcher/MainProgramLauncher.java | 3 +- .../launcher/ResourceLoaderFactoryGetter.java | 16 +------ .../NestedPluginJarResourceLoader.java | 25 +++++----- .../core/classloader/PluginClassLoader.java | 2 +- .../core/launcher/plugin/PluginLauncher.java | 8 +++- .../plugin/pack/BasicRepackager.java | 4 -- .../starblues/plugin/pack/PluginInfo.java | 4 +- .../starblues/plugin/pack/dev/DevConfig.java | 10 ---- 17 files changed, 127 insertions(+), 148 deletions(-) diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java index 113c8ab..a5be752 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java @@ -18,7 +18,9 @@ package com.gitee.starblues.loader.classloader.resource.loader; import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.storage.DefaultResourceStorage; import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; +import com.gitee.starblues.loader.utils.Assert; import com.gitee.starblues.loader.utils.IOUtils; import java.io.*; @@ -41,11 +43,8 @@ public abstract class AbstractResourceLoader implements ResourceLoader{ protected final URL baseUrl; - protected final ResourceStorage resourceStorage; - - protected AbstractResourceLoader(URL baseUrl, ResourceStorage resourceStorage) { + protected AbstractResourceLoader(URL baseUrl) { this.baseUrl = baseUrl; - this.resourceStorage = resourceStorage; } @Override @@ -58,14 +57,14 @@ public abstract class AbstractResourceLoader implements ResourceLoader{ * @throws Exception 初始异常 */ @Override - public final synchronized void load() throws Exception{ + public final synchronized void load(ResourceStorage resourceStorage) throws Exception{ if(loaded){ throw new Exception(this.getClass().getName()+": 已经初始化了, 不能再初始化!"); } try { // 添加root 路径 resourceStorage.add("/", baseUrl, baseUrl); - loadOfChild(); + loadOfChild(resourceStorage); } finally { loaded = true; } @@ -75,34 +74,7 @@ public abstract class AbstractResourceLoader implements ResourceLoader{ * 子类初始化实现 * @throws Exception 初始异常 */ - protected void loadOfChild() throws Exception{}; - - @Override - public Resource findResource(final String name) { - return resourceStorage.get(name); - } - - @Override - public InputStream getInputStream(final String name) { - Resource resourceInfo = resourceStorage.get(name); - if (resourceInfo != null) { - try (InputStream inputStream = resourceInfo.getUrl().openStream(); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){ - IOUtils.copy(inputStream, byteArrayOutputStream); - return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); - } catch (Exception e){ - e.printStackTrace(); - return null; - } - } else { - return null; - } - } - - @Override - public List getResources(){ - return resourceStorage.getAll(); - } + protected abstract void loadOfChild(ResourceStorage resourceStorage) throws Exception; protected byte[] getClassBytes(String path, InputStream inputStream, boolean isClose) throws Exception{ if(!isClass(path)){ @@ -122,7 +94,7 @@ public abstract class AbstractResourceLoader implements ResourceLoader{ @Override public void close() throws Exception { - resourceStorage.close(); + } private static boolean isClass(String path){ diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java index 0aff14d..8cd9509 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java @@ -34,27 +34,27 @@ public class ClassPathLoader extends AbstractResourceLoader { private final URL url; - public ClassPathLoader(URL url, ResourceStorage resourceStorage) { - super(url, resourceStorage); + public ClassPathLoader(URL url) { + super(url); this.url = Objects.requireNonNull(url, "url 不能为空"); } - public ClassPathLoader(File file, ResourceStorage resourceStorage) throws MalformedURLException { - this(file.toPath(), resourceStorage); + public ClassPathLoader(File file) throws MalformedURLException { + this(file.toPath()); } - public ClassPathLoader(Path path, ResourceStorage resourceStorage) throws MalformedURLException { - super(path.toUri().toURL(), resourceStorage); + public ClassPathLoader(Path path) throws MalformedURLException { + super(path.toUri().toURL()); this.url = super.baseUrl; } @Override - protected void loadOfChild() throws Exception { + protected void loadOfChild(ResourceStorage resourceStorage) throws Exception { File file = new File(url.toURI()); - load(file, null); + load(resourceStorage, file, null); } - private void load(File file, String currentPackageName) throws Exception { + private void load(ResourceStorage resourceStorage, File file, String currentPackageName) throws Exception { if(currentPackageName == null){ // 根目录 currentPackageName = ""; @@ -64,7 +64,7 @@ public class ClassPathLoader extends AbstractResourceLoader { } else { currentPackageName = currentPackageName + Resource.PACKAGE_SPLIT + file.getName(); } - loadResource(file, currentPackageName); + loadResource(resourceStorage, file, currentPackageName); } if(file.isDirectory()){ File[] listFiles = file.listFiles(); @@ -72,20 +72,20 @@ public class ClassPathLoader extends AbstractResourceLoader { return; } for (File subFile : listFiles) { - load(subFile, currentPackageName); + load(resourceStorage, subFile, currentPackageName); } } } - private void loadResource(File file, String packageName) throws Exception{ + private void loadResource(ResourceStorage resourceStorage, File file, String packageName) throws Exception{ if(file.isDirectory()){ - addResource(file, packageName + Resource.PACKAGE_SPLIT); + addResource(resourceStorage, file, packageName + Resource.PACKAGE_SPLIT); } else { - addResource(file, packageName); + addResource(resourceStorage, file, packageName); } } - private void addResource(File file, String packageName) throws Exception { + private void addResource(ResourceStorage resourceStorage, File file, String packageName) throws Exception { resourceStorage.add(packageName, url, new URL(url.toString() + packageName), ()->{ if(file.exists() && file.isFile()){ return getClassBytes(file.getPath(), new FileInputStream(file), true); diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java index 77b1351..9e46ff8 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java @@ -17,6 +17,7 @@ package com.gitee.starblues.loader.classloader.resource.loader; import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; import com.gitee.starblues.loader.launcher.ResourceLoaderFactoryGetter; import com.gitee.starblues.loader.utils.IOUtils; import com.gitee.starblues.loader.utils.ResourceUtils; @@ -40,7 +41,7 @@ import java.util.concurrent.ConcurrentHashMap; */ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ - private final Map resourceLoaderMap = new ConcurrentHashMap<>(); + private final Map resourceLoaderMap = new ConcurrentHashMap<>(); private final String classLoaderName; @@ -81,15 +82,12 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ AbstractResourceLoader resourceLoader = null; if(ResourceUtils.isJarFileUrl(url)) { if(ResourceUtils.isJarProtocolUrl(url)){ - resourceLoader = new JarResourceLoader(url, - ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName)); + resourceLoader = new JarResourceLoader(url); } else { - resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile(), - ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName)); + resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile()); } } else if(ResourceUtils.isFileUrl(url)){ - resourceLoader = new ClassPathLoader(url, - ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName)); + resourceLoader = new ClassPathLoader(url); } if(resourceLoader != null){ addResource(resourceLoader); @@ -104,15 +102,18 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ if (resourceLoaderMap.containsKey(resourceLoader.getBaseUrl())) { return; } - resourceLoader.load(); - resourceLoaderMap.put(resourceLoader.getBaseUrl(), resourceLoader); + ResourceStorage resourceStorage = ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName); + resourceLoader.load(resourceStorage); + if(!resourceStorage.isEmpty()){ + resourceLoaderMap.put(resourceLoader.getBaseUrl(), resourceStorage); + } } @Override public List findResources(String name) { List resources = new ArrayList<>(); - for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { - Resource resource = resourceLoader.findResource(name); + for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + Resource resource = resourceStorage.get(name); if(resource != null){ resources.add(resource); } @@ -120,20 +121,11 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ return resources; } - @Override - public URL getBaseUrl() { - return null; - } - - @Override - public void load() throws Exception { - // 忽略 - } @Override public Resource findResource(String name) { - for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { - Resource resourceInfo = resourceLoader.findResource(name); + for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + Resource resourceInfo = resourceStorage.get(name); if(resourceInfo != null){ return resourceInfo; } @@ -143,8 +135,8 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ @Override public InputStream getInputStream(String name) { - for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { - InputStream inputStream = resourceLoader.getInputStream(name); + for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + InputStream inputStream = resourceStorage.getInputStream(name); if(inputStream != null){ return inputStream; } @@ -155,16 +147,16 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ @Override public List getResources() { List resources = new ArrayList<>(); - for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { - resources.addAll(resourceLoader.getResources()); + for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + resources.addAll(resourceStorage.getAll()); } return resources; } @Override public void close() throws Exception { - for (ResourceLoader resourceLoader : resourceLoaderMap.values()) { - IOUtils.closeQuietly(resourceLoader); + for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + IOUtils.closeQuietly(resourceStorage); } resourceLoaderMap.clear(); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java index 08af3fa..816c6f2 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java @@ -37,19 +37,19 @@ public class JarResourceLoader extends AbstractResourceLoader { private ExcludeResource excludeResource = (jarEntry)->false; private IncludeResource includeResource = (jarEntry)->true; - public JarResourceLoader(File file, ResourceStorage resourceStorage) throws Exception{ - super(new URL("jar:" + file.toURI().toURL() + "!/"), resourceStorage); + public JarResourceLoader(File file) throws Exception{ + super(new URL("jar:" + file.toURI().toURL() + "!/")); URL url = file.toURI().toURL(); this.jarInputStream = new JarInputStream(url.openStream()); } - public JarResourceLoader(URL url, ResourceStorage resourceStorage) throws Exception{ - super(url, resourceStorage); + public JarResourceLoader(URL url) throws Exception{ + super(url); this.jarInputStream = new JarInputStream(url.openStream()); } - public JarResourceLoader(URL url, JarInputStream jarInputStream, ResourceStorage resourceStorage) throws Exception{ - super(url, resourceStorage); + public JarResourceLoader(URL url, JarInputStream jarInputStream) throws Exception{ + super(url); this.jarInputStream = jarInputStream; } @@ -68,7 +68,7 @@ public class JarResourceLoader extends AbstractResourceLoader { } @Override - protected void loadOfChild() throws Exception { + protected void loadOfChild(ResourceStorage resourceStorage) throws Exception { // 解析 try { JarEntry jarEntry = null; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java index d7112ca..819aff8 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoader.java @@ -16,11 +16,9 @@ package com.gitee.starblues.loader.classloader.resource.loader; -import com.gitee.starblues.loader.classloader.resource.Resource; +import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; -import java.io.InputStream; import java.net.URL; -import java.util.List; /** * 资源加载者 @@ -32,12 +30,6 @@ public interface ResourceLoader extends AutoCloseable{ URL getBaseUrl(); - void load() throws Exception; - - Resource findResource(String name); - - InputStream getInputStream(String name); - - List getResources(); + void load(ResourceStorage resourceStorage) throws Exception; } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java index ebd592d..3b6a5df 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java @@ -4,6 +4,7 @@ import com.gitee.starblues.loader.classloader.resource.Resource; import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; import java.io.File; +import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.util.List; @@ -14,7 +15,7 @@ import java.util.List; * @author starBlues * @version 3.0.0 */ -public interface ResourceLoaderFactory extends ResourceLoader{ +public interface ResourceLoaderFactory extends AutoCloseable{ void addResource(String path) throws Exception; @@ -27,6 +28,12 @@ public interface ResourceLoaderFactory extends ResourceLoader{ void addResource(ResourceLoader resourceLoader) throws Exception; + Resource findResource(String name); + List findResources(String name); + InputStream getInputStream(String name); + + List getResources(); + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java index 195df1f..89b8337 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java @@ -21,6 +21,9 @@ import com.gitee.starblues.loader.classloader.resource.Resource; import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; import com.gitee.starblues.loader.utils.IOUtils; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; @@ -65,11 +68,33 @@ public class DefaultResourceStorage implements ResourceStorage{ return resourceStorage.get(name); } + @Override + public InputStream getInputStream(String name) { + Resource resourceInfo = resourceStorage.get(name); + if (resourceInfo != null) { + try (InputStream inputStream = resourceInfo.getUrl().openStream(); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){ + IOUtils.copy(inputStream, byteArrayOutputStream); + return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + } catch (Exception e){ + e.printStackTrace(); + return null; + } + } else { + return null; + } + } + @Override public List getAll() { return new ArrayList<>(resourceStorage.values()); } + @Override + public boolean isEmpty() { + return resourceStorage.isEmpty(); + } + @Override public void close() throws Exception { for (Resource resource : resourceStorage.values()) { diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java index fd328a1..5c71d6a 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java @@ -19,6 +19,7 @@ package com.gitee.starblues.loader.classloader.resource.storage; import com.gitee.starblues.loader.classloader.resource.Resource; import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; +import java.io.InputStream; import java.net.URL; import java.util.List; @@ -61,11 +62,24 @@ public interface ResourceStorage extends AutoCloseable{ */ Resource get(String name); + /** + * 获取资源的 InputStream + * @param name 资源名称 + * @return InputStream + */ + InputStream getInputStream(String name); + /** * 得到全部资源 * @return 全部资源列表 */ List getAll(); + /** + * 是否为空 + * @return boolean + */ + boolean isEmpty(); + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java index d0f8649..f9bd4e9 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainJarProgramLauncher.java @@ -78,19 +78,18 @@ public class MainJarProgramLauncher extends MainProgramLauncher{ Archive archive = archives.next(); URL url = archive.getUrl(); String path = url.getPath(); - ResourceStorage resourceStorage = ResourceLoaderFactoryGetter.getMainResourceStorage(); if(path.contains(PROD_CLASSES_URL_SIGN)){ - classLoader.addResource(new MainJarResourceLoader(url, resourceStorage)); + classLoader.addResource(new MainJarResourceLoader(url)); } else { - classLoader.addResource(new JarResourceLoader(url, resourceStorage)); + classLoader.addResource(new JarResourceLoader(url)); } } } private static class MainJarResourceLoader extends JarResourceLoader { - public MainJarResourceLoader(URL url, ResourceStorage resourceStorage) throws Exception { - super(url, resourceStorage); + public MainJarResourceLoader(URL url) throws Exception { + super(url); } @Override diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java index 0d62b0c..3c9a1bd 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/MainProgramLauncher.java @@ -56,7 +56,7 @@ public class MainProgramLauncher extends AbstractLauncher{ } protected ResourceLoaderFactory getResourceLoaderFactory(String... args){ - return ResourceLoaderFactoryGetter.create(MAIN_CLASS_LOADER_NAME, args); + return ResourceLoaderFactoryGetter.get(MAIN_CLASS_LOADER_NAME, args); } protected ClassLoader getParentClassLoader(){ @@ -81,5 +81,4 @@ public class MainProgramLauncher extends AbstractLauncher{ } } - } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java index 417f2e9..8159810 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java @@ -56,7 +56,7 @@ public class ResourceLoaderFactoryGetter { private static volatile String resourceMode; - public static ResourceLoaderFactory create(String classLoaderName, String... args){ + static ResourceLoaderFactory get(String classLoaderName, String... args){ if(resourceMode == null){ synchronized (ResourceLoaderFactory.class){ if(resourceMode == null){ @@ -64,11 +64,7 @@ public class ResourceLoaderFactoryGetter { } } } - return instant(classLoaderName); - } - - public static synchronized ResourceLoaderFactory get(String classLoaderName){ - return instant(classLoaderName); + return new DefaultResourceLoaderFactory(classLoaderName); } private static String parseArg(String... args){ @@ -96,12 +92,4 @@ public class ResourceLoaderFactoryGetter { return resourceStorage; } - public static ResourceStorage getMainResourceStorage(){ - return getResourceStorage(MainProgramLauncher.MAIN_CLASS_LOADER_NAME); - } - - private static ResourceLoaderFactory instant(String classLoaderName){ - return new DefaultResourceLoaderFactory(classLoaderName); - } - } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java index eef2c2c..d0ccdca 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java @@ -43,24 +43,27 @@ public class NestedPluginJarResourceLoader extends AbstractResourceLoader { private final InsidePluginDescriptor pluginDescriptor; private final GenericClassLoader parentClassLoader; + private final ResourceLoaderFactory resourceLoaderFactory; + public NestedPluginJarResourceLoader(InsidePluginDescriptor pluginDescriptor, - GenericClassLoader parentClassLoader) throws Exception { - super(new URL("jar:" + pluginDescriptor.getInsidePluginPath().toUri().toURL() + "!/"), - ResourceLoaderFactoryGetter.getResourceStorage(pluginDescriptor.getPluginId())); + GenericClassLoader parentClassLoader, + ResourceLoaderFactory resourceLoaderFactory) throws Exception { + super(new URL("jar:" + pluginDescriptor.getInsidePluginPath().toUri().toURL() + "!/")); this.pluginDescriptor = pluginDescriptor; this.parentClassLoader = parentClassLoader; + this.resourceLoaderFactory = resourceLoaderFactory; } @Override - protected void loadOfChild() throws Exception { + protected void loadOfChild(ResourceStorage resourceStorage) throws Exception { try (JarFile jarFile = new JarFile(pluginDescriptor.getInsidePluginPath().toFile())) { - addClassPath(jarFile); + addClassPath(resourceStorage, jarFile); addLib(jarFile); } } - private void addClassPath(JarFile jarFile) throws Exception{ + private void addClassPath(ResourceStorage resourceStorage, JarFile jarFile) throws Exception{ String classesPath = pluginDescriptor.getPluginClassPath(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()){ @@ -70,7 +73,7 @@ public class NestedPluginJarResourceLoader extends AbstractResourceLoader { } String realName = jarEntry.getName().replace(classesPath, ""); URL url = new URL(baseUrl.toString() + jarEntry.getName()); - super.resourceStorage.add(realName, baseUrl, url, ()->{ + resourceStorage.add(realName, baseUrl, url, ()->{ return getClassBytes(realName, jarFile.getInputStream(jarEntry), true); }); } @@ -87,12 +90,10 @@ public class NestedPluginJarResourceLoader extends AbstractResourceLoader { InputStream jarFileInputStream = jarFile.getInputStream(jarEntry); URL url = new URL(baseUrl.toString() + pluginLibInfo.getPath() + "!/"); if(pluginLibInfo.isLoadToMain()){ - parentClassLoader.addResource(new JarResourceLoader(url, new JarInputStream(jarFileInputStream), - ResourceLoaderFactoryGetter.getMainResourceStorage())); + parentClassLoader.addResource(new JarResourceLoader(url, new JarInputStream(jarFileInputStream))); } else { - JarResourceLoader jarResourceLoader = new JarResourceLoader(url, - new JarInputStream(jarFileInputStream), resourceStorage); - jarResourceLoader.load(); + JarResourceLoader jarResourceLoader = new JarResourceLoader(url, new JarInputStream(jarFileInputStream)); + resourceLoaderFactory.addResource(jarResourceLoader); } } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java index d254fe8..a76be2c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/PluginClassLoader.java @@ -61,7 +61,7 @@ public class PluginClassLoader extends GenericClassLoader { PluginType pluginType = descriptor.getType(); if(pluginType == PluginType.JAR || pluginType == PluginType.ZIP){ NestedPluginJarResourceLoader resourceLoader = - new NestedPluginJarResourceLoader(descriptor, parentClassLoader); + new NestedPluginJarResourceLoader(descriptor, parentClassLoader, resourceLoaderFactory); resourceLoaderFactory.addResource(resourceLoader); } else { addClasspath(descriptor); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index dccfa2d..b459334 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -20,6 +20,8 @@ import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.core.classloader.PluginClassLoader; import com.gitee.starblues.core.launcher.plugin.involved.PluginLaunchInvolved; import com.gitee.starblues.loader.classloader.GenericClassLoader; +import com.gitee.starblues.loader.classloader.resource.loader.DefaultResourceLoaderFactory; +import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; import com.gitee.starblues.loader.launcher.AbstractLauncher; import com.gitee.starblues.loader.launcher.ResourceLoaderFactoryGetter; import com.gitee.starblues.spring.SpringPluginHook; @@ -65,12 +67,16 @@ public class PluginLauncher extends AbstractLauncher { } PluginClassLoader pluginClassLoader = new PluginClassLoader( pluginId, getParentClassLoader(), mainResourcePatternDefiner, - ResourceLoaderFactoryGetter.get(pluginId) + getResourceLoaderFactory() ); CLASS_LOADER_CACHE.put(pluginId, pluginClassLoader); return pluginClassLoader; } + protected ResourceLoaderFactory getResourceLoaderFactory(){ + return new DefaultResourceLoaderFactory(pluginDescriptor.getPluginId()); + } + protected GenericClassLoader getParentClassLoader() throws Exception { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index 60e9166..b446a65 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -200,10 +200,6 @@ public class BasicRepackager implements Repackager{ } protected String getPluginPath(){ - DevConfig devConfig = repackageMojo.getDevConfig(); - if(devConfig != null && !ObjectUtils.isEmpty(devConfig.getPluginPath())){ - return devConfig.getPluginPath(); - } return repackageMojo.getProject().getBuild().getOutputDirectory(); } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java index 5f60b08..558882c 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -49,13 +49,11 @@ public class PluginInfo { /** * 插件配置文件名称。 - * 和 configFileLocation 配置二选一, 如果都有值则默认使用 getConfigFileName */ private String configFileName; /** - * 插件配置文件路径 - * 和 configFileName 配置二选一, 如果都有值则默认使用 getConfigFileName + * 插件配置文件所在目录。如果不填写, 默认从 target/classes 下读取 */ private String configFileLocation; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java index a64dddd..20ed1b6 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevConfig.java @@ -28,16 +28,6 @@ import java.util.List; @Data public class DevConfig { - /** - * 插件编译的class目录 - */ - private String pluginPath; - - /** - * 插件所有依赖存放的路径 - */ - private String libPath; - /** * 当前项目依赖其他模块的定义。 * 主要定义依赖模块target->classes的目录, 方便开发调试 -- Gitee From 05f43ec731cdcbc7d494ae20a9d235841e3fb1a8 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 3 Mar 2022 18:20:25 +0800 Subject: [PATCH 33/37] update readme --- README.md | 77 ++++--------- README_zh.md | 24 ++-- .../com/gitee/starblues/common/Constants.java | 4 + .../com/gitee/starblues/utils/FilesUtils.java | 19 ++++ .../processor/invoke/InvokeProxyHandler.java | 107 +++++++++++++----- .../classloader/GenericClassLoader.java | 107 ++++++++---------- .../loader/AbstractResourceLoader.java | 12 +- .../resource/loader/ClassPathLoader.java | 2 +- .../loader/DefaultResourceLoaderFactory.java | 91 +++++++++++---- .../resource/loader/JarResourceLoader.java | 2 +- .../loader/ResourceLoaderFactory.java | 67 ++++++++++- .../storage/CacheResourceStorage.java | 7 +- .../storage/DefaultResourceStorage.java | 39 ++++++- .../resource/storage/ResourceStorage.java | 8 +- .../SameRootResourceStorage.java} | 24 +++- .../storage/ShareResourceStorage.java | 14 +-- .../launcher/ResourceLoaderFactoryGetter.java | 16 ++- .../loader/launcher/SpringMainBootstrap.java | 1 + .../starblues/loader/utils/ResourceUtils.java | 30 +++++ .../core/DefaultPluginInsideInfo.java | 6 +- .../starblues/core/DefaultPluginManager.java | 19 +++- .../com/gitee/starblues/core/PluginInfo.java | 4 +- .../gitee/starblues/core/PluginInfoFace.java | 8 +- .../NestedPluginJarResourceLoader.java | 2 +- .../AbstractPluginDescriptorLoader.java | 12 +- .../DefaultInsidePluginDescriptor.java | 1 - .../core/descriptor/PluginLibInfo.java | 7 ++ .../starblues/core/descriptor/PluginType.java | 16 +++ .../core/launcher/plugin/PluginLauncher.java | 1 - .../DefaultIntegrationConfiguration.java | 8 +- .../integration/SpringBootPluginStarter.java | 2 + .../listener/PluginInitializerListener.java | 2 +- .../integration/listener/SwaggerListener.java | 5 + .../starblues/utils/AnnotationsUtils.java | 2 +- .../com/gitee/starblues/utils/OrderUtils.java | 1 - .../plugin/pack/dev/DevRepackager.java | 2 + .../plugin/pack/filter/DependencyFilter.java | 1 - .../starblues/plugin/pack/filter/Exclude.java | 1 - .../plugin/pack/main/JarOuterPackager.java | 1 - 39 files changed, 495 insertions(+), 257 deletions(-) rename springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/{loader/ResourceLoaderGetter.java => storage/SameRootResourceStorage.java} (60%) diff --git a/README.md b/README.md index c9ca3a7..b7c06b8 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,29 @@ # SpringBoot Plugin Development Framework -### Introduce -This framework can develop plugins for extension projects on the `SpringBoot` project, -and can define extension functions such as interface, static file and `Mybatis-xml` separately in the plugin module. - -### Core -- Based on `Pf4j` development. -- Plugin configuration plug in SpringBoot project. -- Plugin development can be carried out on springboot with strong expansibility. -Different plugins can be developed for different projects and different plugin jar packages can be deployed. -- You can specify whether to enable or disable plugins through the configuration file, and you can specify the order in which plugins are started. -- It supports uploading plugins and plugin configuration files to the server, and dynamically deploying and updating plugins without restarting the main program. -- It supports viewing plugin operation status and plugin installation location. -- Without restarting the main program, dynamically install, uninstall, enable, stop, backup and delete plugins through the interface. -- On the plugin application module, `spring annotations` can be used to define components for dependency injection. -- Supports the development of `Http-Restful` interfaces in plugins -- Support to define persistence layer access and other requirements separately in the plugin. -- You can follow the plugin interface provided by the main program to develop any extended functions. -- It supports annotation for any business scenario extension, and uses defined coordinates for scenario hit. -- Plugin can customize independent configuration files according to the production and development environment. Currently only `YML files` are supported. -- It supports user-defined extension development interface, and users can extend additional functions on the reserved interface. -- Supports method calls between plugins. -- Supporting plugin http interface documentation: `Swagger`、`SpringDoc`。 -- The plugin supports custom development of the 'Spring-MVC interceptor`. -- The plugin supports 'Spring-Aop'. - -### Expansion pack -#### `SpringBoot-Mybatis` Expansion - -1. Supports customizing the `mapper` interface, `mapper XML` and the corresponding entity `Bean` in the plugin -2. Support integration `Mybatis`、`Mybatis-Plus`、`Tk-Mybatis` -3. Supports independent configuration of `DataSources` in plugin - -- See details: [SpringBoot Mybatis Expansion](http://www.starblues.cn/extension-doc/Mybatis%E6%89%A9%E5%B1%95.html) - -#### `Static resource access` Extension - -1. Supports accessing static resources in plugins through HTTP -2. Support `Thymeleaf` template engine for interface plugin development +- A new `3.0.0' version is available, a framework for dynamically extending the system. -- See details: [Static Resource Access Extension](http://www.starblues.cn/extension-doc/%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E8%AE%BF%E9%97%AE%E6%89%A9%E5%B1%95.html) - -#### `Plugin Log` Extension - -1. The plugin can independently configure the integrated `logback` log -2. The plugin can independently configure the integrated `log4j2` log - -- See details: [Plugin Log Extension](http://www.starblues.cn/extension-doc/Log%E6%89%A9%E5%B1%95.html) -- Thank for [sousouki](https://gitee.com/caoshx_sousouki) development +### Introduce +The framework can be developed in the `SpringBoot` project plugin, plugin can be used in exactly the same way as `SpringBoot`. Using this framework you can achieve the following requirements: + +- In the plugin, you can develop as a mini `spring-boot` project, which is easy to use. +- The extension of various function points in the system in plugin, for flexible system expansion, no longer need to use branches to deliver different requirements of the project. +- Various frameworks and their various `spring-boot-XXX-starter` can be integrated in plugin. +- Independent dependencies can now be defined in plugin, not in the main program. +- Can perfectly solve the plugin package and plugin package, plugin package and the main program because of the same framework of different versions of the conflict problem. Individual plugin can define different versions of the framework for the same dependency. +- Without the need to restart the main program, you can freely realize the dynamic installation and deployment of the plugin package, to dynamically expand the function of the system. +- Plugin can also integrate microservice modules independently of the main program. +- And so on, you can imagine what pressing needs and extensions this framework brings to you. +### Features +1. It simplifies the integration steps of the framework and makes it easier to get started. +2. Plugin development is closer to `spring-boot` native development. +3. Package plugin with `Maven` to support independent package compilation of plugins. Current support: +- Dev packaging: Package the plugin as a development environment plugin (packaged only once). +- Prod packaging: Package plug-ins into a `jar`, `zip`, `folder`, etc. +4. Plugin support two modes of operation: +- Plugin mode: As a plugin, it is bootloaded by the main program. +- Autonomous boot mode: Starts as a separate `SpringBoot` project。 +5. Self-developed class loader, support plugin definition of a variety of dependent 'jar' packages. +6. Various frameworks and their various `spring-boot-XXX-starter` can be integrated in plugins, such as integration: `mybatis`、`mybatis-plus`、`spring-jpa` etc. ### Environment 1. jdk1.8+d @@ -60,7 +36,7 @@ Different plugins can be developed for different projects and different plugin j ### Doc -- [http://www.starblues.cn/](http://www.starblues.cn/) +- [https://www.yuque.com/starblues/iuyk4y/ypurcw](https://www.yuque.com/starblues/iuyk4y/ypurcw) ### Derivative products #### Background management system with front and rear plugin function @@ -74,9 +50,4 @@ Different plugins can be developed for different projects and different plugin j ### Contact QQ: 859570617(**After you like the framework, you can enter the group. Please note the Gitee/GitHub nickname before entering the group**) -### Framework maintenance -**Welcome all development enthusiasts to participate in the maintenance and extension development of the framework** - -See for extended development documents: - [springboot-plugin-framework Extended](http://www.starblues.cn/extension-doc/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%89%A9%E5%B1%95.html) - diff --git a/README_zh.md b/README_zh.md index 508124b..6d070a1 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,12 +1,13 @@ # springboot插件式开发框架 -- 全新3.0.0版本上线啦,为动态扩展系统而生的框架。 +- 全新`3.0.0`版本上线啦,为动态扩展系统而生的框架。 ### 介绍 -该框架可以在SpringBoot项目上开发出插件功能,在插件中可以和SpringBoot使用方式一模一样。使用了本框架您可以实现如下需求: -- 在插件中,您可以当成一个微型的Spring-Boot项目来开发,简单易用。 +该框架可以在`SpringBoot`项目上开发出插件功能,在插件中可以和`SpringBoot`使用方式一模一样。使用了本框架您可以实现如下需求: + +- 在插件中,您可以当成一个微型的`Spring-Boot`项目来开发,简单易用。 - 在插件中扩展出系统各种功能点,用于系统灵活扩展,再也不用使用分支来交付不同需求的项目了。 -- 在插件中可以集成各种框架及其各种spring-boot-xxx-starter。 +- 在插件中可以集成各种框架及其各种`spring-boot-xxx-starter`。 - 在插件中可以定义独立依赖包了,再也不用在主程序中定义依赖包了。 - 可以完美解决插件包与插件包、插件包与主程序因为同一框架的不同版本冲突问题了。各个插件可以定义同一依赖的不同版本框架。 - 无需重启主程序,可以自由实现插件包的动态安装部署,来动态扩展系统的功能。 @@ -15,14 +16,15 @@ ### 特性 1. 简化了框架的集成步骤,更容易上手。 -2. 使用Maven打包插件,支持对插件的自主打包编译。目前支持: +2. 插件开发更加贴近`spring-boot`原生开发。 +3. 使用`Maven`打包插件,支持对插件的自主打包编译。目前支持: - 开发打包:将插件打包成开发环境下的插件(仅需打包一次)。 -- 生产打包:将插件打包成一个jar、zip、文件夹 -3. 插件支持两模式 -4. 插件模式: 作为一个插件,由主程序引导加载。 -5. 自主启动模式:单独作为一个SpringBoot项目来启动。 -6. 自主的开发的类加载器,支持插件定义各种的依赖jar包。 -7. 在插件中可以集成各种框架及其各种spring-boot-xxx-starter,比如集成mybatis、mybatis-plus、spring-jpa等。 +- 生产打包:将插件打包成一个`jar`、`zip`、`文件夹`等。 +4. 插件支持两种运行模式 +- 插件模式: 作为一个插件,由主程序引导加载。 +- 自主启动模式:单独作为一个`SpringBoot`项目来启动。 +5. 自主的开发的类加载器,支持插件定义各种的依赖`jar`包。 +6. 在插件中可以集成各种框架及其各种`spring-boot-xxx-starter`,比如集成`mybatis`、`mybatis-plus`、`spring-jpa`等。 ### 运行环境 1. jdk1.8+ diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java index c6bec80..2151f6c 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/Constants.java @@ -41,5 +41,9 @@ public abstract class Constants { */ public final static String LOAD_TO_MAIN_SIGN = "@LOAD_TO_MAIN"; + /** + * 相对路径符号标志 + */ + public final static String RELATIVE_SIGN = "~"; } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java index 4b898d1..0351973 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java @@ -16,6 +16,8 @@ package com.gitee.starblues.utils; +import com.gitee.starblues.common.Constants; + import java.io.File; import java.util.function.Supplier; @@ -130,4 +132,21 @@ public class FilesUtils { return stringBuilder.toString(); } + /** + * 解决相对路径 + * @param rootPath 根路径 + * @param relativePath 以 ~ 开头的相对路径 + * @return 处理后的路径 + */ + public static String resolveRelativePath(String rootPath, String relativePath){ + if(ObjectUtils.isEmpty(relativePath)){ + return relativePath; + } + if(relativePath.startsWith(Constants.RELATIVE_SIGN)){ + return joiningFilePath(rootPath, relativePath.replaceFirst(Constants.RELATIVE_SIGN, "")); + } else { + return relativePath; + } + } + } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java index 7d24f63..9efd0e0 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/invoke/InvokeProxyHandler.java @@ -21,9 +21,13 @@ import com.gitee.starblues.annotation.Caller; import com.gitee.starblues.annotation.Supplier; import com.gitee.starblues.spring.invoke.InvokeSupperCache; import com.gitee.starblues.utils.ObjectUtils; +import com.gitee.starblues.utils.ReflectionUtils; +import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Map; import java.util.Objects; /** @@ -44,7 +48,7 @@ public class InvokeProxyHandler implements InvocationHandler { } @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + public Object invoke(Object proxy, Method method, Object[] callerArgs) throws Throwable { String pluginId = callerAnnotation.pluginId(); Object supplierObject = invokeSupperCache.getSupperBean(pluginId, callerAnnotation.value()); if (supplierObject == null) { @@ -56,13 +60,13 @@ public class InvokeProxyHandler implements InvocationHandler { } } Caller.Method callerMethod = method.getAnnotation(Caller.Method.class); - if (args == null) { - args = new Object[]{}; + if (callerArgs == null) { + callerArgs = new Object[]{}; } if (callerMethod == null) { - return notAnnotationInvoke(method, supplierObject, args); + return notAnnotationInvoke(method, supplierObject, callerArgs); } else { - return annotationInvoke(method, callerMethod, supplierObject, args); + return annotationInvoke(method, callerMethod, supplierObject, callerArgs); } } @@ -73,12 +77,12 @@ public class InvokeProxyHandler implements InvocationHandler { * @param method 调用接口的方法 * @param callerMethod 调用者方法注解 * @param supplierObject 调用者对象 - * @param args 传入参数 + * @param callerArgs 调用者参数 * @return 返回值 * @throws Throwable 异常 */ private Object annotationInvoke(Method method, Caller.Method callerMethod, - Object supplierObject, Object[] args) throws Throwable{ + Object supplierObject, Object[] callerArgs) throws Throwable{ String callerMethodName = callerMethod.value(); Class supplierClass = supplierObject.getClass(); @@ -96,26 +100,14 @@ public class InvokeProxyHandler implements InvocationHandler { } if(supplierMethod == null){ // 如果为空, 说明没有找到被调用者的注解, 则走没有注解的代理调用。 - return notAnnotationInvoke(method, supplierObject, args); + return notAnnotationInvoke(method, supplierObject, callerArgs); } Class[] parameterTypes = supplierMethod.getParameterTypes(); - if(parameterTypes.length != args.length){ + if(parameterTypes.length != callerArgs.length){ // 参数不匹配 - return notAnnotationInvoke(method, supplierObject, args); - } - Object[] supplierArgs = new Object[args.length]; - for (int i = 0; i < parameterTypes.length; i++) { - Class parameterType = parameterTypes[i]; - Object arg = args[i]; - if(parameterType == arg.getClass()){ - supplierArgs[i] = arg; - } else { - // 类型不匹配, 尝试使用json序列化 - String json = OBJECT_MAPPER.writeValueAsString(arg); - Object serializeObject = OBJECT_MAPPER.readValue(json, parameterType); - supplierArgs[i] = serializeObject; - } + return notAnnotationInvoke(method, supplierObject, callerArgs); } + Object[] supplierArgs = getSupplierArgs(callerArgs, supplierMethod); Object invokeReturn = supplierMethod.invoke(supplierObject, supplierArgs); return getReturnObject(invokeReturn, method); } @@ -124,22 +116,59 @@ public class InvokeProxyHandler implements InvocationHandler { * 没有注解调用 * @param method 调用接口的方法 * @param supplierObject 提供者对象 - * @param args 传入参数 + * @param callerArgs 调用者参数 * @return 返回值 * @throws Throwable 异常 */ - private Object notAnnotationInvoke(Method method, Object supplierObject, Object[] args) throws Throwable{ + private Object notAnnotationInvoke(Method method, Object supplierObject, Object[] callerArgs) throws Throwable{ String name = method.getName(); - Class[] argClasses = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - argClasses[i] = args[i].getClass(); + Class[] supplierArgClasses = new Class[callerArgs.length]; + ClassLoader classLoader = supplierObject.getClass().getClassLoader(); + for (int i = 0; i < callerArgs.length; i++) { + Object callerArg = callerArgs[i]; + try { + supplierArgClasses[i] = classLoader.loadClass(callerArg.getClass().getName()); + } catch (Exception e){ + supplierArgClasses[i] = callerArg.getClass(); + } } Class supplierClass = supplierObject.getClass(); - Method supplierMethod = supplierClass.getMethod(name, argClasses); - Object invokeReturn = supplierMethod.invoke(supplierObject, args); + Method supplierMethod = null; + try { + supplierMethod = supplierClass.getMethod(name, supplierArgClasses); + } catch (Exception e){ + supplierMethod = findSupplierMethod(supplierClass, name, supplierArgClasses); + } + if(supplierMethod == null){ + throw ReflectionUtils.getNoSuchMethodException(supplierClass, name, supplierArgClasses); + } + Object[] supplierArgs = getSupplierArgs(callerArgs, supplierMethod); + Object invokeReturn = supplierMethod.invoke(supplierObject, supplierArgs); return getReturnObject(invokeReturn, method); } + private Object[] getSupplierArgs(Object[] callerArgs, Method supplierMethod) throws Exception{ + if(callerArgs == null || callerArgs.length == 0){ + return new Class[]{}; + } + Class[] supplierParameterTypes = supplierMethod.getParameterTypes(); + Object[] supplierArgs = new Object[callerArgs.length]; + for (int i = 0; i < supplierParameterTypes.length; i++) { + Class supplierParameterType = supplierParameterTypes[i]; + Object arg = callerArgs[i]; + if(supplierParameterType.isAssignableFrom(arg.getClass())){ + // 类型相同 + supplierArgs[i] = arg; + } else { + // 类型不匹配, 尝试使用json序列化. 当前序列化针对大数据量下性能比较低, 建议将大数据量传输的参数定义到主程序中 + String json = OBJECT_MAPPER.writeValueAsString(arg); + Object serializeObject = OBJECT_MAPPER.readValue(json, supplierParameterType); + supplierArgs[i] = serializeObject; + } + } + return supplierArgs; + } + /** * 得到返回值对象 @@ -160,4 +189,22 @@ public class InvokeProxyHandler implements InvocationHandler { return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructType(method.getGenericReturnType()) ); } } + + private Method findSupplierMethod(Class supplierClass, String methodName, Class[] supplierArgClasses){ + while (supplierClass != null){ + Method[] methods = supplierClass.getMethods(); + for (Method method : methods) { + String name = method.getName(); + if(!Objects.equals(name, methodName)){ + continue; + } + if(method.getParameterTypes().length == supplierArgClasses.length){ + return method; + } + } + supplierClass = supplierClass.getSuperclass(); + } + return null; + } + } \ No newline at end of file diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java index ac3530e..fe1a01f 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/GenericClassLoader.java @@ -16,14 +16,12 @@ package com.gitee.starblues.loader.classloader; - import com.gitee.starblues.loader.classloader.resource.Resource; import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoader; import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; -import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderGetter; import com.gitee.starblues.loader.utils.Assert; import com.gitee.starblues.loader.utils.IOUtils; -import com.gitee.starblues.loader.utils.ObjectUtils; +import com.gitee.starblues.loader.utils.ResourceUtils; import java.io.*; import java.net.URL; @@ -32,7 +30,6 @@ import java.nio.file.Path; import java.util.Enumeration; import java.util.List; import java.util.Map; -import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; /** @@ -111,7 +108,7 @@ public class GenericClassLoader extends URLClassLoader { if (loadedClass != null) { return loadedClass; } - throw new ClassNotFoundException(className); + throw new ClassNotFoundException("ClassLoader[" + name +"]:" + className); } protected Class findClassFromParent(String className) throws ClassNotFoundException{ @@ -174,10 +171,10 @@ public class GenericClassLoader extends URLClassLoader { @Override public URL[] getURLs() { - List resources = resourceLoaderFactory.getResources(); - URL[] urls = new URL[resources.size()]; - for (int i = 0; i < resources.size(); i++) { - urls[i] = resources.get(i).getUrl(); + List urlList = resourceLoaderFactory.getUrls(); + URL[] urls = new URL[urlList.size()]; + for (int i = 0; i < urlList.size(); i++) { + urls[i] = urlList.get(i); } return urls; } @@ -232,21 +229,29 @@ public class GenericClassLoader extends URLClassLoader { public Enumeration getResources(String name) throws IOException { name = formatResourceName(name); Enumeration parentResources = findResourcesFromParent(name); - Vector vector = new Vector<>(); - if(parentResources != null){ - while (parentResources.hasMoreElements()){ - URL url = parentResources.nextElement(); - vector.add(url); - } - } Enumeration localResources = findResourcesFromLocal(name); - if(localResources != null){ - while (localResources.hasMoreElements()){ - URL url = localResources.nextElement(); - vector.add(url); + return new Enumeration() { + + private int index = 0; + + @Override + public boolean hasMoreElements() { + if(parentResources != null && parentResources.hasMoreElements()){ + return true; + } + index = 1; + return localResources.hasMoreElements(); } - } - return vector.elements(); + + @Override + public URL nextElement() { + if(index == 0){ + return parentResources.nextElement(); + } else { + return localResources.nextElement(); + } + } + }; } protected Enumeration findResourcesFromParent(String name) throws IOException{ @@ -257,49 +262,20 @@ public class GenericClassLoader extends URLClassLoader { } protected Enumeration findResourcesFromLocal(String name) throws IOException{ - List resourceList = resourceLoaderFactory.findResources(name); - if(resourceList != null && !resourceList.isEmpty()){ - Vector vector = new Vector<>(); - for (Resource resource : resourceList) { - vector.add(resource.getUrl()); + Enumeration enumeration = resourceLoaderFactory.findResources(name); + return new Enumeration() { + @Override + public boolean hasMoreElements() { + return enumeration.hasMoreElements(); } - return vector.elements(); - } - return null; - } - private String formatClassName(String className) { - className = className.replace( '/', '~' ); - className = className.replace( '.', '/' ) + ".class"; - className = className.replace( '~', '/' ); - return className; - } - - private String formatResourceName(String resourceName){ - if(ObjectUtils.isEmpty(resourceName)) { - return Resource.PACKAGE_SPLIT; - } - String[] split = resourceName.split("/"); - StringBuilder newPath = new StringBuilder(); - for (int i = 0; i < split.length; i++) { - String s = split[i]; - if("".equals(s)){ - continue; + @Override + public URL nextElement() { + return enumeration.nextElement().getUrl(); } - if(i == 0){ - newPath = new StringBuilder(s); - } else { - newPath.append(Resource.PACKAGE_SPLIT).append(s); - } - } - if(resourceName.endsWith(Resource.PACKAGE_SPLIT)){ - newPath.append(Resource.PACKAGE_SPLIT); - } - return newPath.toString(); + }; } - - @Override public void close() throws IOException { synchronized (pluginClassCache){ @@ -308,5 +284,16 @@ public class GenericClassLoader extends URLClassLoader { } } + private String formatResourceName(String name) { + return ResourceUtils.formatStandardName(name); + } + + private String formatClassName(String className) { + className = className.replace( '/', '~' ); + className = className.replace( '.', '/' ) + ".class"; + className = className.replace( '~', '/' ); + return className; + } + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java index a5be752..67d1a91 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/AbstractResourceLoader.java @@ -17,18 +17,12 @@ package com.gitee.starblues.loader.classloader.resource.loader; -import com.gitee.starblues.loader.classloader.resource.Resource; -import com.gitee.starblues.loader.classloader.resource.storage.DefaultResourceStorage; import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; -import com.gitee.starblues.loader.utils.Assert; import com.gitee.starblues.loader.utils.IOUtils; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** * 抽象的资源加载者 @@ -63,7 +57,7 @@ public abstract class AbstractResourceLoader implements ResourceLoader{ } try { // 添加root 路径 - resourceStorage.add("/", baseUrl, baseUrl); + resourceStorage.add("/", baseUrl); loadOfChild(resourceStorage); } finally { loaded = true; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java index 8cd9509..24048c0 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ClassPathLoader.java @@ -86,7 +86,7 @@ public class ClassPathLoader extends AbstractResourceLoader { } private void addResource(ResourceStorage resourceStorage, File file, String packageName) throws Exception { - resourceStorage.add(packageName, url, new URL(url.toString() + packageName), ()->{ + resourceStorage.add(packageName, new URL(url.toString() + packageName), ()->{ if(file.exists() && file.isFile()){ return getClassBytes(file.getPath(), new FileInputStream(file), true); } else { diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java index 9e46ff8..72b6b2a 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java @@ -18,20 +18,25 @@ package com.gitee.starblues.loader.classloader.resource.loader; import com.gitee.starblues.loader.classloader.resource.Resource; import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; +import com.gitee.starblues.loader.classloader.resource.storage.SameRootResourceStorage; import com.gitee.starblues.loader.launcher.ResourceLoaderFactoryGetter; import com.gitee.starblues.loader.utils.IOUtils; import com.gitee.starblues.loader.utils.ResourceUtils; import java.io.File; +import java.io.IOException; import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; +import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.function.Function; /** * 默认的资源加载工厂 @@ -41,7 +46,7 @@ import java.util.concurrent.ConcurrentHashMap; */ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ - private final Map resourceLoaderMap = new ConcurrentHashMap<>(); + private final Map resourceLoaderMap = new ConcurrentHashMap<>(); private final String classLoaderName; @@ -102,7 +107,9 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ if (resourceLoaderMap.containsKey(resourceLoader.getBaseUrl())) { return; } - ResourceStorage resourceStorage = ResourceLoaderFactoryGetter.getResourceStorage(classLoaderName); + SameRootResourceStorage resourceStorage = ResourceLoaderFactoryGetter.getResourceStorage( + classLoaderName, + resourceLoader.getBaseUrl()); resourceLoader.load(resourceStorage); if(!resourceStorage.isEmpty()){ resourceLoaderMap.put(resourceLoader.getBaseUrl(), resourceStorage); @@ -110,32 +117,69 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ } @Override - public List findResources(String name) { - List resources = new ArrayList<>(); - for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + public Resource findResource(String name) { + for (Map.Entry entry : resourceLoaderMap.entrySet()) { + ResourceStorage resourceStorage = entry.getValue(); Resource resource = resourceStorage.get(name); if(resource != null){ - resources.add(resource); + return resource; } } - return resources; + return null; } - @Override - public Resource findResource(String name) { - for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { - Resource resourceInfo = resourceStorage.get(name); - if(resourceInfo != null){ - return resourceInfo; + public Enumeration findResources(String name) { + return new Enumeration() { + private final List list = new ArrayList<>(resourceLoaderMap.values()); + private int index = 0; + private Resource resource = null; + + @Override + public boolean hasMoreElements() { + return next(); } - } - return null; + + @Override + public Resource nextElement() { + if (!next()) { + throw new NoSuchElementException(); + } + Resource r = resource; + resource = null; + return r; + } + + private boolean next() { + if (resource != null) { + return true; + } else { + SameRootResourceStorage resourceStorage; + while (index < list.size()){ + resourceStorage = list.get(index++); + resource = getResource(resourceStorage); + if(resource != null){ + return true; + } + } + return false; + } + } + + private Resource getResource(SameRootResourceStorage resourceStorage){ + resource = resourceStorage.get(name); + if(resource != null){ + return resource; + } + return null; + } + }; } @Override public InputStream getInputStream(String name) { - for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { + for (Map.Entry entry : resourceLoaderMap.entrySet()) { + ResourceStorage resourceStorage = entry.getValue(); InputStream inputStream = resourceStorage.getInputStream(name); if(inputStream != null){ return inputStream; @@ -145,12 +189,8 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ } @Override - public List getResources() { - List resources = new ArrayList<>(); - for (ResourceStorage resourceStorage : resourceLoaderMap.values()) { - resources.addAll(resourceStorage.getAll()); - } - return resources; + public List getUrls() { + return new ArrayList<>(resourceLoaderMap.keySet()); } @Override @@ -160,4 +200,5 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ } resourceLoaderMap.clear(); } + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java index 816c6f2..5984b42 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/JarResourceLoader.java @@ -79,7 +79,7 @@ public class JarResourceLoader extends AbstractResourceLoader { if(includeResource.include(jarEntry)){ String name = resolveName(jarEntry.getName()); URL url = new URL(baseUrl.toString() + name); - resourceStorage.add(name, baseUrl, url, ()->{ + resourceStorage.add(name, url, ()->{ return getClassBytes(name, jarInputStream, false); }); jarInputStream.closeEntry(); diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java index 3b6a5df..e626f42 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderFactory.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.loader.classloader.resource.loader; import com.gitee.starblues.loader.classloader.resource.Resource; @@ -7,6 +23,7 @@ import java.io.File; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; +import java.util.Enumeration; import java.util.List; /** @@ -17,23 +34,67 @@ import java.util.List; */ public interface ResourceLoaderFactory extends AutoCloseable{ - + /** + * 根据路径字符串添加资源 + * @param path 路径字符串 + * @throws Exception 添加资源异常 + */ void addResource(String path) throws Exception; + /** + * 根据文件添加资源 + * @param file 文件 + * @throws Exception 添加资源异常 + */ void addResource(File file) throws Exception; + /** + * 根据路径添加资源 + * @param path 路径 + * @throws Exception 添加资源异常 + */ void addResource(Path path) throws Exception; + /** + * 根据 URL 添加资源 + * @param url URL + * @throws Exception 添加资源异常 + */ void addResource(URL url) throws Exception; + /** + * 根据资源加载器添加资源 + * @param resourceLoader 资源加载者 + * @throws Exception 添加资源异常 + */ void addResource(ResourceLoader resourceLoader) throws Exception; + /** + * 根据资源名称获取第一个资源 + * @param name 资源名称 + * @return Resource + */ Resource findResource(String name); - List findResources(String name); + /** + * 根据资源名称获取资源集合 + * @param name 资源名称 + * @return Resource + */ + Enumeration findResources(String name); + /** + * 根据资源名称获取第一个资源的 InputStream + * @param name 资源名称 + * @return Resource + */ InputStream getInputStream(String name); - List getResources(); + /** + * 获取所有URL + * @return URL + */ + List getUrls(); + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java index 7dfcd0c..9f3872f 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/CacheResourceStorage.java @@ -34,8 +34,13 @@ public class CacheResourceStorage extends DefaultResourceStorage{ protected final Map resourceStorage = new ConcurrentHashMap<>(); + public CacheResourceStorage(URL baseUrl) { + super(baseUrl); + } + @Override - public void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception{ + public void add(String name, URL url, ResourceByteGetter byteGetter) throws Exception{ + name = formatResourceName(name); if(resourceStorage.containsKey(name)){ return; } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java index 89b8337..84a7733 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/DefaultResourceStorage.java @@ -19,7 +19,10 @@ package com.gitee.starblues.loader.classloader.resource.storage; import com.gitee.starblues.loader.classloader.resource.loader.DefaultResource; import com.gitee.starblues.loader.classloader.resource.Resource; import com.gitee.starblues.loader.classloader.resource.ResourceByteGetter; +import com.gitee.starblues.loader.utils.Assert; import com.gitee.starblues.loader.utils.IOUtils; +import com.gitee.starblues.loader.utils.ObjectUtils; +import com.gitee.starblues.loader.utils.ResourceUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -36,40 +39,61 @@ import java.util.concurrent.ConcurrentHashMap; * @author starBlues * @version 3.0.0 */ -public class DefaultResourceStorage implements ResourceStorage{ +public class DefaultResourceStorage extends SameRootResourceStorage{ protected final Map resourceStorage = new ConcurrentHashMap<>(); + public DefaultResourceStorage(URL baseUrl) { + super(baseUrl); + } + @Override - public void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception{ + public void add(String name, URL url, ResourceByteGetter byteGetter) throws Exception{ + Assert.isNotEmpty(name, "name 不能为空"); + Assert.isNotNull(url, "url 不能为空"); + name = formatResourceName(name); if(resourceStorage.containsKey(name)){ return; } DefaultResource defaultResource = new DefaultResource(name, baseUrl, url); - addResource(name, defaultResource); + resourceStorage.put(name, defaultResource); } @Override - public void add(String name, URL baseUrl, URL url) throws Exception{ - this.add(name, baseUrl, url, null); + public void add(String name, URL url) throws Exception{ + this.add(name, url, null); } @Override public boolean exist(String name) { + if(ObjectUtils.isEmpty(name)){ + return false; + } + name = formatResourceName(name); return resourceStorage.containsKey(name); } protected void addResource(String name, Resource resource){ + Assert.isNotEmpty(name, "name 不能为空"); + Assert.isNotNull(resource, "resource 不能为空"); resourceStorage.put(name, resource); } @Override public Resource get(String name) { + if(ObjectUtils.isEmpty(name)){ + return null; + } + name = formatResourceName(name); return resourceStorage.get(name); } @Override public InputStream getInputStream(String name) { + if(ObjectUtils.isEmpty(name)){ + return null; + } + name = formatResourceName(name); Resource resourceInfo = resourceStorage.get(name); if (resourceInfo != null) { try (InputStream inputStream = resourceInfo.getUrl().openStream(); @@ -102,4 +126,9 @@ public class DefaultResourceStorage implements ResourceStorage{ } resourceStorage.clear(); } + + protected final String formatResourceName(String name) { + return ResourceUtils.formatStandardName(name); + } + } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java index 5c71d6a..0720a4e 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ResourceStorage.java @@ -34,19 +34,19 @@ public interface ResourceStorage extends AutoCloseable{ /** * 添加资源 * @param name 资源名称 - * @param baseUrl 资源根URL * @param url 资源url * @param byteGetter 资源字节获取者 + * @throws Exception 添加资源异常 */ - void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception; + void add(String name, URL url, ResourceByteGetter byteGetter) throws Exception; /** * 添加资源 * @param name 资源名称 - * @param baseUrl 资源根URL * @param url 资源url + * @throws Exception 添加资源异常 */ - void add(String name, URL baseUrl, URL url) throws Exception; + void add(String name, URL url) throws Exception; /** * 存在资源 diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/SameRootResourceStorage.java similarity index 60% rename from springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java rename to springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/SameRootResourceStorage.java index c25b2d5..b53b935 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/ResourceLoaderGetter.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/SameRootResourceStorage.java @@ -14,19 +14,31 @@ * limitations under the License. */ -package com.gitee.starblues.loader.classloader.resource.loader; +package com.gitee.starblues.loader.classloader.resource.storage; -import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; +import java.net.URL; /** - * 资源加载获取者 + * 抽象的资源存储 * * @author starBlues * @version 3.0.0 */ -@FunctionalInterface -public interface ResourceLoaderGetter { +public abstract class SameRootResourceStorage implements ResourceStorage { + + protected final URL baseUrl; + + public SameRootResourceStorage(URL baseUrl) { + this.baseUrl = baseUrl; + } + + /** + * 获取 base url + * @return URL + */ + public URL getBaseUrl() { + return baseUrl; + } - ResourceLoader get(ResourceStorage resourceStorage) throws Exception; } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java index a4b6a41..6cd1cc9 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/storage/ShareResourceStorage.java @@ -36,12 +36,14 @@ public class ShareResourceStorage extends DefaultResourceStorage{ private final String key; - public ShareResourceStorage(String key) { + public ShareResourceStorage(String key, URL baseUrl) { + super(baseUrl); this.key = key; } @Override - public void add(String name, URL baseUrl, URL url, ResourceByteGetter byteGetter) throws Exception{ + public void add(String name, URL url, ResourceByteGetter byteGetter) throws Exception{ + name = formatResourceName(name); if(resourceStorage.containsKey(name)){ return; } @@ -102,21 +104,14 @@ public class ShareResourceStorage extends DefaultResourceStorage{ private static class ByteStore{ - private final String resourceName; - private final String commonByteKey; private final Map bytesMap = new HashMap<>(); private ByteStore(String resourceName) { - this.resourceName = resourceName; this.commonByteKey = resourceName + "_ByteStoreCommon"; } - public String getResourceName() { - return resourceName; - } - public synchronized void addByte(String key, byte[] bytes){ Assert.isNotEmpty(key, "classLoaderName 不能为空"); if(bytes == null || bytes.length == 0){ @@ -154,7 +149,6 @@ public class ShareResourceStorage extends DefaultResourceStorage{ return false; } } - } } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java index 8159810..61dbbd9 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/ResourceLoaderFactoryGetter.java @@ -18,11 +18,9 @@ package com.gitee.starblues.loader.launcher; import com.gitee.starblues.loader.classloader.resource.loader.DefaultResourceLoaderFactory; import com.gitee.starblues.loader.classloader.resource.loader.ResourceLoaderFactory; -import com.gitee.starblues.loader.classloader.resource.storage.CacheResourceStorage; -import com.gitee.starblues.loader.classloader.resource.storage.DefaultResourceStorage; -import com.gitee.starblues.loader.classloader.resource.storage.ResourceStorage; -import com.gitee.starblues.loader.classloader.resource.storage.ShareResourceStorage; +import com.gitee.starblues.loader.classloader.resource.storage.*; +import java.net.URL; import java.util.Objects; /** @@ -80,14 +78,14 @@ public class ResourceLoaderFactoryGetter { return null; } - public static ResourceStorage getResourceStorage(String key){ - ResourceStorage resourceStorage = null; + public static SameRootResourceStorage getResourceStorage(String key, URL baseUrl){ + SameRootResourceStorage resourceStorage = null; if(Objects.equals(resourceMode, RESOURCE_MODE_NO_CACHE)){ - resourceStorage = new DefaultResourceStorage(); + resourceStorage = new DefaultResourceStorage(baseUrl); } else if(Objects.equals(resourceMode, RESOURCE_MODE_CACHE_SHARE)){ - resourceStorage = new ShareResourceStorage(key); + resourceStorage = new ShareResourceStorage(key, baseUrl); } else { - resourceStorage = new CacheResourceStorage(); + resourceStorage = new CacheResourceStorage(baseUrl); } return resourceStorage; } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java index 42f709c..19db6ba 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/SpringMainBootstrap.java @@ -20,6 +20,7 @@ import com.gitee.starblues.loader.jar.JarFile; import com.gitee.starblues.loader.launcher.runner.MainMethodRunner; import com.gitee.starblues.loader.launcher.runner.MethodRunner; +import java.io.File; import java.util.Objects; import java.util.concurrent.CountDownLatch; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java index 0b4297c..de76425 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java @@ -32,6 +32,8 @@ public class ResourceUtils { public static final String URL_PROTOCOL_VFSFILE = "vfsfile"; public static final String URL_PROTOCOL_VFS = "vfs"; + public static final String PACKAGE_SPLIT = "/"; + private ResourceUtils(){} /** @@ -67,4 +69,32 @@ public class ResourceUtils { URL_PROTOCOL_VFS.equals(protocol)); } + /** + * 将资源名称统一格式化为标准格式 + * 标准格式为 a/b/c + * @param name 原始资源名称 + * @return 标准资源名称 + */ + public static String formatStandardName(String name){ + if(ObjectUtils.isEmpty(name)) { + return PACKAGE_SPLIT; + } + String[] split = name.split(PACKAGE_SPLIT); + StringBuilder newPath = null; + for (String s : split) { + if ("".equals(s)) { + continue; + } + if (newPath == null) { + newPath = new StringBuilder(s); + } else { + newPath.append(PACKAGE_SPLIT).append(s); + } + } + if(newPath == null || newPath.length() == 0){ + return PACKAGE_SPLIT; + } + return newPath.toString(); + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java index f0b90e5..8e246ec 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java @@ -78,12 +78,12 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { } @Override - public Date startTime() { + public Date getStartTime() { return startTime; } @Override - public Date stopTime() { + public Date getStopTime() { return stopTime; } @@ -96,7 +96,7 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { if(pluginState == PluginState.STARTED){ startTime = new Date(); stopTime = null; - } if(pluginState == PluginState.STOPPED){ + } else if(pluginState == PluginState.STOPPED){ stopTime = new Date(); startTime = null; } else { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index a4bd063..eddda38 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -44,6 +44,7 @@ import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; /** * 抽象的插件管理者 @@ -76,7 +77,7 @@ public class DefaultPluginManager implements PluginManager{ public DefaultPluginManager(RealizeProvider realizeProvider, IntegrationConfiguration configuration) { this.provider = Assert.isNotNull(realizeProvider, "参数 realizeProvider 不能为空"); this.configuration = Assert.isNotNull(configuration, "参数 configuration 不能为空"); - this.pluginRootDirs = configuration.pluginPath(); + this.pluginRootDirs = resolvePath(configuration.pluginPath()); this.pathResolve = getComposePathResolve(); this.basicChecker = realizeProvider.getPluginBasicChecker(); this.launcherChecker = getComposeLauncherChecker(realizeProvider); @@ -105,6 +106,9 @@ public class DefaultPluginManager implements PluginManager{ @Override public String getDefaultPluginRoot() { + if(pluginRootDirs == null){ + return null; + } return pluginRootDirs.stream().findFirst().orElseThrow(()->{ return new PluginException("插件根路径未配置"); }); @@ -584,5 +588,18 @@ public class DefaultPluginManager implements PluginManager{ } } + private List resolvePath(List path){ + if(ObjectUtils.isEmpty(path)){ + return Collections.emptyList(); + } else { + File file = new File(""); + String absolutePath = file.getAbsolutePath(); + return path.stream() + .filter(p->!ObjectUtils.isEmpty(p)) + .map(p->FilesUtils.resolveRelativePath(absolutePath, p)) + .collect(Collectors.toList()); + } + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java index edc51f2..851d1f8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfo.java @@ -55,13 +55,13 @@ public interface PluginInfo { * 启动时间. 只有启动状态 {@link PluginState#STARTED} 才有值。 * @return Date */ - Date startTime(); + Date getStartTime(); /** * 停止时间. 只有停止状态 {@link PluginState#STOPPED} 才有值。 * @return Date */ - Date stopTime(); + Date getStopTime(); /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java index 6873ea7..0822f84 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginInfoFace.java @@ -40,8 +40,8 @@ public class PluginInfoFace implements PluginInfo { this.pluginDescriptor = pluginInsideInfo.getPluginDescriptor().toPluginDescriptor(); this.pluginState = pluginInsideInfo.getPluginState(); this.followSystem = pluginInsideInfo.isFollowSystem(); - this.startTime = pluginInsideInfo.startTime(); - this.stopTime = pluginInsideInfo.stopTime(); + this.startTime = pluginInsideInfo.getStartTime(); + this.stopTime = pluginInsideInfo.getStopTime(); } @Override @@ -65,12 +65,12 @@ public class PluginInfoFace implements PluginInfo { } @Override - public Date startTime() { + public Date getStartTime() { return startTime; } @Override - public Date stopTime() { + public Date getStopTime() { return stopTime; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java index d0ccdca..8bc4af1 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/classloader/NestedPluginJarResourceLoader.java @@ -73,7 +73,7 @@ public class NestedPluginJarResourceLoader extends AbstractResourceLoader { } String realName = jarEntry.getName().replace(classesPath, ""); URL url = new URL(baseUrl.toString() + jarEntry.getName()); - resourceStorage.add(realName, baseUrl, url, ()->{ + resourceStorage.add(realName, url, ()->{ return getClassBytes(realName, jarFile.getInputStream(jarEntry), true); }); } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index a386698..ba0ebe3 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -155,13 +155,19 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor return Collections.emptySet(); } Set pluginLibInfos = new HashSet<>(dependenciesIndex.size()); + File file = new File(""); + String absolutePath = file.getAbsolutePath(); for (String index : dependenciesIndex) { + String libPath; + boolean loadToMain; if(index.endsWith(Constants.LOAD_TO_MAIN_SIGN)){ - String path = index.substring(0, index.lastIndexOf(Constants.LOAD_TO_MAIN_SIGN)); - pluginLibInfos.add(new PluginLibInfo(path, true)); + libPath = index.substring(0, index.lastIndexOf(Constants.LOAD_TO_MAIN_SIGN)); + loadToMain = true; } else { - pluginLibInfos.add(new PluginLibInfo(index, false)); + libPath = index; + loadToMain = false; } + pluginLibInfos.add(new PluginLibInfo(FilesUtils.resolveRelativePath(absolutePath, libPath), loadToMain)); } return pluginLibInfos; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java index 04900f2..4d7b174 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -16,7 +16,6 @@ package com.gitee.starblues.core.descriptor; -import lombok.Data; import lombok.Setter; import java.nio.file.Path; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java index e693592..dbfa29e 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginLibInfo.java @@ -32,7 +32,14 @@ import lombok.ToString; @ToString public class PluginLibInfo { + /** + * 路径 + */ private final String path; + + /** + * 是否加载到主程序中 + */ private final boolean loadToMain; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java index d45c238..4b49c01 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java @@ -1,3 +1,19 @@ +/** + * Copyright [2019-2022] [starBlues] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.gitee.starblues.core.descriptor; /** diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index b459334..fdc3156 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -77,7 +77,6 @@ public class PluginLauncher extends AbstractLauncher { return new DefaultResourceLoaderFactory(pluginDescriptor.getPluginId()); } - protected GenericClassLoader getParentClassLoader() throws Exception { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if(contextClassLoader instanceof GenericClassLoader){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java index 8466305..c80f1bf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/DefaultIntegrationConfiguration.java @@ -16,9 +16,7 @@ package com.gitee.starblues.integration; -import com.gitee.starblues.core.RuntimeMode; import com.gitee.starblues.utils.Assert; -import org.springframework.http.CacheControl; import java.util.ArrayList; import java.util.List; @@ -43,11 +41,7 @@ public abstract class DefaultIntegrationConfiguration implements IntegrationConf @Override public List pluginPath() { List pluginPath = new ArrayList<>(1); - if(environment() == RuntimeMode.DEV){ - pluginPath.add("plugins"); - } else if(environment() == RuntimeMode.PROD){ - pluginPath.add("./plugins/"); - } + pluginPath.add("~/plugins/"); return pluginPath; } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java index 1c85dad..bb5289d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/SpringBootPluginStarter.java @@ -23,6 +23,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** + * spring-boot-starter + * * @author starBlues * @version 3.0.0 */ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java index ab25f60..1da690a 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/PluginInitializerListener.java @@ -21,7 +21,7 @@ package com.gitee.starblues.integration.listener; * 插件初始化监听者 * * @author starBlues - * @version 1.0.0 + * @version 3.0.0 */ public interface PluginInitializerListener { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java index f1ca6c5..a8b4009 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/SwaggerListener.java @@ -45,6 +45,11 @@ public class SwaggerListener implements PluginListener{ refresh(); } + @Override + public void stopSuccess(PluginInfo pluginInfo) { + refresh(); + } + void refresh(){ try { DocumentationPluginsBootstrapper documentationPluginsBootstrapper = SpringBeanUtils.getExistBean(mainApplicationContext, diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java index 6d3836d..1347258 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/AnnotationsUtils.java @@ -22,7 +22,7 @@ import java.lang.annotation.Annotation; * 注解工具 * * @author starBlues - * @version 1.0 + * @version 3.0.0 */ public class AnnotationsUtils { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java index 7cc43b1..ed15420 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/utils/OrderUtils.java @@ -17,7 +17,6 @@ package com.gitee.starblues.utils; -import java.io.File; import java.util.Comparator; import java.util.List; import java.util.function.Function; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java index cb28cda..9e436c2 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/dev/DevRepackager.java @@ -17,8 +17,10 @@ package com.gitee.starblues.plugin.pack.dev; import com.gitee.starblues.plugin.pack.BasicRepackager; +import com.gitee.starblues.plugin.pack.Constant; import com.gitee.starblues.plugin.pack.RepackageMojo; import com.gitee.starblues.plugin.pack.utils.CommonUtils; +import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; import lombok.Getter; import org.apache.maven.artifact.Artifact; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java index 0b9405c..f26792d 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/DependencyFilter.java @@ -16,7 +16,6 @@ package com.gitee.starblues.plugin.pack.filter; -import com.gitee.starblues.plugin.pack.utils.CommonUtils; import com.gitee.starblues.utils.ObjectUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter; diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java index 999dace..5679c55 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/filter/Exclude.java @@ -30,5 +30,4 @@ public class Exclude extends FilterableDependency{ return exclude; } - } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java index ef03650..3eef4d5 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/main/JarOuterPackager.java @@ -47,7 +47,6 @@ public class JarOuterPackager extends JarNestPackager { super(mainRepackager); } - @Override public void repackage() throws MojoExecutionException, MojoFailureException { // 生成依赖文件夹 -- Gitee From b35e3c369c2da4b212f8a8520cc59663b1dffb68 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 3 Mar 2022 18:24:17 +0800 Subject: [PATCH 34/37] update readme --- README_zh.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README_zh.md b/README_zh.md index 6d070a1..97fc1bd 100644 --- a/README_zh.md +++ b/README_zh.md @@ -12,17 +12,17 @@ - 可以完美解决插件包与插件包、插件包与主程序因为同一框架的不同版本冲突问题了。各个插件可以定义同一依赖的不同版本框架。 - 无需重启主程序,可以自由实现插件包的动态安装部署,来动态扩展系统的功能。 - 插件也可以不依赖主程序独立集成微服务模块。 -- ~~~等等,您可以丰富想象该框架给您带来哪些迫切的需求和扩展。 +- 您可以丰富想象该框架给您带来哪些迫切的需求和扩展。 ### 特性 1. 简化了框架的集成步骤,更容易上手。 2. 插件开发更加贴近`spring-boot`原生开发。 3. 使用`Maven`打包插件,支持对插件的自主打包编译。目前支持: -- 开发打包:将插件打包成开发环境下的插件(仅需打包一次)。 -- 生产打包:将插件打包成一个`jar`、`zip`、`文件夹`等。 + 开发打包:将插件打包成开发环境下的插件(仅需打包一次)。 + 生产打包:将插件打包成一个`jar`、`zip`、`文件夹`等。 4. 插件支持两种运行模式 -- 插件模式: 作为一个插件,由主程序引导加载。 -- 自主启动模式:单独作为一个`SpringBoot`项目来启动。 + 插件模式: 作为一个插件,由主程序引导加载。 + 自主启动模式:单独作为一个`SpringBoot`项目来启动。 5. 自主的开发的类加载器,支持插件定义各种的依赖`jar`包。 6. 在插件中可以集成各种框架及其各种`spring-boot-xxx-starter`,比如集成`mybatis`、`mybatis-plus`、`spring-jpa`等。 -- Gitee From 6788f86023ebedfe7a26895a11b853272ff9c3df Mon Sep 17 00:00:00 2001 From: StarBlues Date: Thu, 3 Mar 2022 18:25:04 +0800 Subject: [PATCH 35/37] update readme --- README_zh.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README_zh.md b/README_zh.md index 97fc1bd..4f82f67 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,10 +18,14 @@ 1. 简化了框架的集成步骤,更容易上手。 2. 插件开发更加贴近`spring-boot`原生开发。 3. 使用`Maven`打包插件,支持对插件的自主打包编译。目前支持: + 开发打包:将插件打包成开发环境下的插件(仅需打包一次)。 + 生产打包:将插件打包成一个`jar`、`zip`、`文件夹`等。 4. 插件支持两种运行模式 + 插件模式: 作为一个插件,由主程序引导加载。 + 自主启动模式:单独作为一个`SpringBoot`项目来启动。 5. 自主的开发的类加载器,支持插件定义各种的依赖`jar`包。 6. 在插件中可以集成各种框架及其各种`spring-boot-xxx-starter`,比如集成`mybatis`、`mybatis-plus`、`spring-jpa`等。 -- Gitee From 068f95e274eaddc0a88c05a8b683bc18760b20a4 Mon Sep 17 00:00:00 2001 From: StarBlues Date: Fri, 4 Mar 2022 21:50:48 +0800 Subject: [PATCH 36/37] update package type --- .../gitee/starblues/common/ManifestKey.java | 31 +++++ .../starblues/common/PackageStructure.java | 4 + .../gitee/starblues/common/PackageType.java | 2 + .../starblues/common/PluginDescriptorKey.java | 27 +++-- .../com/gitee/starblues/utils/FilesUtils.java | 20 ++++ ...anifestUtils.java => PropertiesUtils.java} | 20 ++-- .../bootstrap/ConfigurePluginEnvironment.java | 13 ++- .../web/PluginControllerProcessor.java | 2 +- .../loader/DefaultResourceLoaderFactory.java | 2 + .../loader/launcher/runner/MethodRunner.java | 2 +- .../starblues/loader/utils/ResourceUtils.java | 12 ++ .../core/DefaultPluginInsideInfo.java | 4 +- .../starblues/core/DefaultPluginManager.java | 4 +- .../starblues/core/PluginLauncherManager.java | 19 +-- .../com/gitee/starblues/core/PluginState.java | 12 +- .../AbstractPluginDescriptorLoader.java | 102 +++++++++-------- .../DefaultInsidePluginDescriptor.java | 14 ++- .../descriptor/DevPluginDescriptorLoader.java | 28 +++-- .../descriptor/InsidePluginDescriptor.java | 13 ++- .../starblues/core/descriptor/PluginType.java | 50 ++++++-- .../ProdDirPluginDescriptorLoader.java | 34 ++++-- .../ProdPackagePluginDescriptorLoader.java | 51 ++++----- .../ProdPluginDescriptorLoader.java | 4 +- .../core/launcher/plugin/PluginLauncher.java | 3 +- .../launcher/plugin/PluginMethodRunner.java | 5 + .../AutoIntegrationConfiguration.java | 8 +- .../ExtendPointWebConfiguration.java | 62 ++++++---- .../listener/DefaultInitializerListener.java | 11 +- .../spring-configuration-metadata.json | 4 +- .../plugin/pack/BasicRepackager.java | 108 +++++++++++++----- .../gitee/starblues/plugin/pack/Constant.java | 2 + .../starblues/plugin/pack/PluginInfo.java | 5 + .../plugin/pack/prod/DirProdRepackager.java | 20 +++- .../pack/prod/JarNestedProdRepackager.java | 4 +- .../pack/prod/JarOuterProdRepackager.java | 3 +- .../pack/prod/ZipOuterProdRepackager.java | 15 ++- .../plugin/pack/prod/ZipProdRepackager.java | 27 +++-- 37 files changed, 514 insertions(+), 233 deletions(-) rename spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/{ManifestUtils.java => PropertiesUtils.java} (76%) diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java index 6e2cafd..ae91f44 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/ManifestKey.java @@ -16,6 +16,8 @@ package com.gitee.starblues.common; +import java.util.jar.Attributes; + /** * Manifest-Key * @@ -34,6 +36,16 @@ public class ManifestKey { */ public static final String MANIFEST_VERSION_1_0 = "1.0"; + /** + * plugin meta path + */ + public static final String PLUGIN_META_PATH = "Plugin-Meta-Path"; + + /** + * plugin package type + */ + public static final String PLUGIN_PACKAGE_TYPE = "Plugin-Package-Type"; + /** * main class @@ -55,4 +67,23 @@ public class ManifestKey { */ public static final String CLASS_PATH = "Class-Path"; + + + /** + * 获取值 + * + * @param attributes attributes + * @param key 获取的key + * @return 获取的值 + */ + public static String getValue(Attributes attributes, String key){ + try { + return attributes.getValue(key); + } catch (Throwable e){ + // 忽略 + return null; + } + } + + } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java index b83fc0c..95907fd 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageStructure.java @@ -49,6 +49,8 @@ public abstract class PackageStructure { public static final String MANIFEST = "MANIFEST.MF"; + public static final String PLUGIN_META_NAME = "PLUGIN.META"; + public static final String RESOURCES_DEFINE_NAME = "RESOURCES.CONF"; public static final String RESOURCES_DEFINE_DEPENDENCIES = "dependencies.index"; @@ -59,6 +61,8 @@ public abstract class PackageStructure { public static final String PROD_RESOURCES_DEFINE_PATH = META_INF_NAME + SEPARATOR + RESOURCES_DEFINE_NAME; + public static final String PROD_PLUGIN_META_PATH = META_INF_NAME + SEPARATOR + PLUGIN_META_NAME; + public static final String PROD_CLASSES_PATH = CLASSES_NAME + SEPARATOR; public static final String PROD_LIB_PATH = LIB_NAME + SEPARATOR; diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java index aa72ea3..ce11a77 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PackageType.java @@ -24,6 +24,8 @@ package com.gitee.starblues.common; */ public class PackageType { + public static final String PLUGIN_PACKAGE_TYPE_DEV = "dev"; + public static final String PLUGIN_PACKAGE_TYPE_JAR = "jar"; public static final String PLUGIN_PACKAGE_TYPE_JAR_OUTER = "jar-outer"; public static final String PLUGIN_PACKAGE_TYPE_ZIP = "zip"; diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java index 4a66ba9..11bd32e 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/common/PluginDescriptorKey.java @@ -24,26 +24,25 @@ package com.gitee.starblues.common; */ public class PluginDescriptorKey { - public static final String MAIN_CLASS = "Main-Class"; /** Must configure prop **/ - public static final String PLUGIN_ID = "Plugin-Id"; - public static final String PLUGIN_BOOTSTRAP_CLASS = "Plugin-Bootstrap-Class"; - public static final String PLUGIN_VERSION = "Plugin-Version"; + public static final String PLUGIN_ID = "plugin.id"; + public static final String PLUGIN_BOOTSTRAP_CLASS = "plugin.bootstrapClass"; + public static final String PLUGIN_VERSION = "plugin.version"; /** Optional configure prop **/ - public static final String PLUGIN_DESCRIPTION = "Plugin-Description"; - public static final String PLUGIN_PROVIDER = "Plugin-Provider"; - public static final String PLUGIN_DEPENDENCIES = "Plugin-Dependencies"; - public static final String PLUGIN_REQUIRES = "Plugin-Requires"; - public static final String PLUGIN_LICENSE = "Plugin-License"; - public static final String PLUGIN_CONFIG_FILE_NAME = "Plugin-Config-Filename"; - public static final String PLUGIN_CONFIG_FILE_LOCATION = "Plugin-Config-File-Location"; + public static final String PLUGIN_DESCRIPTION = "plugin.description"; + public static final String PLUGIN_PROVIDER = "plugin.provider"; + public static final String PLUGIN_DEPENDENCIES = "plugin.dependencies"; + public static final String PLUGIN_REQUIRES = "plugin.requires"; + public static final String PLUGIN_LICENSE = "plugin.license"; + public static final String PLUGIN_CONFIG_FILE_NAME = "plugin.configFileName"; + public static final String PLUGIN_CONFIG_FILE_LOCATION = "plugin.configFileLocation"; + public static final String PLUGIN_ARGS = "plugin.args"; /** System create prop **/ - public static final String PLUGIN_PATH = "Plugin-Path"; - public static final String PLUGIN_RESOURCES_CONFIG = "Plugin-Resources-Config"; - public static final String PLUGIN_PACKAGE_TYPE = "Plugin-Package-Type"; + public static final String PLUGIN_PATH = "plugin.system.path"; + public static final String PLUGIN_RESOURCES_CONFIG = "plugin.system.resourcesConfig"; } diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java index 0351973..477935f 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/FilesUtils.java @@ -19,6 +19,7 @@ package com.gitee.starblues.utils; import com.gitee.starblues.common.Constants; import java.io.File; +import java.io.IOException; import java.util.function.Supplier; /** @@ -132,6 +133,25 @@ public class FilesUtils { return stringBuilder.toString(); } + public static File createFile(String path) throws IOException { + try { + File file = new File(path); + File parentFile = file.getParentFile(); + if(!parentFile.exists()){ + if(!parentFile.mkdirs()){ + throw new IOException("Create " + parentFile + " dir error"); + } + } + if(file.createNewFile()){ + return file; + } + throw new IOException("Create " + path + " file error"); + } catch (Exception e){ + throw new IOException("Create " + path + " file error"); + } + } + + /** * 解决相对路径 * @param rootPath 根路径 diff --git a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/PropertiesUtils.java similarity index 76% rename from spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java rename to spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/PropertiesUtils.java index 568ada3..22700c7 100644 --- a/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/ManifestUtils.java +++ b/spring-plugin-framework-common/src/main/java/com/gitee/starblues/utils/PropertiesUtils.java @@ -16,7 +16,7 @@ package com.gitee.starblues.utils; -import java.util.jar.Attributes; +import java.util.Properties; /** * 操作 Manifest 工具类 @@ -24,34 +24,34 @@ import java.util.jar.Attributes; * @author starBlues * @version 3.0.0 */ -public abstract class ManifestUtils { +public abstract class PropertiesUtils { - private ManifestUtils(){} + private PropertiesUtils(){} /** * 获取值 * - * @param attributes attributes + * @param properties properties * @param key 获取的key * @return 获取的值或者null */ - public static String getValue(Attributes attributes, String key){ - return getValue(attributes, key, true); + public static String getValue(Properties properties, String key){ + return getValue(properties, key, true); } /** * 获取值 * - * @param attributes attributes + * @param properties properties * @param key 获取的key * @param notExitsThrowException 如果不存在是否抛出异常 * @return 获取的值 */ - public static String getValue(Attributes attributes, String key, boolean notExitsThrowException){ + public static String getValue(Properties properties, String key, boolean notExitsThrowException){ boolean throwException = false; String value = null; try { - value = attributes.getValue(key); + value = properties.getProperty(key); if(value == null && notExitsThrowException){ throwException = true; } @@ -60,7 +60,7 @@ public abstract class ManifestUtils { throwException = true; } if(throwException){ - throw new IllegalStateException("Not found '" + key + "' from " + attributes.getClass().getName()); + throw new IllegalStateException("Not found '" + key + "' config!"); } return value; } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java index 4cd4505..ea0bae3 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/ConfigurePluginEnvironment.java @@ -20,11 +20,13 @@ import com.gitee.starblues.bootstrap.processor.ProcessorContext; import com.gitee.starblues.core.descriptor.InsidePluginDescriptor; import com.gitee.starblues.integration.AutoIntegrationConfiguration; import com.gitee.starblues.utils.Assert; +import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.PluginFileUtils; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; +import java.io.File; import java.util.HashMap; import java.util.Map; @@ -65,7 +67,7 @@ class ConfigurePluginEnvironment { } String configFileLocation = pluginDescriptor.getConfigFileLocation(); if(!ObjectUtils.isEmpty(configFileLocation)){ - env.put(SPRING_CONFIG_LOCATION, configFileLocation); + env.put(SPRING_CONFIG_LOCATION, getConfigFileLocation(configFileLocation)); } env.put(AutoIntegrationConfiguration.ENABLE_STARTER_KEY, false); env.put(SPRING_JMX_UNIQUE_NAMES, true); @@ -81,4 +83,13 @@ class ConfigurePluginEnvironment { } } + private String getConfigFileLocation(String configFileLocation){ + String s = FilesUtils.resolveRelativePath(new File("").getAbsolutePath(), configFileLocation); + if(s.endsWith("/") || s.endsWith(File.separator)){ + return s; + } else { + return s + File.separator; + } + } + } diff --git a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java index 596801b..4d16cdc 100644 --- a/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java +++ b/springboot-plugin-bootstrap/src/main/java/com/gitee/starblues/bootstrap/processor/web/PluginControllerProcessor.java @@ -193,7 +193,7 @@ public class PluginControllerProcessor implements SpringPluginProcessor { private static class ChangeRestPathPostProcessor implements BeanPostProcessor { private final static Logger LOG = LoggerFactory.getLogger(ChangeRestPathPostProcessor.class); - private final static String COMMON_ERROR = "无法统一处理该 Controller 统一请求路径前缀"; + private final static String COMMON_ERROR = "无法统一处理该Controller请求路径前缀"; private final ProcessorContext processorContext; diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java index 72b6b2a..e853705 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/classloader/resource/loader/DefaultResourceLoaderFactory.java @@ -91,6 +91,8 @@ public class DefaultResourceLoaderFactory implements ResourceLoaderFactory{ } else { resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile()); } + } else if(ResourceUtils.isZipFileUrl(url)){ + resourceLoader = new JarResourceLoader(Paths.get(url.toURI()).toFile()); } else if(ResourceUtils.isFileUrl(url)){ resourceLoader = new ClassPathLoader(url); } diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java index 425c980..06e4adb 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/launcher/runner/MethodRunner.java @@ -32,7 +32,7 @@ public class MethodRunner { protected final String className; protected final String runMethodName; - protected final String[] args; + protected String[] args; public MethodRunner(String className, String runMethodName, String[] args) { this.className = checkEmpty(className, "className 不能为空"); diff --git a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java index de76425..30dceae 100644 --- a/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java +++ b/springboot-plugin-framework-loader/src/main/java/com/gitee/starblues/loader/utils/ResourceUtils.java @@ -28,6 +28,7 @@ public class ResourceUtils { public static final String URL_PROTOCOL_FILE = "file"; public static final String URL_PROTOCOL_JAR_FILE = "jar"; public static final String JAR_FILE_EXTENSION = ".jar"; + public static final String ZIP_FILE_EXTENSION = ".zip"; public static final String URL_PROTOCOL_VFSFILE = "vfsfile"; public static final String URL_PROTOCOL_VFS = "vfs"; @@ -48,6 +49,17 @@ public class ResourceUtils { || (URL_PROTOCOL_JAR_FILE.equals(protocol) || extensionIsJar); } + /** + * 是否为zip文件 + * @param url url + * @return boolean + */ + public static boolean isZipFileUrl(URL url) { + String protocol = url.getProtocol(); + boolean extensionIsZip = url.getPath().toLowerCase().endsWith(ZIP_FILE_EXTENSION); + return (URL_PROTOCOL_FILE.equals(protocol) && extensionIsZip); + } + /** * 是否为jar协议的文件 * @param url url diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java index 8e246ec..1f56225 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginInsideInfo.java @@ -93,10 +93,10 @@ public class DefaultPluginInsideInfo implements PluginInsideInfo { } private void resolveTime(PluginState pluginState){ - if(pluginState == PluginState.STARTED){ + if(pluginState == PluginState.STARTED || pluginState == PluginState.STARTED_FAILURE){ startTime = new Date(); stopTime = null; - } else if(pluginState == PluginState.STOPPED){ + } else if(pluginState == PluginState.STOPPED || pluginState == PluginState.STOPPED_FAILURE){ stopTime = new Date(); startTime = null; } else { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java index eddda38..4d405bd 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/DefaultPluginManager.java @@ -399,7 +399,7 @@ public class DefaultPluginManager implements PluginManager{ } PluginInsideInfo pluginInsideInfo = loadFromPath(pluginPath); if(pluginInsideInfo == null){ - throw new PluginException("路径中未发现合法插件"); + return null; } String pluginId = pluginInsideInfo.getPluginId(); if(resolvedPlugins.containsKey(pluginId)){ @@ -422,7 +422,7 @@ public class DefaultPluginManager implements PluginManager{ try (PluginDescriptorLoader pluginDescriptorLoader = provider.getPluginDescriptorLoader()){ InsidePluginDescriptor pluginDescriptor = pluginDescriptorLoader.load(pluginPath); if(pluginDescriptor == null){ - throw new PluginException("非法插件包: " + pluginPath); + return null; } String pluginId = pluginDescriptor.getPluginId(); PluginInsideInfo pluginInsideInfo = new DefaultPluginInsideInfo(pluginDescriptor); diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java index 51ceb25..d825433 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginLauncherManager.java @@ -102,7 +102,7 @@ public class PluginLauncherManager extends DefaultPluginManager{ registryInfo.put(pluginDescriptor.getPluginId(), registryPluginInfo); } catch (Exception e){ // 启动失败, 进行停止 - super.stop(pluginInsideInfo); + pluginInsideInfo.setPluginState(PluginState.STARTED_FAILURE); throw e; } } @@ -115,12 +115,17 @@ public class PluginLauncherManager extends DefaultPluginManager{ if(registryPluginInfo == null){ throw new PluginException("没有发现插件 '" + pluginId + "' 信息"); } - SpringPluginHook springPluginHook = registryPluginInfo.getSpringPluginHook(); - springPluginHook.stopVerify(); - springPluginHook.close(); - invokeSupperCache.remove(pluginId); - registryInfo.remove(pluginId); - super.stop(pluginInsideInfo); + try { + SpringPluginHook springPluginHook = registryPluginInfo.getSpringPluginHook(); + springPluginHook.stopVerify(); + springPluginHook.close(); + invokeSupperCache.remove(pluginId); + registryInfo.remove(pluginId); + super.stop(pluginInsideInfo); + } catch (Exception e){ + pluginInsideInfo.setPluginState(PluginState.STOPPED_FAILURE); + throw e; + } } static class RegistryPluginInfo{ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java index 4951e35..ff12458 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/PluginState.java @@ -38,10 +38,20 @@ public enum PluginState { */ STARTED("STARTED"), + /** + * 启动失败状态 + */ + STARTED_FAILURE("STARTED_FAILURE"), + /** * 停止状态 */ - STOPPED("STOPPED"); + STOPPED("STOPPED"), + + /** + * 停止失败状态 + */ + STOPPED_FAILURE("STOPPED_FAILURE"); private final String status; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java index ba0ebe3..14b11d8 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/AbstractPluginDescriptorLoader.java @@ -20,14 +20,18 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.*; import com.gitee.starblues.core.exception.PluginException; import com.gitee.starblues.utils.FilesUtils; -import com.gitee.starblues.utils.ManifestUtils; +import com.gitee.starblues.utils.PropertiesUtils; import com.gitee.starblues.utils.ObjectUtils; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; @@ -36,7 +40,7 @@ import java.util.jar.Manifest; import static com.gitee.starblues.common.PackageStructure.MANIFEST; import static com.gitee.starblues.common.PluginDescriptorKey.*; -import static com.gitee.starblues.utils.ManifestUtils.getValue; +import static com.gitee.starblues.utils.PropertiesUtils.getValue; /** * 抽象的 PluginDescriptorLoader @@ -50,16 +54,15 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor @Override public InsidePluginDescriptor load(Path location) throws PluginException { - Manifest manifest = null; + PluginMeta pluginMeta = null; try { - manifest = getManifest(location); - if(manifest == null){ - logger.debug("路径[{}]没有发现[{}]", location, MANIFEST); + pluginMeta = getPluginMetaInfo(location); + if(pluginMeta == null || pluginMeta.getPluginMetaInfo() == null){ + logger.debug("路径[{}]没有发现插件配置信息", location); return null; } - return create(manifest, location); + return create(pluginMeta, location); } catch (Exception e) { - logger.error("路径[{}]中存在非法[{}]: {}", location, MANIFEST, e.getMessage()); return null; } } @@ -70,72 +73,58 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor } /** - * 子类获取 Properties - * @param location properties 路径 + * 子类获取插件信息 + * @param location 路径 * @return Properties * @throws Exception 异常 */ - protected abstract Manifest getManifest(Path location) throws Exception; + protected abstract PluginMeta getPluginMetaInfo(Path location) throws Exception; - protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception{ - Attributes attributes = manifest.getMainAttributes(); + protected DefaultInsidePluginDescriptor create(PluginMeta pluginMeta, Path path) throws Exception{ + Properties properties = pluginMeta.getPluginMetaInfo(); DefaultInsidePluginDescriptor descriptor = new DefaultInsidePluginDescriptor( - getValue(attributes, PLUGIN_ID), - getValue(attributes, PLUGIN_VERSION), - getValue(attributes, PLUGIN_BOOTSTRAP_CLASS), + getValue(properties, PLUGIN_ID), + getValue(properties, PLUGIN_VERSION), + getValue(properties, PLUGIN_BOOTSTRAP_CLASS), path ); - PluginResourcesConfig pluginResourcesConfig = getPluginResourcesConfig(path, attributes); + descriptor.setType(PluginType.byName(pluginMeta.getPackageType())); + + PluginResourcesConfig pluginResourcesConfig = getPluginResourcesConfig(path, properties); descriptor.setPluginLibInfo(getPluginLibInfo(pluginResourcesConfig.getDependenciesIndex())); descriptor.setIncludeMainResourcePatterns(pluginResourcesConfig.getLoadMainResourceIncludes()); descriptor.setExcludeMainResourcePatterns(pluginResourcesConfig.getLoadMainResourceExcludes()); - descriptor.setManifest(manifest); - descriptor.setPluginClassPath(getValue(attributes, PLUGIN_PATH, false)); - descriptor.setDescription(getValue(attributes, PLUGIN_DESCRIPTION, false)); - descriptor.setRequires(getValue(attributes, PLUGIN_REQUIRES, false)); - descriptor.setProvider(getValue(attributes, PLUGIN_PROVIDER, false)); - descriptor.setLicense(getValue(attributes, PLUGIN_LICENSE, false)); - descriptor.setConfigFileName(getValue(attributes, PLUGIN_CONFIG_FILE_NAME, false)); - descriptor.setConfigFileLocation(getValue(attributes, PLUGIN_CONFIG_FILE_LOCATION, false)); - - descriptor.setType(getPluginType(attributes)); - - descriptor.setDependencyPlugins(getPluginDependency(attributes)); + descriptor.setProperties(properties); + descriptor.setPluginClassPath(getValue(properties, PLUGIN_PATH, false)); + descriptor.setDescription(getValue(properties, PLUGIN_DESCRIPTION, false)); + descriptor.setRequires(getValue(properties, PLUGIN_REQUIRES, false)); + descriptor.setProvider(getValue(properties, PLUGIN_PROVIDER, false)); + descriptor.setLicense(getValue(properties, PLUGIN_LICENSE, false)); + descriptor.setConfigFileName(getValue(properties, PLUGIN_CONFIG_FILE_NAME, false)); + descriptor.setConfigFileLocation(getValue(properties, PLUGIN_CONFIG_FILE_LOCATION, false)); + descriptor.setArgs(getValue(properties, PLUGIN_ARGS, false)); + + descriptor.setDependencyPlugins(getPluginDependency(properties)); return descriptor; } - protected PluginType getPluginType(Attributes attributes){ - String packageType = ManifestUtils.getValue(attributes, PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, false); - if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_JAR)){ - return PluginType.JAR; - } else if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_JAR_OUTER)){ - return PluginType.JAR_OUTER; - } else if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_ZIP)){ - return PluginType.ZIP; - } else if(Objects.equals(packageType, PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER)){ - return PluginType.ZIP_OUTER; - } else { - return null; - } - } - protected List getPluginDependency(Attributes attributes){ - return AbstractDependencyPlugin.toList(getValue(attributes, PLUGIN_DEPENDENCIES, false), + protected List getPluginDependency(Properties properties){ + return AbstractDependencyPlugin.toList(getValue(properties, PLUGIN_DEPENDENCIES, false), DefaultDependencyPlugin::new); } - - protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception{ - String libIndex = getValue(attributes, PLUGIN_RESOURCES_CONFIG); + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Properties properties) throws Exception{ + String libIndex = getValue(properties, PLUGIN_RESOURCES_CONFIG); if(ObjectUtils.isEmpty(libIndex)){ return new PluginResourcesConfig(); } File file = new File(libIndex); if(!file.exists()){ // 如果绝对路径不存在, 则判断相对路径 - String pluginPath = getValue(attributes, PLUGIN_PATH); + String pluginPath = getValue(properties, PLUGIN_PATH); file = new File(FilesUtils.joiningFilePath(pluginPath, libIndex)); } if(!file.exists()){ @@ -182,4 +171,19 @@ public abstract class AbstractPluginDescriptorLoader implements PluginDescriptor } } + protected Properties getProperties(InputStream inputStream) throws Exception{ + Properties properties = new Properties(); + try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);){ + properties.load(reader); + return properties; + } + } + + @AllArgsConstructor + @Getter + public static class PluginMeta{ + private final String packageType; + private final Properties pluginMetaInfo; + } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java index 4d7b174..ced611f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DefaultInsidePluginDescriptor.java @@ -19,6 +19,7 @@ package com.gitee.starblues.core.descriptor; import lombok.Setter; import java.nio.file.Path; +import java.util.Properties; import java.util.Set; import java.util.jar.Manifest; @@ -35,12 +36,14 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple @Setter private String pluginClassPath; @Setter - private Manifest manifest; + private Properties properties; @Setter private String configFileName; @Setter private String configFileLocation; @Setter + private String args; + @Setter private Set pluginLibInfo; @Setter private Set includeMainResourcePatterns; @@ -84,6 +87,11 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple return configFileLocation; } + @Override + public String getArgs() { + return args; + } + @Override public Path getInsidePluginPath() { return pluginPath; @@ -95,8 +103,8 @@ public class DefaultInsidePluginDescriptor extends DefaultPluginDescriptor imple } @Override - public Manifest getManifest() { - return manifest; + public Properties getProperties() { + return properties; } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java index f398106..3b94a9f 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/DevPluginDescriptorLoader.java @@ -17,11 +17,13 @@ package com.gitee.starblues.core.descriptor; import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PackageType; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Properties; import java.util.jar.Manifest; /** @@ -31,30 +33,26 @@ import java.util.jar.Manifest; */ public class DevPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ - @Override - protected Manifest getManifest(Path location) throws Exception { - String manifestPath = location.toString() + File.separator + PackageStructure.MANIFEST; - File file = new File(manifestPath); + protected PluginMeta getPluginMetaInfo(Path location) throws Exception { + String pluginMetaPath = location.toString() + File.separator + PackageStructure.PLUGIN_META_NAME; + File file = new File(pluginMetaPath); if(!file.exists()){ return null; } - Path path = Paths.get(manifestPath); - try { - return super.getManifest(Files.newInputStream(path)); - } finally { - try { - path.getFileSystem().close(); - } catch (Exception e) { - // 忽略 - } + Path path = Paths.get(pluginMetaPath); + Properties properties = super.getProperties(Files.newInputStream(path)); + if(properties.isEmpty()){ + return null; } + return new PluginMeta(PackageType.PLUGIN_PACKAGE_TYPE_DEV, properties); } @Override - protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { - final DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); + protected DefaultInsidePluginDescriptor create(PluginMeta pluginMeta, Path path) throws Exception { + final DefaultInsidePluginDescriptor descriptor = super.create(pluginMeta, path); descriptor.setType(PluginType.DEV); return descriptor; } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java index 134f8d5..5064060 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/InsidePluginDescriptor.java @@ -17,6 +17,7 @@ package com.gitee.starblues.core.descriptor; import java.nio.file.Path; +import java.util.Properties; import java.util.Set; import java.util.jar.Manifest; @@ -28,10 +29,10 @@ import java.util.jar.Manifest; public interface InsidePluginDescriptor extends PluginDescriptor{ /** - * 得到插件的 Manifest 文件 - * @return Manifest + * 得到插件的 Properties 配置 + * @return Properties */ - Manifest getManifest(); + Properties getProperties(); /** * 获取插件配置文件名称。 @@ -47,6 +48,12 @@ public interface InsidePluginDescriptor extends PluginDescriptor{ */ String getConfigFileLocation(); + /** + * 得到插件启动时参数 + * @return String + */ + String getArgs(); + /** * 得到内部的插件路径 * @return Path diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java index 4b49c01..5614e6c 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/PluginType.java @@ -16,40 +16,72 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.PackageType; +import com.gitee.starblues.core.RuntimeMode; +import com.gitee.starblues.core.exception.PluginException; + +import java.util.Objects; + /** * @author starBlues * @version 3.0.0 */ public enum PluginType { + /** + * 开发模式目录 + */ + DEV(PackageType.PLUGIN_PACKAGE_TYPE_DEV), + /** * jar文件 */ - JAR, + JAR(PackageType.MAIN_PACKAGE_TYPE_JAR), /** * jar-outer 文件 */ - JAR_OUTER, + JAR_OUTER(PackageType.MAIN_PACKAGE_TYPE_JAR_OUTER), /** * zip 文件 */ - ZIP, + ZIP(PackageType.PLUGIN_PACKAGE_TYPE_ZIP), /** * zip-outer 文件 */ - ZIP_OUTER, + ZIP_OUTER(PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER), /** * 生产模式目录 */ - DIR, + DIR(PackageType.PLUGIN_PACKAGE_TYPE_DIR); - /** - * 开发模式目录 - */ - DEV; + public final String name; + + PluginType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public static PluginType byName(String packageType){ + if(Objects.equals(packageType, PluginType.DEV.getName())){ + return PluginType.DEV; + } else if(Objects.equals(packageType, PluginType.JAR.getName())){ + return PluginType.JAR; + } else if(Objects.equals(packageType, PluginType.JAR_OUTER.getName())){ + return PluginType.JAR_OUTER; + } else if(Objects.equals(packageType, PluginType.ZIP.getName())){ + return PluginType.ZIP; + } else if(Objects.equals(packageType, PluginType.ZIP_OUTER.getName())){ + return PluginType.ZIP_OUTER; + } else { + throw new PluginException("不能解析'" + packageType + "'打包类型的插件"); + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java index 04a4495..f4547ab 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdDirPluginDescriptorLoader.java @@ -16,8 +16,10 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.ManifestKey; +import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; -import com.gitee.starblues.utils.ManifestUtils; +import com.gitee.starblues.utils.PropertiesUtils; import com.gitee.starblues.utils.FilesUtils; import com.gitee.starblues.utils.ObjectUtils; import org.apache.commons.io.FileUtils; @@ -29,6 +31,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.List; +import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -45,21 +48,38 @@ import static com.gitee.starblues.common.PackageStructure.*; public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoader{ @Override - protected Manifest getManifest(Path location) throws Exception { + protected PluginMeta getPluginMetaInfo(Path location) throws Exception { File file = new File(FilesUtils.joiningFilePath(location.toString(), resolvePath(PROD_MANIFEST_PATH))); if(!file.exists()){ return null; } Manifest manifest = new Manifest(); + String packageType = null; + String pluginMetaPath = null; try (FileInputStream fileInputStream = new FileInputStream(file)){ manifest.read(fileInputStream); - return manifest; + Attributes attributes = manifest.getMainAttributes(); + packageType = ManifestKey.getValue(attributes, ManifestKey.PLUGIN_PACKAGE_TYPE); + pluginMetaPath = ManifestKey.getValue(attributes, ManifestKey.PLUGIN_META_PATH); } + if(packageType == null || pluginMetaPath == null){ + return null; + } + + File pluginMetaFile = new File(FilesUtils.joiningFilePath(location.toString(), pluginMetaPath)); + if(!pluginMetaFile.exists()){ + return null; + } + Properties properties = super.getProperties(new FileInputStream(pluginMetaFile)); + if(properties.isEmpty()){ + return null; + } + return new PluginMeta(packageType, properties); } @Override - protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { - DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); + protected DefaultInsidePluginDescriptor create(PluginMeta pluginMeta, Path path) throws Exception { + DefaultInsidePluginDescriptor descriptor = super.create(pluginMeta, path); String pathStr = path.toFile().getPath(); descriptor.setPluginClassPath(FilesUtils.joiningFilePath( pathStr, descriptor.getPluginClassPath() @@ -68,10 +88,10 @@ public class ProdDirPluginDescriptorLoader extends AbstractPluginDescriptorLoade } @Override - protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception { + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Properties properties) throws Exception { String pathStr = path.toFile().getPath(); String libIndexFile = getExistResourcesConfFile( - pathStr, ManifestUtils.getValue(attributes, PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG) + pathStr, PropertiesUtils.getValue(properties, PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG) ); if(libIndexFile == null){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java index 7b22ce5..15896fc 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPackagePluginDescriptorLoader.java @@ -17,18 +17,16 @@ package com.gitee.starblues.core.descriptor; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageStructure; -import com.gitee.starblues.common.PackageType; -import com.gitee.starblues.common.PluginDescriptorKey; -import com.gitee.starblues.core.exception.PluginException; -import com.gitee.starblues.utils.ManifestUtils; +import com.gitee.starblues.utils.PropertiesUtils; import com.gitee.starblues.utils.ObjectUtils; import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.nio.file.Path; import java.util.List; -import java.util.Objects; +import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -45,41 +43,41 @@ import static com.gitee.starblues.common.PluginDescriptorKey.PLUGIN_RESOURCES_CO */ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorLoader{ - private final PluginType type; private PluginResourcesConfig pluginResourcesConfig; - public ProdPackagePluginDescriptorLoader(PluginType type) { - this.type = type; + public ProdPackagePluginDescriptorLoader() { } @Override - protected Manifest getManifest(Path location) throws Exception { + protected PluginMeta getPluginMetaInfo(Path location) throws Exception { try (JarFile jarFile = new JarFile(location.toFile())){ Manifest manifest = jarFile.getManifest(); - pluginResourcesConfig = getPluginResourcesConfig(jarFile, manifest); - return manifest; + Attributes attributes = manifest.getMainAttributes(); + String packageType = ManifestKey.getValue(attributes, ManifestKey.PLUGIN_PACKAGE_TYPE); + String pluginMetaPath = ManifestKey.getValue(attributes, ManifestKey.PLUGIN_META_PATH); + if(packageType == null || pluginMetaPath == null){ + return null; + } + JarEntry jarEntry = jarFile.getJarEntry(pluginMetaPath); + if(jarEntry == null){ + return null; + } + Properties properties = super.getProperties(jarFile.getInputStream(jarEntry)); + if(properties.isEmpty()){ + return null; + } + pluginResourcesConfig = getPluginResourcesConfig(jarFile, properties); + return new PluginMeta(packageType, properties); } } @Override - protected PluginResourcesConfig getPluginResourcesConfig(Path path, Attributes attributes) throws Exception { + protected PluginResourcesConfig getPluginResourcesConfig(Path path, Properties properties) throws Exception { return pluginResourcesConfig; } - @Override - protected DefaultInsidePluginDescriptor create(Manifest manifest, Path path) throws Exception { - DefaultInsidePluginDescriptor descriptor = super.create(manifest, path); - PluginType manifestPluginType = descriptor.getType(); - if(manifestPluginType == null){ - descriptor.setType(type); - return descriptor; - } - return descriptor; - } - - protected PluginResourcesConfig getPluginResourcesConfig(JarFile jarFile, Manifest manifest) throws Exception { - Attributes attributes = manifest.getMainAttributes(); - String pluginResourcesConf = ManifestUtils.getValue(attributes, PLUGIN_RESOURCES_CONFIG); + protected PluginResourcesConfig getPluginResourcesConfig(JarFile jarFile, Properties properties) throws Exception { + String pluginResourcesConf = PropertiesUtils.getValue(properties, PLUGIN_RESOURCES_CONFIG); if(ObjectUtils.isEmpty(pluginResourcesConf)){ return new PluginResourcesConfig(); } @@ -92,4 +90,5 @@ public class ProdPackagePluginDescriptorLoader extends AbstractPluginDescriptorL return PluginResourcesConfig.parse(lines); } + } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java index 49aa8fe..41a0583 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/descriptor/ProdPluginDescriptorLoader.java @@ -37,9 +37,9 @@ public class ProdPluginDescriptorLoader implements PluginDescriptorLoader{ @Override public InsidePluginDescriptor load(Path location) throws PluginException { if(ResourceUtils.isJarFile(location)){ - target = new ProdPackagePluginDescriptorLoader(PluginType.JAR); + target = new ProdPackagePluginDescriptorLoader(); } else if(ResourceUtils.isZipFile(location)){ - target = new ProdPackagePluginDescriptorLoader(PluginType.ZIP); + target = new ProdPackagePluginDescriptorLoader(); } else if(ResourceUtils.isDirFile(location)){ target = new ProdDirPluginDescriptorLoader(); } else { diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java index fdc3156..4c5ba78 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginLauncher.java @@ -90,7 +90,8 @@ public class PluginLauncher extends AbstractLauncher { protected SpringPluginHook launch(ClassLoader classLoader, String... args) throws Exception { pluginLaunchInvolved.before(pluginDescriptor, classLoader); try { - SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive).run(classLoader); + SpringPluginHook springPluginHook = (SpringPluginHook) new PluginMethodRunner(pluginInteractive) + .run(classLoader); pluginLaunchInvolved.after(pluginDescriptor, classLoader, springPluginHook); return new SpringPluginHookWrapper(springPluginHook, pluginDescriptor, pluginLaunchInvolved, classLoader); } catch (Throwable throwable){ diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java index 2fa4072..9515cdf 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/core/launcher/plugin/PluginMethodRunner.java @@ -18,6 +18,7 @@ package com.gitee.starblues.core.launcher.plugin; import com.gitee.starblues.core.RuntimeMode; import com.gitee.starblues.loader.launcher.runner.MethodRunner; +import com.gitee.starblues.utils.ObjectUtils; import com.gitee.starblues.utils.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +41,10 @@ public class PluginMethodRunner extends MethodRunner { public PluginMethodRunner(PluginInteractive pluginInteractive) { super(pluginInteractive.getPluginDescriptor().getPluginBootstrapClass(), PLUGIN_RUN_METHOD_NAME, new String[]{}); this.pluginInteractive = pluginInteractive; + String args = pluginInteractive.getPluginDescriptor().getArgs(); + if(!ObjectUtils.isEmpty(args)){ + super.args = args.split(" "); + } } @Override diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java index 1fd65e5..2b5f0ea 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/AutoIntegrationConfiguration.java @@ -85,12 +85,6 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Value("${pluginRestPathPrefix:/plugins}") private String pluginRestPathPrefix; - /** - * 是否启用插件的 rest controller 接口注册. 默认启用 - */ - @Value("${enablePluginRestController:true}") - private Boolean enablePluginRestController; - /** * 是否启用插件id作为rest接口前缀, 默认为启用. * 如果为启用, 则地址为 /pluginRestPathPrefix/pluginId @@ -173,7 +167,7 @@ public class AutoIntegrationConfiguration extends DefaultIntegrationConfiguratio @Override public String pluginRestPathPrefix() { - if(ObjectUtils.isEmpty(pluginRestPathPrefix)){ + if(pluginRestPathPrefix == null){ return super.pluginRestPathPrefix(); } else { return pluginRestPathPrefix; diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java index 75d473f..e1e197d 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/ExtendPointWebConfiguration.java @@ -25,6 +25,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.servlet.resource.ResourceResolver; import org.thymeleaf.spring5.SpringTemplateEngine; @@ -37,41 +38,56 @@ import springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapp * @version 3.0.0 */ @ConditionalOnWebApplication +@Import({ + ExtendPointWebConfiguration.PluginStaticResourceConfiguration.class, + ExtendPointWebConfiguration.PluginThymeleafConfiguration.class, + ExtendPointWebConfiguration.SwaggerListenerConfiguration.class, +}) public class ExtendPointWebConfiguration { - private final GenericApplicationContext applicationContext; - public ExtendPointWebConfiguration(GenericApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean @ConditionalOnClass(ResourceResolver.class) - @ConditionalOnMissingBean - public PluginStaticResourceWebMvcConfigurer pluginWebResourceResolver(PluginStaticResourceConfig resourceConfig){ - return new PluginStaticResourceWebMvcConfigurer(resourceConfig); - } + public static class PluginStaticResourceConfiguration{ - @Bean - @ConditionalOnClass(ResourceResolver.class) - @ConditionalOnMissingBean - public PluginStaticResourceConfig pluginStaticResourceConfig(){ - return new PluginStaticResourceConfig(); + @Bean + @ConditionalOnMissingBean + public PluginStaticResourceWebMvcConfigurer pluginWebResourceResolver(PluginStaticResourceConfig resourceConfig){ + return new PluginStaticResourceWebMvcConfigurer(resourceConfig); + } + + @Bean + @ConditionalOnMissingBean + public PluginStaticResourceConfig pluginStaticResourceConfig() { + return new PluginStaticResourceConfig(); + } } - @Bean @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class }) @ConditionalOnProperty(name = "spring.thymeleaf.enabled", havingValue = "true", matchIfMissing = true) - @ConditionalOnMissingBean - public PluginThymeleafInvolved pluginThymeleafInvolved(){ - return new PluginThymeleafInvolved(); + public static class PluginThymeleafConfiguration{ + + @Bean + @ConditionalOnMissingBean + public PluginThymeleafInvolved pluginThymeleafInvolved(){ + return new PluginThymeleafInvolved(); + } } - @Bean @ConditionalOnClass({ DocumentationPluginsBootstrapper.class }) - @ConditionalOnMissingBean - public SwaggerListener swaggerListener(){ - return new SwaggerListener(applicationContext); + public static class SwaggerListenerConfiguration { + + private final GenericApplicationContext applicationContext; + + public SwaggerListenerConfiguration(GenericApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Bean + @ConditionalOnMissingBean + public SwaggerListener swaggerListener(){ + return new SwaggerListener(applicationContext); + } + } } diff --git a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java index b33bb6f..43ca5c0 100644 --- a/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java +++ b/springboot-plugin-framework/src/main/java/com/gitee/starblues/integration/listener/DefaultInitializerListener.java @@ -41,13 +41,18 @@ public class DefaultInitializerListener implements PluginInitializerListener{ @Override public void complete() { - if(swaggerListener != null){ - swaggerListener.refresh(); - } + refresh(); } @Override public void failure(Throwable throwable) { + refresh(); + } + private void refresh(){ + if(swaggerListener != null){ + swaggerListener.refresh(); + } } + } diff --git a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json index 19f1b55..4eec8b4 100644 --- a/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json +++ b/springboot-plugin-framework/src/main/resources/META-INF/spring-configuration-metadata.json @@ -40,7 +40,7 @@ "type": "java.lang.String", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", "description": "插件的路径. 开发环境下配置为插件模块上级目录; 生产环境下配置到插件jar包存放目录。建议配置绝对路径", - "defaultValue": "/plugins" + "defaultValue": "~/plugins/" }, { "name": "plugin.backupPath", @@ -62,7 +62,7 @@ "defaultValue": "/plugins" }, { - "name": "plugin.pluginRestPathPrefix", + "name": "plugin.enablePluginIdRestPathPrefix", "type": "java.lang.Boolean", "sourceType": "com.gitee.starblues.integration.AutoIntegrationConfiguration", "description": "是否启用插件id作为rest接口前缀", diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java index b446a65..ae69460 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/BasicRepackager.java @@ -19,6 +19,7 @@ package com.gitee.starblues.plugin.pack; import com.gitee.starblues.common.AbstractDependencyPlugin; import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageStructure; +import com.gitee.starblues.common.PackageType; import com.gitee.starblues.plugin.pack.dev.DevConfig; import com.gitee.starblues.plugin.pack.utils.CommonUtils; import com.gitee.starblues.utils.FilesUtils; @@ -32,10 +33,9 @@ import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.*; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -52,6 +52,7 @@ public class BasicRepackager implements Repackager{ @Getter private String rootDir; private String relativeManifestPath; + private String relativePluginMetaPath; private String relativeResourcesDefinePath; protected File resourcesDefineFile; @@ -67,6 +68,7 @@ public class BasicRepackager implements Repackager{ checkPluginInfo(); rootDir = createRootDir(); relativeManifestPath = getRelativeManifestPath(); + relativePluginMetaPath = getRelativePluginMetaPath(); relativeResourcesDefinePath = getRelativeResourcesDefinePath(); try { Manifest manifest = getManifest(); @@ -113,6 +115,10 @@ public class BasicRepackager implements Repackager{ return RESOURCES_DEFINE_NAME; } + protected String getRelativePluginMetaPath(){ + return PLUGIN_META_NAME; + } + protected String createRootDir() throws MojoFailureException { String rootDirPath = getBasicRootDir(); File rootDir = new File(rootDirPath); @@ -150,48 +156,74 @@ public class BasicRepackager implements Repackager{ } protected Manifest getManifest() throws Exception{ - PluginInfo pluginInfo = repackageMojo.getPluginInfo(); Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.putValue(ManifestKey.MANIFEST_VERSION, ManifestKey.MANIFEST_VERSION_1_0); - attributes.putValue(PLUGIN_ID, pluginInfo.getId()); - attributes.putValue(PLUGIN_BOOTSTRAP_CLASS, pluginInfo.getBootstrapClass()); - attributes.putValue(PLUGIN_VERSION, pluginInfo.getVersion()); - attributes.putValue(PLUGIN_PATH, getPluginPath()); + attributes.putValue(ManifestKey.PLUGIN_META_PATH, getPluginMetaInfoPath()); + attributes.putValue(ManifestKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_DEV); + return manifest; + } + + /** + * 得到插件信息存储文件路径 + * @return 插件信息存储文件路径 + * @throws Exception Exception + */ + protected String getPluginMetaInfoPath() throws Exception { + Properties pluginMetaInfo = createPluginMetaInfo(); + return writePluginMetaInfo(pluginMetaInfo); + } + + /** + * 创建插件信息 + * @return Properties + * @throws Exception Exception + */ + protected Properties createPluginMetaInfo() throws Exception { + Properties properties = new Properties(); + PluginInfo pluginInfo = repackageMojo.getPluginInfo(); + properties.put(PLUGIN_ID, pluginInfo.getId()); + properties.put(PLUGIN_BOOTSTRAP_CLASS, pluginInfo.getBootstrapClass()); + properties.put(PLUGIN_VERSION, pluginInfo.getVersion()); + properties.put(PLUGIN_PATH, getPluginPath()); String resourcesDefineFilePath = writeResourcesDefineFile(); if(!ObjectUtils.isEmpty(resourcesDefineFilePath)){ - attributes.putValue(PLUGIN_RESOURCES_CONFIG, resourcesDefineFilePath); + properties.put(PLUGIN_RESOURCES_CONFIG, resourcesDefineFilePath); } String configFileName = pluginInfo.getConfigFileName(); if(!ObjectUtils.isEmpty(configFileName)){ - attributes.putValue(PLUGIN_CONFIG_FILE_NAME, configFileName); + properties.put(PLUGIN_CONFIG_FILE_NAME, configFileName); } String configFileLocation = pluginInfo.getConfigFileLocation(); if(!ObjectUtils.isEmpty(configFileLocation)){ - attributes.putValue(PLUGIN_CONFIG_FILE_LOCATION, configFileLocation); + properties.put(PLUGIN_CONFIG_FILE_LOCATION, configFileLocation); + } + String args = pluginInfo.getArgs(); + if(!ObjectUtils.isEmpty(args)){ + properties.put(PLUGIN_ARGS, args); } String provider = pluginInfo.getProvider(); if(!ObjectUtils.isEmpty(provider)){ - attributes.putValue(PLUGIN_PROVIDER, provider); + properties.put(PLUGIN_PROVIDER, provider); } String requires = pluginInfo.getRequires(); if(!ObjectUtils.isEmpty(requires)){ - attributes.putValue(PLUGIN_REQUIRES, requires); + properties.put(PLUGIN_REQUIRES, requires); } String dependencyPlugins = getDependencyPlugin(pluginInfo); if(!ObjectUtils.isEmpty(dependencyPlugins)){ - attributes.putValue(PLUGIN_DEPENDENCIES, dependencyPlugins); + properties.put(PLUGIN_DEPENDENCIES, dependencyPlugins); } String description = pluginInfo.getDescription(); if(!ObjectUtils.isEmpty(description)){ - attributes.putValue(PLUGIN_DESCRIPTION, description); + properties.put(PLUGIN_DESCRIPTION, description); } String license = pluginInfo.getLicense(); if(!ObjectUtils.isEmpty(license)){ - attributes.putValue(PLUGIN_LICENSE, license); + properties.put(PLUGIN_LICENSE, license); } - return manifest; + return properties; } protected String getDependencyPlugin(PluginInfo pluginInfo){ @@ -199,6 +231,35 @@ public class BasicRepackager implements Repackager{ return AbstractDependencyPlugin.toStr(dependencyPlugins); } + /** + * 写入插件信息 + * @param properties properties + * @return String + * @throws IOException IOException + */ + protected String writePluginMetaInfo(Properties properties) throws Exception { + File pluginMetaFile = createPluginMetaFile(); + try (OutputStreamWriter writer = new OutputStreamWriter( + new FileOutputStream(pluginMetaFile), StandardCharsets.UTF_8)){ + properties.store(writer, Constant.PLUGIN_METE_COMMENTS); + return pluginMetaFile.getPath(); + } + } + + /** + * 创建插件信息存储文件 + * @return File + * @throws IOException 创建文件异常 + */ + protected File createPluginMetaFile() throws IOException { + String path = FilesUtils.joiningFilePath(rootDir, resolvePath(relativePluginMetaPath)); + return FilesUtils.createFile(path); + } + + /** + * 获取插件路径 + * @return 插件路径 + */ protected String getPluginPath(){ return repackageMojo.getProject().getBuild().getOutputDirectory(); } @@ -212,16 +273,7 @@ public class BasicRepackager implements Repackager{ protected File createResourcesDefineFile() throws IOException { String path = FilesUtils.joiningFilePath(rootDir, resolvePath(relativeResourcesDefinePath)); - try { - File file = new File(path); - FileUtils.forceMkdirParent(file); - if(file.createNewFile()){ - return file; - } - throw new IOException("Create " + path + " file error"); - } catch (Exception e){ - throw new IOException("Create " + path + " file error"); - } + return FilesUtils.createFile(path); } protected void writeDependenciesIndex() throws Exception { diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java index afae975..3358372 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/Constant.java @@ -32,6 +32,8 @@ public class Constant { public static final String MODE_DEV = "dev"; public static final String MODE_PROD = "prod"; + public static final String PLUGIN_METE_COMMENTS = "plugin meta configuration"; + public static boolean isPom(String packageType){ return PACKAGING_POM.equalsIgnoreCase(packageType); } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java index 558882c..5d5066f 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/PluginInfo.java @@ -57,6 +57,11 @@ public class PluginInfo { */ private String configFileLocation; + /** + * 插件启动入口参数配置 + */ + private String args; + /** * 插件描述 */ diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java index 8e33d90..bc06e62 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/DirProdRepackager.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageStructure; import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; @@ -31,6 +32,7 @@ import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.io.IOException; import java.util.HashSet; +import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -91,6 +93,11 @@ public class DirProdRepackager extends DevRepackager { return FilesUtils.joiningFilePath(META_INF_NAME, MANIFEST); } + @Override + protected String getRelativePluginMetaPath() { + return FilesUtils.joiningFilePath(META_INF_NAME, PLUGIN_META_NAME); + } + @Override protected String getRelativeResourcesDefinePath() { return FilesUtils.joiningFilePath(META_INF_NAME, RESOURCES_DEFINE_NAME); @@ -100,12 +107,19 @@ public class DirProdRepackager extends DevRepackager { protected Manifest getManifest() throws Exception { Manifest manifest = super.getManifest(); Attributes attributes = manifest.getMainAttributes(); - attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, CLASSES_NAME); - attributes.putValue(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); - attributes.putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_DIR); + attributes.putValue(ManifestKey.PLUGIN_META_PATH, PROD_PLUGIN_META_PATH); + attributes.putValue(ManifestKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER); return manifest; } + @Override + protected Properties createPluginMetaInfo() throws Exception { + Properties properties = super.createPluginMetaInfo(); + properties.put(PluginDescriptorKey.PLUGIN_PATH, CLASSES_NAME); + properties.put(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); + return properties; + } + protected void resolveClasses() throws Exception { String buildDir = repackageMojo.getProject().getBuild().getOutputDirectory(); String path = FilesUtils.joiningFilePath(getRootDir(), CLASSES_NAME); diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java index 5df5b5f..7fc9cf4 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarNestedProdRepackager.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.RepackageMojo; @@ -60,7 +61,8 @@ public class JarNestedProdRepackager extends ZipProdRepackager { @Override protected Manifest getManifest() throws Exception { Manifest manifest = super.getManifest(); - manifest.getMainAttributes().putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_JAR); + manifest.getMainAttributes().putValue( + ManifestKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_JAR); return manifest; } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java index c525826..0132c3b 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/JarOuterProdRepackager.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.RepackageMojo; @@ -44,7 +45,7 @@ public class JarOuterProdRepackager extends ZipOuterProdRepackager { @Override protected Manifest getManifest() throws Exception { Manifest manifest = super.getManifest(); - manifest.getMainAttributes().putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, + manifest.getMainAttributes().putValue(ManifestKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_JAR_OUTER); return manifest; } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java index 5d3e5bf..d393892 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipOuterProdRepackager.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.RepackageMojo; @@ -30,12 +31,12 @@ import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.util.HashSet; +import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; -import static com.gitee.starblues.common.PackageStructure.CLASSES_NAME; -import static com.gitee.starblues.common.PackageStructure.PROD_RESOURCES_DEFINE_PATH; +import static com.gitee.starblues.common.PackageStructure.*; /** * zip-outer 包生成 @@ -88,9 +89,15 @@ public class ZipOuterProdRepackager extends DirProdRepackager { protected Manifest getManifest() throws Exception { Manifest manifest = super.getManifest(); Attributes attributes = manifest.getMainAttributes(); - attributes.putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER); - attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, packageZip.getFileName()); + attributes.putValue(ManifestKey.PLUGIN_META_PATH, PROD_PLUGIN_META_PATH); + attributes.putValue(ManifestKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP_OUTER); return manifest; } + @Override + protected Properties createPluginMetaInfo() throws Exception { + Properties properties = super.createPluginMetaInfo(); + properties.put(PluginDescriptorKey.PLUGIN_PATH, packageZip.getFileName()); + return properties; + } } diff --git a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java index 3140d0e..75f0053 100644 --- a/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java +++ b/springboot-plugin-maven-packager/src/main/java/com/gitee/starblues/plugin/pack/prod/ZipProdRepackager.java @@ -16,6 +16,7 @@ package com.gitee.starblues.plugin.pack.prod; +import com.gitee.starblues.common.ManifestKey; import com.gitee.starblues.common.PackageType; import com.gitee.starblues.common.PluginDescriptorKey; import com.gitee.starblues.plugin.pack.Constant; @@ -34,10 +35,7 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; +import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.jar.Attributes; @@ -127,17 +125,32 @@ public class ZipProdRepackager extends DevRepackager { protected Manifest getManifest() throws Exception { Manifest manifest = super.getManifest(); Attributes attributes = manifest.getMainAttributes(); - attributes.putValue(PluginDescriptorKey.PLUGIN_PATH, PROD_CLASSES_PATH); - attributes.putValue(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); - attributes.putValue(PluginDescriptorKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP); + attributes.putValue(ManifestKey.PLUGIN_META_PATH, PROD_PLUGIN_META_PATH); + attributes.putValue(ManifestKey.PLUGIN_PACKAGE_TYPE, PackageType.PLUGIN_PACKAGE_TYPE_ZIP); return manifest; } + @Override + protected Properties createPluginMetaInfo() throws Exception { + Properties properties = super.createPluginMetaInfo(); + properties.put(PluginDescriptorKey.PLUGIN_RESOURCES_CONFIG, PROD_RESOURCES_DEFINE_PATH); + return properties; + } + @Override protected void writeManifest(Manifest manifest) throws Exception { packageZip.writeManifest(manifest); } + @Override + protected String writePluginMetaInfo(Properties properties) throws Exception { + packageZip.write(PROD_PLUGIN_META_PATH, outputStream->{ + properties.store(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), + Constant.PLUGIN_METE_COMMENTS); + }); + return PROD_PLUGIN_META_PATH; + } + protected void resolveResourcesDefine() throws Exception{ Set dependencyIndexNames = resolveDependencies(); StringBuilder content = new StringBuilder(); -- Gitee From 5ccd0edaf005cb23f6e7654cc2f9910cedda5f2c Mon Sep 17 00:00:00 2001 From: StarBlues Date: Fri, 4 Mar 2022 21:53:50 +0800 Subject: [PATCH 37/37] update pom --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index cea5ce1..5df6ef7 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,6 @@ springboot-plugin-framework springboot-plugin-bootstrap springboot-plugin-maven-packager - springboot-plugin-framework-example -- Gitee