Skip to content

The Unified and Autonomous Development Platform

Rework lib loading logic to be more flexible

robin shine907146b3a486
diff --git a/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/Bootstrap.java b/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/Bootstrap.java
index 0ed799b048..09c9ebeaa9 100644
--- a/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/Bootstrap.java
+++ b/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/Bootstrap.java
@@ -1,362 +1,387 @@
-package com.pmease.commons.bootstrap;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Handler;
-
-import javax.annotation.Nullable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.bridge.SLF4JBridgeHandler;
-
-import ch.qos.logback.classic.LoggerContext;
-import ch.qos.logback.classic.joran.JoranConfigurator;
-import ch.qos.logback.core.joran.spi.JoranException;
-import ch.qos.logback.core.util.StatusPrinter;
-
-public class Bootstrap {
-
- private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class);
-
- public static final int SOCKET_CONNECT_TIMEOUT = 60000;
-
- public static final String APP_LOADER_PROPERTY_NAME = "appLoader";
-
- public static final String LOGBACK_CONFIG_FILE_PROPERTY_NAME = "logback.configurationFile";
-
- public static final String DEFAULT_APP_LOADER = "com.pmease.commons.loader.AppLoader";
-
- public static File installDir;
-
- public static List<File> libFiles;
-
- public static boolean sandboxMode;
-
- public static boolean prodMode;
-
- @Nullable
- public static Command command;
-
- @SuppressWarnings("unchecked")
- public static void main(String[] args) {
- try {
- Locale.setDefault(Locale.US);
-
- File sandboxDir = new File("target/sandbox");
- if (sandboxDir.exists()) {
- Map<String, File> systemClasspath = (Map<String, File>) BootstrapUtils
- .readObject(new File(sandboxDir, "boot/system.classpath"));
- Set<String> bootstrapKeys = (Set<String>) BootstrapUtils
- .readObject(new File(sandboxDir, "boot/bootstrap.keys"));
-
- List<URL> urls = new ArrayList<URL>();
- for (String key : bootstrapKeys) {
- File file = systemClasspath.get(key);
- if (file == null)
- throw new RuntimeException("Unable to find bootstrap file for '" + key + "'.");
- try {
- urls.add(file.toURI().toURL());
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
-
- URLClassLoader bootClassLoader = new URLClassLoader(urls.toArray(new URL[0]),
- Bootstrap.class.getClassLoader().getParent());
- Thread.currentThread().setContextClassLoader(bootClassLoader);
-
- try {
- Class<?> bootstrapClass = bootClassLoader.loadClass(Bootstrap.class.getName());
- bootstrapClass.getMethod("boot", String[].class).invoke(null, new Object[] {args});
- } catch (Exception e) {
- throw BootstrapUtils.unchecked(e);
- }
-
- } else {
- boot(args);
- }
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- @SuppressWarnings("unchecked")
- public static void boot(String[] args) {
- /*
- * Sandbox mode might be checked frequently so we cache the result here
- * to avoid calling File.exists() frequently.
- */
- sandboxMode = new File("target/sandbox").exists();
- prodMode = (System.getProperty("prod") != null);
-
- File loadedFrom = new File(Bootstrap.class.getProtectionDomain().getCodeSource().getLocation().getFile());
-
- if (new File(loadedFrom.getParentFile(), "bootstrap.keys").exists())
- installDir = loadedFrom.getParentFile().getParentFile();
- else if (new File("target/sandbox").exists())
- installDir = new File("target/sandbox");
- else
- throw new RuntimeException("Unable to find product directory.");
-
- try {
- installDir = installDir.getCanonicalFile();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- if (args.length != 0) {
- String[] commandArgs = new String[args.length-1];
- System.arraycopy(args, 1, commandArgs, 0, commandArgs.length);
- command = new Command(args[0], commandArgs);
- } else {
- command = null;
- }
-
- configureLogging();
-
- try {
- if (command == null) {
- getStatusDir().mkdirs();
- if (!getStatusDir().exists()) {
- throw new RuntimeException("Unable to create directory: " + getStatusDir().getAbsolutePath());
- }
-
- if (!sandboxMode) {
- File serverRunningFile = getServerRunningFile();
- if (serverRunningFile.exists())
- throw new RuntimeException("Server is already running");
-
- try {
- serverRunningFile.createNewFile();
- serverRunningFile.deleteOnExit();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- File tempDir = Bootstrap.getTempDir();
- if (tempDir.exists()) {
- logger.info("Cleaning temp directory...");
- BootstrapUtils.cleanDir(tempDir);
- } else if (!tempDir.mkdirs()) {
- throw new RuntimeException("Can not create directory '" + tempDir.getAbsolutePath() + "'.");
- }
- System.setProperty("java.io.tmpdir", tempDir.getAbsolutePath());
-
- logger.info("Launching application from '" + installDir.getAbsolutePath() + "'...");
-
- libFiles = new ArrayList<File>();
-
- File classpathFile = new File(installDir, "boot/system.classpath");
- if (classpathFile.exists()) {
- Map<String, File> systemClasspath = (Map<String, File>) BootstrapUtils.readObject(classpathFile);
-
- Set<String> bootstrapKeys = (Set<String>) BootstrapUtils
- .readObject(new File(installDir, "boot/bootstrap.keys"));
- for (Map.Entry<String, File> entry : systemClasspath.entrySet()) {
- if (!bootstrapKeys.contains(entry.getKey()))
- libFiles.add(entry.getValue());
- }
- } else {
- File libCacheDir = BootstrapUtils.createTempDir("libcache");
-
- for (File file : getLibDir().listFiles()) {
- if (file.getName().endsWith(".jar"))
- libFiles.add(file);
- else if (file.getName().endsWith(".zip"))
- BootstrapUtils.unzip(file, libCacheDir);
- }
- for (File file : getPluginsDir().listFiles()) {
- if (file.getName().endsWith(".jar"))
- libFiles.add(file);
- else if (file.getName().endsWith(".zip"))
- BootstrapUtils.unzip(file, libCacheDir);
- }
-
- for (File file : libCacheDir.listFiles()) {
- if (file.getName().endsWith(".jar"))
- libFiles.add(file);
- }
-
- }
-
- // load our jars first so that we can override classes in third party
- // jars if necessary.
- libFiles.sort((file1, file2) -> {
- Boolean result1 = file1.isDirectory() || file1.getName().startsWith("com.pmease");
- Boolean result2 = file2.isDirectory() || file2.getName().startsWith("com.pmease");
-
- return result2.compareTo(result1);
- });
-
- List<URL> urls = new ArrayList<URL>();
-
- for (File file : libFiles) {
- try {
- urls.add(file.toURI().toURL());
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
-
- ClassLoader appClassLoader = new URLClassLoader(urls.toArray(new URL[0]), Bootstrap.class.getClassLoader()) {
-
- private Map<String, CachedUrl> resourceCache = new ConcurrentHashMap<String, CachedUrl>();
-
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- return super.findClass(name);
- }
-
- @Override
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- return super.loadClass(name);
- }
-
- @Override
- public URL findResource(String name) {
- URL url;
- CachedUrl cachedUrl = resourceCache.get(name);
- if (cachedUrl == null) {
- url = super.findResource(name);
- resourceCache.put(name, new CachedUrl(url));
- } else {
- url = cachedUrl.getUrl();
- }
- return url;
- }
-
- };
- ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(appClassLoader);
-
- try {
- String appLoaderClassName = System.getProperty(APP_LOADER_PROPERTY_NAME);
- if (appLoaderClassName == null)
- appLoaderClassName = DEFAULT_APP_LOADER;
-
- final Startable appLoader;
- try {
- Class<?> appLoaderClass = appClassLoader.loadClass(appLoaderClassName);
- appLoader = (Startable) appLoaderClass.newInstance();
- appLoader.start();
- } catch (Exception e) {
- throw BootstrapUtils.unchecked(e);
- }
-
- Runtime.getRuntime().addShutdownHook(new Thread() {
- public void run() {
- try {
- appLoader.stop();
- } catch (Exception e) {
- throw BootstrapUtils.unchecked(e);
- }
- }
- });
- } finally {
- Thread.currentThread().setContextClassLoader(originClassLoader);
- }
- } catch (Exception e) {
- logger.error("Error booting application", e);
- System.exit(1);
- }
- }
-
- private static void configureLogging() {
- // Set system properties so that they can be used in logback
- // configuration file.
- if (command != null) {
- System.setProperty("logback.logFile", installDir.getAbsolutePath() + "/logs/" + command.getName() + ".log");
- System.setProperty("logback.fileLogPattern", "%-5level - %msg%n");
- System.setProperty("logback.consoleLogPattern", "%-5level - %msg%n");
- } else {
- System.setProperty("logback.logFile", installDir.getAbsolutePath() + "/logs/server.log");
- System.setProperty("logback.consoleLogPattern", "%d{HH:mm:ss,SSS} %-5level %logger{36} - %msg%n");
- System.setProperty("logback.fileLogPattern", "%date %-5level [%thread] %logger{36} %msg%n");
- }
-
- File configFile = new File(installDir, "conf/logback.xml");
- System.setProperty(LOGBACK_CONFIG_FILE_PROPERTY_NAME, configFile.getAbsolutePath());
-
- LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
-
- try {
- JoranConfigurator configurator = new JoranConfigurator();
- configurator.setContext(lc);
- lc.reset();
- configurator.doConfigure(configFile);
- } catch (JoranException je) {
- je.printStackTrace();
- }
- StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
-
- // Redirect JDK logging to slf4j
- java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger("");
- for (Handler handler : jdkLogger.getHandlers())
- jdkLogger.removeHandler(handler);
- SLF4JBridgeHandler.install();
- }
-
- public static File getBinDir() {
- return new File(installDir, "bin");
- }
-
- public static File getBootDir() {
- return new File(installDir, "boot");
- }
-
- public static File getStatusDir() {
- return new File(installDir, "status");
- }
-
- public static File getServerRunningFile() {
- return new File(getStatusDir(), "server_running");
- }
-
- public static File getLibDir() {
- return new File(installDir, "lib");
- }
-
- public static File getTempDir() {
- if (command != null)
- return new File(installDir, "temp/" + command.getName());
- else
- return new File(installDir, "temp/server");
- }
-
- public static File getConfDir() {
- return new File(installDir, "conf");
- }
-
- public static File getSiteDir() {
- return new File(installDir, "site");
- }
-
- public static File getPluginsDir() {
- return new File(installDir, "plugins");
- }
-
- private static class CachedUrl {
- private final URL url;
-
- public CachedUrl(URL url) {
- this.url = url;
- }
-
- public URL getUrl() {
- return url;
- }
- }
-}
+package com.pmease.commons.bootstrap;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.jar.JarFile;
+import java.util.logging.Handler;
+
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.bridge.SLF4JBridgeHandler;
+
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.joran.JoranConfigurator;
+import ch.qos.logback.core.joran.spi.JoranException;
+import ch.qos.logback.core.util.StatusPrinter;
+
+public class Bootstrap {
+
+ private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class);
+
+ public static final int SOCKET_CONNECT_TIMEOUT = 60000;
+
+ public static final String APP_LOADER_PROPERTY_NAME = "appLoader";
+
+ public static final String LOGBACK_CONFIG_FILE_PROPERTY_NAME = "logback.configurationFile";
+
+ public static final String DEFAULT_APP_LOADER = "com.pmease.commons.loader.AppLoader";
+
+ public static File installDir;
+
+ public static boolean sandboxMode;
+
+ public static boolean prodMode;
+
+ @Nullable
+ public static Command command;
+
+ @SuppressWarnings("unchecked")
+ public static void main(String[] args) {
+ try {
+ Locale.setDefault(Locale.US);
+
+ File sandboxDir = new File("target/sandbox");
+ if (sandboxDir.exists()) {
+ Map<String, File> systemClasspath = (Map<String, File>) BootstrapUtils
+ .readObject(new File(sandboxDir, "boot/system.classpath"));
+ Set<String> bootstrapKeys = (Set<String>) BootstrapUtils
+ .readObject(new File(sandboxDir, "boot/bootstrap.keys"));
+
+ List<URL> urls = new ArrayList<URL>();
+ for (String key : bootstrapKeys) {
+ File file = systemClasspath.get(key);
+ if (file == null)
+ throw new RuntimeException("Unable to find bootstrap file for '" + key + "'.");
+ try {
+ urls.add(file.toURI().toURL());
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ URLClassLoader bootClassLoader = new URLClassLoader(urls.toArray(new URL[0]),
+ Bootstrap.class.getClassLoader().getParent());
+ Thread.currentThread().setContextClassLoader(bootClassLoader);
+
+ try {
+ Class<?> bootstrapClass = bootClassLoader.loadClass(Bootstrap.class.getName());
+ bootstrapClass.getMethod("boot", String[].class).invoke(null, new Object[] {args});
+ } catch (Exception e) {
+ throw BootstrapUtils.unchecked(e);
+ }
+
+ } else {
+ boot(args);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public static void boot(String[] args) {
+ /*
+ * Sandbox mode might be checked frequently so we cache the result here
+ * to avoid calling File.exists() frequently.
+ */
+ sandboxMode = new File("target/sandbox").exists();
+ prodMode = (System.getProperty("prod") != null);
+
+ File loadedFrom = new File(Bootstrap.class.getProtectionDomain().getCodeSource().getLocation().getFile());
+
+ if (new File(loadedFrom.getParentFile(), "bootstrap.keys").exists())
+ installDir = loadedFrom.getParentFile().getParentFile();
+ else if (new File("target/sandbox").exists())
+ installDir = new File("target/sandbox");
+ else
+ throw new RuntimeException("Unable to find product directory.");
+
+ try {
+ installDir = installDir.getCanonicalFile();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ if (args.length != 0) {
+ String[] commandArgs = new String[args.length-1];
+ System.arraycopy(args, 1, commandArgs, 0, commandArgs.length);
+ command = new Command(args[0], commandArgs);
+ } else {
+ command = null;
+ }
+
+ configureLogging();
+
+ try {
+ if (command == null) {
+ getStatusDir().mkdirs();
+ if (!getStatusDir().exists()) {
+ throw new RuntimeException("Unable to create directory: " + getStatusDir().getAbsolutePath());
+ }
+
+ if (!sandboxMode) {
+ File serverRunningFile = getServerRunningFile();
+ if (serverRunningFile.exists())
+ throw new RuntimeException("Server is already running");
+
+ try {
+ serverRunningFile.createNewFile();
+ serverRunningFile.deleteOnExit();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ File tempDir = Bootstrap.getTempDir();
+ if (tempDir.exists()) {
+ logger.info("Cleaning temp directory...");
+ BootstrapUtils.cleanDir(tempDir);
+ } else if (!tempDir.mkdirs()) {
+ throw new RuntimeException("Can not create directory '" + tempDir.getAbsolutePath() + "'.");
+ }
+ System.setProperty("java.io.tmpdir", tempDir.getAbsolutePath());
+
+ logger.info("Launching application from '" + installDir.getAbsolutePath() + "'...");
+
+ List<File> libFiles = new ArrayList<File>();
+ libFiles.addAll(getLibFiles(getSiteLibDir()));
+
+ Map<String, File> systemClasspath;
+ File classpathFile = new File(installDir, "boot/system.classpath");
+ if (classpathFile.exists()) {
+ systemClasspath = (Map<String, File>) BootstrapUtils.readObject(classpathFile);
+ } else {
+ systemClasspath = new HashMap<>();
+ }
+ Set<String> bootstrapKeys = (Set<String>) BootstrapUtils
+ .readObject(new File(installDir, "boot/bootstrap.keys"));
+ for (Map.Entry<String, File> entry : systemClasspath.entrySet()) {
+ if (!bootstrapKeys.contains(entry.getKey())) {
+ libFiles.add(entry.getValue());
+ }
+ }
+
+ for (File libFile: getLibFiles(getLibDir())) {
+ if (!systemClasspath.containsKey(libFile.getName()))
+ libFiles.add(libFile);
+ }
+
+ List<URL> urls = new ArrayList<URL>();
+
+ // load our jars first so that we can override classes in third party
+ // jars if necessary.
+ for (File file : libFiles) {
+ if (isPriorityLib(file)) {
+ try {
+ urls.add(file.toURI().toURL());
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+ for (File file : libFiles) {
+ if (!isPriorityLib(file)) {
+ try {
+ urls.add(file.toURI().toURL());
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ ClassLoader appClassLoader = new URLClassLoader(urls.toArray(new URL[0]), Bootstrap.class.getClassLoader()) {
+
+ private Map<String, CachedUrl> resourceCache = new ConcurrentHashMap<String, CachedUrl>();
+
+ @Override
+ protected Class<?> findClass(String name) throws ClassNotFoundException {
+ return super.findClass(name);
+ }
+
+ @Override
+ public Class<?> loadClass(String name) throws ClassNotFoundException {
+ return super.loadClass(name);
+ }
+
+ @Override
+ public URL findResource(String name) {
+ URL url;
+ CachedUrl cachedUrl = resourceCache.get(name);
+ if (cachedUrl == null) {
+ url = super.findResource(name);
+ resourceCache.put(name, new CachedUrl(url));
+ } else {
+ url = cachedUrl.getUrl();
+ }
+ return url;
+ }
+
+ };
+ ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(appClassLoader);
+
+ try {
+ String appLoaderClassName = System.getProperty(APP_LOADER_PROPERTY_NAME);
+ if (appLoaderClassName == null)
+ appLoaderClassName = DEFAULT_APP_LOADER;
+
+ final Startable appLoader;
+ try {
+ Class<?> appLoaderClass = appClassLoader.loadClass(appLoaderClassName);
+ appLoader = (Startable) appLoaderClass.newInstance();
+ appLoader.start();
+ } catch (Exception e) {
+ throw BootstrapUtils.unchecked(e);
+ }
+
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ public void run() {
+ try {
+ appLoader.stop();
+ } catch (Exception e) {
+ throw BootstrapUtils.unchecked(e);
+ }
+ }
+ });
+ } finally {
+ Thread.currentThread().setContextClassLoader(originClassLoader);
+ }
+ } catch (Exception e) {
+ logger.error("Error booting application", e);
+ System.exit(1);
+ }
+ }
+
+ private static boolean isPriorityLib(File lib) {
+ String entryName = "pmease-artifact.properties";
+ if (lib.isDirectory()) {
+ return new File(lib, entryName).exists();
+ } else {
+ try (JarFile jarFile = new JarFile(lib)) {
+ return jarFile.getJarEntry(entryName) != null;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ private static List<File> getLibFiles(File libDir) {
+ List<File> libFiles = new ArrayList<>();
+ File libCacheDir = BootstrapUtils.createTempDir("libcache");
+ for (File file : libDir.listFiles()) {
+ if (file.getName().endsWith(".jar"))
+ libFiles.add(file);
+ else if (file.getName().endsWith(".zip"))
+ BootstrapUtils.unzip(file, libCacheDir);
+ }
+ for (File file : libCacheDir.listFiles()) {
+ if (file.getName().endsWith(".jar"))
+ libFiles.add(file);
+ }
+ return libFiles;
+ }
+
+ private static void configureLogging() {
+ // Set system properties so that they can be used in logback
+ // configuration file.
+ if (command != null) {
+ System.setProperty("logback.logFile", installDir.getAbsolutePath() + "/logs/" + command.getName() + ".log");
+ System.setProperty("logback.fileLogPattern", "%-5level - %msg%n");
+ System.setProperty("logback.consoleLogPattern", "%-5level - %msg%n");
+ } else {
+ System.setProperty("logback.logFile", installDir.getAbsolutePath() + "/logs/server.log");
+ System.setProperty("logback.consoleLogPattern", "%d{HH:mm:ss,SSS} %-5level %logger{36} - %msg%n");
+ System.setProperty("logback.fileLogPattern", "%date %-5level [%thread] %logger{36} %msg%n");
+ }
+
+ File configFile = new File(installDir, "conf/logback.xml");
+ System.setProperty(LOGBACK_CONFIG_FILE_PROPERTY_NAME, configFile.getAbsolutePath());
+
+ LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
+
+ try {
+ JoranConfigurator configurator = new JoranConfigurator();
+ configurator.setContext(lc);
+ lc.reset();
+ configurator.doConfigure(configFile);
+ } catch (JoranException je) {
+ je.printStackTrace();
+ }
+ StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
+
+ // Redirect JDK logging to slf4j
+ java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger("");
+ for (Handler handler : jdkLogger.getHandlers())
+ jdkLogger.removeHandler(handler);
+ SLF4JBridgeHandler.install();
+ }
+
+ public static File getBinDir() {
+ return new File(installDir, "bin");
+ }
+
+ public static File getBootDir() {
+ return new File(installDir, "boot");
+ }
+
+ public static File getStatusDir() {
+ return new File(installDir, "status");
+ }
+
+ public static File getServerRunningFile() {
+ return new File(getStatusDir(), "server_running");
+ }
+
+ public static File getLibDir() {
+ return new File(installDir, "lib");
+ }
+
+ public static File getSiteLibDir() {
+ return new File(getSiteDir(), "lib");
+ }
+
+ public static File getTempDir() {
+ if (command != null)
+ return new File(installDir, "temp/" + command.getName());
+ else
+ return new File(installDir, "temp/server");
+ }
+
+ public static File getConfDir() {
+ return new File(installDir, "conf");
+ }
+
+ public static File getSiteDir() {
+ return new File(installDir, "site");
+ }
+
+ public static File getPluginsDir() {
+ return new File(installDir, "plugins");
+ }
+
+ private static class CachedUrl {
+ private final URL url;
+
+ public CachedUrl(URL url) {
+ this.url = url;
+ }
+
+ public URL getUrl() {
+ return url;
+ }
+ }
+}
diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/command/UpgradeCommand.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/command/UpgradeCommand.java
index 692a4a4780..efe6b2e738 100644
--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/command/UpgradeCommand.java
+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/command/UpgradeCommand.java
@@ -1,343 +1,351 @@
-package com.pmease.commons.hibernate.command;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.validation.Validator;
-
-import org.apache.commons.lang3.SystemUtils;
-import org.hibernate.Interceptor;
-import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
-import org.joda.time.DateTime;
-import org.joda.time.format.DateTimeFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.pmease.commons.bootstrap.Bootstrap;
-import com.pmease.commons.hibernate.DefaultPersistManager;
-import com.pmease.commons.hibernate.HibernateProperties;
-import com.pmease.commons.hibernate.IdManager;
-import com.pmease.commons.hibernate.ModelProvider;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.migration.MigrationHelper;
-import com.pmease.commons.hibernate.migration.Migrator;
-import com.pmease.commons.loader.PluginManager;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.execution.Commandline;
-import com.pmease.commons.util.execution.LineConsumer;
-
-@Singleton
-public class UpgradeCommand extends DefaultPersistManager {
-
- private static final Logger logger = LoggerFactory.getLogger(UpgradeCommand.class);
-
- private static final String BACKUP_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss";
-
- private final String appName;
-
- @Inject
- public UpgradeCommand(Set<ModelProvider> modelProviders, PhysicalNamingStrategy physicalNamingStrategy,
- HibernateProperties properties, Migrator migrator, Interceptor interceptor,
- IdManager idManager, Dao dao, Validator validator, PluginManager pluginManager) {
- super(modelProviders, physicalNamingStrategy, properties, migrator, interceptor, idManager, dao, validator);
- appName = pluginManager.getProduct().getName();
- }
-
- protected Commandline buildCommandline(File upgradeDir, String command, String...commandArgs) {
- Commandline cmdline= new Commandline(System.getProperty("java.home") + "/bin/java");
- cmdline.addArgs("-Xmx" + Runtime.getRuntime().maxMemory()/1024/1024 + "m", "-classpath", "*",
- "com.pmease.commons.bootstrap.Bootstrap", command);
- cmdline.addArgs(commandArgs);
- cmdline.workingDir(new File(upgradeDir, "boot"));
- return cmdline;
- }
-
- private String prefixUpgradeTargetLog(String line) {
- return ">>> " + line;
- }
-
- @Override
- public void start() {
- if (Bootstrap.command.getArgs().length == 0) {
- logger.error("Missing upgrade target parameter. Usage: {} <installation directory of old {} version>",
- Bootstrap.command.getScript(), appName);
- System.exit(1);
- }
- File upgradeDir = new File(Bootstrap.command.getArgs()[0]);
- if (!upgradeDir.isAbsolute())
- upgradeDir = new File(Bootstrap.getBinDir(), upgradeDir.getPath());
-
- if (!upgradeDir.exists()) {
- logger.error("Unable to find directory: {}", upgradeDir.getAbsolutePath());
- System.exit(1);
- }
-
- logger.info("Upgrading {}...", upgradeDir.getAbsolutePath());
-
- if (!new File(upgradeDir, "boot/bootstrap.keys").exists()) {
- logger.error("Invalid {} installation directory: {}, make sure you are specifying the top level "
- + "installation directory (it contains sub directories such as \"bin\", \"boot\", \"conf\", etc)",
- appName, upgradeDir.getAbsolutePath());
- System.exit(1);
- }
-
- if (new File(upgradeDir, "status/server_running").exists()) {
- logger.error("Please stop server running at \"{}\" before upgrading", upgradeDir.getAbsolutePath());
- System.exit(1);
- }
- if (Bootstrap.getServerRunningFile().exists()) {
- logger.error("Please stop server running at \"{}\" before upgrading", Bootstrap.installDir.getAbsolutePath());
- System.exit(1);
- }
-
- AtomicReference<String> oldDataVersion = new AtomicReference<>(null);
- int ret = buildCommandline(upgradeDir, "check_data_version").execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- String prefix = "Data version: ";
- if (line.startsWith(prefix)) {
- oldDataVersion.set(line.substring(prefix.length()));
- logger.info("Old data version: " + oldDataVersion.get());
- } else {
- logger.info(prefixUpgradeTargetLog(line));
- }
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.error(prefixUpgradeTargetLog(line));
- }}
-
- ).getReturnCode();
-
- if (ret != 0) {
- logger.error("Unable to upgrade specified installation due to above error");
- System.exit(1);
- }
-
- AtomicBoolean usingEmbeddedDB = new AtomicBoolean(false);
- ret = buildCommandline(upgradeDir, "db_dialect").execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- String prefix = "Database dialect: ";
- String dialect;
- if (line.startsWith(prefix)) {
- dialect = line.substring(prefix.length());
- logger.info("Database dialect: " + dialect);
- if (dialect.toLowerCase().contains("hsql"))
- usingEmbeddedDB.set(true);
- } else {
- logger.info(prefixUpgradeTargetLog(line));
- }
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.error(prefixUpgradeTargetLog(line));
- }}
-
- ).getReturnCode();
-
- if (ret != 0) {
- logger.error("Unable to upgrade specified installation due to above error");
- System.exit(1);
- }
-
- File upgradeBackup = new File(Bootstrap.installDir, getBackupName(upgradeDir.getName()));
- FileUtils.createDir(upgradeBackup);
- File dbBackup = null;
-
- if (usingEmbeddedDB.get()) {
- logger.info("Backing up old installation directory as {}...", upgradeBackup.getAbsolutePath());
- try {
- FileUtils.copyDirectory(upgradeDir, upgradeBackup);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- if (!MigrationHelper.getVersion(migrator.getClass()).equals(oldDataVersion.get())) {
- dbBackup = new File(upgradeDir, getBackupName("dbbackup") + ".zip");
- logger.info("Backing up database as {}...", dbBackup.getAbsolutePath());
- backupDB(upgradeDir, dbBackup);
- }
- } else {
- // for non-embedded database, we should include database backup in the old installation backup directory
- // in case we need that for database restore after a failed upgrade
- if (!MigrationHelper.getVersion(migrator.getClass()).equals(oldDataVersion.get())) {
- dbBackup = new File(upgradeDir, getBackupName("dbbackup") + ".zip");
- logger.info("Backing up database as {}...", dbBackup.getAbsolutePath());
- backupDB(upgradeDir, dbBackup);
- }
-
- logger.info("Backing up old installation directory as {}...", upgradeBackup.getAbsolutePath());
- try {
- FileUtils.copyDirectory(upgradeDir, upgradeBackup);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- boolean failed;
- try {
- if (dbBackup != null) {
- logger.info("Cleaning database with old program version...");
- ret = buildCommandline(upgradeDir, "clean").execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.info(prefixUpgradeTargetLog(line));
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.error(prefixUpgradeTargetLog(line));
- }
-
- }).getReturnCode();
-
- if (ret != 0) {
- logger.error("Failed to upgrade {}", upgradeDir.getAbsolutePath());
- failed = true;
- } else {
- failed = false;
- }
-
- if (!failed) {
- logger.info("Copying new program files into {}...", upgradeDir.getAbsolutePath());
- copyProgramFilesTo(upgradeDir);
-
- logger.info("Restoring database with new program version...");
- ret = buildCommandline(upgradeDir, "restore", dbBackup.getAbsolutePath()).execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.info(prefixUpgradeTargetLog(line));
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.error(prefixUpgradeTargetLog(line));
- }
-
- }).getReturnCode();
-
- if (ret != 0) {
- logger.error("Failed to upgrade {}", upgradeDir.getAbsolutePath());
- failed = true;
- } else {
- failed = false;
- }
- }
- } else {
- logger.info("Copying new program files into {}...", upgradeDir.getAbsolutePath());
- copyProgramFilesTo(upgradeDir);
- failed = false;
- }
- } catch (Exception e) {
- logger.error("Error upgrading " + upgradeDir.getAbsolutePath(), e);
- failed = true;
- }
-
- if (failed) {
- logger.info("Now restoring old installation directory due to upgrade failure...");
- try {
- /* we do not clean upgradeDir here directly as user may open
- * a command prompt inside the various sub directories to
- * cause it unable to be deleted
- */
- for (File child: upgradeDir.listFiles()) {
- if (child.isDirectory())
- FileUtils.cleanDir(child);
- else
- FileUtils.deleteFile(child);
- }
- FileUtils.copyDirectory(upgradeBackup, upgradeDir);
- logger.info("Old installation directory is now restored.");
- } catch (Exception e2) {
- logger.error("Error restoring old installation directory", e2);
- logger.warn("Please restore it manually by deleting all contents under directory \"{}\", and then copying over all contents under directory \"{}\"",
- upgradeDir.getAbsolutePath(), upgradeBackup.getAbsolutePath());
- }
- if (!usingEmbeddedDB.get() && dbBackup != null) {
- logger.warn("The database might be in an inconsistent state due to upgrade failure. In that case, "
- + "you need to restore the database by first cleaning it, and then running below command:");
- if (SystemUtils.IS_OS_WINDOWS) {
- logger.info(upgradeDir.getAbsolutePath() + File.separator + "bin" + File.separator + "restore.bat " + dbBackup.getAbsolutePath());
- } else {
- logger.info(upgradeDir.getAbsolutePath() + File.separator + "bin" + File.separator + "restore.sh " + dbBackup.getAbsolutePath());
- }
- }
- System.exit(1);
- } else {
- logger.info("Successfully upgraded {}", upgradeDir.getAbsolutePath());
- System.exit(0);
- }
- }
-
- private void backupDB(File upgradeDir, File dbBackup) {
- int ret = buildCommandline(upgradeDir, "backup", dbBackup.getAbsolutePath()).execute(new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.info(prefixUpgradeTargetLog(line));
- }
-
- }, new LineConsumer() {
-
- @Override
- public void consume(String line) {
- logger.error(prefixUpgradeTargetLog(line));
- }
-
- }).getReturnCode();
-
- if (ret != 0) {
- logger.error("Unable to upgrade specified installation due to above error");
- System.exit(1);
- }
- }
-
- private String getBackupName(String name) {
- return name + "~" + DateTimeFormat.forPattern(BACKUP_DATETIME_FORMAT).print(new DateTime());
- }
-
- protected void copyProgramFilesTo(File upgradeDir) {
- cleanAndCopy(new File(Bootstrap.installDir, "3rdparty-licenses"), new File(upgradeDir, "3rdparty-licenses"));
- cleanAndCopy(Bootstrap.getBinDir(), new File(upgradeDir, "bin"));
- cleanAndCopy(Bootstrap.getBootDir(), new File(upgradeDir, "boot"));
- cleanAndCopy(Bootstrap.getLibDir(), new File(upgradeDir, "lib"));
- try {
- FileUtils.copyFile(new File(Bootstrap.installDir, "conf/wrapper-license.conf"),
- new File(upgradeDir, "conf/wrapper-license.conf"));
- FileUtils.copyFile(new File(Bootstrap.installDir, "readme.txt"), new File(upgradeDir, "readme.txt"));
- FileUtils.copyFile(new File(Bootstrap.installDir, "license.txt"), new File(upgradeDir, "license.txt"));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- protected void cleanAndCopy(File srcDir, File destDir) {
- try {
- FileUtils.cleanDir(destDir);
- FileUtils.copyDirectory(srcDir, destDir);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
-}
+package com.pmease.commons.hibernate.command;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.validation.Validator;
+
+import org.apache.commons.lang3.SystemUtils;
+import org.hibernate.Interceptor;
+import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
+import org.joda.time.DateTime;
+import org.joda.time.format.DateTimeFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.pmease.commons.bootstrap.Bootstrap;
+import com.pmease.commons.hibernate.DefaultPersistManager;
+import com.pmease.commons.hibernate.HibernateProperties;
+import com.pmease.commons.hibernate.IdManager;
+import com.pmease.commons.hibernate.ModelProvider;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.migration.MigrationHelper;
+import com.pmease.commons.hibernate.migration.Migrator;
+import com.pmease.commons.loader.PluginManager;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.execution.Commandline;
+import com.pmease.commons.util.execution.LineConsumer;
+
+@Singleton
+public class UpgradeCommand extends DefaultPersistManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(UpgradeCommand.class);
+
+ private static final String BACKUP_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss";
+
+ private final String appName;
+
+ @Inject
+ public UpgradeCommand(Set<ModelProvider> modelProviders, PhysicalNamingStrategy physicalNamingStrategy,
+ HibernateProperties properties, Migrator migrator, Interceptor interceptor,
+ IdManager idManager, Dao dao, Validator validator, PluginManager pluginManager) {
+ super(modelProviders, physicalNamingStrategy, properties, migrator, interceptor, idManager, dao, validator);
+ appName = pluginManager.getProduct().getName();
+ }
+
+ protected Commandline buildCommandline(File upgradeDir, String command, String...commandArgs) {
+ Commandline cmdline= new Commandline(System.getProperty("java.home") + "/bin/java");
+ cmdline.addArgs("-Xmx" + Runtime.getRuntime().maxMemory()/1024/1024 + "m", "-classpath", "*",
+ "com.pmease.commons.bootstrap.Bootstrap", command);
+ cmdline.addArgs(commandArgs);
+ cmdline.workingDir(new File(upgradeDir, "boot"));
+ return cmdline;
+ }
+
+ private String prefixUpgradeTargetLog(String line) {
+ return ">>> " + line;
+ }
+
+ @Override
+ public void start() {
+ if (Bootstrap.command.getArgs().length == 0) {
+ logger.error("Missing upgrade target parameter. Usage: {} <installation directory of old {} version>",
+ Bootstrap.command.getScript(), appName);
+ System.exit(1);
+ }
+ File upgradeDir = new File(Bootstrap.command.getArgs()[0]);
+ if (!upgradeDir.isAbsolute())
+ upgradeDir = new File(Bootstrap.getBinDir(), upgradeDir.getPath());
+
+ if (!upgradeDir.exists()) {
+ logger.error("Unable to find directory: {}", upgradeDir.getAbsolutePath());
+ System.exit(1);
+ }
+
+ logger.info("Upgrading {}...", upgradeDir.getAbsolutePath());
+
+ if (!new File(upgradeDir, "boot/bootstrap.keys").exists()) {
+ logger.error("Invalid {} installation directory: {}, make sure you are specifying the top level "
+ + "installation directory (it contains sub directories such as \"bin\", \"boot\", \"conf\", etc)",
+ appName, upgradeDir.getAbsolutePath());
+ System.exit(1);
+ }
+
+ if (new File(upgradeDir, "status/server_running").exists()) {
+ logger.error("Please stop server running at \"{}\" before upgrading", upgradeDir.getAbsolutePath());
+ System.exit(1);
+ }
+ if (Bootstrap.getServerRunningFile().exists()) {
+ logger.error("Please stop server running at \"{}\" before upgrading", Bootstrap.installDir.getAbsolutePath());
+ System.exit(1);
+ }
+
+ AtomicReference<String> oldDataVersion = new AtomicReference<>(null);
+ int ret = buildCommandline(upgradeDir, "check_data_version").execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ String prefix = "Data version: ";
+ if (line.startsWith(prefix)) {
+ oldDataVersion.set(line.substring(prefix.length()));
+ logger.info("Old data version: " + oldDataVersion.get());
+ } else {
+ logger.info(prefixUpgradeTargetLog(line));
+ }
+ }
+
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.error(prefixUpgradeTargetLog(line));
+ }}
+
+ ).getReturnCode();
+
+ if (ret != 0) {
+ logger.error("Unable to upgrade specified installation due to above error");
+ System.exit(1);
+ }
+
+ AtomicBoolean usingEmbeddedDB = new AtomicBoolean(false);
+ ret = buildCommandline(upgradeDir, "db_dialect").execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ String prefix = "Database dialect: ";
+ String dialect;
+ if (line.startsWith(prefix)) {
+ dialect = line.substring(prefix.length());
+ logger.info("Database dialect: " + dialect);
+ if (dialect.toLowerCase().contains("hsql"))
+ usingEmbeddedDB.set(true);
+ } else {
+ logger.info(prefixUpgradeTargetLog(line));
+ }
+ }
+
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.error(prefixUpgradeTargetLog(line));
+ }}
+
+ ).getReturnCode();
+
+ if (ret != 0) {
+ logger.error("Unable to upgrade specified installation due to above error");
+ System.exit(1);
+ }
+
+ File upgradeBackup = new File(Bootstrap.installDir, getBackupName(upgradeDir.getName()));
+ FileUtils.createDir(upgradeBackup);
+ File dbBackup = null;
+
+ if (usingEmbeddedDB.get()) {
+ logger.info("Backing up old installation directory as {}...", upgradeBackup.getAbsolutePath());
+ try {
+ FileUtils.copyDirectory(upgradeDir, upgradeBackup);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ if (!MigrationHelper.getVersion(migrator.getClass()).equals(oldDataVersion.get())) {
+ dbBackup = new File(upgradeDir, getBackupName("dbbackup") + ".zip");
+ logger.info("Backing up database as {}...", dbBackup.getAbsolutePath());
+ backupDB(upgradeDir, dbBackup);
+ }
+ } else {
+ // for non-embedded database, we should include database backup in the old installation backup directory
+ // in case we need that for database restore after a failed upgrade
+ if (!MigrationHelper.getVersion(migrator.getClass()).equals(oldDataVersion.get())) {
+ dbBackup = new File(upgradeDir, getBackupName("dbbackup") + ".zip");
+ logger.info("Backing up database as {}...", dbBackup.getAbsolutePath());
+ backupDB(upgradeDir, dbBackup);
+ }
+
+ logger.info("Backing up old installation directory as {}...", upgradeBackup.getAbsolutePath());
+ try {
+ FileUtils.copyDirectory(upgradeDir, upgradeBackup);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ boolean failed;
+ try {
+ if (dbBackup != null) {
+ logger.info("Cleaning database with old program version...");
+ ret = buildCommandline(upgradeDir, "clean").execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.info(prefixUpgradeTargetLog(line));
+ }
+
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.error(prefixUpgradeTargetLog(line));
+ }
+
+ }).getReturnCode();
+
+ if (ret != 0) {
+ logger.error("Failed to upgrade {}", upgradeDir.getAbsolutePath());
+ failed = true;
+ } else {
+ failed = false;
+ }
+
+ if (!failed) {
+ logger.info("Copying new program files into {}...", upgradeDir.getAbsolutePath());
+ copyProgramFilesTo(upgradeDir);
+
+ logger.info("Restoring database with new program version...");
+ ret = buildCommandline(upgradeDir, "restore", dbBackup.getAbsolutePath()).execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.info(prefixUpgradeTargetLog(line));
+ }
+
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.error(prefixUpgradeTargetLog(line));
+ }
+
+ }).getReturnCode();
+
+ if (ret != 0) {
+ logger.error("Failed to upgrade {}", upgradeDir.getAbsolutePath());
+ failed = true;
+ } else {
+ failed = false;
+ }
+ }
+ } else {
+ logger.info("Copying new program files into {}...", upgradeDir.getAbsolutePath());
+ copyProgramFilesTo(upgradeDir);
+ failed = false;
+ }
+ } catch (Exception e) {
+ logger.error("Error upgrading " + upgradeDir.getAbsolutePath(), e);
+ failed = true;
+ }
+
+ if (failed) {
+ logger.info("Now restoring old installation directory due to upgrade failure...");
+ try {
+ /* we do not clean upgradeDir here directly as user may open
+ * a command prompt inside the various sub directories to
+ * cause it unable to be deleted
+ */
+ for (File child: upgradeDir.listFiles()) {
+ if (child.isDirectory())
+ FileUtils.cleanDir(child);
+ else
+ FileUtils.deleteFile(child);
+ }
+ FileUtils.copyDirectory(upgradeBackup, upgradeDir);
+ logger.info("Old installation directory is now restored.");
+ } catch (Exception e2) {
+ logger.error("Error restoring old installation directory", e2);
+ logger.warn("Please restore it manually by deleting all contents under directory \"{}\", and then copying over all contents under directory \"{}\"",
+ upgradeDir.getAbsolutePath(), upgradeBackup.getAbsolutePath());
+ }
+ if (!usingEmbeddedDB.get() && dbBackup != null) {
+ logger.warn("The database might be in an inconsistent state due to upgrade failure. In that case, "
+ + "you need to restore the database by first cleaning it, and then running below command:");
+ if (SystemUtils.IS_OS_WINDOWS) {
+ logger.info(upgradeDir.getAbsolutePath() + File.separator + "bin" + File.separator + "restore.bat " + dbBackup.getAbsolutePath());
+ } else {
+ logger.info(upgradeDir.getAbsolutePath() + File.separator + "bin" + File.separator + "restore.sh " + dbBackup.getAbsolutePath());
+ }
+ }
+ System.exit(1);
+ } else {
+ logger.info("Successfully upgraded {}", upgradeDir.getAbsolutePath());
+ System.exit(0);
+ }
+ }
+
+ private void backupDB(File upgradeDir, File dbBackup) {
+ int ret = buildCommandline(upgradeDir, "backup", dbBackup.getAbsolutePath()).execute(new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.info(prefixUpgradeTargetLog(line));
+ }
+
+ }, new LineConsumer() {
+
+ @Override
+ public void consume(String line) {
+ logger.error(prefixUpgradeTargetLog(line));
+ }
+
+ }).getReturnCode();
+
+ if (ret != 0) {
+ logger.error("Unable to upgrade specified installation due to above error");
+ System.exit(1);
+ }
+ }
+
+ private String getBackupName(String name) {
+ return name + "~" + DateTimeFormat.forPattern(BACKUP_DATETIME_FORMAT).print(new DateTime());
+ }
+
+ protected void copyProgramFilesTo(File upgradeDir) {
+ cleanAndCopy(new File(Bootstrap.installDir, "3rdparty-licenses"), new File(upgradeDir, "3rdparty-licenses"));
+ cleanAndCopy(Bootstrap.getBinDir(), new File(upgradeDir, "bin"));
+ cleanAndCopy(Bootstrap.getBootDir(), new File(upgradeDir, "boot"));
+ cleanAndCopy(Bootstrap.getLibDir(), new File(upgradeDir, "lib"));
+ for (File file: Bootstrap.getSiteLibDir().listFiles()) {
+ // end user may put some custom program files in site lib before upgrade,
+ // to override site lib of old version
+ if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) {
+ cleanAndCopy(Bootstrap.getSiteLibDir(), new File(upgradeDir, "site/lib"));
+ break;
+ }
+ }
+ try {
+ FileUtils.copyFile(new File(Bootstrap.installDir, "conf/wrapper-license.conf"),
+ new File(upgradeDir, "conf/wrapper-license.conf"));
+ FileUtils.copyFile(new File(Bootstrap.installDir, "readme.txt"), new File(upgradeDir, "readme.txt"));
+ FileUtils.copyFile(new File(Bootstrap.installDir, "license.txt"), new File(upgradeDir, "license.txt"));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected void cleanAndCopy(File srcDir, File destDir) {
+ try {
+ FileUtils.cleanDir(destDir);
+ FileUtils.copyDirectory(srcDir, destDir);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/gitplex.product/system/3rdparty-licenses/ojdbc-license.txt b/gitplex.product/system/3rdparty-licenses/ojdbc-license.txt
new file mode 100644
index 0000000000..dab7b02e46
--- /dev/null
+++ b/gitplex.product/system/3rdparty-licenses/ojdbc-license.txt
@@ -0,0 +1,77 @@
+Oracle Technology Network License Agreement
+
+Oracle is willing to authorize Your access to software associated with this License Agreement (��Agreement��) only upon the condition that You accept that this Agreement governs Your use of the software. By selecting the ��Accept License Agreement�� button or box (or the equivalent) or installing or using the Programs You indicate Your acceptance of this Agreement and Your agreement, as an authorized representative of Your company or organization (if being acquired for use by an entity) or as an individual, to comply with the license terms that apply to the software that You wish to download and access. If You are not willing to be bound by this Agreement, do not select the ��Accept License Agreement�� button or box (or the equivalent) and do not download or access the software.
+
+Definitions
+"Oracle" refers to Oracle America, Inc. "You" and "Your" refers to (a) a company or organization (each an ��Entity��) accessing the Programs, if use of the Programs will be on behalf of such Entity; or (b) an individual accessing the Programs, if use of the Programs will not be on behalf of an Entity. ��Contractors�� refers to Your agents and contractors (including, without limitation, outsourcers). "Program(s)" refers to Oracle software provided by Oracle pursuant to this Agreement and any updates, error corrections, and/or Program Documentation provided by Oracle. ��Program Documentation�� refers to Program user manuals and Program installation manuals, if any. If available, Program Documentation may be delivered with the Programs and/or may be accessed from www.oracle.com/documentation. ��Associated Product�� refers to the Oracle product(s), if any, and as identified in the Programs documentation or on the Programs download site, with which the Programs are intended to enable or enhance interoperation with Your application(s). ��Separate Terms�� refers to separate license terms that are specified in the Program Documentation, readmes or notice files and that apply to Separately Licensed Third Party Technology. ��Separately Licensed Third Party Technology�� refers to third party technology that is licensed under Separate Terms and not under the terms of this Agreement.
+
+License Rights and Restrictions
+Oracle grants You a nonexclusive, nontransferable, limited license to, subject to the restrictions stated in this Agreement, (a) internally use the Programs solely for the purposes of developing, testing, prototyping and demonstrating Your applications, and running the Programs for Your own internal business operations; and (b) redistribute unmodified Programs and Programs Documentation pursuant to the Programs Redistribution section below. You may allow Your Contractor(s) to use the Programs, provided they are acting on Your behalf to exercise license rights granted in this Agreement and further provided that You are responsible for their compliance with this Agreement in such use. You will have a written agreement with Your Contractor(s) that strictly limits their right to use the Programs and that otherwise protects Oracle��s intellectual property rights to the same extent as this Agreement. You may make copies of the Programs to the extent reasonably necessary to exercise the license rights granted in this Agreement. You may make one copy of the Programs for backup purposes.
+
+Further, You may not:
+
+remove or modify any Program markings or any notice of Oracle��s or a licensor��s proprietary rights;
+use the Programs to provide third party training;
+assign this Agreement or distribute, give, or transfer the Programs or an interest in them to any third party, except as expressly permitted in this Agreement (the foregoing shall not be construed to limit the rights You may otherwise have with respect to Separately Licensed Third Party Technology);
+cause or permit reverse engineering (unless required by law for interoperability), disassembly or decompilation of the Programs; and
+disclose results of any Program benchmark tests without Oracle��s prior consent.
+The Programs may contain source code that, unless expressly licensed in this Agreement for other purposes (for example, licensed under an open source license), is provided solely for reference purposes pursuant to the terms of this Agreement and may not be modified.
+
+All rights not expressly granted in this Agreement are reserved by Oracle. If You want to use the Programs or Your application for any purpose other than as expressly permitted under this Agreement, You must obtain from Oracle or an Oracle reseller a valid Programs license under a separate agreement permitting such use. However, You acknowledge that the Programs may not be intended for production use and/or Oracle may not make a version of the Programs available for production or other purposes; any development or other work You undertake with the Programs is at Your sole risk.
+
+Programs Redistribution
+We grant You a nonexclusive, nontransferable right to copy and distribute unmodified Programs and Programs Documentation as part of and included in Your application that is intended to interoperate with the Associated Product, if any, provided that You do not charge Your end users any additional fees for the use of the Programs. Prior to distributing the Programs and Programs Documentation, You shall require Your end users to execute an agreement binding them to terms, with respect to the Programs and Programs Documentation, materially consistent and no less restrictive than those contained in this section and the sections of this Agreement entitled ��License Rights�� (except that the redistribution right granted to You shall not be included; Your end users may not distribute Programs and Programs Documentation to any third parties), "Ownership and Restrictions," "Export Controls," "Disclaimer of Warranties and Exclusive Remedies," "No Technical Support" (with respect to Oracle support; You may provide Your own support for Programs at Your discretion), "End of Agreement," "Relationship Between the Parties," "Open Source Software," and ��U.S. Government End Users.�� You must also include a provision stating that Your end users shall have no right to distribute the Programs and Programs Documentation, and a provision specifying us as a third party beneficiary of the agreement. You are responsible for obtaining these agreements with Your end users.
+
+You agree to: (a) defend and indemnify us against all claims and damages caused by Your distribution of the Programs and Programs Documentation in breach of this Agreement and/or failure to include the required contractual provisions in Your end user agreement as stated above; (b) keep executed end user agreements and records of end user information including name, address, date of distribution and identity of Programs distributed; (c) allow us to inspect Your end user agreements and records upon request; and, (d) enforce the terms of Your end user agreements so as to effect a timely cure of any end user breach, and to notify us of any breach of the terms.
+
+Ownership
+Oracle or its licensors retain all ownership and intellectual property rights to the Programs.
+
+Third-Party Technology
+The Programs may contain or require the use of third party technology that is provided with the Programs. Oracle may provide certain notices to You in Program Documentation, readmes or notice files in connection with such third party technology. Third party technology will be licensed to You either under the terms of this Agreement or, if specified in the Program Documentation, readmes or notice files, under Separate Terms. Your rights to use Separately Licensed Third Party Technology under Separate Terms are not restricted in any way by this Agreement. However, for clarity, notwithstanding the existence of a notice, third party technology that is not Separately Licensed Third Party Technology shall be deemed part of the Programs and is licensed to You under the terms of this Agreement.
+
+Source Code for Open Source Software
+For software that You receive from Oracle in binary form that is licensed under an open source license that gives You the right to receive the source code for that binary, You can obtain a copy of the applicable source code from https://oss.oracle.com/sources/ or http://www.oracle.com/goto/opensourcecode. If the source code for such software was not provided to You with the binary, You can also receive a copy of the source code on physical media by submitting a written request pursuant to the instructions in the "Written Offer for Source Code" section of the latter website.
+
+Export Controls
+Export laws and regulations of the United States and any other relevant local export laws and regulations apply to the Programs . You agree that such export control laws govern Your use of the Programs (including technical data) and any services deliverables provided under this agreement, and You agree to comply with all such export laws and regulations (including "deemed export" and "deemed re-export" regulations). You agree that no data, information, program and/or materials resulting from Programs or services (or direct products thereof) will be exported, directly or indirectly, in violation of these laws, or will be used for any purpose prohibited by these laws including, without limitation, nuclear, chemical, or biological weapons proliferation, or development of missile technology. Accordingly, You confirm:
+
+You will not download, provide, make available or otherwise export or re-export the Programs, directly or indirectly, to countries prohibited by applicable laws and regulations nor to citizens, nationals or residents of those countries.
+You are not listed on the United States Department of Treasury lists of Specially Designated Nationals and Blocked Persons, Specially Designated Terrorists, and Specially Designated Narcotic Traffickers, nor are You listed on the United States Department of Commerce Table of Denial Orders.
+You will not download or otherwise export or re-export the Programs, directly or indirectly, to persons on the above mentioned lists.
+You will not use the Programs for, and will not allow the Programs to be used for, any purposes prohibited by applicable law, including, without limitation, for the development, design, manufacture or production of nuclear, chemical or biological weapons of mass destruction.
+Information Collection
+The Programs�� installation and/or auto-update processes, if any, may transmit a limited amount of data to Oracle or its service provider about those processes to help Oracle understand and optimize them. Oracle does not associate the data with personally identifiable information. Refer to Oracle��s Privacy Policy at www.oracle.com/privacy.
+
+Disclaimer of Warranties; Limitation of Liability
+THE PROGRAMS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ORACLE FURTHER DISCLAIMS ALL WARRANTIES, EXPRESS AND IMPLIED, INCLUDING WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT .
+
+IN NO EVENT WILL ORACLE BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR DATA USE, INCURRED BY YOU OR ANY THIRD PARTY, WHETHER IN AN ACTION IN CONTRACT OR TORT, EVEN IF ORACLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ORACLE��S ENTIRE LIABILITY FOR DAMAGES UNDER THIS AGREEMENT SHALL IN NO EVENT EXCEED ONE THOUSAND DOLLARS (U.S. $1,000) .
+
+No Technical Support
+Unless Oracle support for the Programs, if any, is expressly included in a separate, current support agreement between You and Oracle, Oracle��s technical support organization will not provide technical support, phone support, or updates to You for the Programs provided under this Agreement.
+
+Audit; Termination
+Oracle may audit Your use of the Programs. You may terminate this Agreement by destroying all copies of the Programs. This Agreement shall automatically terminate without notice if You fail to comply with any of the terms of this Agreement, in which case You shall promptly destroy all copies of the Programs.
+
+U.S. Government End Users
+Programs and/or Programs Documentation delivered to U.S. Government end users are ��commercial computer software�� pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the Programs and/or Programs Documentation shall be subject to the license terms and license restrictions set forth in this Agreement. No other rights are granted to the U.S. Government.
+
+Relationship Between the Parties
+Oracle is an independent contractor and we agree that no partnership, joint venture, or agency relationship exists between us. We each will be responsible for paying our own employees, including employment related taxes and insurance.. Nothing in this agreement shall be construed to limit either party's right to independently develop or distribute software that is functionally similar to the other party's products, so long as proprietary information of the other party is not included in such software.
+
+Entire Agreement; Governing Law
+You agree that this Agreement is the complete agreement for the Programs and this Agreement supersedes all prior or contemporaneous agreements or representations, including any clickwrap, shrinkwrap or similar licenses, or license agreements for prior versions of the Programs. This Agreement may not be modified and the rights and restrictions may not be altered or waived except in a writing signed by authorized representatives of You and of Oracle. If any term of this Agreement is found to be invalid or unenforceable, the remaining provisions will remain effective.
+
+This Agreement is governed by the substantive and procedural laws of the State of California, USA, and You and Oracle agree to submit to the exclusive jurisdiction of, and venue in, the courts of San Francisco or Santa Clara counties in California in any dispute arising out of or relating to this Agreement.
+
+Notices
+Should you have any questions concerning this License Agreement, or if you desire to contact Oracle for any reason, please write:
+
+Oracle America, Inc.
+500 Oracle Parkway
+Redwood City, CA 94065
+
+Oracle Employees: Under no circumstances are Oracle Employees authorized to download software for the purpose of distributing it to customers. Oracle products are available to employees for internal use or demonstration purposes only. In keeping with Oracle's trade compliance obligations under U.S. and applicable multilateral law, failure to comply with this policy could result in disciplinary action up to and including termination.
+
+Last updated: 11 August 2016
\ No newline at end of file
diff --git a/gitplex.product/system/3rdparty-licenses/sqljdbc-license.txt b/gitplex.product/system/3rdparty-licenses/sqljdbc-license.txt
new file mode 100644
index 0000000000..83d811335a
--- /dev/null
+++ b/gitplex.product/system/3rdparty-licenses/sqljdbc-license.txt
@@ -0,0 +1,169 @@
+MICROSOFT SOFTWARE LICENSE TERMS
+
+MICROSOFT JDBC DRIVER 6.0 FOR SQL SERVER
+
+These license terms are an agreement between Microsoft Corporation (or based on where you
+live, one of its affiliates) and you. Please read them. They apply to the software
+named above, which includes the media on which you received it, if any. The terms also apply to
+any Microsoft
+
+� updates,
+� supplements,
+� Internet-based services, and
+� support services
+
+for this software, unless other terms accompany those items. If so, those terms apply.
+
+BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT
+ACCEPT THEM, DO NOT USE THE SOFTWARE.
+
+If you comply with these license terms, you have the rights below.
+
+1. INSTALLATION AND USE RIGHTS.
+
+a. Installation and Use.
+
+i. You may install and use any number of copies of the software on your devices.
+
+b. Third Party Programs. The software may include third party programs that Microsoft,
+not the third party, licenses to you under this agreement. Notices, if any, for the third
+party program are included for your information only.
+
+2. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.
+
+a. Distributable Code.
+
+i. Right to Use and Distribute. You are permitted to distribute the software in programs you
+develop if you comply with the terms below:
+
+* You may copy and distribute the object code form of the software (�Distributable Code�) in
+programs you develop. You may not modify the software.
+* You may permit distributors of your programs to copy and distribute the Distributable Code
+as part of those programs.
+ii. Distribution Requirements. For any Distributable Code you distribute, you must
+* add significant primary functionality to it in your programs;
+* require distributors and external end users to agree to terms that protect it at least as
+much as this agreement;
+* display your valid copyright notice on your programs; and
+* indemnify, defend, and hold harmless Microsoft from any claims, including attorneys� fees,
+related to the distribution or use of your programs.
+iii. Distribution Restrictions. You may not
+* alter any copyright, trademark or patent notice in the Distributable Code;
+* use Microsoft�s trademarks in your programs� names or in a way that suggests your programs
+come from or are endorsed by Microsoft;
+* include Distributable Code in malicious, deceptive or unlawful programs; or
+* modify or distribute the source code of any Distributable Code so that any part of it
+becomes subject to an Excluded License. An Excluded License is one that requires, as a
+condition of use, modification or distribution, that
+* the code be disclosed or distributed in source code form; or
+* others have the right to modify it.
+
+
+3. SCOPE OF LICENSE. The software is licensed, not sold. This agreement only gives you
+some rights to use the software. Microsoft reserves all other rights. Unless applicable law
+gives you more rights despite this limitation, you may use the software only as expressly
+permitted in this agreement. In doing so, you must comply with any technical limitations in
+the software that only allow you to use it in certain ways. You may not
+
+� work around any technical limitations in the software;
+� reverse engineer, decompile or disassemble the software, except and only to the extent
+that applicable law expressly permits, despite this limitation;
+� make more copies of the software than specified in this agreement or allowed by
+applicable law, despite this limitation;
+� publish the software for others to copy;
+� rent, lease or lend the software;
+� transfer the software or this agreement to any third party; or
+� use the software for commercial software hosting services.
+
+4. EXPORT RESTRICTIONS. The software is subject to United States export laws and
+regulations. You must comply with all domestic and international export laws and
+regulations that apply to the software. These laws include restrictions on destinations, end
+users and end use. For additional information, see www.microsoft.com/exporting.
+
+5. SUPPORT SERVICES. Because this software is �as is,� we may not provide support
+services for it.
+
+6. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-
+based services and support services that you use, are the entire agreement for the software
+and support services.
+
+7. APPLICABLE LAW.
+
+a. United States. If you acquired the software in the United States, Washington state law
+governs the interpretation of this agreement and applies to claims for breach of it,
+regardless of conflict of laws principles. The laws of the state where you live govern all
+other claims, including claims under state consumer protection laws, unfair competition
+laws, and in tort.
+
+b. Outside the United States. If you acquired the software in any other country, the laws of
+that country apply.
+
+8. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights
+under the laws of your country. You may also have rights with respect to the party from
+whom you acquired the software. This agreement does not change your rights under the laws
+of your country if the laws of your country do not permit it to do so.
+
+9. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED �AS-IS.� YOU
+BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS
+WARRANTIES, GUARANTEES OR CONDITIONS. YOU MAY HAVE
+ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS
+AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER
+YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
+INFRINGEMENT.
+
+10. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN
+RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP
+TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING
+CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL
+DAMAGES.
+
+This limitation applies to
+
+� anything related to the software, services, content (including code) on third party Internet
+sites, or third party programs, and
+� claims for breach of contract, breach of warranty, guarantee or condition, strict liability,
+negligence, or other tort to the extent permitted by applicable law.
+
+It also applies even if Microsoft knew or should have known about the possibility of the
+damages. The above limitation or exclusion may not apply to you because your country may
+not allow the exclusion or limitation of incidental, consequential or other damages.
+
+Please note: As this software is distributed in Quebec, Canada, some of the clauses in this
+agreement are provided below in French.
+
+Remarque : Ce logiciel �tant distribu� au Qu�bec, Canada, certaines des clauses dans ce
+contrat sont fournies ci-dessous en fran�ais.
+
+EXON�RATION DE GARANTIE. Le logiciel vis� par une licence est offert � tel quel �.
+Toute utilisation de ce logiciel est � votre seule risque et p�ril. Microsoft n�accorde aucune
+autre garantie expresse. Vous pouvez b�n�ficier de droits additionnels en vertu du droit local
+sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont
+permises par le droit locale, les garanties implicites de qualit� marchande, d�ad�quation � un
+usage particulier et d�absence de contrefa�on sont exclues.
+
+LIMITATION DES DOMMAGES-INT�R�TS ET EXCLUSION DE
+RESPONSABILIT� POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de
+ses fournisseurs une indemnisation en cas de dommages directs uniquement � hauteur de 5,00
+$ US. Vous ne pouvez pr�tendre � aucune indemnisation pour les autres dommages, y
+compris les dommages sp�ciaux, indirects ou accessoires et pertes de b�n�fices.
+
+Cette limitation concerne :
+� tout ce qui est reli� au logiciel, aux services ou au contenu (y compris le code) figurant
+sur des sites Internet tiers ou dans des programmes tiers ; et
+� les r�clamations au titre de violation de contrat ou de garantie, ou au titre de
+responsabilit� stricte, de n�gligence ou d�une autre faute dans la limite autoris�e par la loi
+en vigueur.
+
+Elle s�applique �galement, m�me si Microsoft connaissait ou devrait conna�tre l��ventualit�
+d�un tel dommage. Si votre pays n�autorise pas l�exclusion ou la limitation de responsabilit�
+pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la
+limitation ou l�exclusion ci-dessus ne s�appliquera pas � votre �gard.
+
+EFFET JURIDIQUE. Le pr�sent contrat d�crit certains droits juridiques. Vous pourriez avoir
+d�autres droits pr�vus par les lois de votre pays. Le pr�sent contrat ne modifie pas les droits
+que vous conf�rent les lois de votre pays si celles-ci ne le permettent pas.
+
+
+
+
diff --git a/gitplex.product/system/site/lib/put_custom_plugins_and_libs_here b/gitplex.product/system/site/lib/put_custom_plugins_and_libs_here
new file mode 100644
index 0000000000..e69de29bb2