You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by is...@apache.org on 2019/09/29 00:05:28 UTC
[lucene-solr] 01/02: Brought PF4j into Solr
This is an automated email from the ASF dual-hosted git repository.
ishan pushed a commit to branch jira/solr-13662
in repository https://gitbox.apache.org/repos/asf/lucene-solr.git
commit 76e2a57aa08af089ed62f3bb80dcbc4e99c1c5d3
Author: Ishan Chattopadhyaya <is...@apache.org>
AuthorDate: Sun Sep 29 02:26:56 2019 +0530
Brought PF4j into Solr
---
.../java/org/apache/solr/packagemanager/App.java | 59 --
.../apache/solr/packagemanager/SolrPackage.java | 12 -
.../solr/packagemanager/SolrPluginDescriptor.java | 2 +-
.../apache/solr/packagemanager/SolrPluginInfo.java | 2 +-
.../solr/packagemanager/SolrPluginManager.java | 16 +-
.../solr/packagemanager/SolrUpdateManager.java | 166 +++-
.../solr/packagemanager/SolrUpdateRepository.java | 6 +-
.../pf4j/AbstractExtensionFinder.java | 242 ++++++
.../packagemanager/pf4j/AbstractPluginManager.java | 919 +++++++++++++++++++++
.../packagemanager/pf4j/BasePluginRepository.java | 79 ++
.../solr/packagemanager/pf4j/BasicVerifier.java | 40 +
.../pf4j/CompoundPluginDescriptorFinder.java | 81 ++
.../packagemanager/pf4j/CompoundPluginLoader.java | 81 ++
.../pf4j/CompoundPluginRepository.java | 61 ++
.../solr/packagemanager/pf4j/CompoundVerifier.java | 71 ++
.../pf4j/DefaultExtensionFactory.java | 46 ++
.../pf4j/DefaultExtensionFinder.java | 100 +++
.../pf4j/DefaultPluginClasspath.java | 32 +
.../pf4j/DefaultPluginDescriptor.java | 199 +++++
.../packagemanager/pf4j/DefaultPluginFactory.java | 70 ++
.../packagemanager/pf4j/DefaultPluginLoader.java | 86 ++
.../packagemanager/pf4j/DefaultPluginManager.java | 142 ++++
.../pf4j/DefaultPluginRepository.java | 83 ++
.../pf4j/DefaultPluginStatusProvider.java | 98 +++
.../pf4j/DefaultUpdateRepository.java | 168 ++++
.../packagemanager/pf4j/DefaultVersionManager.java | 47 ++
.../packagemanager/pf4j/DependencyResolver.java | 302 +++++++
.../pf4j/DevelopmentPluginClasspath.java | 32 +
.../apache/solr/packagemanager/pf4j/Extension.java | 37 +
.../packagemanager/pf4j/ExtensionDescriptor.java | 31 +
.../solr/packagemanager/pf4j/ExtensionFactory.java | 25 +
.../solr/packagemanager/pf4j/ExtensionFinder.java | 46 ++
.../solr/packagemanager/pf4j/ExtensionPoint.java | 23 +
.../solr/packagemanager/pf4j/ExtensionWrapper.java | 56 ++
.../solr/packagemanager/pf4j/FileDownloader.java | 39 +
.../solr/packagemanager/pf4j/FileVerifier.java | 69 ++
.../solr/packagemanager/pf4j/JarPluginLoader.java | 47 ++
.../packagemanager/pf4j/JarPluginRepository.java | 31 +
.../packagemanager/pf4j/LegacyExtensionFinder.java | 111 +++
.../pf4j/LenientDateTypeAdapter.java | 103 +++
.../pf4j/LoggingPluginStateListener.java | 37 +
.../pf4j/ManifestPluginDescriptorFinder.java | 132 +++
.../apache/solr/packagemanager/pf4j/Plugin.java | 71 ++
.../packagemanager/pf4j/PluginClassLoader.java | 207 +++++
.../solr/packagemanager/pf4j/PluginClasspath.java | 54 ++
.../solr/packagemanager/pf4j/PluginDependency.java | 51 ++
.../solr/packagemanager/pf4j/PluginDescriptor.java | 43 +
.../pf4j/PluginDescriptorFinder.java | 38 +
.../solr/packagemanager/pf4j/PluginException.java | 51 ++
.../solr/packagemanager/pf4j/PluginFactory.java | 25 +
.../solr/packagemanager/pf4j/PluginInfo.java | 95 +++
.../solr/packagemanager/pf4j/PluginLoader.java | 35 +
.../solr/packagemanager/pf4j/PluginManager.java | 182 ++++
.../solr/packagemanager/pf4j/PluginRepository.java | 44 +
.../solr/packagemanager/pf4j/PluginState.java | 75 ++
.../solr/packagemanager/pf4j/PluginStateEvent.java | 60 ++
.../packagemanager/pf4j/PluginStateListener.java | 32 +
.../packagemanager/pf4j/PluginStatusProvider.java | 46 ++
.../solr/packagemanager/pf4j/PluginWrapper.java | 147 ++++
.../pf4j/PropertiesPluginDescriptorFinder.java | 139 ++++
.../solr/packagemanager/pf4j/RuntimeMode.java | 58 ++
.../pf4j/ServiceProviderExtensionFinder.java | 145 ++++
.../packagemanager/pf4j/Sha512SumVerifier.java | 83 ++
.../packagemanager/pf4j/SimpleFileDownloader.java | 151 ++++
.../solr/packagemanager/pf4j/UpdateRepository.java | 71 ++
.../solr/packagemanager/pf4j/VerifyException.java | 34 +
.../solr/packagemanager/pf4j/VersionManager.java | 40 +
.../solr/packagemanager/pf4j/package-info.java | 24 +
.../src/java/org/apache/solr/util/PackageTool.java | 6 +-
69 files changed, 5928 insertions(+), 108 deletions(-)
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/App.java b/solr/core/src/java/org/apache/solr/packagemanager/App.java
deleted file mode 100644
index 8cf8133..0000000
--- a/solr/core/src/java/org/apache/solr/packagemanager/App.java
+++ /dev/null
@@ -1,59 +0,0 @@
-//package org.apache.solr.packagemanager;
-//
-//import java.io.File;
-//import java.nio.file.Paths;
-//import java.util.Collections;
-//
-//import org.pf4j.PluginException;
-//import org.pf4j.update.UpdateManager;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-//
-///**
-// * Hello world!
-// *
-// */
-//public class App {
-//
-// private static final Logger log = LoggerFactory.getLogger(App.class);
-//
-// public static void main( String[] args ) throws PluginException {
-// SolrPluginManager pluginManager = new SolrPluginManager(new File("./plugins"));
-//
-// pluginManager.loadPlugins();
-//
-// // create update manager
-// UpdateManager updateManager = new SolrUpdateManager(pluginManager, Paths.get("repositories.json"));
-// System.out.println(updateManager.getAvailablePlugins());
-//
-// updateManager.installPlugin("question-answer", "1.0.0");
-// System.out.println(updateManager.hasUpdates());
-//
-// System.out.println(pluginManager.deployPlugin("question-answer", Collections.singletonList("abc")));
-//
-// // >> keep system up-to-date <<
-// //boolean systemUpToDate = true;
-// // check for updates
-// /*if (updateManager.hasUpdates()) {
-// List<PluginInfo> updates = updateManager.getUpdates();
-// log.debug("Found {} updates", updates.size());
-// for (PluginInfo plugin : updates) {
-// log.debug("Found update for plugin '{}'", plugin.id);
-// PluginInfo.PluginRelease lastRelease = updateManager.getLastPluginRelease(plugin.id);
-// String lastVersion = lastRelease.version;
-// String installedVersion = pluginManager.getPlugin(plugin.id).getDescriptor().getVersion();
-// log.debug("Update plugin '{}' from version {} to version {}", plugin.id, installedVersion, lastVersion);
-// boolean updated = updateManager.updatePlugin(plugin.id, lastVersion);
-// if (updated) {
-// log.debug("Updated plugin '{}'", plugin.id);
-// } else {
-// log.error("Cannot update plugin '{}'", plugin.id);
-// systemUpToDate = false;
-// }
-// }
-// } else {
-// log.debug("No updates found");
-// }*/
-// }
-//
-//}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/SolrPackage.java b/solr/core/src/java/org/apache/solr/packagemanager/SolrPackage.java
deleted file mode 100644
index b4c4fd7..0000000
--- a/solr/core/src/java/org/apache/solr/packagemanager/SolrPackage.java
+++ /dev/null
@@ -1,12 +0,0 @@
-//package org.apache.solr.packagemanager;
-//
-//import java.util.List;
-//
-//public class SolrPackage {
-// public String name;
-// public String version;
-// public String repository;
-// public String sha256;
-// public List<String> setupCommands;
-// public List<String> updateCommands;
-//}
\ No newline at end of file
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginDescriptor.java b/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginDescriptor.java
index 2904524..938b825 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginDescriptor.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginDescriptor.java
@@ -3,7 +3,7 @@ package org.apache.solr.packagemanager;
import java.util.List;
import org.apache.solr.packagemanager.SolrPluginInfo.Plugin;
-import org.pf4j.DefaultPluginDescriptor;
+import org.apache.solr.packagemanager.pf4j.DefaultPluginDescriptor;
public class SolrPluginDescriptor extends DefaultPluginDescriptor {
final private String id;
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginInfo.java b/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginInfo.java
index a74faa1..c5972c5 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginInfo.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginInfo.java
@@ -3,7 +3,7 @@ package org.apache.solr.packagemanager;
import java.util.List;
-import org.pf4j.update.PluginInfo;
+import org.apache.solr.packagemanager.pf4j.PluginInfo;
import com.google.gson.annotations.SerializedName;
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginManager.java b/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginManager.java
index 37dc2da..f541218 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginManager.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/SolrPluginManager.java
@@ -23,21 +23,7 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.solr.packagemanager.SolrPluginInfo.Metadata;
import org.apache.solr.packagemanager.SolrPluginInfo.Plugin;
-import org.pf4j.AbstractPluginManager;
-import org.pf4j.DefaultVersionManager;
-import org.pf4j.ExtensionFactory;
-import org.pf4j.ExtensionFinder;
-import org.pf4j.PluginDescriptor;
-import org.pf4j.PluginDescriptorFinder;
-import org.pf4j.PluginFactory;
-import org.pf4j.PluginLoader;
-import org.pf4j.PluginRepository;
-import org.pf4j.PluginState;
-import org.pf4j.PluginStateListener;
-import org.pf4j.PluginStatusProvider;
-import org.pf4j.PluginWrapper;
-import org.pf4j.RuntimeMode;
-import org.pf4j.VersionManager;
+import org.apache.solr.packagemanager.pf4j.*;
import com.google.gson.Gson;
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateManager.java b/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateManager.java
index 878a735..1111369 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateManager.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateManager.java
@@ -4,9 +4,13 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
+import java.net.URL;
import java.nio.file.Path;
-import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
@@ -22,37 +26,46 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.solr.packagemanager.SolrPluginInfo.Metadata;
import org.apache.solr.packagemanager.SolrPluginInfo.SolrPluginRelease;
-import org.pf4j.PluginException;
-import org.pf4j.PluginManager;
-import org.pf4j.PluginWrapper;
-import org.pf4j.update.PluginInfo;
-import org.pf4j.update.UpdateManager;
-import org.pf4j.update.UpdateRepository;
+import org.apache.solr.packagemanager.pf4j.CompoundVerifier;
+import org.apache.solr.packagemanager.pf4j.FileDownloader;
+import org.apache.solr.packagemanager.pf4j.FileVerifier;
+import org.apache.solr.packagemanager.pf4j.PluginException;
+import org.apache.solr.packagemanager.pf4j.PluginInfo;
+import org.apache.solr.packagemanager.pf4j.PluginInfo.PluginRelease;
+import org.apache.solr.packagemanager.pf4j.PluginManager;
+import org.apache.solr.packagemanager.pf4j.PluginWrapper;
+import org.apache.solr.packagemanager.pf4j.SimpleFileDownloader;
+import org.apache.solr.packagemanager.pf4j.UpdateRepository;
+import org.apache.solr.packagemanager.pf4j.VersionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
-public class SolrUpdateManager extends UpdateManager {
+public class SolrUpdateManager {
final private PluginManager pluginManager;
final private String repositoriesJsonStr;
+ protected List<UpdateRepository> repositories;
+
+ private VersionManager versionManager;
+ private String systemVersion;
+ private Map<String, PluginRelease> lastPluginRelease = new HashMap<>();
+
private static final Logger log = LoggerFactory.getLogger(SolrUpdateManager.class);
public SolrUpdateManager(PluginManager pluginManager, String repositoriesJsonStr) {
- super(pluginManager, (Path)Paths.get("."));
+ //super(pluginManager, (Path)Paths.get("."));
this.pluginManager = pluginManager;
this.repositoriesJsonStr = repositoriesJsonStr;
}
- @Override
protected synchronized void initRepositoriesFromJson() {
UpdateRepository items[] = new Gson().fromJson(this.repositoriesJsonStr, SolrUpdateRepository[].class);
this.repositories = Arrays.asList(items);
}
- @Override
public synchronized void refresh() {
initRepositoriesFromJson();
for (UpdateRepository updateRepository : repositories) {
@@ -61,17 +74,38 @@ public class SolrUpdateManager extends UpdateManager {
}
- @Override
public synchronized boolean installPlugin(String id, String version) throws PluginException {
return updateOrInstallPackage(Operation.INSTALL, id, version);
}
- @Override
public synchronized boolean updatePlugin(String id, String version) throws PluginException {
return updateOrInstallPackage(Operation.UPDATE, id, version);
}
+ public List<PluginInfo> getPlugins() {
+ List<PluginInfo> list = new ArrayList<>(getPluginsMap().values());
+ Collections.sort(list);
+
+ return list;
+ }
+
+ public Map<String, PluginInfo> getPluginsMap() {
+ Map<String, PluginInfo> pluginsMap = new HashMap<>();
+ for (UpdateRepository repository : getRepositories()) {
+ pluginsMap.putAll(repository.getPlugins());
+ }
+
+ return pluginsMap;
+ }
+
+ public List<UpdateRepository> getRepositories() {
+ refresh();
+ return repositories;
+ }
+
+
+
private boolean updateOrInstallPackage(Operation op, String id, String version) throws PluginException {
//System.out.println("ENTERS HERE");
// Download to temporary location
@@ -209,4 +243,110 @@ public class SolrUpdateManager extends UpdateManager {
return uploadToBlobHandler(new File("tmp-metadata").toPath());
}
+ /**
+ * Downloads a plugin with given coordinates, runs all {@link FileVerifier}s
+ * and returns a path to the downloaded file.
+ *
+ * @param id of plugin
+ * @param version of plugin or null to download latest
+ * @return Path to file which will reside in a temporary folder in the system default temp area
+ * @throws PluginException if download failed
+ */
+ protected Path downloadPlugin(String id, String version) throws PluginException {
+ try {
+ PluginRelease release = findReleaseForPlugin(id, version);
+ Path downloaded = getFileDownloader(id).downloadFile(new URL(release.url));
+ getFileVerifier(id).verify(new FileVerifier.Context(id, release), downloaded);
+ return downloaded;
+ } catch (IOException e) {
+ throw new PluginException(e, "Error during download of plugin {}", id);
+ }
+ }
+
+ /**
+ * Finds the {@link FileDownloader} to use for this repository.
+ *
+ * @param pluginId the plugin we wish to download
+ * @return FileDownloader instance
+ */
+ protected FileDownloader getFileDownloader(String pluginId) {
+ for (UpdateRepository ur : repositories) {
+ if (ur.getPlugin(pluginId) != null && ur.getFileDownloader() != null) {
+ return ur.getFileDownloader();
+ }
+ }
+
+ return new SimpleFileDownloader();
+ }
+
+ /**
+ * Gets a file verifier to use for this plugin. First tries to use custom verifier
+ * configured for the repository, then fallback to the default CompoundVerifier
+ *
+ * @param pluginId the plugin we wish to download
+ * @return FileVerifier instance
+ */
+ protected FileVerifier getFileVerifier(String pluginId) {
+ for (UpdateRepository ur : repositories) {
+ if (ur.getPlugin(pluginId) != null && ur.getFileVerfier() != null) {
+ return ur.getFileVerfier();
+ }
+ }
+
+ return new CompoundVerifier();
+ }
+
+ /**
+ * Resolves Release from id and version.
+ *
+ * @param id of plugin
+ * @param version of plugin or null to locate latest version
+ * @return PluginRelease for downloading
+ * @throws PluginException if id or version does not exist
+ */
+ protected PluginRelease findReleaseForPlugin(String id, String version) throws PluginException {
+ PluginInfo pluginInfo = getPluginsMap().get(id);
+ if (pluginInfo == null) {
+ log.info("Plugin with id {} does not exist in any repository", id);
+ throw new PluginException("Plugin with id {} not found in any repository", id);
+ }
+
+ if (version == null) {
+ return getLastPluginRelease(id);
+ }
+
+ for (PluginRelease release : pluginInfo.releases) {
+ if (versionManager.compareVersions(version, release.version) == 0 && release.url != null) {
+ return release;
+ }
+ }
+
+ throw new PluginException("Plugin {} with version @{} does not exist in the repository", id, version);
+ }
+
+ /**
+ * Returns the last release version of this plugin for given system version, regardless of release date.
+ *
+ * @return PluginRelease which has the highest version number
+ */
+ public PluginRelease getLastPluginRelease(String id) {
+ PluginInfo pluginInfo = getPluginsMap().get(id);
+ if (pluginInfo == null) {
+ return null;
+ }
+
+ if (!lastPluginRelease.containsKey(id)) {
+ for (PluginRelease release : pluginInfo.releases) {
+ if (systemVersion.equals("0.0.0") || versionManager.checkVersionConstraint(systemVersion, release.requires)) {
+ if (lastPluginRelease.get(id) == null) {
+ lastPluginRelease.put(id, release);
+ } else if (versionManager.compareVersions(release.version, lastPluginRelease.get(id).version) > 0) {
+ lastPluginRelease.put(id, release);
+ }
+ }
+ }
+ }
+
+ return lastPluginRelease.get(id);
+ }
}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateRepository.java
index 4739ff6..847ccc9 100644
--- a/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateRepository.java
+++ b/solr/core/src/java/org/apache/solr/packagemanager/SolrUpdateRepository.java
@@ -11,10 +11,8 @@ import java.util.HashMap;
import java.util.Map;
import org.apache.solr.packagemanager.SolrPluginInfo.SolrPluginRelease;
-import org.pf4j.update.DefaultUpdateRepository;
-import org.pf4j.update.PluginInfo;
-import org.pf4j.update.PluginInfo.PluginRelease;
-import org.pf4j.update.util.LenientDateTypeAdapter;
+import org.apache.solr.packagemanager.pf4j.*;
+import org.apache.solr.packagemanager.pf4j.PluginInfo.PluginRelease;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/AbstractExtensionFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/AbstractExtensionFinder.java
new file mode 100644
index 0000000..4757dc1
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/AbstractExtensionFinder.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright 2015 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.ClassUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Decebal Suiu
+ */
+public abstract class AbstractExtensionFinder implements ExtensionFinder, PluginStateListener {
+
+ private static final Logger log = LoggerFactory.getLogger(AbstractExtensionFinder.class);
+
+ protected PluginManager pluginManager;
+ protected volatile Map<String, Set<String>> entries; // cache by pluginId
+
+ public AbstractExtensionFinder(PluginManager pluginManager) {
+ this.pluginManager = pluginManager;
+ }
+
+ public abstract Map<String, Set<String>> readPluginsStorages();
+
+ public abstract Map<String, Set<String>> readClasspathStorages();
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> List<ExtensionWrapper<T>> find(Class<T> type) {
+ log.debug("Finding extensions of extension point '{}'", type.getName());
+ Map<String, Set<String>> entries = getEntries();
+ List<ExtensionWrapper<T>> result = new ArrayList<>();
+
+ // add extensions found in classpath and plugins
+ for (String pluginId : entries.keySet()) {
+ // classpath's extensions <=> pluginId = null
+ List<ExtensionWrapper<T>> pluginExtensions = find(type, pluginId);
+ result.addAll(pluginExtensions);
+ }
+
+ if (entries.isEmpty()) {
+ log.debug("No extensions found for extension point '{}'", type.getName());
+ } else {
+ log.debug("Found {} extensions for extension point '{}'", result.size(), type.getName());
+ }
+
+ // sort by "ordinal" property
+ Collections.sort(result);
+
+ return result;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> List<ExtensionWrapper<T>> find(Class<T> type, String pluginId) {
+ log.debug("Finding extensions of extension point '{}' for plugin '{}'", type.getName(), pluginId);
+ List<ExtensionWrapper<T>> result = new ArrayList<>();
+
+ // classpath's extensions <=> pluginId = null
+ Set<String> classNames = findClassNames(pluginId);
+ if (classNames == null || classNames.isEmpty()) {
+ return result;
+ }
+
+ if (pluginId != null) {
+ PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId);
+ if (PluginState.STARTED != pluginWrapper.getPluginState()) {
+ return result;
+ }
+
+ log.trace("Checking extensions from plugin '{}'", pluginId);
+ } else {
+ log.trace("Checking extensions from classpath");
+ }
+
+ ClassLoader classLoader = (pluginId != null) ? pluginManager.getPluginClassLoader(pluginId) : getClass().getClassLoader();
+
+ for (String className : classNames) {
+ try {
+ log.debug("Loading class '{}' using class loader '{}'", className, classLoader);
+ Class<?> extensionClass = classLoader.loadClass(className);
+
+ log.debug("Checking extension type '{}'", className);
+ if (type.isAssignableFrom(extensionClass)) {
+ ExtensionWrapper extensionWrapper = createExtensionWrapper(extensionClass);
+ result.add(extensionWrapper);
+ log.debug("Added extension '{}' with ordinal {}", className, extensionWrapper.getOrdinal());
+ } else {
+ log.trace("'{}' is not an extension for extension point '{}'", className, type.getName());
+ if (RuntimeMode.DEVELOPMENT.equals(pluginManager.getRuntimeMode())) {
+ checkDifferentClassLoaders(type, extensionClass);
+ }
+ }
+ } catch (ClassNotFoundException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ if (result.isEmpty()) {
+ log.debug("No extensions found for extension point '{}'", type.getName());
+ } else {
+ log.debug("Found {} extensions for extension point '{}'", result.size(), type.getName());
+ }
+
+ // sort by "ordinal" property
+ Collections.sort(result);
+
+ return result;
+ }
+
+ @Override
+ public List<ExtensionWrapper> find(String pluginId) {
+ log.debug("Finding extensions from plugin '{}'", pluginId);
+ List<ExtensionWrapper> result = new ArrayList<>();
+
+ Set<String> classNames = findClassNames(pluginId);
+ if (classNames.isEmpty()) {
+ return result;
+ }
+
+ if (pluginId != null) {
+ PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId);
+ if (PluginState.STARTED != pluginWrapper.getPluginState()) {
+ return result;
+ }
+
+ log.trace("Checking extensions from plugin '{}'", pluginId);
+ } else {
+ log.trace("Checking extensions from classpath");
+ }
+
+ ClassLoader classLoader = (pluginId != null) ? pluginManager.getPluginClassLoader(pluginId) : getClass().getClassLoader();
+
+ for (String className : classNames) {
+ try {
+ log.debug("Loading class '{}' using class loader '{}'", className, classLoader);
+ Class<?> extensionClass = classLoader.loadClass(className);
+
+ ExtensionWrapper extensionWrapper = createExtensionWrapper(extensionClass);
+ result.add(extensionWrapper);
+ log.debug("Added extension '{}' with ordinal {}", className, extensionWrapper.getOrdinal());
+ } catch (ClassNotFoundException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ if (result.isEmpty()) {
+ log.debug("No extensions found for plugin '{}'", pluginId);
+ } else {
+ log.debug("Found {} extensions for plugin '{}'", result.size(), pluginId);
+ }
+
+ // sort by "ordinal" property
+ Collections.sort(result);
+
+ return result;
+ }
+
+ @Override
+ public Set<String> findClassNames(String pluginId) {
+ return getEntries().get(pluginId);
+ }
+
+ @Override
+ public void pluginStateChanged(PluginStateEvent event) {
+ // TODO optimize (do only for some transitions)
+ // clear cache
+ entries = null;
+ }
+
+ protected void debugExtensions(Set<String> extensions) {
+ if (log.isDebugEnabled()) {
+ if (extensions.isEmpty()) {
+ log.debug("No extensions found");
+ } else {
+ log.debug("Found possible {} extensions:", extensions.size());
+ for (String extension : extensions) {
+ log.debug(" " + extension);
+ }
+ }
+ }
+ }
+
+ private Map<String, Set<String>> readStorages() {
+ Map<String, Set<String>> result = new LinkedHashMap<>();
+
+ result.putAll(readClasspathStorages());
+ result.putAll(readPluginsStorages());
+
+ return result;
+ }
+
+ private Map<String, Set<String>> getEntries() {
+ if (entries == null) {
+ entries = readStorages();
+ }
+
+ return entries;
+ }
+
+ private ExtensionWrapper createExtensionWrapper(Class<?> extensionClass) {
+ int ordinal = 0;
+ if (extensionClass.isAnnotationPresent(Extension.class)) {
+ ordinal = extensionClass.getAnnotation(Extension.class).ordinal();
+ }
+ ExtensionDescriptor descriptor = new ExtensionDescriptor(ordinal, extensionClass);
+
+ return new ExtensionWrapper<>(descriptor, pluginManager.getExtensionFactory());
+ }
+
+ private void checkDifferentClassLoaders(Class<?> type, Class<?> extensionClass) {
+ ClassLoader typeClassLoader = type.getClassLoader(); // class loader of extension point
+ ClassLoader extensionClassLoader = extensionClass.getClassLoader();
+ boolean match = ClassUtils.getAllInterfacesNames(extensionClass).contains(type.getSimpleName());
+ if (match && !extensionClassLoader.equals(typeClassLoader)) {
+ // in this scenario the method 'isAssignableFrom' returns only FALSE
+ // see http://www.coderanch.com/t/557846/java/java/FWIW-FYI-isAssignableFrom-isInstance-differing
+ log.error("Different class loaders: '{}' (E) and '{}' (EP)", extensionClassLoader, typeClassLoader);
+ }
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/AbstractPluginManager.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/AbstractPluginManager.java
new file mode 100644
index 0000000..6bc12e6
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/AbstractPluginManager.java
@@ -0,0 +1,919 @@
+/*
+ * Copyright 2016 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.pf4j.util.StringUtils;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * This class implements the boilerplate plugin code that any {@link PluginManager}
+ * implementation would have to support.
+ * It helps cut the noise out of the subclass that handles plugin management.
+ *
+ * @author Decebal Suiu
+ */
+public abstract class AbstractPluginManager implements PluginManager {
+
+ private static final Logger log = LoggerFactory.getLogger(AbstractPluginManager.class);
+
+ private Path pluginsRoot;
+
+ protected ExtensionFinder extensionFinder;
+
+ private PluginDescriptorFinder pluginDescriptorFinder;
+
+ /*
+ * A map of plugins this manager is responsible for (the key is the 'pluginId').
+ */
+ protected Map<String, PluginWrapper> plugins;
+
+ /*
+ * A map of plugin class loaders (the key is the 'pluginId').
+ */
+ private Map<String, ClassLoader> pluginClassLoaders;
+
+ /*
+ * A list with unresolved plugins (unresolved dependency).
+ */
+ private List<PluginWrapper> unresolvedPlugins;
+
+ /**
+ * A list with all resolved plugins (resolved dependency).
+ */
+ private List<PluginWrapper> resolvedPlugins;
+
+ /*
+ * A list with started plugins.
+ */
+ private List<PluginWrapper> startedPlugins;
+
+ /*
+ * The registered {@link PluginStateListener}s.
+ */
+ private List<PluginStateListener> pluginStateListeners;
+
+ /*
+ * Cache value for the runtime mode.
+ * No need to re-read it because it wont change at runtime.
+ */
+ private RuntimeMode runtimeMode;
+
+ /*
+ * The system version used for comparisons to the plugin requires attribute.
+ */
+ private String systemVersion = "0.0.0";
+
+ private PluginRepository pluginRepository;
+ private PluginFactory pluginFactory;
+ private ExtensionFactory extensionFactory;
+ private PluginStatusProvider pluginStatusProvider;
+ private DependencyResolver dependencyResolver;
+ private PluginLoader pluginLoader;
+ private boolean exactVersionAllowed = false;
+
+ private VersionManager versionManager;
+
+ /**
+ * The plugins root is supplied by {@code System.getProperty("pf4j.pluginsDir", "plugins")}.
+ */
+ public AbstractPluginManager() {
+ initialize();
+ }
+
+ /**
+ * Constructs {@code AbstractPluginManager} with the given plugins root.
+ *
+ * @param pluginsRoot the root to search for plugins
+ */
+ public AbstractPluginManager(Path pluginsRoot) {
+ this.pluginsRoot = pluginsRoot;
+
+ initialize();
+ }
+
+ @Override
+ public void setSystemVersion(String version) {
+ systemVersion = version;
+ }
+
+ @Override
+ public String getSystemVersion() {
+ return systemVersion;
+ }
+
+ @Override
+ public List<PluginWrapper> getPlugins() {
+ return new ArrayList<>(plugins.values());
+ }
+
+ @Override
+ public List<PluginWrapper> getPlugins(PluginState pluginState) {
+ List<PluginWrapper> plugins = new ArrayList<>();
+ for (PluginWrapper plugin : getPlugins()) {
+ if (pluginState.equals(plugin.getPluginState())) {
+ plugins.add(plugin);
+ }
+ }
+
+ return plugins;
+ }
+
+ @Override
+ public List<PluginWrapper> getResolvedPlugins() {
+ return resolvedPlugins;
+ }
+
+ @Override
+ public List<PluginWrapper> getUnresolvedPlugins() {
+ return unresolvedPlugins;
+ }
+
+ @Override
+ public List<PluginWrapper> getStartedPlugins() {
+ return startedPlugins;
+ }
+
+ @Override
+ public PluginWrapper getPlugin(String pluginId) {
+ return plugins.get(pluginId);
+ }
+
+ @Override
+ public String loadPlugin(Path pluginPath) {
+ if ((pluginPath == null) || Files.notExists(pluginPath)) {
+ throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginPath));
+ }
+
+ log.debug("Loading plugin from '{}'", pluginPath);
+
+ try {
+ PluginWrapper pluginWrapper = loadPluginFromPath(pluginPath);
+
+ // try to resolve the loaded plugin together with other possible plugins that depend on this plugin
+ resolvePlugins();
+
+ return pluginWrapper.getDescriptor().getPluginId();
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return null;
+ }
+
+ /**
+ * Load plugins.
+ */
+ @Override
+ public void loadPlugins() {
+ log.debug("Lookup plugins in '{}'", pluginsRoot);
+ // check for plugins root
+ if (Files.notExists(pluginsRoot) || !Files.isDirectory(pluginsRoot)) {
+ log.warn("No '{}' root", pluginsRoot);
+ return;
+ }
+
+ // get all plugin paths from repository
+ List<Path> pluginPaths = pluginRepository.getPluginPaths();
+
+ // check for no plugins
+ if (pluginPaths.isEmpty()) {
+ log.info("No plugins");
+ return;
+ }
+
+ log.debug("Found {} possible plugins: {}", pluginPaths.size(), pluginPaths);
+
+ // load plugins from plugin paths
+ for (Path pluginPath : pluginPaths) {
+ try {
+ loadPluginFromPath(pluginPath);
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ // resolve plugins
+ try {
+ resolvePlugins();
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Unload the specified plugin and it's dependents.
+ */
+ @Override
+ public boolean unloadPlugin(String pluginId) {
+ return unloadPlugin(pluginId, true);
+ }
+
+ private boolean unloadPlugin(String pluginId, boolean unloadDependents) {
+ try {
+ if (unloadDependents) {
+ List<String> dependents = dependencyResolver.getDependents(pluginId);
+ while (!dependents.isEmpty()) {
+ String dependent = dependents.remove(0);
+ unloadPlugin(dependent, false);
+ dependents.addAll(0, dependencyResolver.getDependents(dependent));
+ }
+ }
+
+ PluginState pluginState = stopPlugin(pluginId, false);
+ if (PluginState.STARTED == pluginState) {
+ return false;
+ }
+
+ PluginWrapper pluginWrapper = getPlugin(pluginId);
+ log.info("Unload plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
+
+ // remove the plugin
+ plugins.remove(pluginId);
+ getResolvedPlugins().remove(pluginWrapper);
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+
+ // remove the classloader
+ Map<String, ClassLoader> pluginClassLoaders = getPluginClassLoaders();
+ if (pluginClassLoaders.containsKey(pluginId)) {
+ ClassLoader classLoader = pluginClassLoaders.remove(pluginId);
+ if (classLoader instanceof Closeable) {
+ try {
+ ((Closeable) classLoader).close();
+ } catch (IOException e) {
+ log.error("Cannot close classloader", e);
+ }
+ }
+ }
+
+ return true;
+ } catch (IllegalArgumentException e) {
+ // ignore not found exceptions because this method is recursive
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean deletePlugin(String pluginId) {
+ checkPluginId(pluginId);
+
+ PluginWrapper pluginWrapper = getPlugin(pluginId);
+ PluginState pluginState = stopPlugin(pluginId);
+ if (PluginState.STARTED == pluginState) {
+ log.error("Failed to stop plugin '{}' on delete", pluginId);
+ return false;
+ }
+
+ if (!unloadPlugin(pluginId)) {
+ log.error("Failed to unload plugin '{}' on delete", pluginId);
+ return false;
+ }
+
+ Path pluginPath = pluginWrapper.getPluginPath();
+
+ return pluginRepository.deletePluginPath(pluginPath);
+ }
+
+ /**
+ * Start all active plugins.
+ */
+ @Override
+ public void startPlugins() {
+ for (PluginWrapper pluginWrapper : resolvedPlugins) {
+ PluginState pluginState = pluginWrapper.getPluginState();
+ if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) {
+ try {
+ log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
+ pluginWrapper.getPlugin().start();
+ pluginWrapper.setPluginState(PluginState.STARTED);
+ startedPlugins.add(pluginWrapper);
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+ }
+ }
+
+ /**
+ * Start the specified plugin and it's dependencies.
+ */
+ @Override
+ public PluginState startPlugin(String pluginId) {
+ checkPluginId(pluginId);
+
+ PluginWrapper pluginWrapper = getPlugin(pluginId);
+ PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
+ PluginState pluginState = pluginWrapper.getPluginState();
+ if (PluginState.STARTED == pluginState) {
+ log.debug("Already started plugin '{}'", getPluginLabel(pluginDescriptor));
+ return PluginState.STARTED;
+ }
+
+ if (!resolvedPlugins.contains(pluginWrapper)) {
+ log.warn("Cannot start an unresolved plugin '{}'", getPluginLabel(pluginDescriptor));
+ return pluginState;
+ }
+
+ if (PluginState.DISABLED == pluginState) {
+ // automatically enable plugin on manual plugin start
+ if (!enablePlugin(pluginId)) {
+ return pluginState;
+ }
+ }
+
+ for (PluginDependency dependency : pluginDescriptor.getDependencies()) {
+ startPlugin(dependency.getPluginId());
+ }
+
+ try {
+ log.info("Start plugin '{}'", getPluginLabel(pluginDescriptor));
+ pluginWrapper.getPlugin().start();
+ pluginWrapper.setPluginState(PluginState.STARTED);
+ startedPlugins.add(pluginWrapper);
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return pluginWrapper.getPluginState();
+ }
+
+ /**
+ * Stop all active plugins.
+ */
+ @Override
+ public void stopPlugins() {
+ // stop started plugins in reverse order
+ Collections.reverse(startedPlugins);
+ Iterator<PluginWrapper> itr = startedPlugins.iterator();
+ while (itr.hasNext()) {
+ PluginWrapper pluginWrapper = itr.next();
+ PluginState pluginState = pluginWrapper.getPluginState();
+ if (PluginState.STARTED == pluginState) {
+ try {
+ log.info("Stop plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
+ pluginWrapper.getPlugin().stop();
+ pluginWrapper.setPluginState(PluginState.STOPPED);
+ itr.remove();
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+ }
+ }
+
+ /**
+ * Stop the specified plugin and it's dependents.
+ */
+ @Override
+ public PluginState stopPlugin(String pluginId) {
+ return stopPlugin(pluginId, true);
+ }
+
+ private PluginState stopPlugin(String pluginId, boolean stopDependents) {
+ checkPluginId(pluginId);
+
+ PluginWrapper pluginWrapper = getPlugin(pluginId);
+ PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
+ PluginState pluginState = pluginWrapper.getPluginState();
+ if (PluginState.STOPPED == pluginState) {
+ log.debug("Already stopped plugin '{}'", getPluginLabel(pluginDescriptor));
+ return PluginState.STOPPED;
+ }
+
+ // test for disabled plugin
+ if (PluginState.DISABLED == pluginState) {
+ // do nothing
+ return pluginState;
+ }
+
+ if (stopDependents) {
+ List<String> dependents = dependencyResolver.getDependents(pluginId);
+ while (!dependents.isEmpty()) {
+ String dependent = dependents.remove(0);
+ stopPlugin(dependent, false);
+ dependents.addAll(0, dependencyResolver.getDependents(dependent));
+ }
+ }
+
+ try {
+ log.info("Stop plugin '{}'", getPluginLabel(pluginDescriptor));
+ pluginWrapper.getPlugin().stop();
+ pluginWrapper.setPluginState(PluginState.STOPPED);
+ startedPlugins.remove(pluginWrapper);
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+ } catch (PluginException e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return pluginWrapper.getPluginState();
+ }
+
+ private void checkPluginId(String pluginId) {
+ if (!plugins.containsKey(pluginId)) {
+ throw new IllegalArgumentException(String.format("Unknown pluginId %s", pluginId));
+ }
+ }
+
+ @Override
+ public boolean disablePlugin(String pluginId) {
+ checkPluginId(pluginId);
+
+ PluginWrapper pluginWrapper = getPlugin(pluginId);
+ PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
+ PluginState pluginState = pluginWrapper.getPluginState();
+ if (PluginState.DISABLED == pluginState) {
+ log.debug("Already disabled plugin '{}'", getPluginLabel(pluginDescriptor));
+ return true;
+ }
+
+ if (PluginState.STOPPED == stopPlugin(pluginId)) {
+ pluginWrapper.setPluginState(PluginState.DISABLED);
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, PluginState.STOPPED));
+
+ if (!pluginStatusProvider.disablePlugin(pluginId)) {
+ return false;
+ }
+
+ log.info("Disabled plugin '{}'", getPluginLabel(pluginDescriptor));
+
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean enablePlugin(String pluginId) {
+ checkPluginId(pluginId);
+
+ PluginWrapper pluginWrapper = getPlugin(pluginId);
+ if (!isPluginValid(pluginWrapper)) {
+ log.warn("Plugin '{}' can not be enabled", getPluginLabel(pluginWrapper.getDescriptor()));
+ return false;
+ }
+
+ PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
+ PluginState pluginState = pluginWrapper.getPluginState();
+ if (PluginState.DISABLED != pluginState) {
+ log.debug("Plugin '{}' is not disabled", getPluginLabel(pluginDescriptor));
+ return true;
+ }
+
+ if (!pluginStatusProvider.enablePlugin(pluginId)) {
+ return false;
+ }
+
+ pluginWrapper.setPluginState(PluginState.CREATED);
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+
+ log.info("Enabled plugin '{}'", getPluginLabel(pluginDescriptor));
+
+ return true;
+ }
+
+ /**
+ * Get the {@link ClassLoader} for plugin.
+ */
+ @Override
+ public ClassLoader getPluginClassLoader(String pluginId) {
+ return pluginClassLoaders.get(pluginId);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> List<Class<T>> getExtensionClasses(Class<T> type) {
+ List<ExtensionWrapper<T>> extensionsWrapper = extensionFinder.find(type);
+ List<Class<T>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
+ for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
+ Class<T> c = (Class<T>) extensionWrapper.getDescriptor().extensionClass;
+ extensionClasses.add(c);
+ }
+
+ return extensionClasses;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> List<Class<T>> getExtensionClasses(Class<T> type, String pluginId) {
+ List<ExtensionWrapper<T>> extensionsWrapper = extensionFinder.find(type, pluginId);
+ List<Class<T>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
+ for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
+ Class<T> c = (Class<T>) extensionWrapper.getDescriptor().extensionClass;
+ extensionClasses.add(c);
+ }
+
+ return extensionClasses;
+ }
+
+ @Override
+ public <T> List<T> getExtensions(Class<T> type) {
+ List<ExtensionWrapper<T>> extensionsWrapper = extensionFinder.find(type);
+ List<T> extensions = new ArrayList<>(extensionsWrapper.size());
+ for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
+ extensions.add(extensionWrapper.getExtension());
+ }
+
+ return extensions;
+ }
+
+ @Override
+ public <T> List<T> getExtensions(Class<T> type, String pluginId) {
+ List<ExtensionWrapper<T>> extensionsWrapper = extensionFinder.find(type, pluginId);
+ List<T> extensions = new ArrayList<>(extensionsWrapper.size());
+ for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
+ extensions.add(extensionWrapper.getExtension());
+ }
+
+ return extensions;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public List getExtensions(String pluginId) {
+ List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
+ List extensions = new ArrayList<>(extensionsWrapper.size());
+ for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
+ extensions.add(extensionWrapper.getExtension());
+ }
+
+ return extensions;
+ }
+
+ @Override
+ public Set<String> getExtensionClassNames(String pluginId) {
+ return extensionFinder.findClassNames(pluginId);
+ }
+
+ @Override
+ public ExtensionFactory getExtensionFactory() {
+ return extensionFactory;
+ }
+
+ // TODO remove
+ public PluginLoader getPluginLoader() {
+ return pluginLoader;
+ }
+
+ public Path getPluginsRoot() {
+ return pluginsRoot;
+ }
+
+ @Override
+ public RuntimeMode getRuntimeMode() {
+ if (runtimeMode == null) {
+ // retrieves the runtime mode from system
+ String modeAsString = System.getProperty("pf4j.mode", RuntimeMode.DEPLOYMENT.toString());
+ runtimeMode = RuntimeMode.byName(modeAsString);
+ }
+
+ return runtimeMode;
+ }
+
+ @Override
+ public PluginWrapper whichPlugin(Class<?> clazz) {
+ ClassLoader classLoader = clazz.getClassLoader();
+ for (PluginWrapper plugin : resolvedPlugins) {
+ if (plugin.getPluginClassLoader() == classLoader) {
+ return plugin;
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public synchronized void addPluginStateListener(PluginStateListener listener) {
+ pluginStateListeners.add(listener);
+ }
+
+ @Override
+ public synchronized void removePluginStateListener(PluginStateListener listener) {
+ pluginStateListeners.remove(listener);
+ }
+
+ public String getVersion() {
+ String version = null;
+
+ Package pf4jPackage = PluginManager.class.getPackage();
+ if (pf4jPackage != null) {
+ version = pf4jPackage.getImplementationVersion();
+ if (version == null) {
+ version = pf4jPackage.getSpecificationVersion();
+ }
+ }
+
+ return (version != null) ? version : "0.0.0";
+ }
+
+ protected abstract PluginRepository createPluginRepository();
+
+ protected abstract PluginFactory createPluginFactory();
+
+ protected abstract ExtensionFactory createExtensionFactory();
+
+ protected abstract PluginDescriptorFinder createPluginDescriptorFinder();
+
+ protected abstract ExtensionFinder createExtensionFinder();
+
+ protected abstract PluginStatusProvider createPluginStatusProvider();
+
+ protected abstract PluginLoader createPluginLoader();
+
+ protected abstract VersionManager createVersionManager();
+
+ protected PluginDescriptorFinder getPluginDescriptorFinder() {
+ return pluginDescriptorFinder;
+ }
+
+ protected PluginFactory getPluginFactory() {
+ return pluginFactory;
+ }
+
+ protected Map<String, ClassLoader> getPluginClassLoaders() {
+ return pluginClassLoaders;
+ }
+
+ protected void initialize() {
+ plugins = new HashMap<>();
+ pluginClassLoaders = new HashMap<>();
+ unresolvedPlugins = new ArrayList<>();
+ resolvedPlugins = new ArrayList<>();
+ startedPlugins = new ArrayList<>();
+
+ pluginStateListeners = new ArrayList<>();
+
+ if (pluginsRoot == null) {
+ pluginsRoot = createPluginsRoot();
+ }
+
+ System.setProperty("pf4j.pluginsDir", pluginsRoot.toString());
+
+ pluginRepository = createPluginRepository();
+ pluginFactory = createPluginFactory();
+ extensionFactory = createExtensionFactory();
+ pluginDescriptorFinder = createPluginDescriptorFinder();
+ extensionFinder = createExtensionFinder();
+ pluginStatusProvider = createPluginStatusProvider();
+ pluginLoader = createPluginLoader();
+
+ versionManager = createVersionManager();
+ dependencyResolver = new DependencyResolver(versionManager);
+ }
+
+ /**
+ * Add the possibility to override the plugins root.
+ * If a {@code pf4j.pluginsDir} system property is defined than this method returns that root.
+ * If {@link #getRuntimeMode()} returns {@link RuntimeMode#DEVELOPMENT} than {@code ../plugins}
+ * is returned else this method returns {@code plugins}.
+ *
+ * @return the plugins root
+ */
+ protected Path createPluginsRoot() {
+ String pluginsDir = System.getProperty("pf4j.pluginsDir");
+ if (pluginsDir == null) {
+ if (isDevelopment()) {
+ pluginsDir = "../plugins";
+ } else {
+ pluginsDir = "plugins";
+ }
+ }
+
+ return Paths.get(pluginsDir);
+ }
+
+ /**
+ * Check if this plugin is valid (satisfies "requires" param) for a given system version.
+ *
+ * @param pluginWrapper the plugin to check
+ * @return true if plugin satisfies the "requires" or if requires was left blank
+ */
+ protected boolean isPluginValid(PluginWrapper pluginWrapper) {
+ String requires = pluginWrapper.getDescriptor().getRequires().trim();
+ if (!isExactVersionAllowed() && requires.matches("^\\d+\\.\\d+\\.\\d+$")) {
+ // If exact versions are not allowed in requires, rewrite to >= expression
+ requires = ">=" + requires;
+ }
+ if (systemVersion.equals("0.0.0") || versionManager.checkVersionConstraint(systemVersion, requires)) {
+ return true;
+ }
+
+ PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
+ log.warn("Plugin '{}' requires a minimum system version of {}, and you have {}",
+ getPluginLabel(pluginDescriptor),
+ pluginWrapper.getDescriptor().getRequires(),
+ getSystemVersion());
+
+ return false;
+ }
+
+ protected boolean isPluginDisabled(String pluginId) {
+ return pluginStatusProvider.isPluginDisabled(pluginId);
+ }
+
+ protected void resolvePlugins() throws PluginException {
+ // retrieves the plugins descriptors
+ List<PluginDescriptor> descriptors = new ArrayList<>();
+ for (PluginWrapper plugin : plugins.values()) {
+ descriptors.add(plugin.getDescriptor());
+ }
+
+ DependencyResolver.Result result = dependencyResolver.resolve(descriptors);
+
+ if (result.hasCyclicDependency()) {
+ throw new DependencyResolver.CyclicDependencyException();
+ }
+
+ List<String> notFoundDependencies = result.getNotFoundDependencies();
+ if (!notFoundDependencies.isEmpty()) {
+ throw new DependencyResolver.DependenciesNotFoundException(notFoundDependencies);
+ }
+
+ List<DependencyResolver.WrongDependencyVersion> wrongVersionDependencies = result.getWrongVersionDependencies();
+ if (!wrongVersionDependencies.isEmpty()) {
+ throw new DependencyResolver.DependenciesWrongVersionException(wrongVersionDependencies);
+ }
+
+ List<String> sortedPlugins = result.getSortedPlugins();
+
+ // move plugins from "unresolved" to "resolved"
+ for (String pluginId : sortedPlugins) {
+ PluginWrapper pluginWrapper = plugins.get(pluginId);
+ if (unresolvedPlugins.remove(pluginWrapper)) {
+ PluginState pluginState = pluginWrapper.getPluginState();
+ pluginWrapper.setPluginState(PluginState.RESOLVED);
+
+ resolvedPlugins.add(pluginWrapper);
+ log.info("Plugin '{}' resolved", getPluginLabel(pluginWrapper.getDescriptor()));
+
+ firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
+ }
+ }
+ }
+
+ protected synchronized void firePluginStateEvent(PluginStateEvent event) {
+ for (PluginStateListener listener : pluginStateListeners) {
+ log.trace("Fire '{}' to '{}'", event, listener);
+ listener.pluginStateChanged(event);
+ }
+ }
+
+ protected PluginWrapper loadPluginFromPath(Path pluginPath) throws PluginException {
+ // test for plugin duplication
+ String pluginId = idForPath(pluginPath);
+ if (pluginId != null) {
+ log.warn("Plugin '{}' already loaded with id '{}'", pluginPath, pluginId);
+ return null;
+ }
+
+ // retrieves the plugin descriptor
+ PluginDescriptorFinder pluginDescriptorFinder = getPluginDescriptorFinder();
+ log.debug("Use '{}' to find plugins descriptors", pluginDescriptorFinder);
+ log.debug("Finding plugin descriptor for plugin '{}'", pluginPath);
+ PluginDescriptor pluginDescriptor = pluginDescriptorFinder.find(pluginPath);
+ validatePluginDescriptor(pluginDescriptor);
+ log.debug("Found descriptor {}", pluginDescriptor);
+ String pluginClassName = pluginDescriptor.getPluginClass();
+ log.debug("Class '{}' for plugin '{}'", pluginClassName, pluginPath);
+
+ // load plugin
+ log.debug("Loading plugin '{}'", pluginPath);
+ ClassLoader pluginClassLoader = getPluginLoader().loadPlugin(pluginPath, pluginDescriptor);
+ log.debug("Loaded plugin '{}' with class loader '{}'", pluginPath, pluginClassLoader);
+
+ // create the plugin wrapper
+ log.debug("Creating wrapper for plugin '{}'", pluginPath);
+ PluginWrapper pluginWrapper = new PluginWrapper(this, pluginDescriptor, pluginPath, pluginClassLoader);
+ pluginWrapper.setPluginFactory(getPluginFactory());
+ pluginWrapper.setRuntimeMode(getRuntimeMode());
+
+ // test for disabled plugin
+ if (isPluginDisabled(pluginDescriptor.getPluginId())) {
+ log.info("Plugin '{}' is disabled", pluginPath);
+ pluginWrapper.setPluginState(PluginState.DISABLED);
+ }
+
+ // validate the plugin
+ if (!isPluginValid(pluginWrapper)) {
+ log.info("Plugin '{}' is disabled", pluginPath);
+ pluginWrapper.setPluginState(PluginState.DISABLED);
+ }
+
+ log.debug("Created wrapper '{}' for plugin '{}'", pluginWrapper, pluginPath);
+
+ pluginId = pluginDescriptor.getPluginId();
+
+ // add plugin to the list with plugins
+ plugins.put(pluginId, pluginWrapper);
+ getUnresolvedPlugins().add(pluginWrapper);
+
+ // add plugin class loader to the list with class loaders
+ getPluginClassLoaders().put(pluginId, pluginClassLoader);
+
+ return pluginWrapper;
+ }
+
+ /**
+ * Tests for already loaded plugins on given path.
+ *
+ * @param pluginPath the path to investigate
+ * @return id of plugin or null if not loaded
+ */
+ protected String idForPath(Path pluginPath) {
+ for (PluginWrapper plugin : plugins.values()) {
+ if (plugin.getPluginPath().equals(pluginPath)) {
+ return plugin.getPluginId();
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Override this to change the validation criteria.
+ *
+ * @param descriptor the plugin descriptor to validate
+ * @throws PluginException if validation fails
+ */
+ protected void validatePluginDescriptor(PluginDescriptor descriptor) throws PluginException {
+ if (StringUtils.isNullOrEmpty(descriptor.getPluginId())) {
+ throw new PluginException("Field 'id' cannot be empty");
+ }
+
+ if (StringUtils.isNullOrEmpty(descriptor.getPluginClass())) {
+ throw new PluginException("Field 'class' cannot be empty");
+ }
+
+ if (descriptor.getVersion() == null) {
+ throw new PluginException("Field 'version' cannot be empty");
+ }
+ }
+
+ // TODO add this method in PluginManager as default method for Java 8.
+ protected boolean isDevelopment() {
+ return RuntimeMode.DEVELOPMENT.equals(getRuntimeMode());
+ }
+
+ /**
+ * @return true if exact versions in requires is allowed
+ */
+ public boolean isExactVersionAllowed() {
+ return exactVersionAllowed;
+ }
+
+ /**
+ * Set to true to allow requires expression to be exactly x.y.z.
+ * The default is false, meaning that using an exact version x.y.z will
+ *
+ * @param exactVersionAllowed set to true or false
+ */
+ public void setExactVersionAllowed(boolean exactVersionAllowed) {
+ this.exactVersionAllowed = exactVersionAllowed;
+ }
+
+ @Override
+ public VersionManager getVersionManager() {
+ return versionManager;
+ }
+
+ protected String getPluginLabel(PluginDescriptor pluginDescriptor) {
+ return pluginDescriptor.getPluginId() + "@" + pluginDescriptor.getVersion();
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/BasePluginRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/BasePluginRepository.java
new file mode 100644
index 0000000..a392772
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/BasePluginRepository.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Decebal Suiu
+ * @author Mário Franco
+ */
+public class BasePluginRepository implements PluginRepository {
+
+ protected final Path pluginsRoot;
+ protected FileFilter filter;
+
+ public BasePluginRepository(Path pluginsRoot) {
+ this.pluginsRoot = pluginsRoot;
+ }
+
+ public BasePluginRepository(Path pluginsRoot, FileFilter filter) {
+ this.pluginsRoot = pluginsRoot;
+ this.filter = filter;
+ }
+
+ public void setFilter(FileFilter filter) {
+ this.filter = filter;
+ }
+
+ @Override
+ public List<Path> getPluginPaths() {
+ File[] files = pluginsRoot.toFile().listFiles(filter);
+
+ if ((files == null) || files.length == 0) {
+ return Collections.emptyList();
+ }
+
+ List<Path> paths = new ArrayList<>(files.length);
+ for (File file : files) {
+ paths.add(file.toPath());
+ }
+
+ return paths;
+ }
+
+ @Override
+ public boolean deletePluginPath(Path pluginPath) {
+ try {
+ FileUtils.delete(pluginPath);
+ return true;
+ } catch (NoSuchFileException nsf) {
+ return false; // Return false on not found to be compatible with previous API
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/BasicVerifier.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/BasicVerifier.java
new file mode 100644
index 0000000..f912b06
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/BasicVerifier.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+/**
+ * Verifies that the file exists is a regular file and has a non-null size
+ */
+public class BasicVerifier implements FileVerifier {
+ /**
+ * Verifies a plugin release according to certain rules
+ *
+ * @param context the file verifier context object
+ * @param file the path to the downloaded file itself
+ * @throws IOException if there was a problem accessing file
+ * @throws VerifyException in case of problems verifying the file
+ */
+ @Override
+ public void verify(Context context, Path file) throws VerifyException, IOException {
+ if (!Files.isRegularFile(file) || Files.size(file) == 0) {
+ throw new VerifyException("File {} is not a regular file or has size 0", file);
+ }
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginDescriptorFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginDescriptorFinder.java
new file mode 100644
index 0000000..76b2bec
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginDescriptorFinder.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2017 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Decebal Suiu
+ */
+public class CompoundPluginDescriptorFinder implements PluginDescriptorFinder {
+
+ private static final Logger log = LoggerFactory.getLogger(CompoundPluginDescriptorFinder.class);
+
+ private List<PluginDescriptorFinder> finders = new ArrayList<>();
+
+ public CompoundPluginDescriptorFinder add(PluginDescriptorFinder finder) {
+ if (finder == null) {
+ throw new IllegalArgumentException("null not allowed");
+ }
+
+ finders.add(finder);
+
+ return this;
+ }
+
+ public int size() {
+ return finders.size();
+ }
+
+ @Override
+ public boolean isApplicable(Path pluginPath) {
+ for (PluginDescriptorFinder finder : finders) {
+ if (finder.isApplicable(pluginPath)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public PluginDescriptor find(Path pluginPath) throws PluginException {
+ for (PluginDescriptorFinder finder : finders) {
+ if (finder.isApplicable(pluginPath)) {
+ log.debug("'{}' is applicable for plugin '{}'", finder, pluginPath);
+ try {
+ PluginDescriptor pluginDescriptor = finder.find(pluginPath);
+ if (pluginDescriptor != null) {
+ return pluginDescriptor;
+ }
+ } catch (Exception e) {
+ // log the exception and continue with the next finder
+ log.error(e.getMessage()); // ?!
+ }
+ } else {
+ log.debug("'{}' is not applicable for plugin '{}'", finder, pluginPath);
+ }
+ }
+
+ throw new PluginException("No PluginDescriptorFinder for plugin '{}'", pluginPath);
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginLoader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginLoader.java
new file mode 100644
index 0000000..84f505b
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginLoader.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2017 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Decebal Suiu
+ */
+public class CompoundPluginLoader implements PluginLoader {
+
+ private static final Logger log = LoggerFactory.getLogger(CompoundPluginLoader.class);
+
+ private List<PluginLoader> loaders = new ArrayList<>();
+
+ public CompoundPluginLoader add(PluginLoader loader) {
+ if (loader == null) {
+ throw new IllegalArgumentException("null not allowed");
+ }
+
+ loaders.add(loader);
+
+ return this;
+ }
+
+ public int size() {
+ return loaders.size();
+ }
+
+ @Override
+ public boolean isApplicable(Path pluginPath) {
+ for (PluginLoader loader : loaders) {
+ if (loader.isApplicable(pluginPath)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) {
+ for (PluginLoader loader : loaders) {
+ if (loader.isApplicable(pluginPath)) {
+ log.debug("'{}' is applicable for plugin '{}'", loader, pluginPath);
+ try {
+ ClassLoader classLoader = loader.loadPlugin(pluginPath, pluginDescriptor);
+ if (classLoader != null) {
+ return classLoader;
+ }
+ } catch (Exception e) {
+ // log the exception and continue with the next loader
+ log.error(e.getMessage()); // ?!
+ }
+ } else {
+ log.debug("'{}' is not applicable for plugin '{}'", loader, pluginPath);
+ }
+ }
+
+ throw new RuntimeException("No PluginLoader for plugin '" + pluginPath + "' and descriptor '" + pluginDescriptor + "'");
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginRepository.java
new file mode 100644
index 0000000..419d530
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundPluginRepository.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Decebal Suiu
+ * @author Mário Franco
+ */
+public class CompoundPluginRepository implements PluginRepository {
+
+ private List<PluginRepository> repositories = new ArrayList<>();
+
+ public CompoundPluginRepository add(PluginRepository repository) {
+ if (repository == null) {
+ throw new IllegalArgumentException("null not allowed");
+ }
+
+ repositories.add(repository);
+
+ return this;
+ }
+
+ @Override
+ public List<Path> getPluginPaths() {
+ List<Path> paths = new ArrayList<>();
+ for (PluginRepository repository : repositories) {
+ paths.addAll(repository.getPluginPaths());
+ }
+
+ return paths;
+ }
+
+ @Override
+ public boolean deletePluginPath(Path pluginPath) {
+ for (PluginRepository repository : repositories) {
+ if (repository.deletePluginPath(pluginPath)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundVerifier.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundVerifier.java
new file mode 100644
index 0000000..be804cf
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/CompoundVerifier.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class CompoundVerifier implements FileVerifier {
+ /**
+ * Default list of verifiers
+ */
+ public static final List<FileVerifier> ALL_DEFAULT_FILE_VERIFIERS = Arrays.asList(
+ new BasicVerifier(),
+ new Sha512SumVerifier());
+
+ private List<FileVerifier> verifiers = new ArrayList<>();
+
+ /**
+ * Default constructor which will add the default verifiers to start with
+ */
+ public CompoundVerifier() {
+ setVerifiers(ALL_DEFAULT_FILE_VERIFIERS);
+ }
+
+ /**
+ * Constructs a Compound verifier using the supplied list of verifiers instead of the default ones
+ * @param verifiers the list of verifiers to apply
+ */
+ public CompoundVerifier(List<FileVerifier> verifiers) {
+ this.verifiers = verifiers;
+ }
+
+ /**
+ * Verifies a plugin release using all configured {@link FileVerifier}s
+ *
+ * @param context the file verifier context object
+ * @param file the path to the downloaded file itself
+ * @throws IOException if there was a problem accessing file
+ * @throws VerifyException in case of problems verifying the file
+ */
+ @Override
+ public void verify(Context context, Path file) throws IOException, VerifyException {
+ for (FileVerifier verifier : getVerifiers()) {
+ verifier.verify(context, file);
+ }
+ }
+
+ public List<FileVerifier> getVerifiers() {
+ return verifiers;
+ }
+
+ public void setVerifiers(List<FileVerifier> verifiers) {
+ this.verifiers = verifiers;
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultExtensionFactory.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultExtensionFactory.java
new file mode 100644
index 0000000..c6d913e
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultExtensionFactory.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The default implementation for ExtensionFactory.
+ * It uses Class.newInstance() method.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultExtensionFactory implements ExtensionFactory {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultExtensionFactory.class);
+
+ /**
+ * Creates an extension instance. If an error occurs than that error is logged and the method returns null.
+ */
+ @Override
+ public Object create(Class<?> extensionClass) {
+ log.debug("Create instance for extension '{}'", extensionClass.getName());
+ try {
+ return extensionClass.newInstance();
+ } catch (Exception e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return null;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultExtensionFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultExtensionFinder.java
new file mode 100644
index 0000000..ffb1dc3
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultExtensionFinder.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2013 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * The default implementation for {@link ExtensionFinder}.
+ * It's a compound {@code ExtensionFinder}.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultExtensionFinder implements ExtensionFinder, PluginStateListener {
+
+ protected PluginManager pluginManager;
+ protected List<ExtensionFinder> finders = new ArrayList<>();
+
+ public DefaultExtensionFinder(PluginManager pluginManager) {
+ this.pluginManager = pluginManager;
+
+ add(new LegacyExtensionFinder(pluginManager));
+// add(new ServiceProviderExtensionFinder(pluginManager));
+ }
+
+ @Override
+ public <T> List<ExtensionWrapper<T>> find(Class<T> type) {
+ List<ExtensionWrapper<T>> extensions = new ArrayList<>();
+ for (ExtensionFinder finder : finders) {
+ extensions.addAll(finder.find(type));
+ }
+
+ return extensions;
+ }
+
+ @Override
+ public <T> List<ExtensionWrapper<T>> find(Class<T> type, String pluginId) {
+ List<ExtensionWrapper<T>> extensions = new ArrayList<>();
+ for (ExtensionFinder finder : finders) {
+ extensions.addAll(finder.find(type, pluginId));
+ }
+
+ return extensions;
+ }
+
+ @Override
+ public List<ExtensionWrapper> find(String pluginId) {
+ List<ExtensionWrapper> extensions = new ArrayList<>();
+ for (ExtensionFinder finder : finders) {
+ extensions.addAll(finder.find(pluginId));
+ }
+
+ return extensions;
+ }
+
+ @Override
+ public Set<String> findClassNames(String pluginId) {
+ Set<String> classNames = new HashSet<>();
+ for (ExtensionFinder finder : finders) {
+ classNames.addAll(finder.findClassNames(pluginId));
+ }
+
+ return classNames;
+ }
+
+ @Override
+ public void pluginStateChanged(PluginStateEvent event) {
+ for (ExtensionFinder finder : finders) {
+ if (finder instanceof PluginStateListener) {
+ ((PluginStateListener) finder).pluginStateChanged(event);
+ }
+ }
+ }
+
+ public DefaultExtensionFinder addServiceProviderExtensionFinder() {
+ return add(new ServiceProviderExtensionFinder(pluginManager));
+ }
+
+ public DefaultExtensionFinder add(ExtensionFinder finder) {
+ finders.add(finder);
+
+ return this;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginClasspath.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginClasspath.java
new file mode 100644
index 0000000..64a8d13
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginClasspath.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2016 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * The default values are {@code classes} and {@code lib}.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultPluginClasspath extends PluginClasspath {
+
+ public DefaultPluginClasspath() {
+ super();
+
+ addClassesDirectories("classes");
+ addLibDirectories("lib");
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginDescriptor.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginDescriptor.java
new file mode 100644
index 0000000..78e4c9a
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginDescriptor.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Decebal Suiu
+ */
+public class DefaultPluginDescriptor implements PluginDescriptor {
+
+ private String pluginId;
+ private String pluginDescription;
+ private String pluginClass;
+ private String version;
+ private String requires = "*"; // SemVer format
+ private String provider;
+ private List<PluginDependency> dependencies;
+ private String license;
+
+ public DefaultPluginDescriptor() {
+ dependencies = new ArrayList<>();
+ }
+
+ public DefaultPluginDescriptor(String pluginId, String pluginDescription, String pluginClass, String version, String requires, String provider, String license) {
+ this();
+ this.pluginId = pluginId;
+ this.pluginDescription = pluginDescription;
+ this.pluginClass = pluginClass;
+ this.version = version;
+ this.requires = requires;
+ this.provider = provider;
+ this.license = license;
+ }
+
+ public void addDependency(PluginDependency dependency) {
+ this.dependencies.add(dependency);
+ }
+
+ /**
+ * Returns the unique identifier of this plugin.
+ */
+ @Override
+ public String getPluginId() {
+ return pluginId;
+ }
+
+ /**
+ * Returns the description of this plugin.
+ */
+ @Override
+ public String getPluginDescription() {
+ return pluginDescription;
+ }
+
+ /**
+ * Returns the name of the class that implements Plugin interface.
+ */
+ @Override
+ public String getPluginClass() {
+ return pluginClass;
+ }
+
+ /**
+ * Returns the version of this plugin.
+ */
+ @Override
+ public String getVersion() {
+ return version;
+ }
+
+ /**
+ * Returns string version of requires
+ *
+ * @return String with requires expression on SemVer format
+ */
+ @Override
+ public String getRequires() {
+ return requires;
+ }
+
+ /**
+ * Returns the provider name of this plugin.
+ */
+ @Override
+ public String getProvider() {
+ return provider;
+ }
+
+ /**
+ * Returns the legal license of this plugin, e.g. "Apache-2.0", "MIT" etc
+ */
+ @Override
+ public String getLicense() {
+ return license;
+ }
+
+ /**
+ * Returns all dependencies declared by this plugin.
+ * Returns an empty array if this plugin does not declare any require.
+ */
+ @Override
+ public List<PluginDependency> getDependencies() {
+ return dependencies;
+ }
+
+ @Override
+ public String toString() {
+ return "PluginDescriptor [pluginId=" + pluginId + ", pluginClass="
+ + pluginClass + ", version=" + version + ", provider="
+ + provider + ", dependencies=" + dependencies + ", description="
+ + pluginDescription + ", requires=" + requires + ", license="
+ + license + "]";
+ }
+
+ protected DefaultPluginDescriptor setPluginId(String pluginId) {
+ this.pluginId = pluginId;
+
+ return this;
+ }
+
+ protected PluginDescriptor setPluginDescription(String pluginDescription) {
+ this.pluginDescription = pluginDescription;
+
+ return this;
+ }
+
+ protected PluginDescriptor setPluginClass(String pluginClassName) {
+ this.pluginClass = pluginClassName;
+
+ return this;
+ }
+
+
+ protected DefaultPluginDescriptor setPluginVersion(String version) {
+ this.version = version;
+
+ return this;
+ }
+
+ protected PluginDescriptor setProvider(String provider) {
+ this.provider = provider;
+
+ return this;
+ }
+
+ protected PluginDescriptor setRequires(String requires) {
+ this.requires = requires;
+
+ return this;
+ }
+
+ protected PluginDescriptor setDependencies(String dependencies) {
+ if (dependencies != null) {
+ dependencies = dependencies.trim();
+ if (dependencies.isEmpty()) {
+ this.dependencies = Collections.emptyList();
+ } else {
+ this.dependencies = new ArrayList<>();
+ String[] tokens = dependencies.split(",");
+ for (String dependency : tokens) {
+ dependency = dependency.trim();
+ if (!dependency.isEmpty()) {
+ this.dependencies.add(new PluginDependency(dependency));
+ }
+ }
+ if (this.dependencies.isEmpty()) {
+ this.dependencies = Collections.emptyList();
+ }
+ }
+ } else {
+ this.dependencies = Collections.emptyList();
+ }
+
+ return this;
+ }
+
+ public PluginDescriptor setLicense(String license) {
+ this.license = license;
+
+ return this;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginFactory.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginFactory.java
new file mode 100644
index 0000000..816ad5b
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginFactory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+
+/**
+ * The default implementation for {@link PluginFactory}.
+ * It uses {@link Class#newInstance()} method.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultPluginFactory implements PluginFactory {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultExtensionFactory.class);
+
+ /**
+ * Creates a plugin instance. If an error occurs than that error is logged and the method returns null.
+ */
+ @Override
+ public Plugin create(final PluginWrapper pluginWrapper) {
+ String pluginClassName = pluginWrapper.getDescriptor().getPluginClass();
+ log.debug("Create instance for plugin '{}'", pluginClassName);
+
+ Class<?> pluginClass;
+ try {
+ pluginClass = pluginWrapper.getPluginClassLoader().loadClass(pluginClassName);
+ } catch (ClassNotFoundException e) {
+ log.error(e.getMessage(), e);
+ return null;
+ }
+
+ // once we have the class, we can do some checks on it to ensure
+ // that it is a valid implementation of a plugin.
+ int modifiers = pluginClass.getModifiers();
+ if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)
+ || (!Plugin.class.isAssignableFrom(pluginClass))) {
+ log.error("The plugin class '{}' is not valid", pluginClassName);
+ return null;
+ }
+
+ // create the plugin instance
+ try {
+ Constructor<?> constructor = pluginClass.getConstructor(PluginWrapper.class);
+ return (Plugin) constructor.newInstance(pluginWrapper);
+ } catch (Exception e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return null;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginLoader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginLoader.java
new file mode 100644
index 0000000..8a6514d
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginLoader.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2016 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+ * Load all information needed by a plugin.
+ * This means add to classpath all jar files from {@code lib} directory
+ * and all class files from {@code classes}.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultPluginLoader implements PluginLoader {
+
+ protected PluginManager pluginManager;
+ protected PluginClasspath pluginClasspath;
+
+ public DefaultPluginLoader(PluginManager pluginManager, PluginClasspath pluginClasspath) {
+ this.pluginManager = pluginManager;
+ this.pluginClasspath = pluginClasspath;
+ }
+
+ @Override
+ public boolean isApplicable(Path pluginPath) {
+ return Files.exists(pluginPath) && Files.isDirectory(pluginPath);
+ }
+
+ @Override
+ public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) {
+ PluginClassLoader pluginClassLoader = createPluginClassLoader(pluginPath, pluginDescriptor);
+
+ loadClasses(pluginPath, pluginClassLoader);
+ loadJars(pluginPath, pluginClassLoader);
+
+ return pluginClassLoader;
+ }
+
+ protected PluginClassLoader createPluginClassLoader(Path pluginPath, PluginDescriptor pluginDescriptor) {
+ return new PluginClassLoader(pluginManager, pluginDescriptor, getClass().getClassLoader());
+ }
+
+ /**
+ * Add all {@code *.class} files from {@code classes} directories to plugin class loader.
+ */
+ protected void loadClasses(Path pluginPath, PluginClassLoader pluginClassLoader) {
+ for (String directory : pluginClasspath.getClassesDirectories()) {
+ File file = pluginPath.resolve(directory).toFile();
+ if (file.exists() && file.isDirectory()) {
+ pluginClassLoader.addFile(file);
+ }
+ }
+ }
+
+ /**
+ * Add all {@code *.jar} files from {@code lib} directories to plugin class loader.
+ */
+ protected void loadJars(Path pluginPath, PluginClassLoader pluginClassLoader) {
+ for (String libDirectory : pluginClasspath.getLibDirectories()) {
+ Path file = pluginPath.resolve(libDirectory);
+ List<File> jars = FileUtils.getJars(file);
+ for (File jar : jars) {
+ pluginClassLoader.addFile(jar);
+ }
+ }
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginManager.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginManager.java
new file mode 100644
index 0000000..c2ac174
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginManager.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.nio.file.Path;
+
+/**
+ * Default implementation of the {@link PluginManager} interface.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultPluginManager extends AbstractPluginManager {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultPluginManager.class);
+
+ protected PluginClasspath pluginClasspath;
+
+ public DefaultPluginManager() {
+ super();
+ }
+
+ /**
+ * Use {@link DefaultPluginManager#DefaultPluginManager(Path)}.
+ */
+ @Deprecated
+ public DefaultPluginManager(File pluginsDir) {
+ this(pluginsDir.toPath());
+ }
+
+ public DefaultPluginManager(Path pluginsRoot) {
+ super(pluginsRoot);
+ }
+
+ @Override
+ protected PluginDescriptorFinder createPluginDescriptorFinder() {
+ return new CompoundPluginDescriptorFinder()
+ .add(new PropertiesPluginDescriptorFinder())
+ .add(new ManifestPluginDescriptorFinder());
+ }
+
+ @Override
+ protected ExtensionFinder createExtensionFinder() {
+ DefaultExtensionFinder extensionFinder = new DefaultExtensionFinder(this);
+ addPluginStateListener(extensionFinder);
+
+ return extensionFinder;
+ }
+
+ @Override
+ protected PluginFactory createPluginFactory() {
+ return new DefaultPluginFactory();
+ }
+
+ @Override
+ protected ExtensionFactory createExtensionFactory() {
+ return new DefaultExtensionFactory();
+ }
+
+ @Override
+ protected PluginStatusProvider createPluginStatusProvider() {
+ return new DefaultPluginStatusProvider(getPluginsRoot());
+ }
+
+ @Override
+ protected PluginRepository createPluginRepository() {
+ return new CompoundPluginRepository()
+ .add(new DefaultPluginRepository(getPluginsRoot(), isDevelopment()))
+ .add(new JarPluginRepository(getPluginsRoot()));
+ }
+
+ @Override
+ protected PluginLoader createPluginLoader() {
+ return new CompoundPluginLoader()
+ .add(new DefaultPluginLoader(this, pluginClasspath))
+ .add(new JarPluginLoader(this));
+ }
+
+ @Override
+ protected VersionManager createVersionManager() {
+ return new DefaultVersionManager();
+ }
+
+ /**
+ * By default if {@link DefaultPluginManager#isDevelopment()} returns true
+ * than a {@link DevelopmentPluginClasspath} is returned
+ * else this method returns {@link DefaultPluginClasspath}.
+ */
+ protected PluginClasspath createPluginClasspath() {
+ return isDevelopment() ? new DevelopmentPluginClasspath() : new DefaultPluginClasspath();
+ }
+
+ @Override
+ protected void initialize() {
+ pluginClasspath = createPluginClasspath();
+
+ super.initialize();
+
+ if (isDevelopment()) {
+ addPluginStateListener(new LoggingPluginStateListener());
+ }
+
+ log.info("PF4J version {} in '{}' mode", getVersion(), getRuntimeMode());
+ }
+
+ /**
+ * Load a plugin from disk. If the path is a zip file, first unpack
+ * @param pluginPath plugin location on disk
+ * @return PluginWrapper for the loaded plugin or null if not loaded
+ * @throws PluginException if problems during load
+ */
+ @Override
+ protected PluginWrapper loadPluginFromPath(Path pluginPath) throws PluginException {
+ // First unzip any ZIP files
+ try {
+ pluginPath = FileUtils.expandIfZip(pluginPath);
+ } catch (Exception e) {
+ log.warn("Failed to unzip " + pluginPath, e);
+ return null;
+ }
+
+ return super.loadPluginFromPath(pluginPath);
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginRepository.java
new file mode 100644
index 0000000..5306ae3
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginRepository.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.AndFileFilter;
+import org.pf4j.util.DirectoryFileFilter;
+import org.pf4j.util.FileUtils;
+import org.pf4j.util.HiddenFilter;
+import org.pf4j.util.NotFileFilter;
+import org.pf4j.util.OrFileFilter;
+import org.pf4j.util.ZipFileFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.pf4j.util.NameFileFilter;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+ * @author Decebal Suiu
+ */
+public class DefaultPluginRepository extends BasePluginRepository {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultPluginRepository.class);
+
+ public DefaultPluginRepository(Path pluginsRoot, boolean development) {
+ super(pluginsRoot);
+
+ AndFileFilter pluginsFilter = new AndFileFilter(new DirectoryFileFilter());
+ pluginsFilter.addFileFilter(new NotFileFilter(createHiddenPluginFilter(development)));
+ setFilter(pluginsFilter);
+ }
+
+ @Override
+ public List<Path> getPluginPaths() {
+ // expand plugins zip files
+ File[] pluginZips = pluginsRoot.toFile().listFiles(new ZipFileFilter());
+ if ((pluginZips != null) && pluginZips.length > 0) {
+ for (File pluginZip : pluginZips) {
+ try {
+ FileUtils.expandIfZip(pluginZip.toPath());
+ } catch (IOException e) {
+ log.error("Cannot expand plugin zip '{}'", pluginZip);
+ log.error(e.getMessage(), e);
+ }
+ }
+ }
+
+ return super.getPluginPaths();
+ }
+
+ @Override
+ public boolean deletePluginPath(Path pluginPath) {
+ FileUtils.optimisticDelete(FileUtils.findWithEnding(pluginPath, ".zip", ".ZIP", ".Zip"));
+ return super.deletePluginPath(pluginPath);
+ }
+
+ protected FileFilter createHiddenPluginFilter(boolean development) {
+ OrFileFilter hiddenPluginFilter = new OrFileFilter(new HiddenFilter());
+
+ if (development) {
+ hiddenPluginFilter.addFileFilter(new NameFileFilter("target"));
+ }
+
+ return hiddenPluginFilter;
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginStatusProvider.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginStatusProvider.java
new file mode 100644
index 0000000..d16e8e5
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultPluginStatusProvider.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+ * The default implementation for {@link PluginStatusProvider}.
+ *
+ * @author Decebal Suiu
+ * @author Mário Franco
+ */
+public class DefaultPluginStatusProvider implements PluginStatusProvider {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultPluginStatusProvider.class);
+
+ private final Path pluginsRoot;
+
+ private List<String> enabledPlugins;
+ private List<String> disabledPlugins;
+
+ public DefaultPluginStatusProvider(Path pluginsRoot) {
+ this.pluginsRoot = pluginsRoot;
+
+ initialize();
+ }
+
+ private void initialize() {
+ try {
+ // create a list with plugin identifiers that should be only accepted by this manager (whitelist from plugins/enabled.txt file)
+ enabledPlugins = FileUtils.readLines(pluginsRoot.resolve("enabled.txt"), true);
+ log.info("Enabled plugins: {}", enabledPlugins);
+
+ // create a list with plugin identifiers that should not be accepted by this manager (blacklist from plugins/disabled.txt file)
+ disabledPlugins = FileUtils.readLines(pluginsRoot.resolve("disabled.txt"), true);
+ log.info("Disabled plugins: {}", disabledPlugins);
+ } catch (IOException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public boolean isPluginDisabled(String pluginId) {
+ if (disabledPlugins.contains(pluginId)) {
+ return true;
+ }
+
+ return !enabledPlugins.isEmpty() && !enabledPlugins.contains(pluginId);
+ }
+
+ @Override
+ public boolean disablePlugin(String pluginId) {
+ if (disabledPlugins.add(pluginId)) {
+ try {
+ FileUtils.writeLines(disabledPlugins, pluginsRoot.resolve("disabled.txt").toFile());
+ } catch (IOException e) {
+ log.error("Failed to disable plugin {}", pluginId, e);
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean enablePlugin(String pluginId) {
+ try {
+ if (disabledPlugins.remove(pluginId)) {
+ FileUtils.writeLines(disabledPlugins, pluginsRoot.resolve("disabled.txt").toFile());
+ }
+ } catch (IOException e) {
+ log.error("Failed to enable plugin {}", pluginId, e);
+ return false;
+ }
+
+ return true;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultUpdateRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultUpdateRepository.java
new file mode 100644
index 0000000..81efb2f
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultUpdateRepository.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import org.apache.solr.packagemanager.pf4j.PluginInfo.PluginRelease;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.*;
+
+/**
+ * The default implementation of {@link UpdateRepository}.
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultUpdateRepository implements UpdateRepository {
+
+ private static final String DEFAULT_PLUGINS_JSON_FILENAME = "plugins.json";
+ private static final Logger log = LoggerFactory.getLogger(DefaultUpdateRepository.class);
+
+ private String id;
+ private URL url;
+ private String pluginsJsonFileName;
+
+ private Map<String, PluginInfo> plugins;
+
+ /**
+ * Instantiates a new default update repository. The default plugins JSON file
+ * name {@code plugins.json} will be used. Please use
+ * {@link #DefaultUpdateRepository(String, URL, String)} if you want to choose
+ * another file name than {@code plugins.json}}.
+ *
+ * @param id the repository id
+ * @param url the repository url
+ */
+ public DefaultUpdateRepository(String id, URL url) {
+ this(id, url, DEFAULT_PLUGINS_JSON_FILENAME);
+ }
+
+ public DefaultUpdateRepository(String id, URL url, String pluginsJsonFileName) {
+ this.id = id;
+ this.url = url;
+ this.pluginsJsonFileName = pluginsJsonFileName;
+ }
+
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ @Override
+ public URL getUrl() {
+ return url;
+ }
+
+ @Override
+ public Map<String, PluginInfo> getPlugins() {
+ if (plugins == null) {
+ initPlugins();
+ }
+
+ return plugins;
+ }
+
+ @Override
+ public PluginInfo getPlugin(String id) {
+ return getPlugins().get(id);
+ }
+
+ private void initPlugins() {
+ Reader pluginsJsonReader;
+ try {
+ URL pluginsUrl = new URL(getUrl(), getPluginsJsonFileName());
+ log.debug("Read plugins of '{}' repository from '{}'", id, pluginsUrl);
+ pluginsJsonReader = new InputStreamReader(pluginsUrl.openStream());
+ } catch (Exception e) {
+ log.error(e.getMessage(), e);
+ plugins = Collections.emptyMap();
+ return;
+ }
+
+ Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new LenientDateTypeAdapter()).create();
+ PluginInfo[] items = gson.fromJson(pluginsJsonReader, PluginInfo[].class);
+ plugins = new HashMap<>(items.length);
+ for (PluginInfo p : items) {
+ for (PluginRelease r : p.releases) {
+ try {
+ r.url = new URL(getUrl(), r.url).toString();
+ if (r.date.getTime() == 0) {
+ log.warn("Illegal release date when parsing {}@{}, setting to epoch", p.id, r.version);
+ }
+ } catch (MalformedURLException e) {
+ log.warn("Skipping release {} of plugin {} due to failure to build valid absolute URL. Url was {}{}", r.version, p.id, getUrl(), r.url);
+ }
+ }
+ p.setRepositoryId(getId());
+ plugins.put(p.id, p);
+ }
+ log.debug("Found {} plugins in repository '{}'", plugins.size(), id);
+ }
+
+ /**
+ * Causes {@code plugins.json} to be read again to look for new updates from repositories.
+ */
+ @Override
+ public void refresh() {
+ plugins = null;
+ }
+
+ @Override
+ public FileDownloader getFileDownloader() {
+ return new SimpleFileDownloader();
+ }
+
+ /**
+ * Gets a file verifier to execute on the downloaded file for it to be claimed valid.
+ * May be a CompoundVerifier in order to chain several verifiers.
+ * @return list of {@link FileVerifier}s
+ */
+ @Override
+ public FileVerifier getFileVerfier() {
+ return new CompoundVerifier();
+ }
+
+ /**
+ * Gets the plugins json file name. Returns {@code plugins.json} if null.
+ *
+ * @return the plugins json file name
+ */
+ public String getPluginsJsonFileName() {
+ if (pluginsJsonFileName == null) {
+ pluginsJsonFileName = DEFAULT_PLUGINS_JSON_FILENAME;
+ }
+
+ return pluginsJsonFileName;
+ }
+
+ /**
+ * Choose another file name than {@code plugins.json}.
+ *
+ * @param pluginsJsonFileName the name (relative) of plugins.json file.
+ * If null, will default to {@code plugins.json}
+ */
+ public void setPluginsJsonFileName(String pluginsJsonFileName) {
+ this.pluginsJsonFileName = pluginsJsonFileName;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultVersionManager.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultVersionManager.java
new file mode 100644
index 0000000..9c0b4d0
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DefaultVersionManager.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2017 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import com.github.zafarkhaja.semver.Version;
+import com.github.zafarkhaja.semver.expr.Expression;
+import org.pf4j.util.StringUtils;
+
+/**
+ * Default implementation for {@link VersionManager}.
+ * This implementation uses jSemVer (a Java implementation of the SemVer Specification).
+ *
+ * @author Decebal Suiu
+ */
+public class DefaultVersionManager implements VersionManager {
+
+ /**
+ * Checks if a version satisfies the specified SemVer {@link Expression} string.
+ * If the constraint is empty or null then the method returns true.
+ * Constraint examples: {@code >2.0.0} (simple), {@code ">=1.4.0 & <1.6.0"} (range).
+ * See https://github.com/zafarkhaja/jsemver#semver-expressions-api-ranges for more info.
+ *
+ */
+ @Override
+ public boolean checkVersionConstraint(String version, String constraint) {
+ return StringUtils.isNullOrEmpty(constraint) || Version.valueOf(version).satisfies(constraint);
+ }
+
+ @Override
+ public int compareVersions(String v1, String v2) {
+ return Version.valueOf(v1).compareTo(Version.valueOf(v2));
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DependencyResolver.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DependencyResolver.java
new file mode 100644
index 0000000..cd5b690
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DependencyResolver.java
@@ -0,0 +1,302 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.pf4j.util.DirectedGraph;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This class builds a dependency graph for a list of plugins (descriptors).
+ * The entry point is the {@link #resolve(List)} method, method that returns a {@link Result} object.
+ * The {@code Result} class contains nice information about the result of resolve operation (if it's a cyclic dependency,
+ * they are not found dependencies, they are dependencies with wrong version).
+ * This class is very useful for if-else scenarios.
+ *
+ * Only some attributes (pluginId, dependencies and pluginVersion) from {@link PluginDescriptor} are used in
+ * the process of {@code resolve} operation.
+ *
+ * @author Decebal Suiu
+ */
+public class DependencyResolver {
+
+ private static final Logger log = LoggerFactory.getLogger(DependencyResolver.class);
+
+ private VersionManager versionManager;
+
+ private DirectedGraph<String> dependenciesGraph; // the value is 'pluginId'
+ private DirectedGraph<String> dependentsGraph; // the value is 'pluginId'
+ private boolean resolved;
+
+ public DependencyResolver(VersionManager versionManager) {
+ this.versionManager = versionManager;
+ }
+
+ public Result resolve(List<PluginDescriptor> plugins) {
+ // create graphs
+ dependenciesGraph = new DirectedGraph<>();
+ dependentsGraph = new DirectedGraph<>();
+
+ // populate graphs
+ Map<String, PluginDescriptor> pluginByIds = new HashMap<>();
+ for (PluginDescriptor plugin : plugins) {
+ addPlugin(plugin);
+ pluginByIds.put(plugin.getPluginId(), plugin);
+ }
+
+ log.debug("Graph: {}", dependenciesGraph);
+
+ // get a sorted list of dependencies
+ List<String> sortedPlugins = dependenciesGraph.reverseTopologicalSort();
+ log.debug("Plugins order: {}", sortedPlugins);
+
+ // create the result object
+ Result result = new Result(sortedPlugins);
+
+ resolved = true;
+
+ if (sortedPlugins != null) { // no cyclic dependency
+ // detect not found dependencies
+ for (String pluginId : sortedPlugins) {
+ if (!pluginByIds.containsKey(pluginId)) {
+ result.addNotFoundDependency(pluginId);
+ }
+ }
+ }
+
+ // check dependencies versions
+ for (PluginDescriptor plugin : plugins) {
+ String pluginId = plugin.getPluginId();
+ String existingVersion = plugin.getVersion();
+
+ List<String> dependents = getDependents(pluginId);
+ while (!dependents.isEmpty()) {
+ String dependentId = dependents.remove(0);
+ PluginDescriptor dependent = pluginByIds.get(dependentId);
+ String requiredVersion = getDependencyVersionSupport(dependent, pluginId);
+ boolean ok = checkDependencyVersion(requiredVersion, existingVersion);
+ if (!ok) {
+ result.addWrongDependencyVersion(new WrongDependencyVersion(pluginId, dependentId, existingVersion, requiredVersion));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Retrieves the plugins ids that the given plugin id directly depends on.
+ *
+ */
+ public List<String> getDependencies(String pluginId) {
+ checkResolved();
+ return dependenciesGraph.getNeighbors(pluginId);
+ }
+
+ /**
+ * Retrieves the plugins ids that the given content is a direct dependency of.
+ *
+ */
+ public List<String> getDependents(String pluginId) {
+ checkResolved();
+ return dependentsGraph.getNeighbors(pluginId);
+ }
+
+ /**
+ * Check if an existing version of dependency is compatible with the required version (from plugin descriptor).
+ *
+ */
+ protected boolean checkDependencyVersion(String requiredVersion, String existingVersion) {
+ return versionManager.checkVersionConstraint(existingVersion, requiredVersion);
+ }
+
+ private void addPlugin(PluginDescriptor descriptor) {
+ String pluginId = descriptor.getPluginId();
+ List<PluginDependency> dependencies = descriptor.getDependencies();
+ if (dependencies.isEmpty()) {
+ dependenciesGraph.addVertex(pluginId);
+ dependentsGraph.addVertex(pluginId);
+ } else {
+ for (PluginDependency dependency : dependencies) {
+ dependenciesGraph.addEdge(pluginId, dependency.getPluginId());
+ dependentsGraph.addEdge(dependency.getPluginId(), pluginId);
+ }
+ }
+ }
+
+ private void checkResolved() {
+ if (!resolved) {
+ throw new IllegalStateException("Call 'resolve' method first");
+ }
+ }
+
+ private String getDependencyVersionSupport(PluginDescriptor dependent, String dependencyId) {
+ List<PluginDependency> dependencies = dependent.getDependencies();
+ for (PluginDependency dependency : dependencies) {
+ if (dependencyId.equals(dependency.getPluginId())) {
+ return dependency.getPluginVersionSupport();
+ }
+ }
+
+ throw new IllegalStateException("Cannot find a dependency with id '" + dependencyId +
+ "' for plugin '" + dependent.getPluginId() + "'");
+ }
+
+ public static class Result {
+
+ private boolean cyclicDependency;
+ private List<String> notFoundDependencies; // value is "pluginId"
+ private List<String> sortedPlugins; // value is "pluginId"
+ private List<WrongDependencyVersion> wrongVersionDependencies;
+
+ Result(List<String> sortedPlugins) {
+ if (sortedPlugins == null) {
+ cyclicDependency = true;
+ this.sortedPlugins = Collections.emptyList();
+ } else {
+ this.sortedPlugins = new ArrayList<>(sortedPlugins);
+ }
+
+ notFoundDependencies = new ArrayList<>();
+ wrongVersionDependencies = new ArrayList<>();
+ }
+
+ /**
+ * Returns true is a cyclic dependency was detected.
+ */
+ public boolean hasCyclicDependency() {
+ return cyclicDependency;
+ }
+
+ /**
+ * Returns a list with dependencies required that were not found.
+ */
+ public List<String> getNotFoundDependencies() {
+ return notFoundDependencies;
+ }
+
+ /**
+ * Returns a list with dependencies with wrong version.
+ */
+ public List<WrongDependencyVersion> getWrongVersionDependencies() {
+ return wrongVersionDependencies;
+ }
+
+ /**
+ * Get the list of plugins in dependency sorted order.
+ */
+ public List<String> getSortedPlugins() {
+ return sortedPlugins;
+ }
+
+ void addNotFoundDependency(String pluginId) {
+ notFoundDependencies.add(pluginId);
+ }
+
+ void addWrongDependencyVersion(WrongDependencyVersion wrongDependencyVersion) {
+ wrongVersionDependencies.add(wrongDependencyVersion);
+ }
+
+ }
+
+ public static class WrongDependencyVersion {
+
+ private String dependencyId; // value is "pluginId"
+ private String dependentId; // value is "pluginId"
+ private String existingVersion;
+ private String requiredVersion;
+
+ WrongDependencyVersion(String dependencyId, String dependentId, String existingVersion, String requiredVersion) {
+ this.dependencyId = dependencyId;
+ this.dependentId = dependentId;
+ this.existingVersion = existingVersion;
+ this.requiredVersion = requiredVersion;
+ }
+
+ public String getDependencyId() {
+ return dependencyId;
+ }
+
+ public String getDependentId() {
+ return dependentId;
+ }
+
+ public String getExistingVersion() {
+ return existingVersion;
+ }
+
+ public String getRequiredVersion() {
+ return requiredVersion;
+ }
+
+ }
+
+ /**
+ * It will be thrown if a cyclic dependency is detected.
+ */
+ public static class CyclicDependencyException extends PluginException {
+
+ public CyclicDependencyException() {
+ super("Cyclic dependencies");
+ }
+
+ }
+
+ /**
+ * Indicates that the dependencies required were not found.
+ */
+ public static class DependenciesNotFoundException extends PluginException {
+
+ private List<String> dependencies;
+
+ public DependenciesNotFoundException(List<String> dependencies) {
+ super("Dependencies '{}' not found", dependencies);
+
+ this.dependencies = dependencies;
+ }
+
+ public List<String> getDependencies() {
+ return dependencies;
+ }
+
+ }
+
+ /**
+ * Indicates that some dependencies have wrong version.
+ */
+ public static class DependenciesWrongVersionException extends PluginException {
+
+ private List<WrongDependencyVersion> dependencies;
+
+ public DependenciesWrongVersionException(List<WrongDependencyVersion> dependencies) {
+ super("Dependencies '{}' have wrong version", dependencies);
+
+ this.dependencies = dependencies;
+ }
+
+ public List<WrongDependencyVersion> getDependencies() {
+ return dependencies;
+ }
+
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DevelopmentPluginClasspath.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DevelopmentPluginClasspath.java
new file mode 100644
index 0000000..af1a2f3
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/DevelopmentPluginClasspath.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2013 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * Overwrite classes directories to {@code target/classes} and lib directories to {@code target/lib}.
+ *
+ * @author Decebal Suiu
+ */
+public class DevelopmentPluginClasspath extends PluginClasspath {
+
+ public DevelopmentPluginClasspath() {
+ super();
+
+ addClassesDirectories("target/classes");
+ addLibDirectories("target/lib");
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Extension.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Extension.java
new file mode 100644
index 0000000..9f3b094
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Extension.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+/**
+ * @author Decebal Suiu
+ */
+@Retention(RUNTIME)
+@Target(TYPE)
+@Inherited
+@Documented
+public @interface Extension {
+
+ int ordinal() default 0;
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionDescriptor.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionDescriptor.java
new file mode 100644
index 0000000..487fdaa
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionDescriptor.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * @author Decebal Suiu
+ */
+public class ExtensionDescriptor {
+
+ public final int ordinal;
+ public final Class<?> extensionClass;
+
+ public ExtensionDescriptor(int ordinal, Class<?> extensionClass) {
+ this.ordinal = ordinal;
+ this.extensionClass = extensionClass;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionFactory.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionFactory.java
new file mode 100644
index 0000000..a8b402f
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionFactory.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * Creates an extension instance.
+ */
+public interface ExtensionFactory {
+
+ Object create(Class<?> extensionClass);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionFinder.java
new file mode 100644
index 0000000..9663288
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionFinder.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * @author Decebal Suiu
+ */
+public interface ExtensionFinder {
+
+ /**
+ * Retrieves a list with all extensions found for an extension point.
+ */
+ <T> List<ExtensionWrapper<T>> find(Class<T> type);
+
+ /**
+ * Retrieves a list with all extensions found for an extension point and a plugin.
+ */
+ <T> List<ExtensionWrapper<T>> find(Class<T> type, String pluginId);
+
+ /**
+ * Retrieves a list with all extensions found for a plugin
+ */
+ List<ExtensionWrapper> find(String pluginId);
+
+ /**
+ * Retrieves a list with all extension class names found for a plugin.
+ */
+ Set<String> findClassNames(String pluginId);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionPoint.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionPoint.java
new file mode 100644
index 0000000..cceef1a
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionPoint.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * @author Decebal Suiu
+ */
+public interface ExtensionPoint {
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionWrapper.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionWrapper.java
new file mode 100644
index 0000000..2b8960a
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ExtensionWrapper.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * A wrapper over extension instance.
+ *
+ * @author Decebal Suiu
+ */
+public class ExtensionWrapper<T> implements Comparable<ExtensionWrapper<T>> {
+
+ private final ExtensionDescriptor descriptor;
+ private final ExtensionFactory extensionFactory;
+ private T extension; // cache
+
+ public ExtensionWrapper(ExtensionDescriptor descriptor, ExtensionFactory extensionFactory) {
+ this.descriptor = descriptor;
+ this.extensionFactory = extensionFactory;
+ }
+
+ @SuppressWarnings("unchecked")
+ public T getExtension() {
+ if (extension == null) {
+ extension = (T) extensionFactory.create(descriptor.extensionClass);
+ }
+
+ return extension;
+ }
+
+ public ExtensionDescriptor getDescriptor() {
+ return descriptor;
+ }
+
+ public int getOrdinal() {
+ return descriptor.ordinal;
+ }
+
+ @Override
+ public int compareTo(ExtensionWrapper<T> o) {
+ return (getOrdinal() - o.getOrdinal());
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/FileDownloader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/FileDownloader.java
new file mode 100644
index 0000000..c77aeb8
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/FileDownloader.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+
+import java.io.IOException;
+import java.net.URL;
+import java.nio.file.Path;
+
+/**
+ * Interface to download a file.
+ */
+public interface FileDownloader {
+
+ /**
+ * Downloads a file to destination. The implementation should download to a temporary folder.
+ * Implementations may choose to support different protocols such as http, https, ftp, file...
+ * The path returned must be of temporary nature and will most probably be moved/deleted by consumer.
+ *
+ * @param fileUrl the URL representing the file to download
+ * @return Path of downloaded file, typically in a temporary folder
+ * @throws IOException if there was an IO problem during download
+ * @throws PluginException in case of other problems, such as unsupported protocol
+ */
+ Path downloadFile(URL fileUrl) throws PluginException, IOException;
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/FileVerifier.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/FileVerifier.java
new file mode 100644
index 0000000..b09a523
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/FileVerifier.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Interface to verify a file.
+ */
+public interface FileVerifier {
+
+ /**
+ * Verifies a plugin release according to certain rules
+ *
+ * @param context the file verifier context object
+ * @param file the path to the downloaded file itself
+ * @throws IOException if there was a problem accessing file
+ * @throws VerifyException in case of problems verifying the file
+ */
+ void verify(Context context, Path file) throws IOException, VerifyException;
+
+ /**
+ * Context to be passed to file verifiers
+ */
+ class Context {
+ public String id;
+ public Date date;
+ public String version;
+ public String requires;
+ public String url;
+ public String sha512sum;
+ public Map<String,Object> meta = new HashMap<>();
+
+ public Context(String id, PluginInfo.PluginRelease pluginRelease) {
+ this.id = id;
+ this.date = pluginRelease.date;
+ this.version = pluginRelease.version;
+ this.requires = pluginRelease.requires;
+ this.url = pluginRelease.url;
+ this.sha512sum = pluginRelease.sha512sum;
+ }
+
+ public Context(String id, Date date, String version, String requires, String url, String sha512sum) {
+ this.id = id;
+ this.date = date;
+ this.version = version;
+ this.requires = requires;
+ this.url = url;
+ this.sha512sum = sha512sum;
+ }
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/JarPluginLoader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/JarPluginLoader.java
new file mode 100644
index 0000000..2dc2cde
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/JarPluginLoader.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2017 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+/**
+ * @author Decebal Suiu
+ */
+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, getClass().getClassLoader());
+ pluginClassLoader.addFile(pluginPath.toFile());
+
+ return pluginClassLoader;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/JarPluginRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/JarPluginRepository.java
new file mode 100644
index 0000000..28d0404
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/JarPluginRepository.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2016 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.JarFileFilter;
+
+import java.nio.file.Path;
+
+/**
+ * @author Decebal Suiu
+ */
+public class JarPluginRepository extends BasePluginRepository {
+
+ public JarPluginRepository(Path pluginsRoot) {
+ super(pluginsRoot, new JarFileFilter());
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LegacyExtensionFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LegacyExtensionFinder.java
new file mode 100644
index 0000000..5655baf
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LegacyExtensionFinder.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2013 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.pf4j.processor.LegacyExtensionStorage;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * All extensions declared in a plugin are indexed in a file {@code META-INF/extensions.idx}.
+ * This class lookup extensions in all extensions index files {@code META-INF/extensions.idx}.
+ *
+ * @author Decebal Suiu
+ */
+public class LegacyExtensionFinder extends AbstractExtensionFinder {
+
+ private static final Logger log = LoggerFactory.getLogger(LegacyExtensionFinder.class);
+
+ public LegacyExtensionFinder(PluginManager pluginManager) {
+ super(pluginManager);
+ }
+
+ @Override
+ public Map<String, Set<String>> readClasspathStorages() {
+ log.debug("Reading extensions storages from classpath");
+ Map<String, Set<String>> result = new LinkedHashMap<>();
+
+ Set<String> bucket = new HashSet<>();
+ try {
+ Enumeration<URL> urls = getClass().getClassLoader().getResources(getExtensionsResource());
+ while (urls.hasMoreElements()) {
+ URL url = urls.nextElement();
+ log.debug("Read '{}'", url.getFile());
+ try (Reader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
+ LegacyExtensionStorage.read(reader, bucket);
+ }
+ }
+
+ debugExtensions(bucket);
+
+ result.put(null, bucket);
+ } catch (IOException e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return result;
+ }
+
+ @Override
+ public Map<String, Set<String>> readPluginsStorages() {
+ log.debug("Reading extensions storages from plugins");
+ Map<String, Set<String>> result = new LinkedHashMap<>();
+
+ List<PluginWrapper> plugins = pluginManager.getPlugins();
+ for (PluginWrapper plugin : plugins) {
+ String pluginId = plugin.getDescriptor().getPluginId();
+ log.debug("Reading extensions storage from plugin '{}'", pluginId);
+ Set<String> bucket = new HashSet<>();
+
+ try {
+ URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource());
+ if (url != null) {
+ log.debug("Read '{}'", url.getFile());
+ try (Reader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
+ LegacyExtensionStorage.read(reader, bucket);
+ }
+ } else {
+ log.debug("Cannot find '{}'", getExtensionsResource());
+ }
+
+ debugExtensions(bucket);
+
+ result.put(pluginId, bucket);
+ } catch (IOException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ return result;
+ }
+
+ private static String getExtensionsResource() {
+ return LegacyExtensionStorage.EXTENSIONS_RESOURCE;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LenientDateTypeAdapter.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LenientDateTypeAdapter.java
new file mode 100644
index 0000000..a589129
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LenientDateTypeAdapter.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2011 Google Inc
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * Fork of com.google.gson.internal.bind.DateTypeAdapter
+ */
+public class LenientDateTypeAdapter extends TypeAdapter<Date> {
+ public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
+ @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+ public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+ return typeToken.getRawType() == Date.class ? (TypeAdapter<T>) new LenientDateTypeAdapter() : null;
+ }
+ };
+
+ private final DateFormat enUsFormat
+ = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US);
+ private final DateFormat localFormat
+ = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT);
+ private final DateFormat iso8601Format = buildIso8601Format();
+ private final DateFormat shortFormat = buildShortFormat();
+
+ private static DateFormat buildIso8601Format() {
+ DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
+ iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return iso8601Format;
+ }
+
+ private static DateFormat buildShortFormat() {
+ DateFormat shortFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
+ shortFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return shortFormat;
+ }
+
+ @Override
+ public Date read(JsonReader in) throws IOException {
+ if (in.peek() == JsonToken.NULL) {
+ in.nextNull();
+ return null;
+ }
+ return deserializeToDate(in.nextString());
+ }
+
+ private synchronized Date deserializeToDate(String json) {
+ try {
+ return localFormat.parse(json);
+ } catch (ParseException ignored) {
+ }
+ try {
+ return enUsFormat.parse(json);
+ } catch (ParseException ignored) {
+ }
+ try {
+ return iso8601Format.parse(json);
+ } catch (ParseException ignored) {
+ }
+ try {
+ return shortFormat.parse(json);
+ } catch (ParseException e) {
+ return new Date(0);
+ }
+ }
+
+ @Override
+ public synchronized void write(JsonWriter out, Date value) throws IOException {
+ if (value == null) {
+ out.nullValue();
+ return;
+ }
+ String dateFormatAsString = enUsFormat.format(value);
+ out.value(dateFormatAsString);
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LoggingPluginStateListener.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LoggingPluginStateListener.java
new file mode 100644
index 0000000..8ef3a405
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/LoggingPluginStateListener.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2018 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * It's an implementation of {@link PluginStateListener} that writes all events to logger (DEBUG level).
+ * This listener is added automatically by {@link DefaultPluginManager} for {@code dev} mode.
+ *
+ * @author Decebal Suiu
+ */
+public class LoggingPluginStateListener implements PluginStateListener {
+
+ private static final Logger log = LoggerFactory.getLogger(LoggingPluginStateListener.class);
+
+ @Override
+ public void pluginStateChanged(PluginStateEvent event) {
+ log.debug("The state of plugin '{}' has changed from '{}' to '{}'", event.getPlugin().getPluginId(),
+ event.getOldState(), event.getPluginState());
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ManifestPluginDescriptorFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ManifestPluginDescriptorFinder.java
new file mode 100644
index 0000000..9c88d56
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ManifestPluginDescriptorFinder.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+import org.pf4j.util.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+/**
+ * Read the plugin descriptor from the manifest file.
+ *
+ * @author Decebal Suiu
+ */
+public class ManifestPluginDescriptorFinder implements PluginDescriptorFinder {
+
+ private static final Logger log = LoggerFactory.getLogger(ManifestPluginDescriptorFinder.class);
+
+ @Override
+ public boolean isApplicable(Path pluginPath) {
+ return Files.exists(pluginPath) && (Files.isDirectory(pluginPath) || FileUtils.isJarFile(pluginPath));
+ }
+
+ @Override
+ public PluginDescriptor find(Path pluginPath) throws PluginException {
+ Manifest manifest = readManifest(pluginPath);
+
+ return createPluginDescriptor(manifest);
+ }
+
+ protected Manifest readManifest(Path pluginPath) throws PluginException {
+ if (FileUtils.isJarFile(pluginPath)) {
+ try (JarFile jar = new JarFile(pluginPath.toFile())) {
+ Manifest manifest = jar.getManifest();
+ if (manifest != null) {
+ return manifest;
+ }
+ } catch (IOException e) {
+ throw new PluginException(e);
+ }
+ }
+
+ Path manifestPath = getManifestPath(pluginPath);
+ if (manifestPath == null) {
+ throw new PluginException("Cannot find the manifest path");
+ }
+
+ log.debug("Lookup plugin descriptor in '{}'", manifestPath);
+ if (Files.notExists(manifestPath)) {
+ throw new PluginException("Cannot find '{}' path", manifestPath);
+ }
+
+ try (InputStream input = Files.newInputStream(manifestPath)) {
+ return new Manifest(input);
+ } catch (IOException e) {
+ throw new PluginException(e);
+ }
+ }
+
+ protected Path getManifestPath(Path pluginPath) throws PluginException {
+ if (Files.isDirectory(pluginPath)) {
+ // legacy (the path is something like "classes/META-INF/MANIFEST.MF")
+ return FileUtils.findFile(pluginPath,"MANIFEST.MF");
+ }
+
+ return null;
+ }
+
+ protected PluginDescriptor createPluginDescriptor(Manifest manifest) {
+ DefaultPluginDescriptor pluginDescriptor = createPluginDescriptorInstance();
+
+ // TODO validate !!!
+ Attributes attributes = manifest.getMainAttributes();
+ String id = attributes.getValue("Plugin-Id");
+ pluginDescriptor.setPluginId(id);
+
+ String description = attributes.getValue("Plugin-Description");
+ if (StringUtils.isNullOrEmpty(description)) {
+ pluginDescriptor.setPluginDescription("");
+ } else {
+ pluginDescriptor.setPluginDescription(description);
+ }
+
+ String clazz = attributes.getValue("Plugin-Class");
+ pluginDescriptor.setPluginClass(clazz);
+
+ String version = attributes.getValue("Plugin-Version");
+ if (StringUtils.isNotNullOrEmpty(version)) {
+ pluginDescriptor.setPluginVersion(version);
+ }
+
+ String provider = attributes.getValue("Plugin-Provider");
+ pluginDescriptor.setProvider(provider);
+ String dependencies = attributes.getValue("Plugin-Dependencies");
+ pluginDescriptor.setDependencies(dependencies);
+
+ String requires = attributes.getValue("Plugin-Requires");
+ if (StringUtils.isNotNullOrEmpty(requires)) {
+ pluginDescriptor.setRequires(requires);
+ }
+
+ pluginDescriptor.setLicense(attributes.getValue("Plugin-License"));
+
+ return pluginDescriptor;
+ }
+
+ protected DefaultPluginDescriptor createPluginDescriptorInstance() {
+ return new DefaultPluginDescriptor();
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Plugin.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Plugin.java
new file mode 100644
index 0000000..139bf56
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Plugin.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class will be extended by all plugins and
+ * serve as the common class between a plugin and the application.
+ *
+ * @author Decebal Suiu
+ */
+public abstract class Plugin {
+
+ /**
+ * Makes logging service available for descending classes.
+ */
+ protected final Logger log = LoggerFactory.getLogger(getClass());
+
+ /**
+ * Wrapper of the plugin.
+ */
+ protected PluginWrapper wrapper;
+
+ /**
+ * Constructor to be used by plugin manager for plugin instantiation.
+ * Your plugins have to provide constructor with this exact signature to
+ * be successfully loaded by manager.
+ */
+ public Plugin(final PluginWrapper wrapper) {
+ if (wrapper == null) {
+ throw new IllegalArgumentException("Wrapper cannot be null");
+ }
+
+ this.wrapper = wrapper;
+ }
+
+ /**
+ * Retrieves the wrapper of this plug-in.
+ */
+ public final PluginWrapper getWrapper() {
+ return wrapper;
+ }
+
+ /**
+ * Start method is called by the application when the plugin is loaded.
+ */
+ public void start() throws PluginException {
+ }
+
+ /**
+ * Stop method is called by the application when the plugin is unloaded.
+ */
+ public void stop() throws PluginException {
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginClassLoader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginClassLoader.java
new file mode 100644
index 0000000..bd4fae8
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginClassLoader.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.List;
+
+/**
+ * One instance of this class should be created by plugin manager for every available plug-in.
+ * By default, this class loader is a Parent Last ClassLoader - it loads the classes from the plugin's jars
+ * before delegating to the parent class loader.
+ * Use {@link #parentFirst} to change the loading strategy.
+ *
+ * @author Decebal Suiu
+ */
+public class PluginClassLoader extends URLClassLoader {
+
+ private static final Logger log = LoggerFactory.getLogger(PluginClassLoader.class);
+
+ private static final String JAVA_PACKAGE_PREFIX = "java.";
+ private static final String PLUGIN_PACKAGE_PREFIX = "org.pf4j.";
+
+ private PluginManager pluginManager;
+ private PluginDescriptor pluginDescriptor;
+ private boolean parentFirst;
+
+ public PluginClassLoader(PluginManager pluginManager, PluginDescriptor pluginDescriptor, ClassLoader parent) {
+ this(pluginManager, pluginDescriptor, parent, false);
+ }
+
+ /**
+ * If {@code parentFirst} is {@code true}, indicates that the parent {@link ClassLoader} should be consulted
+ * before trying to load the a class through this loader.
+ */
+ public PluginClassLoader(PluginManager pluginManager, PluginDescriptor pluginDescriptor, ClassLoader parent, boolean parentFirst) {
+ super(new URL[0], parent);
+
+ this.pluginManager = pluginManager;
+ this.pluginDescriptor = pluginDescriptor;
+ this.parentFirst = parentFirst;
+ }
+
+ @Override
+ public void addURL(URL url) {
+ log.debug("Add '{}'", url);
+ super.addURL(url);
+ }
+
+ public void addFile(File file) {
+ try {
+ addURL(file.getCanonicalFile().toURI().toURL());
+ } catch (IOException e) {
+// throw new RuntimeException(e);
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * By default, it uses a child first delegation model rather than the standard parent first.
+ * If the requested class cannot be found in this class loader, the parent class loader will be consulted
+ * via the standard {@link ClassLoader#loadClass(String)} mechanism.
+ * Use {@link #parentFirst} to change the loading strategy.
+ */
+ @Override
+ public Class<?> loadClass(String className) throws ClassNotFoundException {
+ synchronized (getClassLoadingLock(className)) {
+ // first check whether it's a system class, delegate to the system loader
+ if (className.startsWith(JAVA_PACKAGE_PREFIX)) {
+ return findSystemClass(className);
+ }
+
+ // if the class it's a part of the plugin engine use parent class loader
+ if (className.startsWith(PLUGIN_PACKAGE_PREFIX) && !className.startsWith("org.pf4j.demo")) {
+// log.trace("Delegate the loading of PF4J class '{}' to parent", className);
+ return getParent().loadClass(className);
+ }
+
+ log.trace("Received request to load class '{}'", className);
+
+ // second check whether it's already been loaded
+ Class<?> loadedClass = findLoadedClass(className);
+ if (loadedClass != null) {
+ log.trace("Found loaded class '{}'", className);
+ return loadedClass;
+ }
+
+ if (!parentFirst) {
+ // nope, try to load locally
+ try {
+ loadedClass = findClass(className);
+ log.trace("Found class '{}' in plugin classpath", className);
+ return loadedClass;
+ } catch (ClassNotFoundException e) {
+ // try next step
+ }
+
+ // look in dependencies
+ loadedClass = loadClassFromDependencies(className);
+ if (loadedClass != null) {
+ log.trace("Found class '{}' in dependencies", className);
+ return loadedClass;
+ }
+
+ log.trace("Couldn't find class '{}' in plugin classpath. Delegating to parent", className);
+
+ // use the standard ClassLoader (which follows normal parent delegation)
+ return super.loadClass(className);
+ } else {
+ // try to load from parent
+ try {
+ return super.loadClass(className);
+ } catch (ClassCastException e) {
+ // try next step
+ }
+
+ log.trace("Couldn't find class '{}' in parent. Delegating to plugin classpath", className);
+
+ // nope, try to load locally
+ try {
+ loadedClass = findClass(className);
+ log.trace("Found class '{}' in plugin classpath", className);
+ return loadedClass;
+ } catch (ClassNotFoundException e) {
+ // try next step
+ }
+
+ // look in dependencies
+ loadedClass = loadClassFromDependencies(className);
+ if (loadedClass != null) {
+ log.trace("Found class '{}' in dependencies", className);
+ return loadedClass;
+ }
+
+ throw new ClassNotFoundException(className);
+ }
+ }
+ }
+
+ /**
+ * Load the named resource from this plugin.
+ * By default, this implementation checks the plugin's classpath first then delegates to the parent.
+ * Use {@link #parentFirst} to change the loading strategy.
+ *
+ * @param name the name of the resource.
+ * @return the URL to the resource, {@code null} if the resource was not found.
+ */
+ @Override
+ public URL getResource(String name) {
+ log.trace("Received request to load resource '{}'", name);
+ if (!parentFirst) {
+ URL url = findResource(name);
+ if (url != null) {
+ log.trace("Found resource '{}' in plugin classpath", name);
+ return url;
+ }
+
+ log.trace("Couldn't find resource '{}' in plugin classpath. Delegating to parent", name);
+
+ return super.getResource(name);
+ } else {
+ URL url = super.getResource(name);
+ if (url != null) {
+ log.trace("Found resource '{}' in parent", name);
+ return url;
+ }
+
+ log.trace("Couldn't find resource '{}' in parent", name);
+
+ return findResource(name);
+ }
+ }
+
+ private Class<?> loadClassFromDependencies(String className) {
+ log.trace("Search in dependencies for class '{}'", className);
+ List<PluginDependency> dependencies = pluginDescriptor.getDependencies();
+ for (PluginDependency dependency : dependencies) {
+ ClassLoader classLoader = pluginManager.getPluginClassLoader(dependency.getPluginId());
+ try {
+ return classLoader.loadClass(className);
+ } catch (ClassNotFoundException e) {
+ // try next dependency
+ }
+ }
+
+ return null;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginClasspath.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginClasspath.java
new file mode 100644
index 0000000..f6c146b
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginClasspath.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2013 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * The classpath of the plugin.
+ * It contains {@code classes} directories and {@code lib} directories (directories that contains jars).
+ *
+ * @author Decebal Suiu
+ */
+public class PluginClasspath {
+
+ private List<String> classesDirectories;
+ private List<String> libDirectories;
+
+ public PluginClasspath() {
+ classesDirectories = new ArrayList<>();
+ libDirectories = new ArrayList<>();
+ }
+
+ public List<String> getClassesDirectories() {
+ return classesDirectories;
+ }
+
+ public void addClassesDirectories(String... classesDirectories) {
+ this.classesDirectories.addAll(Arrays.asList(classesDirectories));
+ }
+
+ public List<String> getLibDirectories() {
+ return libDirectories;
+ }
+
+ public void addLibDirectories(String... libDirectories) {
+ this.libDirectories.addAll(Arrays.asList(libDirectories));
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDependency.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDependency.java
new file mode 100644
index 0000000..6b8539f
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDependency.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * @author Decebal Suiu
+ */
+public class PluginDependency {
+
+ private String pluginId;
+ private String pluginVersionSupport = "*";
+
+ public PluginDependency(String dependency) {
+ int index = dependency.indexOf('@');
+ if (index == -1) {
+ this.pluginId = dependency;
+ } else {
+ this.pluginId = dependency.substring(0, index);
+ if (dependency.length() > index + 1) {
+ this.pluginVersionSupport = dependency.substring(index + 1);
+ }
+ }
+ }
+
+ public String getPluginId() {
+ return pluginId;
+ }
+
+ public String getPluginVersionSupport() {
+ return pluginVersionSupport;
+ }
+
+ @Override
+ public String toString() {
+ return "PluginDependency [pluginId=" + pluginId + ", pluginVersionSupport=" + pluginVersionSupport + "]";
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDescriptor.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDescriptor.java
new file mode 100644
index 0000000..21ba53f
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDescriptor.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2015 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.List;
+
+/**
+ * A plugin descriptor contains information about a plug-in.
+ *
+ * @author Decebal Suiu
+ */
+public interface PluginDescriptor {
+
+ String getPluginId();
+
+ String getPluginDescription();
+
+ String getPluginClass();
+
+ String getVersion();
+
+ String getRequires();
+
+ String getProvider();
+
+ String getLicense();
+
+ List<PluginDependency> getDependencies();
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDescriptorFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDescriptorFinder.java
new file mode 100644
index 0000000..0f46167
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginDescriptorFinder.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.nio.file.Path;
+
+/**
+ * Find a plugin descriptor for a plugin path.
+ * You can find the plugin descriptor in manifest file {@link ManifestPluginDescriptorFinder},
+ * properties file {@link PropertiesPluginDescriptorFinder}, xml file,
+ * java services (with {@link java.util.ServiceLoader}), etc.
+ *
+ * @author Decebal Suiu
+ */
+public interface PluginDescriptorFinder {
+
+ /**
+ * Returns true if this finder is applicable to the given {@link Path}.
+ *
+ */
+ boolean isApplicable(Path pluginPath);
+
+ PluginDescriptor find(Path pluginPath) throws PluginException;
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginException.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginException.java
new file mode 100644
index 0000000..818c685
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginException.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.StringUtils;
+
+/**
+ * An exception used to indicate that a plugin problem occurred.
+ *
+ * @author Decebal Suiu
+ */
+public class PluginException extends Exception {
+
+ public PluginException() {
+ super();
+ }
+
+ public PluginException(String message) {
+ super(message);
+ }
+
+ public PluginException(Throwable cause) {
+ super(cause);
+ }
+
+ public PluginException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public PluginException(Throwable cause, String message, Object... args) {
+ super(StringUtils.format(message, args), cause);
+ }
+
+ public PluginException(String message, Object... args) {
+ super(StringUtils.format(message, args));
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginFactory.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginFactory.java
new file mode 100644
index 0000000..635fc71
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginFactory.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * Creates a plugin instance.
+ */
+public interface PluginFactory {
+
+ Plugin create(PluginWrapper pluginWrapper);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginInfo.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginInfo.java
new file mode 100644
index 0000000..c70803e
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginInfo.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * {@code PluginInfo} describing a plugin from a repository.
+ */
+public class PluginInfo implements Serializable, Comparable<PluginInfo> {
+
+ public String id;
+ public String name;
+ public String description;
+ public String provider;
+ public String projectUrl;
+ public List<PluginRelease> releases;
+
+ // This is metadata added at parse time, not part of the published plugins.json
+ private String repositoryId;
+
+
+ @Override
+ public int compareTo(PluginInfo o) {
+ return id.compareTo(o.id);
+ }
+
+ public String getRepositoryId() {
+ return repositoryId;
+ }
+
+ public void setRepositoryId(String repositoryId) {
+ this.repositoryId = repositoryId;
+ }
+
+ @Override
+ public String toString() {
+ return "PluginInfo{" +
+ "id='" + id + '\'' +
+ ", name='" + name + '\'' +
+ ", description='" + description + '\'' +
+ ", provider='" + provider + '\'' +
+ ", projectUrl='" + projectUrl + '\'' +
+ ", releases=" + releases +
+ ", repositoryId='" + repositoryId + '\'' +
+ '}';
+ }
+
+ /**
+ * A concrete release.
+ */
+ public static class PluginRelease implements Serializable {
+
+ public String version;
+ public Date date;
+ public String requires;
+ public String url;
+ /**
+ * Optional sha512 digest checksum. Can be one of
+ * <ul>
+ * <li><sha512 sum string></li>
+ * <li>URL to an external sha512 file</li>
+ * <li>".sha512" as a shortcut for saying download a <filename>.sha512 file next to the zip/jar file</li>
+ * </ul>
+ */
+ public String sha512sum;
+
+ @Override
+ public String toString() {
+ return "PluginRelease{" +
+ "version='" + version + '\'' +
+ ", date=" + date +
+ ", requires='" + requires + '\'' +
+ ", url='" + url + '\'' +
+ ", sha512sum='" + sha512sum + '\'' +
+ '}';
+ }
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginLoader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginLoader.java
new file mode 100644
index 0000000..37d7e24
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginLoader.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.nio.file.Path;
+
+/**
+ * Load all information (classes) needed by a plugin.
+ *
+ * @author Decebal Suiu
+ */
+public interface PluginLoader {
+
+ /**
+ * Returns true if this loader is applicable to the given {@link Path}.
+ *
+ */
+ boolean isApplicable(Path pluginPath);
+
+ ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginManager.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginManager.java
new file mode 100644
index 0000000..1d0928c
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginManager.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Provides the functionality for plugin management such as load,
+ * start and stop the plugins.
+ *
+ * @author Decebal Suiu
+ */
+public interface PluginManager {
+
+ /**
+ * Retrieves all plugins.
+ */
+ List<PluginWrapper> getPlugins();
+
+ /**
+ * Retrieves all plugins with this state.
+ */
+ List<PluginWrapper> getPlugins(PluginState pluginState);
+
+ /**
+ * Retrieves all resolved plugins (with resolved dependency).
+ */
+ List<PluginWrapper> getResolvedPlugins();
+
+ /**
+ * Retrieves all unresolved plugins (with unresolved dependency).
+ */
+ List<PluginWrapper> getUnresolvedPlugins();
+
+ /**
+ * Retrieves all started plugins.
+ */
+ List<PluginWrapper> getStartedPlugins();
+
+ /**
+ * Retrieves the plugin with this id, or null if the plugin does not exist.
+ *
+ * @param pluginId The pluginId for the plugin you are trying to get.
+ * @return A PluginWrapper object for this plugin, or null if it does not exist.
+ */
+ PluginWrapper getPlugin(String pluginId);
+
+ /**
+ * Load plugins.
+ */
+ void loadPlugins();
+
+ /**
+ * Load a plugin.
+ *
+ * @return the pluginId of the installed plugin or null
+ */
+ String loadPlugin(Path pluginPath);
+
+ /**
+ * Start all active plugins.
+ */
+ void startPlugins();
+
+ /**
+ * Start the specified plugin and it's dependencies.
+ *
+ * @return the plugin state
+ */
+ PluginState startPlugin(String pluginId);
+
+ /**
+ * Stop all active plugins.
+ */
+ void stopPlugins();
+
+ /**
+ * Stop the specified plugin and it's dependencies.
+ *
+ * @return the plugin state
+ */
+ PluginState stopPlugin(String pluginId);
+
+ /**
+ * Unload a plugin.
+ *
+ * @return true if the plugin was unloaded
+ */
+ boolean unloadPlugin(String pluginId);
+
+ /**
+ * Disables a plugin from being loaded.
+ *
+ * @return true if plugin is disabled
+ */
+ boolean disablePlugin(String pluginId);
+
+ /**
+ * Enables a plugin that has previously been disabled.
+ *
+ * @return true if plugin is enabled
+ */
+ boolean enablePlugin(String pluginId);
+
+ /**
+ * Deletes a plugin.
+ *
+ * @return true if the plugin was deleted
+ */
+ boolean deletePlugin(String pluginId);
+
+ ClassLoader getPluginClassLoader(String pluginId);
+
+ <T> List<Class<T>> getExtensionClasses(Class<T> type);
+
+ <T> List<Class<T>> getExtensionClasses(Class<T> type, String pluginId);
+
+ <T> List<T> getExtensions(Class<T> type);
+
+ <T> List<T> getExtensions(Class<T> type, String pluginId);
+
+ List getExtensions(String pluginId);
+
+ Set<String> getExtensionClassNames(String pluginId);
+
+ ExtensionFactory getExtensionFactory();
+
+ /**
+ * The runtime mode. Must currently be either DEVELOPMENT or DEPLOYMENT.
+ */
+ RuntimeMode getRuntimeMode();
+
+ /**
+ * Retrieves the {@link PluginWrapper} that loaded the given class 'clazz'.
+ */
+ PluginWrapper whichPlugin(Class<?> clazz);
+
+ void addPluginStateListener(PluginStateListener listener);
+
+ void removePluginStateListener(PluginStateListener listener);
+
+ /**
+ * Set the system version. This is used to compare against the plugin
+ * requires attribute. The default system version is 0.0.0 which
+ * disables all version checking.
+ *
+ * @default 0.0.0
+ */
+ void setSystemVersion(String version);
+
+ /**
+ * Returns the system version.
+ *
+ * @return the system version
+ */
+ String getSystemVersion();
+
+ /**
+ * Gets the path of the folder where plugins are installed
+ * @return Path of plugins root
+ */
+ Path getPluginsRoot();
+
+ VersionManager getVersionManager();
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginRepository.java
new file mode 100644
index 0000000..2e552e9
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginRepository.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+ * Directory that contains plugins. A plugin could be a zip file.
+ *
+ * @author Decebal Suiu
+ * @author Mário Franco
+ */
+public interface PluginRepository {
+
+ /**
+ * List all plugin paths.
+ *
+ * @return a list of files
+ */
+ List<Path> getPluginPaths();
+
+ /**
+ * Removes a plugin from the repository.
+ *
+ * @param pluginPath the plugin path
+ * @return true if deleted
+ */
+ boolean deletePluginPath(Path pluginPath);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginState.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginState.java
new file mode 100644
index 0000000..075b81c
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginState.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * @author Decebal Suiu
+ */
+public class PluginState {
+
+ /**
+ * The runtime knows the plugin is there. It knows about the plugin path, the plugin descriptor.
+ */
+ public static final PluginState CREATED = new PluginState("CREATED");
+
+ /**
+ * The plugin cannot be used.
+ */
+ public static final PluginState DISABLED = new PluginState("DISABLED");
+
+ /**
+ * The plugin is created. All the dependencies are created and resolved.
+ * The plugin is ready to be started.
+ */
+ public static final PluginState RESOLVED = new PluginState("RESOLVED");
+
+ /**
+ * The {@link Plugin#start()} has executed. A started plugin may contribute extensions.
+ */
+ public static final PluginState STARTED = new PluginState("STARTED");
+
+ /**
+ * The {@link Plugin#stop()} has executed.
+ */
+ public static final PluginState STOPPED = new PluginState("STOPPED");
+
+ private String status;
+
+ private PluginState(String status) {
+ this.status = status;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ PluginState that = (PluginState) o;
+
+ return status.equals(that.status);
+ }
+
+ @Override
+ public int hashCode() {
+ return status.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return status;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStateEvent.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStateEvent.java
new file mode 100644
index 0000000..650ec74
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStateEvent.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.EventObject;
+
+/**
+ * @author Decebal Suiu
+ */
+public class PluginStateEvent extends EventObject {
+
+ private PluginWrapper plugin;
+ private PluginState oldState;
+
+ public PluginStateEvent(PluginManager source, PluginWrapper plugin, PluginState oldState) {
+ super(source);
+
+ this.plugin = plugin;
+ this.oldState = oldState;
+ }
+
+ @Override
+ public PluginManager getSource() {
+ return (PluginManager) super.getSource();
+ }
+
+ public PluginWrapper getPlugin() {
+ return plugin;
+ }
+
+ public PluginState getPluginState() {
+ return plugin.getPluginState();
+ }
+
+ public PluginState getOldState() {
+ return oldState;
+ }
+
+ @Override
+ public String toString() {
+ return "PluginStateEvent [plugin=" + plugin.getPluginId() +
+ ", newState=" + getPluginState() +
+ ", oldState=" + oldState +
+ ']';
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStateListener.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStateListener.java
new file mode 100644
index 0000000..e6c2f17
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStateListener.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2014 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.EventListener;
+
+/**
+ * PluginStateListener defines the interface for an object that listens to plugin state changes.
+ *
+ * @author Decebal Suiu
+ */
+public interface PluginStateListener extends EventListener {
+
+ /**
+ * Invoked when a plugin's state (for example DISABLED, STARTED) is changed.
+ */
+ void pluginStateChanged(PluginStateEvent event);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStatusProvider.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStatusProvider.java
new file mode 100644
index 0000000..8d6b9c4
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginStatusProvider.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+/**
+ * @author Decebal Suiu
+ * @author Mário Franco
+ */
+public interface PluginStatusProvider {
+
+ /**
+ * Checks if the plugin is disabled or not
+ *
+ * @param pluginId the plugin id
+ * @return if the plugin is disabled or not
+ */
+ boolean isPluginDisabled(String pluginId);
+
+ /**
+ * Disables a plugin from being loaded.
+ *
+ * @return true if plugin is disabled
+ */
+ boolean disablePlugin(String pluginId);
+
+ /**
+ * Enables a plugin that has previously been disabled.
+ *
+ * @return true if plugin is enabled
+ */
+ boolean enablePlugin(String pluginId);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginWrapper.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginWrapper.java
new file mode 100644
index 0000000..c795ec0
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PluginWrapper.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.nio.file.Path;
+
+/**
+ * A wrapper over plugin instance.
+ *
+ * @author Decebal Suiu
+ */
+public class PluginWrapper {
+
+ private PluginManager pluginManager;
+ private PluginDescriptor descriptor;
+ private Path pluginPath;
+ private ClassLoader pluginClassLoader;
+ private PluginFactory pluginFactory;
+ private PluginState pluginState;
+ private RuntimeMode runtimeMode;
+
+ Plugin plugin; // cache
+
+ public PluginWrapper(PluginManager pluginManager, PluginDescriptor descriptor, Path pluginPath, ClassLoader pluginClassLoader) {
+ this.pluginManager = pluginManager;
+ this.descriptor = descriptor;
+ this.pluginPath = pluginPath;
+ this.pluginClassLoader = pluginClassLoader;
+
+ pluginState = PluginState.CREATED;
+ }
+
+ /**
+ * Returns the plugin manager.
+ */
+ public PluginManager getPluginManager() {
+ return pluginManager;
+ }
+
+ /**
+ * Returns the plugin descriptor.
+ */
+ public PluginDescriptor getDescriptor() {
+ return descriptor;
+ }
+
+ /**
+ * Returns the path of this plugin.
+ */
+ public Path getPluginPath() {
+ return pluginPath;
+ }
+
+ /**
+ * Returns the plugin class loader used to load classes and resources
+ * for this plug-in. The class loader can be used to directly access
+ * plug-in resources and classes.
+ */
+ public ClassLoader getPluginClassLoader() {
+ return pluginClassLoader;
+ }
+
+ public Plugin getPlugin() {
+ if (plugin == null) {
+ plugin = pluginFactory.create(this);
+ }
+
+ return plugin;
+ }
+
+ public PluginState getPluginState() {
+ return pluginState;
+ }
+
+ public RuntimeMode getRuntimeMode() {
+ return runtimeMode;
+ }
+
+ /**
+ * Shortcut
+ */
+ public String getPluginId() {
+ return getDescriptor().getPluginId();
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + descriptor.getPluginId().hashCode();
+
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+
+ if (obj == null) {
+ return false;
+ }
+
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+
+ PluginWrapper other = (PluginWrapper) obj;
+ if (!descriptor.getPluginId().equals(other.descriptor.getPluginId())) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "PluginWrapper [descriptor=" + descriptor + ", pluginPath=" + pluginPath + "]";
+ }
+
+ void setPluginState(PluginState pluginState) {
+ this.pluginState = pluginState;
+ }
+
+ void setRuntimeMode(RuntimeMode runtimeMode) {
+ this.runtimeMode = runtimeMode;
+ }
+
+ void setPluginFactory(PluginFactory pluginFactory) {
+ this.pluginFactory = pluginFactory;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PropertiesPluginDescriptorFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PropertiesPluginDescriptorFinder.java
new file mode 100644
index 0000000..a224cb7
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/PropertiesPluginDescriptorFinder.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2012 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.util.FileUtils;
+import org.pf4j.util.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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.util.Properties;
+
+/**
+ * Find a plugin descriptor in a properties file (in plugin repository).
+ *
+ * @author Decebal Suiu
+ */
+public class PropertiesPluginDescriptorFinder implements PluginDescriptorFinder {
+
+ private static final Logger log = LoggerFactory.getLogger(PropertiesPluginDescriptorFinder.class);
+
+ private static final String DEFAULT_PROPERTIES_FILE_NAME = "plugin.properties";
+
+ protected String propertiesFileName;
+
+ public PropertiesPluginDescriptorFinder() {
+ this(DEFAULT_PROPERTIES_FILE_NAME);
+ }
+
+ public PropertiesPluginDescriptorFinder(String propertiesFileName) {
+ this.propertiesFileName = propertiesFileName;
+ }
+
+ @Override
+ public boolean isApplicable(Path pluginPath) {
+ return Files.exists(pluginPath) && (Files.isDirectory(pluginPath) || FileUtils.isJarFile(pluginPath));
+ }
+
+ @Override
+ public PluginDescriptor find(Path pluginPath) throws PluginException {
+ Properties properties = readProperties(pluginPath);
+
+ return createPluginDescriptor(properties);
+ }
+
+ protected Properties readProperties(Path pluginPath) throws PluginException {
+ Path propertiesPath = getPropertiesPath(pluginPath, propertiesFileName);
+ if (propertiesPath == null) {
+ throw new PluginException("Cannot find the properties path");
+ }
+
+ log.debug("Lookup plugin descriptor in '{}'", propertiesPath);
+ if (Files.notExists(propertiesPath)) {
+ throw new PluginException("Cannot find '{}' path", propertiesPath);
+ }
+
+ Properties properties = new Properties();
+ try (InputStream input = Files.newInputStream(propertiesPath)) {
+ properties.load(input);
+ } catch (IOException e) {
+ throw new PluginException(e);
+ }
+
+ return properties;
+ }
+
+ protected Path getPropertiesPath(Path pluginPath, String propertiesFileName) throws PluginException {
+ if (Files.isDirectory(pluginPath)) {
+ return pluginPath.resolve(Paths.get(propertiesFileName));
+ } else {
+ // it's a jar file
+ try {
+ return FileUtils.getPath(pluginPath, propertiesFileName);
+ } catch (IOException e) {
+ throw new PluginException(e);
+ }
+ }
+ }
+
+ protected PluginDescriptor createPluginDescriptor(Properties properties) {
+ DefaultPluginDescriptor pluginDescriptor = createPluginDescriptorInstance();
+
+ // TODO validate !!!
+ String id = properties.getProperty("plugin.id");
+ pluginDescriptor.setPluginId(id);
+
+ String description = properties.getProperty("plugin.description");
+ if (StringUtils.isNullOrEmpty(description)) {
+ pluginDescriptor.setPluginDescription("");
+ } else {
+ pluginDescriptor.setPluginDescription(description);
+ }
+
+ String clazz = properties.getProperty("plugin.class");
+ pluginDescriptor.setPluginClass(clazz);
+
+ String version = properties.getProperty("plugin.version");
+ if (StringUtils.isNotNullOrEmpty(version)) {
+ pluginDescriptor.setPluginVersion(version);
+ }
+
+ String provider = properties.getProperty("plugin.provider");
+ pluginDescriptor.setProvider(provider);
+
+ String dependencies = properties.getProperty("plugin.dependencies");
+ pluginDescriptor.setDependencies(dependencies);
+
+ String requires = properties.getProperty("plugin.requires");
+ if (StringUtils.isNotNullOrEmpty(requires)) {
+ pluginDescriptor.setRequires(requires);
+ }
+
+ pluginDescriptor.setLicense(properties.getProperty("plugin.license"));
+
+ return pluginDescriptor;
+ }
+
+ protected DefaultPluginDescriptor createPluginDescriptorInstance() {
+ return new DefaultPluginDescriptor();
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/RuntimeMode.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/RuntimeMode.java
new file mode 100644
index 0000000..e31617d
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/RuntimeMode.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2013 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+/**
+ * @author Decebal Suiu
+ */
+public enum RuntimeMode {
+
+ DEVELOPMENT("development"), // development
+ DEPLOYMENT("deployment"); // deployment
+
+ private final String name;
+
+ private static final Map<String, RuntimeMode> map = new HashMap<>();
+
+ static {
+ for (RuntimeMode mode : RuntimeMode.values()) {
+ map.put(mode.name, mode);
+ }
+ }
+
+ private RuntimeMode(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ public static RuntimeMode byName(String name) {
+ if (map.containsKey(name)) {
+ return map.get(name);
+ }
+
+ throw new NoSuchElementException("Cannot found PF4J runtime mode with name '" + name +
+ "'. Must be 'development' or 'deployment'.");
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ServiceProviderExtensionFinder.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ServiceProviderExtensionFinder.java
new file mode 100644
index 0000000..cbcce48
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/ServiceProviderExtensionFinder.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2015 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.pf4j.processor.ServiceProviderExtensionStorage;
+import org.pf4j.util.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitOption;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * The {@link java.util.ServiceLoader} base implementation for {@link ExtensionFinder}.
+ * This class lookup extensions in all extensions index files {@code META-INF/services}.
+ *
+ * @author Decebal Suiu
+ */
+public class ServiceProviderExtensionFinder extends AbstractExtensionFinder {
+
+ private static final Logger log = LoggerFactory.getLogger(ServiceProviderExtensionFinder.class);
+
+ public ServiceProviderExtensionFinder(PluginManager pluginManager) {
+ super(pluginManager);
+ }
+
+ @Override
+ public Map<String, Set<String>> readClasspathStorages() {
+ log.debug("Reading extensions storages from classpath");
+ Map<String, Set<String>> result = new LinkedHashMap<>();
+
+ final Set<String> bucket = new HashSet<>();
+ try {
+ URL url = getClass().getClassLoader().getResource(getExtensionsResource());
+ if (url != null) {
+ Path extensionPath;
+ if (url.toURI().getScheme().equals("jar")) {
+ extensionPath = FileUtils.getPath(url.toURI(), getExtensionsResource());
+ } else {
+ extensionPath = Paths.get(url.toURI());
+ }
+
+ bucket.addAll(readExtensions(extensionPath));
+ }
+
+ debugExtensions(bucket);
+
+ result.put(null, bucket);
+ } catch (IOException | URISyntaxException e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return result;
+ }
+
+ @Override
+ public Map<String, Set<String>> readPluginsStorages() {
+ log.debug("Reading extensions storages from plugins");
+ Map<String, Set<String>> result = new LinkedHashMap<>();
+
+ List<PluginWrapper> plugins = pluginManager.getPlugins();
+ for (PluginWrapper plugin : plugins) {
+ String pluginId = plugin.getDescriptor().getPluginId();
+ log.debug("Reading extensions storages for plugin '{}'", pluginId);
+ final Set<String> bucket = new HashSet<>();
+
+ try {
+ URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource());
+ if (url != null) {
+ Path extensionPath;
+ if (url.toURI().getScheme().equals("jar")) {
+ extensionPath = FileUtils.getPath(url.toURI(), getExtensionsResource());
+ } else {
+ extensionPath = Paths.get(url.toURI());
+ }
+
+ bucket.addAll(readExtensions(extensionPath));
+ } else {
+ log.debug("Cannot find '{}'", getExtensionsResource());
+ }
+
+ debugExtensions(bucket);
+
+ result.put(pluginId, bucket);
+ } catch (IOException | URISyntaxException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+
+ return result;
+ }
+
+ private static String getExtensionsResource() {
+ return ServiceProviderExtensionStorage.EXTENSIONS_RESOURCE;
+ }
+
+ private Set<String> readExtensions(Path extensionPath) throws IOException {
+ final Set<String> result = new HashSet<>();
+ Files.walkFileTree(extensionPath, Collections.<FileVisitOption>emptySet(), 1, new SimpleFileVisitor<Path>() {
+
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ log.debug("Read '{}'", file);
+ try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
+ ServiceProviderExtensionStorage.read(reader, result);
+ }
+
+ return FileVisitResult.CONTINUE;
+ }
+
+ });
+
+ return result;
+ }
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Sha512SumVerifier.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Sha512SumVerifier.java
new file mode 100644
index 0000000..26f2535
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/Sha512SumVerifier.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.apache.commons.codec.digest.DigestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.lang.invoke.MethodHandles;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+/**
+ * Verifies that the SHA512 checksum of a downloaded file equals the checksum given in
+ * the plugins.json descriptor. This helps validate that the file downloaded is exactly
+ * the same as intended. Especially useful when dealing with meta repositories pointing
+ * to S3 or other 3rd party download locations that could have been tampered with.
+ */
+public class Sha512SumVerifier implements FileVerifier {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ /**
+ * Verifies a plugin release according to certain rules
+ *
+ * @param context the file verifier context object
+ * @param file the path to the downloaded file itself
+ * @throws IOException if there was a problem accessing file
+ * @throws VerifyException in case of problems verifying the file
+ */
+ @Override
+ public void verify(Context context, Path file) throws VerifyException, IOException {
+ String expectedSha512sum;
+ try {
+ if (context.sha512sum == null) {
+ log.debug("No sha512 checksum specified, skipping verification");
+ return;
+ } else if (context.sha512sum.equalsIgnoreCase(".sha512")) {
+ String url = context.url.substring(0, context.url.lastIndexOf(".")) + ".sha512";
+ expectedSha512sum = getUrlContents(url).split(" ")[0].trim();
+ } else if (context.sha512sum.startsWith("http")) {
+ expectedSha512sum = getUrlContents(context.sha512sum).split(" ")[0].trim();
+ } else {
+ expectedSha512sum = context.sha512sum;
+ }
+ } catch (IOException e) {
+ throw new VerifyException(e, "SHA512 checksum verification failed, could not download SHA512 file ({})", context.sha512sum);
+ }
+
+ log.debug("Verifying sha512 checksum of file {}", file.getFileName());
+ String actualSha512sum = DigestUtils.sha512Hex(Files.newInputStream(file));
+ if (actualSha512sum.equalsIgnoreCase(expectedSha512sum)) {
+ log.debug("Checksum OK");
+ return;
+ }
+ throw new VerifyException("SHA512 checksum of downloaded file " + file.getFileName()
+ + " does not match that from plugin descriptor. Got " + actualSha512sum
+ + " but expected " + expectedSha512sum);
+ }
+
+ private String getUrlContents(String url) throws IOException {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(
+ new URL(url).openStream()))) {
+ return reader.readLine();
+ }
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/SimpleFileDownloader.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/SimpleFileDownloader.java
new file mode 100644
index 0000000..c0a4c93
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/SimpleFileDownloader.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.ConnectException;
+import java.net.HttpURLConnection;
+import java.net.URISyntaxException;
+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.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+
+/**
+ * Downloads a file from a URL.
+ *
+ * @author Decebal Suiu
+ */
+public class SimpleFileDownloader implements FileDownloader {
+
+ private static final Logger log = LoggerFactory.getLogger(SimpleFileDownloader.class);
+
+ /**
+ * Downloads a file. If HTTP(S) or FTP, stream content, if local file:/ do a simple filesystem copy to tmp folder.
+ * Other protocols not supported.
+ *
+ * @param fileUrl the URI representing the file to download
+ * @return the path of downloaded/copied file
+ * @throws IOException in case of network or IO problems
+ * @throws PluginException in case of other problems
+ */
+ public Path downloadFile(URL fileUrl) throws PluginException, IOException {
+ switch (fileUrl.getProtocol()) {
+ case "http":
+ case "https":
+ case "ftp":
+ return downloadFileHttp(fileUrl);
+ case "file":
+ return copyLocalFile(fileUrl);
+ default:
+ throw new PluginException("URL protocol {} not supported", fileUrl.getProtocol());
+ }
+ }
+
+ /**
+ * Efficient copy of file in case of local file system.
+ *
+ * @param fileUrl source file
+ * @return path of target file
+ * @throws IOException if problems during copy
+ * @throws PluginException in case of other problems
+ */
+ protected Path copyLocalFile(URL fileUrl) throws IOException, PluginException {
+ Path destination = Files.createTempDirectory("pf4j-update-downloader");
+ destination.toFile().deleteOnExit();
+
+ try {
+ Path fromFile = Paths.get(fileUrl.toURI());
+ String path = fileUrl.getPath();
+ String fileName = path.substring(path.lastIndexOf('/') + 1);
+ Path toFile = destination.resolve(fileName);
+ Files.copy(fromFile, toFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
+
+ return toFile;
+ } catch (URISyntaxException e) {
+ throw new PluginException("Something wrong with given URL", e);
+ }
+ }
+
+ /**
+ * Downloads file from HTTP or FTP.
+ *
+ * @param fileUrl source file
+ * @return path of downloaded file
+ * @throws IOException if IO problems
+ * @throws PluginException if validation fails or any other problems
+ */
+ protected Path downloadFileHttp(URL fileUrl) throws IOException, PluginException {
+ Path destination = Files.createTempDirectory("pf4j-update-downloader");
+ destination.toFile().deleteOnExit();
+
+ String path = fileUrl.getPath();
+ String fileName = path.substring(path.lastIndexOf('/') + 1);
+ Path file = destination.resolve(fileName);
+
+ // set up the URL connection
+ URLConnection connection = fileUrl.openConnection();
+
+ // connect to the remote site (may takes some time)
+ connection.connect();
+
+ // check for http authorization
+ HttpURLConnection httpConnection = (HttpURLConnection) connection;
+ if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
+ throw new ConnectException("HTTP Authorization failure");
+ }
+
+ // try to get the server-specified last-modified date of this artifact
+ long lastModified = httpConnection.getHeaderFieldDate("Last-Modified", System.currentTimeMillis());
+
+ // try to get the input stream (three times)
+ InputStream is = null;
+ for (int i = 0; i < 3; i++) {
+ try {
+ is = connection.getInputStream();
+ break;
+ } catch (IOException e) {
+ log.error(e.getMessage(), e);
+ }
+ }
+ if (is == null) {
+ throw new ConnectException("Can't get '" + fileUrl + " to '" + file + "'");
+ }
+
+ // reade from remote resource and write to the local file
+ FileOutputStream fos = new FileOutputStream(file.toFile());
+ byte[] buffer = new byte[1024];
+ int length;
+ while ((length = is.read(buffer)) >= 0) {
+ fos.write(buffer, 0, length);
+ }
+ fos.close();
+ is.close();
+
+ log.debug("Set last modified of '{}' to '{}'", file, lastModified);
+ Files.setLastModifiedTime(file, FileTime.fromMillis(lastModified));
+
+ return file;
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/UpdateRepository.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/UpdateRepository.java
new file mode 100644
index 0000000..f46bc7b
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/UpdateRepository.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.net.URL;
+import java.util.Map;
+
+/**
+ * Contract for update repositories.
+ */
+public interface UpdateRepository {
+
+ /**
+ * @return the ID of this repository. This must be unique
+ */
+ String getId();
+
+ /**
+ * @return the URL of this repository as a String
+ */
+ URL getUrl();
+
+ /**
+ * Get all plugin information for this repository.
+ *
+ * @return Map of PluginId and PluginInfo
+ */
+ Map<String, PluginInfo> getPlugins();
+
+ /**
+ * Get a particular plugin information from this repository.
+ *
+ * @param id the id of the plugin
+ * @return the PluginInfo
+ */
+ PluginInfo getPlugin(String id);
+
+ /**
+ * Flushes cached info to force re-fetching repository state on next get.
+ */
+ void refresh();
+
+ /**
+ * Each repository has the option of overriding the download process.
+ * They can e.g. do checksum, signature verifications etc.
+ * To use the default downloader, return null.
+ *
+ * @return the FileDownloader to use for this repository or null if you do not wish to override
+ */
+ FileDownloader getFileDownloader();
+
+ /**
+ * Gets a file verifier to execute on the downloaded file for it to be claimed valid.
+ * May be a CompoundVerifier in order to chain several verifiers.
+ * @return {@link FileVerifier}
+ */
+ FileVerifier getFileVerfier();
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/VerifyException.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/VerifyException.java
new file mode 100644
index 0000000..ef88cf5
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/VerifyException.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+
+/**
+ * Marker exception for plugin verification failure
+ */
+public class VerifyException extends PluginException {
+ public VerifyException(String message) {
+ super(message);
+ }
+
+ public VerifyException(Throwable cause, String message, Object... args) {
+ super(cause, message, args);
+ }
+
+ public VerifyException(String message, Object... args) {
+ super(message, args);
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/VersionManager.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/VersionManager.java
new file mode 100644
index 0000000..7da7670
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/VersionManager.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2017 Decebal Suiu
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+import java.util.Comparator;
+
+/**
+ * Manager responsible for versions of plugins.
+ *
+ * @author Decebal Suiu
+ */
+public interface VersionManager {
+
+ /**
+ * Check if a {@code constraint} and a {@code version} match.
+ * A possible constrain can be {@code >=1.0.0 & <2.0.0}.
+ *
+ */
+ boolean checkVersionConstraint(String version, String constraint);
+
+ /**
+ * Compare two versions. It's similar with {@link Comparator#compare(Object, Object)}.
+ *
+ */
+ int compareVersions(String v1, String v2);
+
+}
diff --git a/solr/core/src/java/org/apache/solr/packagemanager/pf4j/package-info.java b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/package-info.java
new file mode 100644
index 0000000..55a83c8
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/packagemanager/pf4j/package-info.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2012-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Implementations of {@link org.pf4j.update.FileVerifier} interface.
+ * An verifier implementation will do a specific kind of check on the downloaded plugin file
+ * in orer to verify that it is complete, safe, compliant or whatever needs to be verified.
+ */
+package org.apache.solr.packagemanager.pf4j;
+
+
diff --git a/solr/core/src/java/org/apache/solr/util/PackageTool.java b/solr/core/src/java/org/apache/solr/util/PackageTool.java
index e138fae..8fd9670 100644
--- a/solr/core/src/java/org/apache/solr/util/PackageTool.java
+++ b/solr/core/src/java/org/apache/solr/util/PackageTool.java
@@ -38,9 +38,9 @@ import org.apache.solr.packagemanager.SolrUpdateManager;
import org.apache.solr.util.SolrCLI.StatusTool;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.pf4j.PluginException;
-import org.pf4j.PluginWrapper;
-import org.pf4j.update.PluginInfo;
+import org.apache.solr.packagemanager.pf4j.PluginException;
+import org.apache.solr.packagemanager.pf4j.PluginWrapper;
+import org.apache.solr.packagemanager.pf4j.PluginInfo;
import com.google.gson.Gson;