The Unified and Autonomous Development Platform
Enhance commons to be able to handle command scripts
robin shine66af355e83e3
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.javaindex 2692357805..2f0b371f66 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@@ -25,39 +25,41 @@ 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;++ public static String[] args;@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, "bin/system.classpath"));+ .readObject(new File(sandboxDir, "boot/system.classpath"));Set<String> bootstrapKeys = (Set<String>) BootstrapUtils- .readObject(new File(sandboxDir, "bin/bootstrap.keys"));-+ .readObject(new File(sandboxDir, "boot/bootstrap.keys"));+List<URL> urls = new ArrayList<URL>();- for (String key: bootstrapKeys) {+ for (String key : bootstrapKeys) {File file = systemClasspath.get(key);- if (file == null)+ if (file == null)throw new RuntimeException("Unable to find bootstrap file for '" + key + "'.");try {urls.add(file.toURI().toURL());@@ -65,19 +67,18 @@ public class Bootstrap {throw new RuntimeException(e);}}-- URLClassLoader bootClassLoader = new URLClassLoader(- urls.toArray(new URL[0]),++ 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});+ bootstrapClass.getMethod("boot", String[].class).invoke(null, new Object[] {args});} catch (Exception e) {throw BootstrapUtils.unchecked(e);}-+} else {boot(args);}@@ -86,45 +87,66 @@ public class Bootstrap {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.+ * 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());+ 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+ elsethrow new RuntimeException("Unable to find product directory.");-+try {installDir = installDir.getCanonicalFile();} catch (IOException e) {throw new RuntimeException(e);}- configureLogging();+ Bootstrap.args = args;+ if (getCommand() == null) {+ getStatusDir().mkdir();+ 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);+ }+ }+ }++ configureLogging();+logger.info("Launching application from '" + installDir.getAbsolutePath() + "'...");libFiles = new ArrayList<File>();-- File classpathFile = new File(installDir, "bin/system.classpath");++ 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, "bin/bootstrap.keys"));- for (Map.Entry<String, File> entry: systemClasspath.entrySet()) {+ .readObject(new File(installDir, "boot/bootstrap.keys"));+ for (Map.Entry<String, File> entry : systemClasspath.entrySet()) {if (!bootstrapKeys.contains(entry.getKey()))libFiles.add(entry.getValue());}@@ -132,46 +154,47 @@ public class Bootstrap {if (getLibCacheDir().exists()) {BootstrapUtils.cleanDir(getLibCacheDir());} else if (!getLibCacheDir().mkdir()) {- throw new RuntimeException("Failed to create lib cache directory '"- + getLibCacheDir().getAbsolutePath() + "'");+ throw new RuntimeException(+ "Failed to create lib cache directory '" + getLibCacheDir().getAbsolutePath() + "'");}- for (File file: getLibDir().listFiles()) {+ for (File file : getLibDir().listFiles()) {if (file.getName().endsWith(".jar"))libFiles.add(file);else if (file.getName().endsWith(".zip"))BootstrapUtils.unzip(file, getLibCacheDir(), null);}-- for (File file: getLibCacheDir().listFiles()) {++ for (File file : getLibCacheDir().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.+ // 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) {++ 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>();-+@Overrideprotected Class<?> findClass(String name) throws ClassNotFoundException {return super.findClass(name);@@ -194,16 +217,16 @@ public class Bootstrap {}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);@@ -212,7 +235,7 @@ public class Bootstrap {} catch (Exception e) {throw BootstrapUtils.unchecked(e);}-+Runtime.getRuntime().addShutdownHook(new Thread() {public void run() {try {@@ -226,30 +249,34 @@ public class Bootstrap {Thread.currentThread().setContextClassLoader(originClassLoader);}}-+private static void configureLogging() {- // Set system properties so that they can be used in logback configuration file.+ // Set system properties so that they can be used in logback+ // configuration file.System.setProperty("installDir", installDir.getAbsolutePath());- System.setProperty("logback.configurationFile", new File(installDir, "conf/logback.xml").getAbsolutePath());-+ if (getCommand() != null)+ System.setProperty("bootstrapCommand", getCommand());+ else+ System.setProperty("bootstrapCommand", "server");++ 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();- if (System.getProperty(LOGBACK_CONFIG_FILE_PROPERTY_NAME) != null)- configurator.doConfigure(new File(System.getProperty(LOGBACK_CONFIG_FILE_PROPERTY_NAME)));- else- configurator.doConfigure(new File(installDir, "conf/logback.xml"));- } 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())++ 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();}@@ -258,33 +285,93 @@ public class Bootstrap {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() {- return new File(installDir, "temp");+ if (args.length != 0)+ return new File(installDir, "temp/" + args[0]);+ else+ return new File(installDir, "temp/server");}public static File getLibCacheDir() {- return new File(getLibDir(), ".cache");+ if (args.length != 0)+ return new File(getLibDir(), ".cache/" + args[0]);+ else+ return new File(getLibDir(), ".cache/server");}public static File getConfDir() {return new File(installDir, "conf");}-+public static File getSiteDir() {return new File(installDir, "site");}+ /**+ * Get command being executed+ * @return+ * <tt>null</tt> if not executing a command+ */+ public static String getCommand() {+ if (args.length != 0)+ return args[0];+ else+ return null;+ }++ /**+ * Get full name of command script+ * @return+ * <tt>null</tt> if not executing a command+ */+ public static String getCommandFile() {+ String command = getCommand();+ if (command != null) {+ if (BootstrapUtils.isWindows())+ return command + ".bat";+ else+ return command + ".sh";+ } else {+ return null;+ }+ }++ /**+ * Get the directory to store intermediate files generated by the command+ * @return+ * <tt>null</tt> if not executing a command+ */+ public static File getCommandDir() {+ String command = getCommand();+ if (command != null)+ return new File(installDir, command);+ else+ return null;+ }+private static class CachedUrl {private final URL url;-+public CachedUrl(URL url) {this.url = url;}-+public URL getUrl() {return url;}diff --git a/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/BootstrapUtils.java b/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/BootstrapUtils.javaindex 00f2c72a92..f90d482b6b 100644--- a/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/BootstrapUtils.java+++ b/commons.bootstrap/src/main/java/com/pmease/commons/bootstrap/BootstrapUtils.java@@ -178,6 +178,11 @@ public class BootstrapUtils {}}+ public static boolean isWindows() {+ String osName = System.getProperty("os.name");+ return osName != null && osName.startsWith("Windows");+ }+public static boolean visitDir(File dir, FileVisitor visitor) {if (!dir.exists())throw new RuntimeException("Directory '" + dir.getAbsolutePath() + "' does not exist.");diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultIdManager.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultIdManager.javaindex 14e2e3fc4c..8e12ecff72 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultIdManager.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultIdManager.java@@ -1,62 +1,60 @@-package com.pmease.commons.hibernate;--import java.util.HashMap;-import java.util.Map;-import java.util.concurrent.atomic.AtomicLong;--import javax.inject.Inject;-import javax.inject.Provider;-import javax.inject.Singleton;--import org.hibernate.Criteria;-import org.hibernate.SessionFactory;-import org.hibernate.criterion.Projections;-import org.hibernate.metadata.ClassMetadata;--import com.pmease.commons.hibernate.dao.Dao;--@Singleton-public class DefaultIdManager implements IdManager {-- private final Dao dao;-- private final Provider<SessionFactory> sessionFactoryProvider;-- private final Map<Class<?>, AtomicLong> nextIds = new HashMap<>();-- @Inject- public DefaultIdManager(Dao dao, Provider<SessionFactory> sessionFactoryProvider) {- this.dao = dao;- this.sessionFactoryProvider = sessionFactoryProvider;- }-- private long getMaxId(Class<?> entityClass) {- Criteria criteria = dao.getSession().createCriteria(entityClass);- criteria.setProjection(Projections.max("id"));- Long maxId = (Long) criteria.uniqueResult();- if (maxId == null)- maxId = 0L;- return maxId;- }-- @Sessional- @Override- public void init() {- for (ClassMetadata metadata: sessionFactoryProvider.get().getAllClassMetadata().values()) {- Class<?> entityClass = metadata.getMappedClass();- nextIds.put(entityClass, new AtomicLong(getMaxId(entityClass)+1));- }- }-- @Sessional- @Override- public void init(Class<?> entityClass) {- nextIds.get(entityClass).set(getMaxId(entityClass)+1);- }-- @Override- public long nextId(Class<?> entityClass) {- return nextIds.get(entityClass).getAndIncrement();- }--}+package com.pmease.commons.hibernate;++import java.util.HashMap;+import java.util.Map;+import java.util.concurrent.atomic.AtomicLong;++import javax.inject.Inject;+import javax.inject.Singleton;++import org.hibernate.Criteria;+import org.hibernate.criterion.Projections;+import org.hibernate.metadata.ClassMetadata;++import com.pmease.commons.hibernate.dao.Dao;++@Singleton+public class DefaultIdManager implements IdManager {++ private final Dao dao;++ private final PersistManager persistManager;++ private final Map<Class<?>, AtomicLong> nextIds = new HashMap<>();++ @Inject+ public DefaultIdManager(Dao dao, PersistManager persistManager) {+ this.dao = dao;+ this.persistManager = persistManager;+ }++ private long getMaxId(Class<?> entityClass) {+ Criteria criteria = dao.getSession().createCriteria(entityClass);+ criteria.setProjection(Projections.max("id"));+ Long maxId = (Long) criteria.uniqueResult();+ if (maxId == null)+ maxId = 0L;+ return maxId;+ }++ @Sessional+ @Override+ public void init() {+ for (ClassMetadata metadata: persistManager.getSessionFactory().getAllClassMetadata().values()) {+ Class<?> entityClass = metadata.getMappedClass();+ nextIds.put(entityClass, new AtomicLong(getMaxId(entityClass)+1));+ }+ }++ @Sessional+ @Override+ public void init(Class<?> entityClass) {+ nextIds.get(entityClass).set(getMaxId(entityClass)+1);+ }++ @Override+ public long nextId(Class<?> entityClass) {+ return nextIds.get(entityClass).getAndIncrement();+ }++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultPersistManager.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultPersistManager.javaindex 202b8df02c..5bc239ec54 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultPersistManager.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultPersistManager.java@@ -1,592 +1,628 @@-package com.pmease.commons.hibernate;--import java.io.File;-import java.io.FileOutputStream;-import java.io.FilenameFilter;-import java.io.IOException;-import java.io.OutputStream;-import java.lang.reflect.Field;-import java.sql.Connection;-import java.sql.DriverManager;-import java.sql.ResultSet;-import java.sql.SQLException;-import java.sql.Statement;-import java.util.ArrayList;-import java.util.Collections;-import java.util.EnumSet;-import java.util.Iterator;-import java.util.List;-import java.util.Properties;-import java.util.Set;--import javax.inject.Named;-import javax.persistence.ManyToOne;--import org.apache.commons.io.IOUtils;-import org.dom4j.DocumentHelper;-import org.dom4j.Element;-import org.dom4j.io.OutputFormat;-import org.dom4j.io.XMLWriter;-import org.dom4j.io.XPP3Reader;-import org.hibernate.Criteria;-import org.hibernate.Interceptor;-import org.hibernate.Query;-import org.hibernate.ReplicationMode;-import org.hibernate.Session;-import org.hibernate.SessionFactory;-import org.hibernate.Transaction;-import org.hibernate.boot.Metadata;-import org.hibernate.boot.MetadataSources;-import org.hibernate.boot.model.naming.Identifier;-import org.hibernate.boot.model.naming.PhysicalNamingStrategy;-import org.hibernate.boot.registry.StandardServiceRegistry;-import org.hibernate.boot.registry.StandardServiceRegistryBuilder;-import org.hibernate.criterion.Order;-import org.hibernate.criterion.Projections;-import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;-import org.hibernate.tool.hbm2ddl.SchemaExport;-import org.hibernate.tool.schema.TargetType;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.common.base.Charsets;-import com.google.common.base.Preconditions;-import com.google.common.base.Throwables;-import com.google.inject.Inject;-import com.google.inject.Provider;-import com.google.inject.Singleton;-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.hibernate.migration.VersionTable;-import com.pmease.commons.hibernate.migration.VersionedDocument;-import com.pmease.commons.util.BeanUtils;-import com.pmease.commons.util.ClassUtils;-import com.pmease.commons.util.FileUtils;--@Singleton-public class DefaultPersistManager implements PersistManager, Provider<SessionFactory> {-- private static final Logger logger = LoggerFactory.getLogger(DefaultPersistManager.class);-- private final Set<ModelProvider> modelProviders;-- private final PhysicalNamingStrategy physicalNamingStrategy;-- private final Properties properties;-- private final Migrator migrator;-- private final Interceptor interceptor;-- private final IdManager idManager;-- private final Dao dao;-- private StandardServiceRegistry serviceRegistry;-- private Metadata metadata;-- private volatile SessionFactory sessionFactory;-- private String dbDataVersion;-- @Inject- public DefaultPersistManager(Set<ModelProvider> modelProviders, PhysicalNamingStrategy physicalNamingStrategy,- @Named("hibernate") Properties properties, Migrator migrator, Interceptor interceptor,- IdManager idManager, Dao dao) {- this.modelProviders = modelProviders;- this.physicalNamingStrategy = physicalNamingStrategy;- this.properties = properties;- this.migrator = migrator;- this.interceptor = interceptor;- this.idManager = idManager;- this.dao = dao;- }-- private boolean isMySQL() {- return properties.getProperty(PropertyNames.DIALECT).toLowerCase().contains("mysql");- }-- private boolean isHSQL() {- return properties.getProperty(PropertyNames.DIALECT).toLowerCase().contains("hsql");- }-- public void execute(List<String> sqls) {- Connection conn = null;- Statement stmt = null;- try {- conn = getConnection();- stmt = conn.createStatement();- for (String sql: sqls) {- logger.debug("Executing sql: " + sql);- stmt.execute(sql);- }- } catch (SQLException e) {- throw new RuntimeException(e);- } finally {- if (stmt != null) {- try {- stmt.close();- } catch (SQLException e) {- }- }- if (conn != null) {- try {- conn.close();- } catch (SQLException e) {- }- }- }- }-- @Override- public void start() {- Preconditions.checkState(sessionFactory == null);-- serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();-- dbDataVersion = readDbDataVersion();-- logger.info("Checking data version...");- String appDataVersion = MigrationHelper.getVersion(migrator.getClass());- if (dbDataVersion != null && !dbDataVersion.equals(appDataVersion)) {- throw new RuntimeException("Data version mismatch "- + "(database data version: "+ dbDataVersion + ", application data version: "+ appDataVersion + "). "- + "Please follow instructions in the upgrade guide to upgrade the database.");- }-- MetadataSources metadataSources = new MetadataSources(serviceRegistry);- for (Class<? extends AbstractEntity> each: ClassUtils.findImplementations(AbstractEntity.class, AbstractEntity.class)) {- metadataSources.addAnnotatedClass(each);- }-- for (ModelProvider provider: modelProviders) {- for (Class<? extends AbstractEntity> modelClass: provider.getModelClasses())- metadataSources.addAnnotatedClass(modelClass);- }-- metadata = metadataSources.getMetadataBuilder().applyPhysicalNamingStrategy(physicalNamingStrategy).build();-- if (dbDataVersion == null) {- File tempFile = null;- try {- tempFile = File.createTempFile("schema", ".sql");- new SchemaExport().setOutputFile(tempFile.getAbsolutePath())- .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);- List<String> sqls = new ArrayList<String>();- for (String sql: FileUtils.readLines(tempFile)) {- if (shouldInclude(sql))- sqls.add(sql);- }- execute(sqls);- } catch (IOException e) {- throw new RuntimeException(e);- } finally {- if (tempFile != null)- tempFile.delete();- }-- sessionFactory = metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();-- idManager.init();-- Session session = sessionFactory.openSession();- Transaction transaction = session.beginTransaction();- try {- VersionTable dataVersion = new VersionTable();- dataVersion.versionColumn = appDataVersion;- session.save(dataVersion);- session.flush();- transaction.commit();- } catch (Exception e) {- transaction.rollback();- } finally {- session.close();- }- } else {- sessionFactory = metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();- idManager.init();- }- }-- @Override- public void stop() {- if (sessionFactory != null) {- Preconditions.checkState(!sessionFactory.isClosed());- sessionFactory.close();- sessionFactory = null;- }- }-- @Override- public SessionFactory get() {- if (sessionFactory == null)- throw new RuntimeException("Persist service is either not started or is not configured.");- return sessionFactory;- }-- @Override- public boolean isReady() {- return sessionFactory != null;- }-- private Connection getConnection() {- try {- Class.forName(properties.getProperty(PropertyNames.DRIVER_PROPNAME));- Connection conn = DriverManager.getConnection(- properties.getProperty(PropertyNames.URL_PROPNAME),- properties.getProperty(PropertyNames.USER_PROPNAME),- properties.getProperty(PropertyNames.PASSWORD_PROPNAME));- return conn;- } catch (Exception e) {- throw Throwables.propagate(e);- }- }-- @Override- public String getDbDataVersion() {- return dbDataVersion;- }-- private String getVersionTableName() {- JdbcEnvironment environment = serviceRegistry.getService(JdbcEnvironment.class);- Identifier identifier = Identifier.toIdentifier(VersionTable.class.getSimpleName());- return physicalNamingStrategy.toPhysicalTableName(identifier, environment).getText().toLowerCase();- }-- private String getVersionFieldName() {- return VersionTable.class.getFields()[0].getName();- }-- private String getVersionColumnName() {- JdbcEnvironment environment = serviceRegistry.getService(JdbcEnvironment.class);- Identifier identifier = Identifier.toIdentifier(getVersionFieldName());- return physicalNamingStrategy.toPhysicalColumnName(identifier, environment).getText();- }-- private String readDbDataVersion() {- Connection conn = null;- Statement stmt = null;- ResultSet resultset = null;- try {- conn = getConnection();- conn.setAutoCommit(false);- String versionTableName = getVersionTableName();- resultset = conn.getMetaData().getTables(null, null, versionTableName, null);- if (!resultset.next()) {- return null;- } else {- try {- logger.info("Version table found. Catalog: {}, Schema: {}, Name: {}, Type: {}",- resultset.getString("TABLE_CAT"), resultset.getString("TABLE_SCHEM"),- resultset.getString("TABLE_NAME"), resultset.getString("TABLE_TYPE"));- } catch (Exception e) {- }- }- resultset.close();- stmt = conn.createStatement();- resultset = stmt.executeQuery("select " + getVersionColumnName() + " from " + versionTableName);- if (!resultset.next())- throw new RuntimeException("No data version found in database.");- String dataVersion = resultset.getString(1);- if (resultset.next())- throw new RuntimeException("Illegal data version format in database");- return dataVersion;- } catch (Throwable e) {- if (e.getMessage() != null && e.getMessage().contains("ORA-00942"))- return null;- else- throw Throwables.propagate(e);- } finally {- if (resultset != null) {- try {- resultset.close();- } catch (SQLException e) {- }- }- if (stmt != null) {- try {- stmt.close();- } catch (SQLException e) {- }- }- if (conn != null) {- try {- conn.close();- } catch (SQLException e) {- }- }- }- }-- @Override- public void migrate(File dataDir) {- File versionFile = new File(dataDir, VersionTable.class.getSimpleName() + "s.xml");- VersionedDocument dom = readFile(versionFile);- List<Element> elements = dom.getRootElement().elements();- if (elements.size() != 1)- throw new RuntimeException("Incorrect data format: illegal data version");- Element versionElement = elements.iterator().next().element(getVersionFieldName());- if (versionElement == null) {- throw new RuntimeException("Incorrect data format: no data version");- }-- if (MigrationHelper.migrate(versionElement.getText(), migrator, dataDir)) {- versionElement.setText(MigrationHelper.getVersion(migrator.getClass()));- writeFile(versionFile, dom, false);- }- }-- private void writeFile(File file, VersionedDocument dom, boolean pretty) {- OutputStream os = null;- try {- os = new FileOutputStream(file);- OutputFormat format = new OutputFormat();- format.setIndent(pretty);- format.setNewlines(pretty);- format.setEncoding(Charsets.UTF_8.name());- XMLWriter writer = new XMLWriter(os, format);- writer.write(dom);- } catch (Exception e) {- throw Throwables.propagate(e);- } finally {- IOUtils.closeQuietly(os);- }- }-- private VersionedDocument readFile(File file) {- try {- char[] chars = FileUtils.readFileToString(file, Charsets.UTF_8.name()).toCharArray();- return new VersionedDocument(new XPP3Reader().read(chars));- } catch (Exception e) {- throw Throwables.propagate(e);- }- }-- /**- * Determines whether or not entityType1 has transitive foreign key- * dependency on entityType2.- *- * @param entityType1- * @param entityType2- * @return- */- private boolean hasForeignKeyDependency(Class<?> entityType1, Class<?> entityType2) {- for (Field field: BeanUtils.getFields(entityType1)) {- if (field.getAnnotation(ManyToOne.class) != null) {- if (field.getType() == entityType2)- return true;- if (field.getType() != entityType1 &&- hasForeignKeyDependency(field.getType(), entityType2)) {- return true;- }- }- }-- return false;- }-- @Override- public List<Class<?>> getEntityTypes() {- List<Class<?>> entityTypes = new ArrayList<>();- for (Iterator<String> it = sessionFactory.getAllClassMetadata().keySet().iterator(); it.hasNext();) {- String entityTypeName = (String) it.next();- try {- entityTypes.add(Class.forName(entityTypeName));- } catch (ClassNotFoundException e) {- throw new RuntimeException(e);- }- }-- /* Collections.sort does not work here */- List<Class<?>> sorted = new ArrayList<Class<?>>();- while (!entityTypes.isEmpty()) {- Class<?> dependencyLeaf = null;- for (Class<?> entityType: entityTypes) {- boolean hasDependents = false;- for (Class<?> each: entityTypes) {- if (each != entityType) {- if (hasForeignKeyDependency(each, entityType)) {- hasDependents = true;- break;- }- }- }- if (!hasDependents) {- dependencyLeaf = entityType;- break;- }- }- if (dependencyLeaf != null) {- sorted.add(dependencyLeaf);- entityTypes.remove(dependencyLeaf);- } else {- throw new RuntimeException("Looped foreigh key dependency found between model classes");- }- }- return sorted;- }-- @Override- @Sessional- public void exportData(File exportDir, int batchSize) {- for (Class<?> entityType: getEntityTypes()) {- logger.info("Exporting table '" + entityType.getSimpleName() + "'...");-- logger.info("Querying table ids...");-- Criteria criteria = dao.getSession().createCriteria(entityType, "entity")- .setProjection(Projections.property("entity.id")).addOrder(Order.asc("id"));- @SuppressWarnings("unchecked")- List<Long> ids = criteria.list();- int count = ids.size();-- for (int i=0; i<count/batchSize; i++) {- exportEntity(entityType, ids, i*batchSize, batchSize, batchSize, exportDir);- // clear session to free memory- dao.getSession().clear();- }-- if (count%batchSize != 0) {- exportEntity(entityType, ids, count/batchSize*batchSize, count%batchSize, batchSize, exportDir);- }- logger.info("");- }-- }-- private void exportEntity(Class<?> entityType, List<Long> ids, int start, int count, int batchSize, File exportDir) {- logger.info("Loading table rows ({}->{}) from database...", String.valueOf(start+1), (start + count));-- Query query = dao.getSession().createQuery("from " + entityType.getSimpleName() + " where id>=:fromId and id<=:toId");- query.setParameter("fromId", ids.get(start));- query.setParameter("toId", ids.get(start+count-1));-- logger.info("Converting table rows to XML...");- VersionedDocument dom = new VersionedDocument();- Element rootElement = dom.addElement("list");- for (Object entity: query.list())- rootElement.appendContent(VersionedDocument.fromBean(entity));- String fileName;-- if (start == 0)- fileName = entityType.getSimpleName() + "s.xml";- else- fileName = entityType.getSimpleName() + "s.xml." + (start/batchSize + 1);-- logger.info("Writing resulting XML to file '" + fileName + "...");- writeFile(new File(exportDir, fileName), dom, true);- }-- /*- * We do not use @Transactional annotation and will manage the session and transaction manually- * in this method to reduce memory usage if importing a large database.- */- @Sessional- @Override- public void importData(File dataDir) {- // check version- File versionFile = new File(dataDir, VersionTable.class.getSimpleName() + "s.xml");- VersionedDocument dom = readFile(versionFile);- List<Element> elements = dom.getRootElement().elements();- if (elements.size() != 1)- throw new RuntimeException("Incorrect data format: illegal data version");- Element versionElement = elements.iterator().next().element(getVersionFieldName());- if (versionElement == null) {- throw new RuntimeException("Incorrect data format: no data version");- }-- if (versionElement.getText().equals(MigrationHelper.getVersion(migrator.getClass()))) {- throw new RuntimeException("Data version mismatch");- }-- File tempFile = null;- try {- logger.info("Clearing database...");-- tempFile = File.createTempFile("schema", ".sql");- new SchemaExport().setOutputFile(tempFile.getAbsolutePath())- .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);- List<String> sqls = new ArrayList<String>();- for (String sql: FileUtils.readLines(tempFile)) {- sqls.add(sql);- }- execute(sqls);-- tempFile = File.createTempFile("schema", ".sql");- new SchemaExport().setOutputFile(tempFile.getAbsolutePath())- .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);- sqls.clear();- for (String sql: FileUtils.readLines(tempFile)) {- if (shouldInclude(sql) && !isCreatingForeignKey(sql))- sqls.add(sql);- }- execute(sqls);-- List<Class<?>> entityTypes = getEntityTypes();- Collections.reverse(entityTypes);- for (Class<?> entityType: entityTypes) {- File[] dataFiles = dataDir.listFiles(new FilenameFilter() {-- @Override- public boolean accept(File dir, String name) {- return name.startsWith(entityType.getSimpleName() + "s.xml");- }-- });- for (File file: dataFiles) {- try {- logger.info("Importing from data file '" + file.getName() + "'...");- dao.getSession().beginTransaction();- dom = readFile(file);- for (Element element: dom.getRootElement().elements()) {- element.detach();- AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();- dao.getSession().replicate(entity, ReplicationMode.EXCEPTION);- }- dao.getSession().flush();- dao.getSession().clear();- dao.getSession().getTransaction().commit();- } catch (Throwable e) {- dao.getSession().getTransaction().rollback();- throw Throwables.propagate(e);- }- }- }-- logger.info("Applying foreign key constraints...");-- tempFile = File.createTempFile("schema", ".sql");- new SchemaExport().setOutputFile(tempFile.getAbsolutePath())- .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);- sqls.clear();- for (String sql: FileUtils.readLines(tempFile)) {- if (isCreatingForeignKey(sql)) {- sqls.add(sql);- }- }- execute(sqls);- } catch (IOException e) {- throw new RuntimeException(e);- } finally {- if (tempFile != null)- tempFile.delete();- }- }-- private boolean isCreatingForeignKey(String sql) {- return sql.toLowerCase().contains(" foreign key ");- }-- private boolean shouldInclude(String sql) {- // some databases will create index on foreign keys automatically, so- // we skip creating indexes for those- if (!sql.toLowerCase().startsWith("create index") || !sql.toLowerCase().endsWith("_id)")) {- return true;- } else {- return !isMySQL() && !isHSQL();- }- }--}+package com.pmease.commons.hibernate;++import java.io.File;+import java.io.FileOutputStream;+import java.io.FilenameFilter;+import java.io.IOException;+import java.io.OutputStream;+import java.lang.reflect.Field;+import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.ArrayList;+import java.util.Collections;+import java.util.EnumSet;+import java.util.Iterator;+import java.util.List;+import java.util.Properties;+import java.util.Set;++import javax.inject.Named;+import javax.persistence.ManyToOne;++import org.apache.commons.io.IOUtils;+import org.dom4j.DocumentHelper;+import org.dom4j.Element;+import org.dom4j.io.OutputFormat;+import org.dom4j.io.XMLWriter;+import org.dom4j.io.XPP3Reader;+import org.hibernate.Criteria;+import org.hibernate.Interceptor;+import org.hibernate.Query;+import org.hibernate.ReplicationMode;+import org.hibernate.Session;+import org.hibernate.SessionFactory;+import org.hibernate.Transaction;+import org.hibernate.boot.Metadata;+import org.hibernate.boot.MetadataSources;+import org.hibernate.boot.model.naming.Identifier;+import org.hibernate.boot.model.naming.PhysicalNamingStrategy;+import org.hibernate.boot.registry.StandardServiceRegistry;+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;+import org.hibernate.criterion.Order;+import org.hibernate.criterion.Projections;+import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;+import org.hibernate.tool.hbm2ddl.SchemaExport;+import org.hibernate.tool.schema.TargetType;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.google.common.base.Charsets;+import com.google.common.base.Throwables;+import com.google.inject.Inject;+import com.google.inject.Singleton;+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.hibernate.migration.VersionTable;+import com.pmease.commons.hibernate.migration.VersionedDocument;+import com.pmease.commons.util.BeanUtils;+import com.pmease.commons.util.ClassUtils;+import com.pmease.commons.util.FileUtils;++@Singleton+public class DefaultPersistManager implements PersistManager {++ private static final Logger logger = LoggerFactory.getLogger(DefaultPersistManager.class);++ protected final Set<ModelProvider> modelProviders;++ protected final PhysicalNamingStrategy physicalNamingStrategy;++ protected final Properties properties;++ protected final Migrator migrator;++ protected final Interceptor interceptor;++ protected final IdManager idManager;++ protected final Dao dao;++ protected final StandardServiceRegistry serviceRegistry;++ protected volatile SessionFactory sessionFactory;++ @Inject+ public DefaultPersistManager(Set<ModelProvider> modelProviders, PhysicalNamingStrategy physicalNamingStrategy,+ @Named("hibernate") Properties properties, Migrator migrator, Interceptor interceptor,+ IdManager idManager, Dao dao) {+ this.modelProviders = modelProviders;+ this.physicalNamingStrategy = physicalNamingStrategy;+ this.properties = properties;+ this.migrator = migrator;+ this.interceptor = interceptor;+ this.idManager = idManager;+ this.dao = dao;+ serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();+ }++ private boolean isMySQL() {+ return properties.getProperty(PropertyNames.DIALECT).toLowerCase().contains("mysql");+ }++ private boolean isHSQL() {+ return properties.getProperty(PropertyNames.DIALECT).toLowerCase().contains("hsql");+ }++ protected void execute(List<String> sqls, boolean failOnError) {+ Connection conn = null;+ Statement stmt = null;+ try {+ conn = getConnection();+ stmt = conn.createStatement();+ for (String sql: sqls) {+ logger.debug("Executing sql: " + sql);+ if (failOnError) {+ stmt.execute(sql);+ } else {+ try {+ stmt.execute(sql);+ } catch (Exception e) {+ logger.error("Error executing sql", e);+ }+ }+ }+ } catch (SQLException e) {+ throw new RuntimeException(e);+ } finally {+ if (stmt != null) {+ try {+ stmt.close();+ } catch (SQLException e) {+ }+ }+ if (conn != null) {+ try {+ conn.close();+ } catch (SQLException e) {+ }+ }+ }+ }++ protected Metadata buildMetadata() {+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);+ for (Class<? extends AbstractEntity> each: ClassUtils.findImplementations(AbstractEntity.class, AbstractEntity.class)) {+ metadataSources.addAnnotatedClass(each);+ }++ for (ModelProvider provider: modelProviders) {+ for (Class<? extends AbstractEntity> modelClass: provider.getModelClasses())+ metadataSources.addAnnotatedClass(modelClass);+ }++ return metadataSources.getMetadataBuilder().applyPhysicalNamingStrategy(physicalNamingStrategy).build();+ }++ protected SessionFactory buildSessionFactory(Metadata metadata) {+ return metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();+ }++ @Override+ public void start() {+ String dbDataVersion = readDbDataVersion();++ logger.info("Checking data version...");+ String appDataVersion = MigrationHelper.getVersion(migrator.getClass());+ if (dbDataVersion != null && !dbDataVersion.equals(appDataVersion)) {+ throw new RuntimeException("Data version mismatch "+ + "(database data version: "+ dbDataVersion + ", application data version: "+ appDataVersion + "). "+ + "Please upgrade the database.");+ }++ Metadata metadata = buildMetadata();++ if (dbDataVersion == null) {+ File tempFile = null;+ try {+ tempFile = File.createTempFile("schema", ".sql");+ new SchemaExport().setOutputFile(tempFile.getAbsolutePath())+ .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);+ List<String> sqls = new ArrayList<String>();+ for (String sql: FileUtils.readLines(tempFile)) {+ if (shouldInclude(sql))+ sqls.add(sql);+ }+ execute(sqls, true);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } finally {+ if (tempFile != null)+ tempFile.delete();+ }++ sessionFactory = buildSessionFactory(metadata);++ idManager.init();++ Session session = sessionFactory.openSession();+ Transaction transaction = session.beginTransaction();+ try {+ VersionTable dataVersion = new VersionTable();+ dataVersion.versionColumn = appDataVersion;+ session.save(dataVersion);+ session.flush();+ transaction.commit();+ } catch (Exception e) {+ transaction.rollback();+ } finally {+ session.close();+ }+ } else {+ sessionFactory = metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();+ idManager.init();+ }+ }++ @Override+ public void stop() {+ if (sessionFactory != null) {+ sessionFactory.close();+ sessionFactory = null;+ }+ }++ protected Connection getConnection() {+ try {+ Class.forName(properties.getProperty(PropertyNames.DRIVER_PROPNAME));+ Connection conn = DriverManager.getConnection(+ properties.getProperty(PropertyNames.URL_PROPNAME),+ properties.getProperty(PropertyNames.USER_PROPNAME),+ properties.getProperty(PropertyNames.PASSWORD_PROPNAME));+ return conn;+ } catch (Exception e) {+ throw Throwables.propagate(e);+ }+ }++ private String getVersionTableName() {+ JdbcEnvironment environment = serviceRegistry.getService(JdbcEnvironment.class);+ Identifier identifier = Identifier.toIdentifier(VersionTable.class.getSimpleName());+ return physicalNamingStrategy.toPhysicalTableName(identifier, environment).getText();+ }++ private String getVersionFieldName() {+ return VersionTable.class.getFields()[0].getName();+ }++ private String getVersionColumnName() {+ JdbcEnvironment environment = serviceRegistry.getService(JdbcEnvironment.class);+ Identifier identifier = Identifier.toIdentifier(getVersionFieldName());+ return physicalNamingStrategy.toPhysicalColumnName(identifier, environment).getText();+ }++ protected String readDbDataVersion() {+ try (Connection conn = getConnection()) {+ conn.setAutoCommit(false);+ String versionTableName = getVersionTableName();+ boolean versionTableExists = false;+ try (ResultSet resultset = conn.getMetaData().getTables(null, null, versionTableName.toUpperCase(), null)) {+ if (resultset.next())+ versionTableExists = true;+ }+ if (!versionTableExists) {+ try (ResultSet resultset = conn.getMetaData().getTables(null, null, versionTableName.toLowerCase(), null)) {+ if (resultset.next()) {+ versionTableExists = true;+ }+ }+ }+ if (!versionTableExists) {+ return null;+ } else {+ try ( Statement stmt = conn.createStatement();+ ResultSet resultset = stmt.executeQuery("select " + getVersionColumnName() + " from " + versionTableName)) {+ if (!resultset.next())+ throw new RuntimeException("No data version found in database: this is normally caused "+ + "by unsuccessful restore/upgrade, please clean the database and try again");+ String dataVersion = resultset.getString(1);+ if (resultset.next())+ throw new RuntimeException("Illegal data version format in database");+ return dataVersion;+ }+ }+ } catch (Throwable e) {+ if (e.getMessage() != null && e.getMessage().contains("ORA-00942"))+ return null;+ else+ throw Throwables.propagate(e);+ }+ }++ @Override+ public void migrate(File dataDir) {+ File versionFile = new File(dataDir, VersionTable.class.getSimpleName() + "s.xml");+ VersionedDocument dom = readFile(versionFile);+ List<Element> elements = dom.getRootElement().elements();+ if (elements.size() != 1)+ throw new RuntimeException("Incorrect data format: illegal data version");+ Element versionElement = elements.iterator().next().element(getVersionFieldName());+ if (versionElement == null) {+ throw new RuntimeException("Incorrect data format: no data version");+ }++ if (MigrationHelper.migrate(versionElement.getText(), migrator, dataDir)) {+ versionElement.setText(MigrationHelper.getVersion(migrator.getClass()));+ writeFile(versionFile, dom, false);+ }+ }++ private void writeFile(File file, VersionedDocument dom, boolean pretty) {+ OutputStream os = null;+ try {+ os = new FileOutputStream(file);+ OutputFormat format = new OutputFormat();+ format.setIndent(pretty);+ format.setNewlines(pretty);+ format.setEncoding(Charsets.UTF_8.name());+ XMLWriter writer = new XMLWriter(os, format);+ writer.write(dom);+ } catch (Exception e) {+ throw Throwables.propagate(e);+ } finally {+ IOUtils.closeQuietly(os);+ }+ }++ private VersionedDocument readFile(File file) {+ try {+ char[] chars = FileUtils.readFileToString(file, Charsets.UTF_8.name()).toCharArray();+ return new VersionedDocument(new XPP3Reader().read(chars));+ } catch (Exception e) {+ throw Throwables.propagate(e);+ }+ }++ /**+ * Determines whether or not entityType1 has transitive foreign key+ * dependency on entityType2.+ *+ * @param entityType1+ * @param entityType2+ * @return+ */+ private boolean hasForeignKeyDependency(Class<?> entityType1, Class<?> entityType2) {+ for (Field field: BeanUtils.getFields(entityType1)) {+ if (field.getAnnotation(ManyToOne.class) != null) {+ if (field.getType() == entityType2)+ return true;+ if (field.getType() != entityType1 &&+ hasForeignKeyDependency(field.getType(), entityType2)) {+ return true;+ }+ }+ }++ return false;+ }++ /**+ * @return hibernate entity types ordered using foreign key dependency+ * information. For example, Build type comes before Configuration+ * type as it has Build has foreign key reference to Configuration.+ */+ private List<Class<?>> getEntityTypes(SessionFactory sessionFactory) {+ List<Class<?>> entityTypes = new ArrayList<>();+ for (Iterator<String> it = sessionFactory.getAllClassMetadata().keySet().iterator(); it.hasNext();) {+ String entityTypeName = (String) it.next();+ try {+ entityTypes.add(Class.forName(entityTypeName));+ } catch (ClassNotFoundException e) {+ throw new RuntimeException(e);+ }+ }++ /* Collections.sort does not work here */+ List<Class<?>> sorted = new ArrayList<Class<?>>();+ while (!entityTypes.isEmpty()) {+ Class<?> dependencyLeaf = null;+ for (Class<?> entityType: entityTypes) {+ boolean hasDependents = false;+ for (Class<?> each: entityTypes) {+ if (each != entityType) {+ if (hasForeignKeyDependency(each, entityType)) {+ hasDependents = true;+ break;+ }+ }+ }+ if (!hasDependents) {+ dependencyLeaf = entityType;+ break;+ }+ }+ if (dependencyLeaf != null) {+ sorted.add(dependencyLeaf);+ entityTypes.remove(dependencyLeaf);+ } else {+ throw new RuntimeException("Looped foreigh key dependency found between model classes");+ }+ }+ return sorted;+ }++ @Sessional+ @Override+ public void exportData(File exportDir, int batchSize) {+ Session session = sessionFactory.openSession();+ for (Class<?> entityType: getEntityTypes(sessionFactory)) {+ logger.info("Exporting table '" + entityType.getSimpleName() + "'...");++ logger.info("Querying table ids...");++ Criteria criteria = session.createCriteria(entityType, "entity")+ .setProjection(Projections.property("entity.id")).addOrder(Order.asc("id"));+ @SuppressWarnings("unchecked")+ List<Long> ids = criteria.list();+ int count = ids.size();++ for (int i=0; i<count/batchSize; i++) {+ exportEntity(session, entityType, ids, i*batchSize, batchSize, batchSize, exportDir);+ // clear session to free memory+ session.clear();+ }++ if (count%batchSize != 0) {+ exportEntity(session, entityType, ids, count/batchSize*batchSize, count%batchSize, batchSize, exportDir);+ }+ logger.info("");+ }+ }++ private void exportEntity(Session session, Class<?> entityType, List<Long> ids, int start, int count, int batchSize, File exportDir) {+ logger.info("Loading table rows ({}->{}) from database...", String.valueOf(start+1), (start + count));++ Query query = session.createQuery("from " + entityType.getSimpleName() + " where id>=:fromId and id<=:toId");+ query.setParameter("fromId", ids.get(start));+ query.setParameter("toId", ids.get(start+count-1));++ logger.info("Converting table rows to XML...");+ VersionedDocument dom = new VersionedDocument();+ Element rootElement = dom.addElement("list");+ for (Object entity: query.list())+ rootElement.appendContent(VersionedDocument.fromBean(entity));+ String fileName;++ if (start == 0)+ fileName = entityType.getSimpleName() + "s.xml";+ else+ fileName = entityType.getSimpleName() + "s.xml." + (start/batchSize + 1);++ logger.info("Writing resulting XML to file '" + fileName + "...");+ writeFile(new File(exportDir, fileName), dom, true);+ }++ /*+ * We do not use @Transactional annotation and will manage the session and transaction manually+ * in this method to reduce memory usage if importing a large database.+ */+ @Sessional+ @Override+ public void importData(Metadata metadata, File dataDir) {+ Session session = dao.getSession();+ // check version+ File versionFile = new File(dataDir, VersionTable.class.getSimpleName() + "s.xml");+ VersionedDocument dom = readFile(versionFile);+ List<Element> elements = dom.getRootElement().elements();+ if (elements.size() != 1)+ throw new RuntimeException("Incorrect data format: illegal data version");+ Element versionElement = elements.iterator().next().element(getVersionFieldName());+ if (versionElement == null) {+ throw new RuntimeException("Incorrect data format: no data version");+ }++ if (!versionElement.getText().equals(MigrationHelper.getVersion(migrator.getClass()))) {+ throw new RuntimeException("Data version mismatch");+ }++ logger.info("Clearing database...");+ dropAll(metadata);++ logger.info("Creating tables...");+ createTables(metadata);++ List<Class<?>> entityTypes = getEntityTypes(sessionFactory);+ Collections.reverse(entityTypes);+ for (Class<?> entityType: entityTypes) {+ File[] dataFiles = dataDir.listFiles(new FilenameFilter() {++ @Override+ public boolean accept(File dir, String name) {+ return name.startsWith(entityType.getSimpleName() + "s.xml");+ }++ });+ for (File file: dataFiles) {+ try {+ logger.info("Importing from data file '" + file.getName() + "'...");+ session.beginTransaction();+ dom = readFile(file);+ for (Element element: dom.getRootElement().elements()) {+ element.detach();+ AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();+ session.replicate(entity, ReplicationMode.EXCEPTION);+ }+ session.flush();+ session.clear();+ session.getTransaction().commit();+ } catch (Throwable e) {+ session.getTransaction().rollback();+ throw Throwables.propagate(e);+ }+ }+ }++ logger.info("Applying foreign key constraints...");++ applyForeignKeyConstraints(metadata);+ }++ @Override+ public void applyForeignKeyConstraints(Metadata metadata) {+ File tempFile = null;+ try {+ tempFile = File.createTempFile("schema", ".sql");+ new SchemaExport().setOutputFile(tempFile.getAbsolutePath())+ .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);+ List<String> sqls = new ArrayList<>();+ for (String sql: FileUtils.readLines(tempFile)) {+ if (isApplyingForeignKeyConstraints(sql)) {+ sqls.add(sql);+ }+ }+ execute(sqls, true);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } finally {+ if (tempFile != null)+ tempFile.delete();+ }+ }++ private void createTables(Metadata metadata) {+ File tempFile = null;+ try {+ tempFile = File.createTempFile("schema", ".sql");+ new SchemaExport().setOutputFile(tempFile.getAbsolutePath())+ .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);+ List<String> sqls = new ArrayList<>();+ for (String sql: FileUtils.readLines(tempFile)) {+ if (shouldInclude(sql) && !isApplyingForeignKeyConstraints(sql))+ sqls.add(sql);+ }+ execute(sqls, true);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } finally {+ if (tempFile != null)+ FileUtils.deleteFile(tempFile);+ }+ }++ @Override+ public void dropForeignKeyConstraints(Metadata metadata) {+ File tempFile = null;+ try {+ tempFile = File.createTempFile("schema", ".sql");+ new SchemaExport().setOutputFile(tempFile.getAbsolutePath())+ .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);+ List<String> sqls = new ArrayList<>();+ for (String sql: FileUtils.readLines(tempFile)) {+ if (isDroppingForeignKeyConstraints(sql))+ sqls.add(sql);+ }+ execute(sqls, false);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } finally {+ if (tempFile != null)+ tempFile.delete();+ }+ }++ private void dropAll(Metadata metadata) {+ File tempFile = null;+ try {+ tempFile = File.createTempFile("schema", ".sql");+ new SchemaExport().setOutputFile(tempFile.getAbsolutePath())+ .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);+ List<String> sqls = new ArrayList<>();+ for (String sql: FileUtils.readLines(tempFile)) {+ sqls.add(sql);+ }+ execute(sqls, false);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } finally {+ if (tempFile != null)+ tempFile.delete();+ }+ }++ private boolean isApplyingForeignKeyConstraints(String sql) {+ return sql.toLowerCase().contains(" foreign key ");+ }++ private boolean isDroppingForeignKeyConstraints(String sql) {+ return sql.toLowerCase().contains(" drop constraint ");+ }++ private boolean shouldInclude(String sql) {+ // some databases will create index on foreign keys automatically, so+ // we skip creating indexes for those+ if (!sql.toLowerCase().startsWith("create index") || !sql.toLowerCase().endsWith("_id)")) {+ return true;+ } else {+ return !isMySQL() && !isHSQL();+ }+ }++ @Override+ public SessionFactory getSessionFactory() {+ return sessionFactory;+ }++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultReapplyDBConstraintsManager.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultReapplyDBConstraintsManager.javanew file mode 100644index 0000000000..a968985c57--- /dev/null+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultReapplyDBConstraintsManager.java@@ -0,0 +1,65 @@+package com.pmease.commons.hibernate;++import java.util.Properties;+import java.util.Set;++import javax.inject.Inject;+import javax.inject.Named;+import javax.inject.Singleton;++import org.hibernate.Interceptor;+import org.hibernate.SessionFactory;+import org.hibernate.boot.Metadata;+import org.hibernate.boot.model.naming.PhysicalNamingStrategy;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.pmease.commons.bootstrap.Bootstrap;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.hibernate.migration.MigrationHelper;+import com.pmease.commons.hibernate.migration.Migrator;++@Singleton+public class DefaultReapplyDBConstraintsManager extends DefaultPersistManager {++ private static final Logger logger = LoggerFactory.getLogger(DefaultReapplyDBConstraintsManager.class);++ @Inject+ public DefaultReapplyDBConstraintsManager(Set<ModelProvider> modelProviders, PhysicalNamingStrategy physicalNamingStrategy,+ @Named("hibernate") Properties properties, Migrator migrator, Interceptor interceptor,+ IdManager idManager, Dao dao) {+ super(modelProviders, physicalNamingStrategy, properties, migrator, interceptor, idManager, dao);+ }++ @Override+ public void start() {+ if (Bootstrap.getServerRunningFile().exists()) {+ logger.error("Please stop server before reapply db constraints");+ System.exit(1);+ }+ String dbDataVersion = readDbDataVersion();+ if (dbDataVersion == null) {+ logger.error("Database is not populated yet");+ System.exit(1);+ }+ String appDataVersion = MigrationHelper.getVersion(migrator.getClass());+ if (dbDataVersion != null && !dbDataVersion.equals(appDataVersion)) {+ logger.error("Can not apply constraints to a database populated by a different program version");+ System.exit(1);+ }++ Metadata metadata = buildMetadata();+ dropForeignKeyConstraints(metadata);+ applyForeignKeyConstraints(metadata);++ logger.info("Database constraints is applied successfully");++ System.exit(0);+ }++ @Override+ public SessionFactory getSessionFactory() {+ throw new UnsupportedOperationException();+ }++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultRestoreManager.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultRestoreManager.javanew file mode 100644index 0000000000..de460cf969--- /dev/null+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultRestoreManager.java@@ -0,0 +1,76 @@+package com.pmease.commons.hibernate;++import java.io.File;+import java.util.Properties;+import java.util.Set;++import javax.inject.Inject;+import javax.inject.Named;+import javax.inject.Singleton;++import org.hibernate.Interceptor;+import org.hibernate.boot.Metadata;+import org.hibernate.boot.model.naming.PhysicalNamingStrategy;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.pmease.commons.bootstrap.Bootstrap;+import com.pmease.commons.bootstrap.BootstrapUtils;+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.util.FileUtils;++@Singleton+public class DefaultRestoreManager extends DefaultPersistManager {++ private static final Logger logger = LoggerFactory.getLogger(DefaultRestoreManager.class);++ @Inject+ public DefaultRestoreManager(Set<ModelProvider> modelProviders, PhysicalNamingStrategy physicalNamingStrategy,+ @Named("hibernate") Properties properties, Migrator migrator, Interceptor interceptor,+ IdManager idManager, Dao dao) {+ super(modelProviders, physicalNamingStrategy, properties, migrator, interceptor, idManager, dao);+ }++ @Override+ public void start() {+ if (Bootstrap.args.length < 2) {+ logger.error("Missing backup file parameter. Usage: {} <path to database backup file>", Bootstrap.getCommandFile());+ System.exit(1);+ }+ File backupFile = new File(Bootstrap.args[1]);+ if (!backupFile.isAbsolute())+ backupFile = new File(Bootstrap.getBinDir(), backupFile.getPath());++ if (!backupFile.exists()) {+ logger.error("Unable to find file {}", backupFile.getAbsolutePath());+ System.exit(1);+ }++ if (Bootstrap.getServerRunningFile().exists()) {+ logger.error("Please stop server before restore");+ System.exit(1);+ }+ String dbDataVersion = readDbDataVersion();+ String appDataVersion = MigrationHelper.getVersion(migrator.getClass());+ if (dbDataVersion != null && !dbDataVersion.equals(appDataVersion)) {+ logger.error("Data version mismatch, please clean the database first");+ System.exit(1);+ }++ Metadata metadata = buildMetadata();+ sessionFactory = metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();++ File dataDir = Bootstrap.getCommandDir();+ FileUtils.cleanDir(dataDir);+ BootstrapUtils.unzip(backupFile, dataDir, null);+ importData(metadata, dataDir);++ sessionFactory.close();+ logger.info("Database is restored successfully");++ System.exit(0);+ }++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultUnitOfWork.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultUnitOfWork.javaindex 0f0e14d4db..f50f363edc 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultUnitOfWork.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/DefaultUnitOfWork.java@@ -1,119 +1,112 @@-package com.pmease.commons.hibernate;--import java.util.concurrent.Callable;-import java.util.concurrent.ExecutorService;--import org.hibernate.FlushMode;-import org.hibernate.Session;-import org.hibernate.SessionFactory;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.inject.Inject;-import com.google.inject.Provider;-import com.google.inject.Singleton;-import com.pmease.commons.util.ObjectReference;--@Singleton-public class DefaultUnitOfWork implements UnitOfWork, Provider<Session> {-- private static final Logger logger = LoggerFactory.getLogger(DefaultUnitOfWork.class);-- private final Provider<SessionFactory> sessionFactoryProvider;-- private final ExecutorService executorService;-- private final ThreadLocal<ObjectReference<Session>> sessionReferenceHolder = new ThreadLocal<ObjectReference<Session>>() {-- @Override- protected ObjectReference<Session> initialValue() {- return new ObjectReference<Session>() {-- @Override- protected Session openObject() {- Session session = sessionFactoryProvider.get().openSession();-- // Session is supposed to be able to write only in transactional methods- session.setFlushMode(FlushMode.MANUAL);-- return session;- }-- @Override- protected void closeObject(Session session) {- session.close();- }-- };- }-- };-- @Inject- public DefaultUnitOfWork(Provider<SessionFactory> sessionFactoryProvider, ExecutorService executorService) {- this.sessionFactoryProvider = sessionFactoryProvider;- this.executorService = executorService;- }-- public void begin() {- sessionReferenceHolder.get().open();- }-- public void end() {- sessionReferenceHolder.get().close();- }-- public Session get() {- return getSession();- }-- public Session getSession() {- return sessionReferenceHolder.get().get();- }-- public SessionFactory getSessionFactory() {- return sessionFactoryProvider.get();- }-- @Override- public <T> T call(Callable<T> callable) {- begin();- try {- return callable.call();- } catch (Exception e) {- throw new RuntimeException(e);- } finally {- end();- }- }-- @Override- public void doAsync(final Runnable runnable) {- executorService.execute(new Runnable() {-- @Override- public void run() {- begin();- try {- runnable.run();- } catch (Exception e) {- logger.error("Error executing within unit of work.", e);- } finally {- end();- }- }-- });- }-- @Override- public void run(Runnable runnable) {- begin();- try {- runnable.run();- } finally {- end();- }- }-+package com.pmease.commons.hibernate;++import java.util.concurrent.Callable;+import java.util.concurrent.ExecutorService;++import org.hibernate.FlushMode;+import org.hibernate.Session;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.google.inject.Inject;+import com.google.inject.Singleton;+import com.pmease.commons.util.ObjectReference;++@Singleton+public class DefaultUnitOfWork implements UnitOfWork {++ private static final Logger logger = LoggerFactory.getLogger(DefaultUnitOfWork.class);++ private final PersistManager persistManager;++ private final ExecutorService executorService;++ private final ThreadLocal<ObjectReference<Session>> sessionReferenceHolder = new ThreadLocal<ObjectReference<Session>>() {++ @Override+ protected ObjectReference<Session> initialValue() {+ return new ObjectReference<Session>() {++ @Override+ protected Session openObject() {+ Session session = persistManager.getSessionFactory().openSession();++ // Session is supposed to be able to write only in transactional methods+ session.setFlushMode(FlushMode.MANUAL);++ return session;+ }++ @Override+ protected void closeObject(Session session) {+ session.close();+ }++ };+ }++ };++ @Inject+ public DefaultUnitOfWork(PersistManager persistManager, ExecutorService executorService) {+ this.persistManager = persistManager;+ this.executorService = executorService;+ }++ @Override+ public void begin() {+ sessionReferenceHolder.get().open();+ }++ @Override+ public void end() {+ sessionReferenceHolder.get().close();+ }++ @Override+ public Session getSession() {+ return sessionReferenceHolder.get().get();+ }++ @Override+ public <T> T call(Callable<T> callable) {+ begin();+ try {+ return callable.call();+ } catch (Exception e) {+ throw new RuntimeException(e);+ } finally {+ end();+ }+ }++ @Override+ public void doAsync(final Runnable runnable) {+ executorService.execute(new Runnable() {++ @Override+ public void run() {+ begin();+ try {+ runnable.run();+ } catch (Exception e) {+ logger.error("Error executing within unit of work.", e);+ } finally {+ end();+ }+ }++ });+ }++ @Override+ public void run(Runnable runnable) {+ begin();+ try {+ runnable.run();+ } finally {+ end();+ }+ }+}\ No newline at end of filediff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateFilter.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateFilter.javaindex d71637cc8c..7aa9950352 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateFilter.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateFilter.java@@ -1,48 +1,48 @@-package com.pmease.commons.hibernate;--import java.io.IOException;--import javax.servlet.Filter;-import javax.servlet.FilterChain;-import javax.servlet.FilterConfig;-import javax.servlet.ServletException;-import javax.servlet.ServletRequest;-import javax.servlet.ServletResponse;--import com.google.inject.Inject;-import com.google.inject.Singleton;--@Singleton-public class HibernateFilter implements Filter {-- private final UnitOfWork unitOfWork;-- private final PersistManager persistService;-- @Inject- public HibernateFilter(UnitOfWork unitOfWork, PersistManager persistService) {- this.unitOfWork = unitOfWork;- this.persistService = persistService;- }-- public void destroy() {- }-- public void doFilter(ServletRequest request, ServletResponse response,- FilterChain chain) throws IOException, ServletException {- if (persistService.isReady()) {- unitOfWork.begin();- try {- chain.doFilter(request, response);- } finally {- unitOfWork.end();- }- } else {- chain.doFilter(request, response);- }- }-- public void init(FilterConfig config) throws ServletException {- }--}+package com.pmease.commons.hibernate;++import java.io.IOException;++import javax.servlet.Filter;+import javax.servlet.FilterChain;+import javax.servlet.FilterConfig;+import javax.servlet.ServletException;+import javax.servlet.ServletRequest;+import javax.servlet.ServletResponse;++import com.google.inject.Inject;+import com.google.inject.Singleton;++@Singleton+public class HibernateFilter implements Filter {++ private final UnitOfWork unitOfWork;++ private final PersistManager persistManager;++ @Inject+ public HibernateFilter(UnitOfWork unitOfWork, PersistManager persistManager) {+ this.unitOfWork = unitOfWork;+ this.persistManager = persistManager;+ }++ public void destroy() {+ }++ public void doFilter(ServletRequest request, ServletResponse response,+ FilterChain chain) throws IOException, ServletException {+ if (persistManager.getSessionFactory() != null) {+ unitOfWork.begin();+ try {+ chain.doFilter(request, response);+ } finally {+ unitOfWork.end();+ }+ } else {+ chain.doFilter(request, response);+ }+ }++ public void init(FilterConfig config) throws ServletException {+ }++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateModule.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateModule.javaindex a806f0e5a1..da7d3048aa 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateModule.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernateModule.java@@ -1,193 +1,196 @@-package com.pmease.commons.hibernate;--import java.io.Serializable;-import java.lang.reflect.AnnotatedElement;-import java.lang.reflect.Field;-import java.lang.reflect.Method;-import java.util.ArrayList;-import java.util.Collection;-import java.util.Properties;--import javax.inject.Provider;-import javax.inject.Singleton;-import javax.persistence.OneToMany;-import javax.persistence.Transient;-import javax.persistence.Version;--import org.hibernate.CallbackException;-import org.hibernate.Interceptor;-import org.hibernate.Session;-import org.hibernate.SessionFactory;-import org.hibernate.boot.model.naming.PhysicalNamingStrategy;-import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;-import org.hibernate.collection.internal.PersistentBag;-import org.hibernate.type.Type;--import com.google.common.collect.Lists;-import com.google.inject.matcher.AbstractMatcher;-import com.google.inject.matcher.Matchers;-import com.google.inject.name.Names;-import com.google.inject.util.Providers;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.hibernate.dao.DefaultDao;-import com.pmease.commons.hibernate.jackson.HibernateObjectMapperConfigurator;-import com.pmease.commons.hibernate.migration.JpaConverter;-import com.pmease.commons.hibernate.migration.PersistentBagConverter;-import com.pmease.commons.hibernate.migration.VersionTable;-import com.pmease.commons.jackson.ObjectMapperConfigurator;-import com.pmease.commons.jetty.ServletConfigurator;-import com.pmease.commons.loader.AbstractPlugin;-import com.pmease.commons.loader.AbstractPluginModule;-import com.pmease.commons.util.ClassUtils;-import com.thoughtworks.xstream.XStream;-import com.thoughtworks.xstream.annotations.XStreamOmitField;-import com.thoughtworks.xstream.converters.basic.NullConverter;-import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;-import com.thoughtworks.xstream.converters.extended.ISO8601SqlTimestampConverter;-import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;-import com.thoughtworks.xstream.core.JVM;-import com.thoughtworks.xstream.mapper.MapperWrapper;--public class HibernateModule extends AbstractPluginModule {-- @Override- protected void configure() {- super.configure();-- // Use an optional binding here in case our client does not like to- // start persist service provided by this plugin- bind(Interceptor.class).to(HibernateInterceptor.class);- bind(Properties.class).annotatedWith(Names.named("hibernate")).toProvider(Providers.<Properties>of(null));- bind(PhysicalNamingStrategy.class).to(PhysicalNamingStrategyStandardImpl.class);-- bind(PersistManager.class).to(DefaultPersistManager.class);- bind(SessionFactory.class).toProvider(DefaultPersistManager.class);- bind(UnitOfWork.class).to(DefaultUnitOfWork.class);- bind(Session.class).toProvider(DefaultUnitOfWork.class);- bind(IdManager.class).to(DefaultIdManager.class);- bind(Dao.class).to(DefaultDao.class);-- TransactionInterceptor transactionInterceptor = new TransactionInterceptor();- requestInjection(transactionInterceptor);-- bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {-- @Override- public boolean matches(AnnotatedElement element) {- return element.isAnnotationPresent(Transactional.class) && !((Method) element).isSynthetic();- }-- }, transactionInterceptor);-- SessionInterceptor sessionInterceptor = new SessionInterceptor();- requestInjection(sessionInterceptor);-- bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {-- @Override- public boolean matches(AnnotatedElement element) {- return element.isAnnotationPresent(Sessional.class) && !((Method) element).isSynthetic();- }-- }, sessionInterceptor);-- contribute(ObjectMapperConfigurator.class, HibernateObjectMapperConfigurator.class);- contribute(ServletConfigurator.class, HibernateServletConfigurator.class);-- contribute(PersistListener.class, new PersistListener() {-- @Override- public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)- throws CallbackException {- return false;- }-- @Override- public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)- throws CallbackException {- return false;- }-- @Override- public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,- String[] propertyNames, Type[] types) throws CallbackException {- return false;- }-- @Override- public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)- throws CallbackException {- }- });-- contribute(ModelProvider.class, new ModelProvider() {-- @SuppressWarnings("unchecked")- @Override- public Collection<Class<? extends AbstractEntity>> getModelClasses() {- return Lists.newArrayList(VersionTable.class);- }-- });-- // put your guice bindings here- bind(XStream.class).toProvider(new Provider<XStream>() {-- @SuppressWarnings("rawtypes")- @Override- public XStream get() {- ReflectionProvider reflectionProvider = JVM.newReflectionProvider();- XStream xstream = new XStream(reflectionProvider) {-- @Override- protected MapperWrapper wrapMapper(MapperWrapper next) {- return new MapperWrapper(next) {-- @Override- public boolean shouldSerializeMember(Class definedIn, String fieldName) {- Field field = reflectionProvider.getField(definedIn, fieldName);-- return field.getAnnotation(XStreamOmitField.class) == null &&- field.getAnnotation(Transient.class) == null &&- field.getAnnotation(OneToMany.class) == null &&- field.getAnnotation(Version.class) == null;- }-- @SuppressWarnings("unchecked")- @Override- public String serializedClass(Class type) {- if (type == PersistentBag.class)- return super.serializedClass(ArrayList.class);- else if (type != null)- return super.serializedClass(ClassUtils.unproxy(type));- else- return super.serializedClass(type);- }-- };- }-- };-- // register NullConverter as highest; otherwise NPE when unmarshal a map- // containing an entry with value set to null.- xstream.registerConverter(new NullConverter(), XStream.PRIORITY_VERY_HIGH);- xstream.registerConverter(new PersistentBagConverter(xstream.getMapper()), 200);- xstream.registerConverter(new JpaConverter(xstream.getMapper(), xstream.getReflectionProvider()));- xstream.registerConverter(new ISO8601DateConverter(), 100);- xstream.registerConverter(new ISO8601SqlTimestampConverter(), 100);- xstream.autodetectAnnotations(true);-- return xstream;- }-- }).in(Singleton.class);-- }-- @Override- protected Class<? extends AbstractPlugin> getPluginClass() {- return HibernatePlugin.class;- }--}+package com.pmease.commons.hibernate;++import java.io.Serializable;+import java.lang.reflect.AnnotatedElement;+import java.lang.reflect.Field;+import java.lang.reflect.Method;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Properties;++import javax.inject.Provider;+import javax.inject.Singleton;+import javax.persistence.OneToMany;+import javax.persistence.Transient;+import javax.persistence.Version;++import org.hibernate.CallbackException;+import org.hibernate.Interceptor;+import org.hibernate.boot.model.naming.PhysicalNamingStrategy;+import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;+import org.hibernate.collection.internal.PersistentBag;+import org.hibernate.type.Type;++import com.google.common.collect.Lists;+import com.google.inject.matcher.AbstractMatcher;+import com.google.inject.matcher.Matchers;+import com.google.inject.name.Names;+import com.google.inject.util.Providers;+import com.pmease.commons.bootstrap.Bootstrap;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.hibernate.dao.DefaultDao;+import com.pmease.commons.hibernate.jackson.HibernateObjectMapperConfigurator;+import com.pmease.commons.hibernate.migration.JpaConverter;+import com.pmease.commons.hibernate.migration.PersistentBagConverter;+import com.pmease.commons.hibernate.migration.VersionTable;+import com.pmease.commons.jackson.ObjectMapperConfigurator;+import com.pmease.commons.jetty.ServletConfigurator;+import com.pmease.commons.loader.AbstractPlugin;+import com.pmease.commons.loader.AbstractPluginModule;+import com.pmease.commons.loader.AppLoader;+import com.pmease.commons.util.ClassUtils;+import com.thoughtworks.xstream.XStream;+import com.thoughtworks.xstream.annotations.XStreamOmitField;+import com.thoughtworks.xstream.converters.basic.NullConverter;+import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;+import com.thoughtworks.xstream.converters.extended.ISO8601SqlTimestampConverter;+import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;+import com.thoughtworks.xstream.core.JVM;+import com.thoughtworks.xstream.mapper.MapperWrapper;++public class HibernateModule extends AbstractPluginModule {++ @Override+ protected void configure() {+ super.configure();++ // Use an optional binding here in case our client does not like to+ // start persist service provided by this plugin+ bind(Interceptor.class).to(HibernateInterceptor.class);+ bind(Properties.class).annotatedWith(Names.named("hibernate")).toProvider(Providers.<Properties>of(null));+ bind(PhysicalNamingStrategy.class).to(PhysicalNamingStrategyStandardImpl.class);++ bind(UnitOfWork.class).to(DefaultUnitOfWork.class);+ bind(IdManager.class).to(DefaultIdManager.class);+ bind(Dao.class).to(DefaultDao.class);++ TransactionInterceptor transactionInterceptor = new TransactionInterceptor();+ requestInjection(transactionInterceptor);++ bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {++ @Override+ public boolean matches(AnnotatedElement element) {+ return element.isAnnotationPresent(Transactional.class) && !((Method) element).isSynthetic();+ }++ }, transactionInterceptor);++ SessionInterceptor sessionInterceptor = new SessionInterceptor();+ requestInjection(sessionInterceptor);++ bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {++ @Override+ public boolean matches(AnnotatedElement element) {+ return element.isAnnotationPresent(Sessional.class) && !((Method) element).isSynthetic();+ }++ }, sessionInterceptor);++ contribute(ObjectMapperConfigurator.class, HibernateObjectMapperConfigurator.class);+ contribute(ServletConfigurator.class, HibernateServletConfigurator.class);++ contribute(PersistListener.class, new PersistListener() {++ @Override+ public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)+ throws CallbackException {+ return false;+ }++ @Override+ public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)+ throws CallbackException {+ return false;+ }++ @Override+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,+ String[] propertyNames, Type[] types) throws CallbackException {+ return false;+ }++ @Override+ public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)+ throws CallbackException {+ }+ });++ contribute(ModelProvider.class, new ModelProvider() {++ @SuppressWarnings("unchecked")+ @Override+ public Collection<Class<? extends AbstractEntity>> getModelClasses() {+ return Lists.newArrayList(VersionTable.class);+ }++ });++ // put your guice bindings here+ bind(XStream.class).toProvider(new Provider<XStream>() {++ @SuppressWarnings("rawtypes")+ @Override+ public XStream get() {+ ReflectionProvider reflectionProvider = JVM.newReflectionProvider();+ XStream xstream = new XStream(reflectionProvider) {++ @Override+ protected MapperWrapper wrapMapper(MapperWrapper next) {+ return new MapperWrapper(next) {++ @Override+ public boolean shouldSerializeMember(Class definedIn, String fieldName) {+ Field field = reflectionProvider.getField(definedIn, fieldName);++ return field.getAnnotation(XStreamOmitField.class) == null &&+ field.getAnnotation(Transient.class) == null &&+ field.getAnnotation(OneToMany.class) == null &&+ field.getAnnotation(Version.class) == null;+ }++ @SuppressWarnings("unchecked")+ @Override+ public String serializedClass(Class type) {+ if (type == PersistentBag.class)+ return super.serializedClass(ArrayList.class);+ else if (type != null)+ return super.serializedClass(ClassUtils.unproxy(type));+ else+ return super.serializedClass(type);+ }++ };+ }++ };++ // register NullConverter as highest; otherwise NPE when unmarshal a map+ // containing an entry with value set to null.+ xstream.registerConverter(new NullConverter(), XStream.PRIORITY_VERY_HIGH);+ xstream.registerConverter(new PersistentBagConverter(xstream.getMapper()), 200);+ xstream.registerConverter(new JpaConverter(xstream.getMapper(), xstream.getReflectionProvider()));+ xstream.registerConverter(new ISO8601DateConverter(), 100);+ xstream.registerConverter(new ISO8601SqlTimestampConverter(), 100);+ xstream.autodetectAnnotations(true);++ return xstream;+ }++ }).in(Singleton.class);++ if (AppLoader.COMMAND_RESTORE.equals(Bootstrap.getCommand()))+ bind(PersistManager.class).to(DefaultRestoreManager.class);+ else if (AppLoader.COMMAND_REAPPLY_DB_CONSTRAINTS.equals(Bootstrap.getCommand()))+ bind(PersistManager.class).to(DefaultReapplyDBConstraintsManager.class);+ else+ bind(PersistManager.class).to(DefaultPersistManager.class);+ }++ @Override+ protected Class<? extends AbstractPlugin> getPluginClass() {+ return HibernatePlugin.class;+ }++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernatePlugin.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernatePlugin.javaindex 05fa4da939..f603870d4d 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernatePlugin.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/HibernatePlugin.java@@ -5,21 +5,21 @@ import com.pmease.commons.loader.AbstractPlugin;public class HibernatePlugin extends AbstractPlugin {- private final PersistManager persistService;+ private final PersistManager persistManager;@Inject- public HibernatePlugin(PersistManager persistService) {- this.persistService = persistService;+ public HibernatePlugin(PersistManager persistManager) {+ this.persistManager = persistManager;}@Overridepublic void start() {- persistService.start();+ persistManager.start();}@Overridepublic void stop() {- persistService.stop();+ persistManager.stop();}}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PersistManager.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PersistManager.javaindex 0e3b11c1f8..9e7c87a8b9 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PersistManager.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/PersistManager.java@@ -1,31 +1,28 @@-package com.pmease.commons.hibernate;--import java.io.File;-import java.util.List;--public interface PersistManager {-- void start();-- void stop();-- boolean isReady();-- String getDbDataVersion();-- /**- * @return hibernate entity types ordered using foreign key dependency- * information. For example, Build type comes before Configuration- * type as it has Build has foreign key reference to Configuration.- */- List<Class<?>> getEntityTypes();-- void migrate(File dataDir);-- void exportData(File dataDir, int batchSize);-- // This method should only be called by a bootstrap action. That is, when the- // server is stopped. So it does not need an exclusive database lock.- void importData(File dataDir);--}+package com.pmease.commons.hibernate;++import java.io.File;++import org.hibernate.SessionFactory;+import org.hibernate.boot.Metadata;++public interface PersistManager {++ SessionFactory getSessionFactory();++ void start();++ void stop();++ void migrate(File dataDir);++ void exportData(File dataDir, int batchSize);++ // This method should only be called by a bootstrap action. That is, when the+ // server is stopped. So it does not need an exclusive database lock.+ void importData(Metadata metadata, File dataDir);++ void dropForeignKeyConstraints(Metadata metadata);++ void applyForeignKeyConstraints(Metadata metadata);++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/UnitOfWork.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/UnitOfWork.javaindex 9d81cb51e2..2e7b6da5e4 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/UnitOfWork.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/UnitOfWork.java@@ -1,39 +1,37 @@-/**- * Copyright (C) 2010 Google, Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package com.pmease.commons.hibernate;--import java.util.concurrent.Callable;--import org.hibernate.Session;-import org.hibernate.SessionFactory;--public interface UnitOfWork {-- void begin();-- void end();-- <T> T call(Callable<T> callable);-- void run(Runnable runnable);-- void doAsync(Runnable runnable);-- Session getSession();-- SessionFactory getSessionFactory();-}+/**+ * Copyright (C) 2010 Google, Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.pmease.commons.hibernate;++import java.util.concurrent.Callable;++import org.hibernate.Session;++public interface UnitOfWork {++ void begin();++ void end();++ <T> T call(Callable<T> callable);++ void run(Runnable runnable);++ void doAsync(Runnable runnable);++ Session getSession();++}diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.javaindex 1f63baa8d4..fa99348905 100644--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java@@ -1,175 +1,171 @@-package com.pmease.commons.hibernate.dao;--import java.io.ObjectStreamException;-import java.io.Serializable;-import java.util.List;-import java.util.concurrent.ExecutorService;--import javax.inject.Inject;-import javax.inject.Provider;-import javax.inject.Singleton;-import javax.transaction.Status;-import javax.transaction.Synchronization;--import org.hibernate.Criteria;-import org.hibernate.Session;-import org.hibernate.criterion.Projections;--import com.pmease.commons.hibernate.AbstractEntity;-import com.pmease.commons.hibernate.Sessional;-import com.pmease.commons.hibernate.Transactional;-import com.pmease.commons.hibernate.UnitOfWork;-import com.pmease.commons.loader.ListenerRegistry;-import com.pmease.commons.loader.ManagedSerializedForm;--@Singleton-@SuppressWarnings("unchecked")-public class DefaultDao implements Dao, Serializable {-- private final Provider<Session> sessionProvider;-- private final ListenerRegistry listenerRegistry;-- private final ExecutorService executorService;-- private final UnitOfWork unitOfWork;-- @Inject- public DefaultDao(Provider<Session> sessionProvider, UnitOfWork unitOfWork,- ListenerRegistry listenerRegistry, ExecutorService executorService) {- this.sessionProvider = sessionProvider;- this.unitOfWork = unitOfWork;- this.listenerRegistry = listenerRegistry;- this.executorService = executorService;- }-- @Sessional- @Override- public <T extends AbstractEntity> T get(Class<T> entityClass, Long entityId) {- return (T) getSession().get(unproxy(getSession(), entityClass), entityId);- }-- @Sessional- @Override- public <T extends AbstractEntity> T load(Class<T> entityClass, Long entityId) {- return (T) getSession().load(unproxy(getSession(), entityClass), entityId);- }-- @Transactional- @Override- public void persist(AbstractEntity entity) {- boolean isNew = entity.isNew();- getSession().saveOrUpdate(entity);- listenerRegistry.post(new EntityPersisted(entity, isNew));- }-- @Transactional- @Override- public void remove(AbstractEntity entity) {- getSession().delete(entity);- listenerRegistry.post(new EntityRemoved(entity));- }-- @Override- public Session getSession() {- return sessionProvider.get();- }-- protected <T extends AbstractEntity> Class<T> unproxy(Session session, Class<T> entityClass) {- //class meta data will be null if entityClass is not registered with Hibernate or when- //it is a Hibernate proxy class (e.x. test.googlecode.genericdao.model.Person_$$_javassist_5).- //So if a class is not recognized, we will look at superclasses to see if- //it is a proxy.- while (session.getSessionFactory().getClassMetadata(entityClass) == null) {- entityClass = (Class<T>) entityClass.getSuperclass();- if (Object.class.equals(entityClass))- return null;- }-- return entityClass;- }-- @Sessional- @Override- public <T extends AbstractEntity> List<T> findRange(EntityCriteria<T> entityCriteria, int firstResult, int maxResults) {- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());- if (firstResult != 0)- criteria.setFirstResult(firstResult);- if (maxResults != 0)- criteria.setMaxResults(maxResults);- return criteria.list();- }-- @Sessional- @Override- public <T extends AbstractEntity> List<T> findAll(EntityCriteria<T> entityCriteria) {- return findRange(entityCriteria, 0, 0);- }-- @Sessional- @Override- public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());- criteria.setFirstResult(0);- criteria.setMaxResults(1);- return (T) criteria.uniqueResult();- }-- @Override- public <T extends AbstractEntity> int count(EntityCriteria<T> entityCriteria) {- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());- criteria.setProjection(Projections.rowCount());- return ((Long) criteria.uniqueResult()).intValue();- }-- public Object writeReplace() throws ObjectStreamException {- return new ManagedSerializedForm(Dao.class);- }-- @Sessional- @Override- public <T extends AbstractEntity> List<T> findAll(Class<T> entityClass) {- return findRange(EntityCriteria.of(entityClass), 0, 0);- }-- @Override- public void doAfterCommit(Runnable runnable) {- getSession().getTransaction().registerSynchronization(new Synchronization() {-- @Override- public void beforeCompletion() {- }-- @Override- public void afterCompletion(int status) {- if (status == Status.STATUS_COMMITTED)- runnable.run();- }- });- }-- @Override- public void doAsyncAfterCommit(Runnable runnable) {- doAfterCommit(new Runnable() {-- @Override- public void run() {- executorService.submit(runnable);- }-- });- }-- @Override- public void doUnitOfWorkAsyncAfterCommit(Runnable runnable) {- doAfterCommit(new Runnable() {-- @Override- public void run() {- unitOfWork.doAsync(runnable);- }-- });- }--}+package com.pmease.commons.hibernate.dao;++import java.io.ObjectStreamException;+import java.io.Serializable;+import java.util.List;+import java.util.concurrent.ExecutorService;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.transaction.Status;+import javax.transaction.Synchronization;++import org.hibernate.Criteria;+import org.hibernate.Session;+import org.hibernate.criterion.Projections;++import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.commons.hibernate.Sessional;+import com.pmease.commons.hibernate.Transactional;+import com.pmease.commons.hibernate.UnitOfWork;+import com.pmease.commons.loader.ListenerRegistry;+import com.pmease.commons.loader.ManagedSerializedForm;++@Singleton+@SuppressWarnings("unchecked")+public class DefaultDao implements Dao, Serializable {++ private final UnitOfWork unitOfWork;++ private final ListenerRegistry listenerRegistry;++ private final ExecutorService executorService;++ @Inject+ public DefaultDao(UnitOfWork unitOfWork, ListenerRegistry listenerRegistry,+ ExecutorService executorService) {+ this.unitOfWork = unitOfWork;+ this.listenerRegistry = listenerRegistry;+ this.executorService = executorService;+ }++ @Sessional+ @Override+ public <T extends AbstractEntity> T get(Class<T> entityClass, Long entityId) {+ return (T) getSession().get(unproxy(getSession(), entityClass), entityId);+ }++ @Sessional+ @Override+ public <T extends AbstractEntity> T load(Class<T> entityClass, Long entityId) {+ return (T) getSession().load(unproxy(getSession(), entityClass), entityId);+ }++ @Transactional+ @Override+ public void persist(AbstractEntity entity) {+ boolean isNew = entity.isNew();+ getSession().saveOrUpdate(entity);+ listenerRegistry.post(new EntityPersisted(entity, isNew));+ }++ @Transactional+ @Override+ public void remove(AbstractEntity entity) {+ getSession().delete(entity);+ listenerRegistry.post(new EntityRemoved(entity));+ }++ @Override+ public Session getSession() {+ return unitOfWork.getSession();+ }++ protected <T extends AbstractEntity> Class<T> unproxy(Session session, Class<T> entityClass) {+ //class meta data will be null if entityClass is not registered with Hibernate or when+ //it is a Hibernate proxy class (e.x. test.googlecode.genericdao.model.Person_$$_javassist_5).+ //So if a class is not recognized, we will look at superclasses to see if+ //it is a proxy.+ while (session.getSessionFactory().getClassMetadata(entityClass) == null) {+ entityClass = (Class<T>) entityClass.getSuperclass();+ if (Object.class.equals(entityClass))+ return null;+ }++ return entityClass;+ }++ @Sessional+ @Override+ public <T extends AbstractEntity> List<T> findRange(EntityCriteria<T> entityCriteria, int firstResult, int maxResults) {+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());+ if (firstResult != 0)+ criteria.setFirstResult(firstResult);+ if (maxResults != 0)+ criteria.setMaxResults(maxResults);+ return criteria.list();+ }++ @Sessional+ @Override+ public <T extends AbstractEntity> List<T> findAll(EntityCriteria<T> entityCriteria) {+ return findRange(entityCriteria, 0, 0);+ }++ @Sessional+ @Override+ public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());+ criteria.setFirstResult(0);+ criteria.setMaxResults(1);+ return (T) criteria.uniqueResult();+ }++ @Override+ public <T extends AbstractEntity> int count(EntityCriteria<T> entityCriteria) {+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());+ criteria.setProjection(Projections.rowCount());+ return ((Long) criteria.uniqueResult()).intValue();+ }++ public Object writeReplace() throws ObjectStreamException {+ return new ManagedSerializedForm(Dao.class);+ }++ @Sessional+ @Override+ public <T extends AbstractEntity> List<T> findAll(Class<T> entityClass) {+ return findRange(EntityCriteria.of(entityClass), 0, 0);+ }++ @Override+ public void doAfterCommit(Runnable runnable) {+ getSession().getTransaction().registerSynchronization(new Synchronization() {++ @Override+ public void beforeCompletion() {+ }++ @Override+ public void afterCompletion(int status) {+ if (status == Status.STATUS_COMMITTED)+ runnable.run();+ }+ });+ }++ @Override+ public void doAsyncAfterCommit(Runnable runnable) {+ doAfterCommit(new Runnable() {++ @Override+ public void run() {+ executorService.submit(runnable);+ }++ });+ }++ @Override+ public void doUnitOfWorkAsyncAfterCommit(Runnable runnable) {+ doAfterCommit(new Runnable() {++ @Override+ public void run() {+ unitOfWork.doAsync(runnable);+ }++ });+ }++}diff --git a/commons.jetty/src/main/java/com/pmease/commons/jetty/DefaultJettyManager.java b/commons.jetty/src/main/java/com/pmease/commons/jetty/DefaultJettyManager.javanew file mode 100644index 0000000000..0e9a590b43--- /dev/null+++ b/commons.jetty/src/main/java/com/pmease/commons/jetty/DefaultJettyManager.java@@ -0,0 +1,113 @@+package com.pmease.commons.jetty;++import java.util.ArrayList;+import java.util.Collections;+import java.util.EnumSet;+import java.util.List;+import java.util.Set;++import javax.inject.Provider;+import javax.inject.Singleton;+import javax.servlet.DispatcherType;++import org.eclipse.jetty.server.Server;+import org.eclipse.jetty.server.handler.gzip.GzipHandler;+import org.eclipse.jetty.servlet.ErrorPageErrorHandler;+import org.eclipse.jetty.servlet.ServletContextHandler;++import com.google.inject.Inject;+import com.google.inject.servlet.GuiceFilter;+import com.pmease.commons.bootstrap.BootstrapUtils;++@Singleton+public class DefaultJettyManager implements JettyManager {++ private static final int MAX_CONTENT_SIZE = 5000000;++ private Server server;++ private ServletContextHandler contextHandler;++ private final Provider<Set<ServerConfigurator>> serverConfiguratorsProvider;++ private final Provider<Set<ServletConfigurator>> servletConfiguratorsProvider;++ /*+ * Inject providers here to avoid circurlar dependencies when dependency graph gets complicated+ */+ @Inject+ public DefaultJettyManager(+ Provider<Set<ServerConfigurator>> serverConfiguratorsProvider,+ Provider<Set<ServletConfigurator>> servletConfiguratorsProvider) {+ this.serverConfiguratorsProvider = serverConfiguratorsProvider;+ this.servletConfiguratorsProvider = servletConfiguratorsProvider;+ }++ @Override+ public void start() {+ server = createServer();++ try {+ server.start();+ } catch (Exception e) {+ throw BootstrapUtils.unchecked(e);+ }+ }++ @Override+ public void stop() {+ if (server != null) {+ try {+ server.stop();+ } catch (Exception e) {+ throw BootstrapUtils.unchecked(e);+ }+ }+ }++ @Override+ public ServletContextHandler getContextHandler() {+ return contextHandler;+ }++ private Server createServer() {+ server = new Server();++ contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);+ contextHandler.setMaxFormContentSize(MAX_CONTENT_SIZE);++ contextHandler.setClassLoader(JettyPlugin.class.getClassLoader());++ contextHandler.setErrorHandler(new ErrorPageErrorHandler());+ contextHandler.addFilter(DisableTraceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));++ /*+ * By default contributions is in reverse dependency order. We reverse the order so that+ * servlet and filter contributions in dependency plugins comes first.+ */+ List<ServletConfigurator> servletConfigurators = new ArrayList<>(servletConfiguratorsProvider.get());+ Collections.reverse(servletConfigurators);+ for (ServletConfigurator configurator: servletConfigurators) {+ configurator.configure(contextHandler);+ }++ /*+ * Add Guice filter as last filter in order to make sure that filters and servlets+ * configured in Guice web module can be filtered correctly by filters added to+ * Jetty context directly.+ */+ contextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));++ GzipHandler gzipHandler = new GzipHandler();+ gzipHandler.setIncludedMimeTypes("text/css", "application/javascript", "text/javascript");+ gzipHandler.setHandler(contextHandler);++ server.setHandler(gzipHandler);++ for (ServerConfigurator configurator: serverConfiguratorsProvider.get())+ configurator.configure(server);++ return server;+ }++}diff --git a/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyManager.java b/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyManager.javanew file mode 100644index 0000000000..d27f801843--- /dev/null+++ b/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyManager.java@@ -0,0 +1,13 @@+package com.pmease.commons.jetty;++import org.eclipse.jetty.servlet.ServletContextHandler;++public interface JettyManager {++ void start();++ void stop();++ ServletContextHandler getContextHandler();++}diff --git a/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyModule.java b/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyModule.javaindex 2e7934a605..47afa97af4 100644--- a/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyModule.java+++ b/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyModule.java@@ -2,8 +2,10 @@ package com.pmease.commons.jetty;import org.eclipse.jetty.server.SessionManager;+import com.pmease.commons.bootstrap.Bootstrap;import com.pmease.commons.loader.AbstractPlugin;import com.pmease.commons.loader.AbstractPluginModule;+import com.pmease.commons.loader.AppLoader;public class JettyModule extends AbstractPluginModule {@@ -12,6 +14,13 @@ public class JettyModule extends AbstractPluginModule {super.configure();bind(SessionManager.class).toProvider(SessionManagerProvider.class);+ if (AppLoader.COMMAND_RESTORE.equals(Bootstrap.getCommand())+ || AppLoader.COMMAND_UPGRADE.equals(Bootstrap.getCommand())+ || AppLoader.COMMAND_REAPPLY_DB_CONSTRAINTS.equals(Bootstrap.getCommand())) {+ bind(JettyManager.class).to(NoJettyManager.class);+ } else {+ bind(JettyManager.class).to(DefaultJettyManager.class);+ }}@Overridediff --git a/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyPlugin.java b/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyPlugin.javaindex cd041ddbcb..4a6cadd2a4 100644--- a/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyPlugin.java+++ b/commons.jetty/src/main/java/com/pmease/commons/jetty/JettyPlugin.java@@ -1,113 +1,25 @@-package com.pmease.commons.jetty;--import java.util.ArrayList;-import java.util.Collections;-import java.util.EnumSet;-import java.util.List;-import java.util.Set;--import javax.inject.Provider;-import javax.servlet.DispatcherType;--import org.eclipse.jetty.server.Server;-import org.eclipse.jetty.server.handler.gzip.GzipHandler;-import org.eclipse.jetty.servlet.ErrorPageErrorHandler;-import org.eclipse.jetty.servlet.ServletContextHandler;--import com.google.inject.Inject;-import com.google.inject.servlet.GuiceFilter;-import com.pmease.commons.bootstrap.BootstrapUtils;-import com.pmease.commons.loader.AbstractPlugin;--public class JettyPlugin extends AbstractPlugin {-- private static final int MAX_CONTENT_SIZE = 5000000;-- private Server server;-- private ServletContextHandler contextHandler;-- private final Provider<Set<ServerConfigurator>> serverConfiguratorsProvider;-- private final Provider<Set<ServletConfigurator>> servletConfiguratorsProvider;-- /*- * Inject providers here to avoid circurlar dependencies when dependency graph gets complicated- */- @Inject- public JettyPlugin(- Provider<Set<ServerConfigurator>> serverConfiguratorsProvider,- Provider<Set<ServletConfigurator>> servletConfiguratorsProvider) {- this.serverConfiguratorsProvider = serverConfiguratorsProvider;- this.servletConfiguratorsProvider = servletConfiguratorsProvider;- }-- @Override- public void start() {- server = createServer();-- try {- server.start();- } catch (Exception e) {- throw BootstrapUtils.unchecked(e);- }- }-- @Override- public void stop() {- try {- server.stop();- } catch (Exception e) {- throw BootstrapUtils.unchecked(e);- }- }-- public ServletContextHandler getContextHandler() {- return contextHandler;- }-- public Server getServer() {- return server;- }-- private Server createServer() {- server = new Server();-- contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);- contextHandler.setMaxFormContentSize(MAX_CONTENT_SIZE);-- contextHandler.setClassLoader(JettyPlugin.class.getClassLoader());-- contextHandler.setErrorHandler(new ErrorPageErrorHandler());- contextHandler.addFilter(DisableTraceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));-- /*- * By default contributions is in reverse dependency order. We reverse the order so that- * servlet and filter contributions in dependency plugins comes first.- */- List<ServletConfigurator> servletConfigurators = new ArrayList<>(servletConfiguratorsProvider.get());- Collections.reverse(servletConfigurators);- for (ServletConfigurator configurator: servletConfigurators) {- configurator.configure(contextHandler);- }-- /*- * Add Guice filter as last filter in order to make sure that filters and servlets- * configured in Guice web module can be filtered correctly by filters added to- * Jetty context directly.- */- contextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));-- GzipHandler gzipHandler = new GzipHandler();- gzipHandler.setIncludedMimeTypes("text/css", "application/javascript", "text/javascript");- gzipHandler.setHandler(contextHandler);-- server.setHandler(gzipHandler);-- for (ServerConfigurator configurator: serverConfiguratorsProvider.get())- configurator.configure(server);-- return server;- }--}+package com.pmease.commons.jetty;++import com.google.inject.Inject;+import com.pmease.commons.loader.AbstractPlugin;++public class JettyPlugin extends AbstractPlugin {++ private final JettyManager jettyManager;++ @Inject+ public JettyPlugin(JettyManager jettyManager) {+ this.jettyManager = jettyManager;+ }++ @Override+ public void start() {+ jettyManager.start();+ }++ @Override+ public void stop() {+ jettyManager.stop();+ }++}diff --git a/commons.jetty/src/main/java/com/pmease/commons/jetty/NoJettyManager.java b/commons.jetty/src/main/java/com/pmease/commons/jetty/NoJettyManager.javanew file mode 100644index 0000000000..01c0b7d897--- /dev/null+++ b/commons.jetty/src/main/java/com/pmease/commons/jetty/NoJettyManager.java@@ -0,0 +1,23 @@+package com.pmease.commons.jetty;++import javax.inject.Singleton;++import org.eclipse.jetty.servlet.ServletContextHandler;++@Singleton+public class NoJettyManager implements JettyManager {++ @Override+ public void start() {+ }++ @Override+ public void stop() {+ }++ @Override+ public ServletContextHandler getContextHandler() {+ throw new UnsupportedOperationException();+ }++}diff --git a/commons.jetty/src/main/java/com/pmease/commons/jetty/SessionManagerProvider.java b/commons.jetty/src/main/java/com/pmease/commons/jetty/SessionManagerProvider.javaindex fcef1dce4c..5ee3c7b3c6 100644--- a/commons.jetty/src/main/java/com/pmease/commons/jetty/SessionManagerProvider.java+++ b/commons.jetty/src/main/java/com/pmease/commons/jetty/SessionManagerProvider.java@@ -9,16 +9,16 @@ import org.eclipse.jetty.server.SessionManager;@Singletonpublic class SessionManagerProvider implements Provider<SessionManager> {- private final JettyPlugin plugin;+ private final JettyManager jettyManager;@Inject- public SessionManagerProvider(JettyPlugin plugin) {- this.plugin = plugin;+ public SessionManagerProvider(JettyManager jettyManager) {+ this.jettyManager = jettyManager;}@Overridepublic SessionManager get() {- return plugin.getContextHandler().getSessionHandler().getSessionManager();+ return jettyManager.getContextHandler().getSessionHandler().getSessionManager();}}diff --git a/commons.jsw/pom.xml b/commons.jsw/pom.xmlindex d27188e354..ed50622343 100644--- a/commons.jsw/pom.xml+++ b/commons.jsw/pom.xml@@ -27,7 +27,9 @@<unzip src="wrapper/wrapper-delta-pack-st.zip" dest="${project.build.outputDirectory}" overwrite="true"><regexpmapper from="^.*?/(.*)" to="\1"/></unzip>- <copy file="wrapper/wrapper.conf" tofile="${project.build.outputDirectory}/wrapper.conf"/>+ <copy todir="${project.build.outputDirectory}/customization">+ <fileset dir="wrapper/customization"></fileset>+ </copy></target></configuration></execution>diff --git a/commons.jsw/wrapper/customization/AppCommand.bat.in b/commons.jsw/wrapper/customization/AppCommand.bat.innew file mode 100644index 0000000000..de715eddad--- /dev/null+++ b/commons.jsw/wrapper/customization/AppCommand.bat.in@@ -0,0 +1,197 @@+@echo off+setlocal++rem+rem Copyright (c) 1999, 2016 Tanuki Software, Ltd.+rem http://www.tanukisoftware.com+rem All rights reserved.+rem+rem This software is the proprietary information of Tanuki Software.+rem You shall use it only in accordance with the terms of the+rem license agreement you entered into with Tanuki Software.+rem http://wrapper.tanukisoftware.com/doc/english/licenseOverview.html+rem+rem Java Service Wrapper command based script.+rem++rem -----------------------------------------------------------------------------+rem These settings can be modified to fit the needs of your application+rem Optimized for use with version 3.5.29-st of the Wrapper.++rem The base name for the Wrapper binary.+set _WRAPPER_BASE=wrapper++rem The directory where the Wrapper binary (.exe) file is located. It can be+rem either an absolute or a relative path. If the path contains any special+rem characters, please make sure to quote the variable.+set _WRAPPER_DIR=../boot++rem The name and location of the Wrapper configuration file. This will be used+rem if the user does not specify a configuration file as the first parameter to+rem this script.+set _WRAPPER_CONF="../conf/%_WRAPPER_BASE%.conf"++rem _FIXED_COMMAND tells the script to use a hard coded command rather than+rem expecting the first parameter of the command line to be the command.+rem By default the command will will be expected to be the first parameter.+@set_fixed_command@++rem _PASS_THROUGH tells the script to pass all parameters through to the JVM+rem as is. If _FIXED_COMMAND is specified then all parameters will be passed.+rem If not set then all parameters starting with the second will be passed.+set _PASS_THROUGH=true++rem Do not modify anything beyond this point+rem -----------------------------------------------------------------------------++if "%OS%"=="Windows_NT" goto nt+echo This script only works with NT-based versions of Windows.+goto :eof++:nt+rem Find the application home.+rem if no path path specified do the default action+IF not DEFINED _WRAPPER_DIR goto dir_undefined+set _WRAPPER_DIR_QUOTED="%_WRAPPER_DIR:"=%"+if not "%_WRAPPER_DIR:~-2,1%" == "\" set _WRAPPER_DIR_QUOTED="%_WRAPPER_DIR_QUOTED:"=%\"+rem check if absolute path+if "%_WRAPPER_DIR_QUOTED:~2,1%" == ":" goto absolute_path+if "%_WRAPPER_DIR_QUOTED:~1,1%" == "\" goto absolute_path+rem everythig else means relative path+set _REALPATH="%~dp0%_WRAPPER_DIR_QUOTED:"=%"+goto pathfound++:dir_undefined+rem Use a relative path to the wrapper %~dp0 is location of current script under NT+set _REALPATH="%~dp0"+goto pathfound+:absolute_path+rem Use an absolute path to the wrapper+set _REALPATH="%_WRAPPER_DIR_QUOTED:"=%"++:pathfound+rem+rem Decide on the specific Wrapper binary to use (See delta-pack)+rem+if "%PROCESSOR_ARCHITEW6432%"=="AMD64" goto amd64+if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto amd64+if "%PROCESSOR_ARCHITECTURE%"=="IA64" goto ia64+set _WRAPPER_L_EXE="%_REALPATH:"=%%_WRAPPER_BASE%-windows-x86-32.exe"+goto search+:amd64+set _WRAPPER_L_EXE="%_REALPATH:"=%%_WRAPPER_BASE%-windows-x86-64.exe"+goto search+:ia64+set _WRAPPER_L_EXE="%_REALPATH:"=%%_WRAPPER_BASE%-windows-ia-64.exe"+goto search+:search+set _WRAPPER_EXE="%_WRAPPER_L_EXE:"=%"+if exist %_WRAPPER_EXE% goto conf+set _WRAPPER_EXE="%_REALPATH:"=%%_WRAPPER_BASE%.exe"+if exist %_WRAPPER_EXE% goto conf+echo Unable to locate a Wrapper executable using any of the following names:+echo %_WRAPPER_L_EXE%+echo %_WRAPPER_EXE%+pause+goto :eof++:conf+if not [%_FIXED_COMMAND%]==[] (+ set _COMMAND=%_FIXED_COMMAND%+) else (+ set _COMMAND=%1+ shift+)++rem Collect all parameters+:parameters+set _PARAMETERS=%_PARAMETERS% %1+shift+if not [%1]==[] goto parameters++:callcommand+rem+rem Run the application.+rem At runtime, the current directory will be that of wrapper.exe+rem+set _MATCHED=true+if [%_COMMAND%]==[console] (+ if [%_PASS_THROUGH%]==[] (+ %_WRAPPER_EXE% -c "%_WRAPPER_CONF%" %_PARAMETERS%+ ) else (+ %_WRAPPER_EXE% -c "%_WRAPPER_CONF%" @properties_and_parameters@ %_PARAMETERS%+ )+) else if [%_COMMAND%]==[setup] (+ call :setup+) else if [%_COMMAND%]==[teardown] (+ call :teardown+) else if [%_COMMAND%]==[start] (+ call :start+) else if [%_COMMAND%]==[stop] (+ call :stop+) else if [%_COMMAND%]==[install] (+ if [%_PASS_THROUGH%]==[] (+ %_WRAPPER_EXE% -i "%_WRAPPER_CONF%" %_PARAMETERS%+ ) else (+ %_WRAPPER_EXE% -i "%_WRAPPER_CONF%" -- %_PARAMETERS%+ )+) else if [%_COMMAND%]==[installstart] (+ if [%_PASS_THROUGH%]==[] (+ %_WRAPPER_EXE% -it "%_WRAPPER_CONF%" %_PARAMETERS%+ ) else (+ %_WRAPPER_EXE% -it "%_WRAPPER_CONF%" -- %_PARAMETERS%+ )+) else if [%_COMMAND%]==[update] (+ if [%_PASS_THROUGH%]==[] (+ %_WRAPPER_EXE% -u "%_WRAPPER_CONF%" %_PARAMETERS%+ ) else (+ %_WRAPPER_EXE% -u "%_WRAPPER_CONF%" -- %_PARAMETERS%+ )+) else if [%_COMMAND%]==[pause] (+ %_WRAPPER_EXE% -a "%_WRAPPER_CONF%"+) else if [%_COMMAND%]==[resume] (+ %_WRAPPER_EXE% -e "%_WRAPPER_CONF%"+) else if [%_COMMAND%]==[status] (+ %_WRAPPER_EXE% -q "%_WRAPPER_CONF%"+) else if [%_COMMAND%]==[remove] (+ %_WRAPPER_EXE% -r "%_WRAPPER_CONF%"+) else if [%_COMMAND%]==[restart] (+ call :stop+ call :start+) else (+ set _MATCHED=+ goto showusage+)++if errorlevel 1 (+ if [%_MATCHED%]==[] goto showusage+)+goto :eof++:showusage+rem A command was not specified, or it was now known.+if not [%_COMMAND%]==[] (+ echo Unknown command: %_COMMAND%+ echo.+)+if [%_PASS_THROUGH%]==[] (+ echo Usage: %0 [ console : setup : teardown : start : pause : resume : stop : restart : install : installstart : update : remove : status ]+) else (+ echo Usage: %0 [ console {JavaAppArgs} : setup : teardown : start : pause : resume : stop : restart : install {JavaAppArgs} : installstart {JavaAppArgs} : update {JavaAppArgs} : remove : status ]+)+pause+goto :eof+++:setup+ %_WRAPPER_EXE% -su "%_WRAPPER_CONF%"+ goto :eof+:teardown+ %_WRAPPER_EXE% -td "%_WRAPPER_CONF%"+ goto :eof+:start+ %_WRAPPER_EXE% -t "%_WRAPPER_CONF%"+ goto :eof+:stop+ %_WRAPPER_EXE% -p "%_WRAPPER_CONF%"+ goto :eofdiff --git a/commons.jsw/wrapper/customization/sh.script.in b/commons.jsw/wrapper/customization/sh.script.innew file mode 100644index 0000000000..e46f5f2bce--- /dev/null+++ b/commons.jsw/wrapper/customization/sh.script.in@@ -0,0 +1,2164 @@+#! /bin/sh++#+# Copyright (c) 1999, 2016 Tanuki Software, Ltd.+# http://www.tanukisoftware.com+# All rights reserved.+#+# This software is the proprietary information of Tanuki Software.+# You shall use it only in accordance with the terms of the+# license agreement you entered into with Tanuki Software.+# http://wrapper.tanukisoftware.com/doc/english/licenseOverview.html+#+# Java Service Wrapper sh script. Suitable for starting and stopping+# wrapped Java applications on UNIX platforms.+#++#-----------------------------------------------------------------------------+# These settings can be modified to fit the needs of your application+# Optimized for use with version 3.5.29-st of the Wrapper.++# IMPORTANT - Please always stop and uninstall an application before making+# any changes to this file. Failure to do so could remove the+# script's ability to control the application.++# Initialization block for the install_initd and remove_initd scripts used by+# SUSE linux, CentOS and RHEL distributions.+# Note: From CentOS 6, make sure the BEGIN INIT INFO section is before any line+# of code otherwise the service won't be displayed in the Service+# Configuration GUI.+### BEGIN INIT INFO+# Provides: @app.name@+# Required-Start: $local_fs $network $syslog+# Should-Start:+# Required-Stop:+# Default-Start: 2 3 4 5+# Default-Stop: 0 1 6+# Short-Description: @app.long.name@+# Description: @app.description@+### END INIT INFO++# Application+APP_NAME="@app.name@"+APP_LONG_NAME="@app.long.name@"++# If uncommented (and set to false), APP_NAME and APP_LONG_NAME will no longer+# be passed to the wrapper. See documentation for details.+#APP_NAME_PASS_TO_WRAPPER=false++# Wrapper+WRAPPER_CMD="../boot/wrapper"+WRAPPER_CONF="../conf/wrapper.conf"++# Priority at which to run the wrapper. See "man nice" for valid priorities.+# nice is only used if a priority is specified.+PRIORITY=++# Location of the pid file.+PIDDIR="../status"++# PIDFILE_CHECK_PID tells the script to double check whether the pid in the pid+# file actually exists and belongs to this application. When not set, only+# check the pid, but not what it is. This is only needed when multiple+# applications need to share the same pid file.+PIDFILE_CHECK_PID=true++# FIXED_COMMAND tells the script to use a hard coded action rather than+# expecting the first parameter of the command line to be the command.+# By default the command will will be expected to be the first parameter.+@set_fixed_command@++# PASS_THROUGH tells the script to pass all arguments through to the JVM+# as is. If FIXED_COMMAND is specified then all arguments will be passed.+# If not set then all arguments starting with the second will be passed.+@set_pass_through@++# If uncommented, causes the Wrapper to be shutdown using an anchor file.+# When launched with the 'start' command, it will also ignore all INT and+# TERM signals.+#IGNORE_SIGNALS=true++# Wrapper will start the JVM asynchronously. Your application may have some+# initialization tasks and it may be desirable to wait a few seconds+# before returning. For example, to delay the invocation of following+# startup scripts. Setting WAIT_AFTER_STARTUP to a positive number will+# cause the start command to delay for the indicated period of time+# (in seconds).+#+WAIT_AFTER_STARTUP=0++# If set, wait for the wrapper to report that the daemon has started+WAIT_FOR_STARTED_STATUS=true+WAIT_FOR_STARTED_TIMEOUT=120++# If set, the status, start_msg and stop_msg commands will print out detailed+# state information on the Wrapper and Java processes.+#DETAIL_STATUS=true++# If set, the 'pause' and 'resume' commands will be enabled. These make it+# possible to pause the JVM or Java application without completely stopping+# the Wrapper. See the wrapper.pausable and wrapper.pausable.stop_jvm+# properties for more information.+#PAUSABLE=true++# If specified, the Wrapper will be run as the specified user.+# IMPORTANT - Make sure that the user has the required privileges to write+# the PID file and wrapper.log files. Failure to be able to write the log+# file will cause the Wrapper to exit without any way to write out an error+# message.+# NOTE - This will set the user which is used to run the Wrapper as well as+# the JVM and is not useful in situations where a privileged resource or+# port needs to be allocated prior to the user being changed.+#RUN_AS_USER=++# Set the full path to the 'su' command (substitute user).+# NOTE - In case 'su' is not in the PATH, you can set the absolute path here,+# for example:+# SU_BIN=/bin/su+# NOTE - For Red Hat, the script will use '/sbin/runuser' if it is present and+# ignore the value of SU_BIN.+SU_BIN=su++# Set option for 'su'.+# In case the user set in RUN_AS_USER has no bash set, the 'su' command will fail.+# The workaround for GNU/Linux system is to specify which bash to use with+# the '-s' option.+#SU_OPTS="-s /bin/bash"++# Set the full path to the 'id' command.+# For example:+# ID_BIN=/usr/bin/id+ID_BIN=id++# By default we show a detailed usage block. Uncomment to show brief usage.+#BRIEF_USAGE=true++# OS service management tool: flag for using Upstart when installing (rather than init.d rc.d).+USE_UPSTART=++# OS service management tool: flag for using systemd when installing.+USE_SYSTEMD=++# Flag for AIX to start/stop the Wrapper without using the System Resource+# Controller (SRC).This is useful when you want to start the Wrapper as a+# daemon (without installing it) and when APP_NAME is longer than 14 chars.+# In case you install the Wrapper as a service, make sure to set SKIP_SRC+# to null (empty value).+SKIP_SRC=++# When installing on Mac OSX platforms, the following domain will be used to+# prefix the plist file name.+PLIST_DOMAIN=org.tanukisoftware.wrapper++# When installing on Mac OSX platforms, this parameter controls whether the daemon+# is to be kept continuously running or to let demand and conditions control the+# invocation.+MACOSX_KEEP_RUNNING="false"++# The following two lines are used by the chkconfig command. Change as is+# appropriate for your application. They should remain commented.+# chkconfig: 2345 20 80+# description: @app.long.name@++# Set run level to use when installing the application to start and stop on+# system startup and shutdown. It is important that the application always+# be uninstalled before making any changes to the run levels.+# It is also possible to specify different run levels based on the individual+# platform. When doing so this script will look for defined run levels in+# the following order:+# 1) "RUN_LEVEL_S_$DIST_OS" or "RUN_LEVEL_K_$DIST_OS", where "$DIST_OS" is+# the value of DIST_OS. "RUN_LEVEL_S_solaris=20" for example.+# 2) RUN_LEVEL_S or RUN_LEVEL_K, to specify specify start or stop run levels.+# 3) RUN_LEVEL, to specify a general run level.+RUN_LEVEL=20++# Do not modify anything beyond this point+#-----------------------------------------------------------------------------++# check if we are running under Cygwin terminal.+# Note: on some OS's (for example Solaris, MacOS), -o is not a valid parameter+# and it shows an error message. We redirect stderr to null so the error message+# doesn't show up.+CYGWIN=`uname -o 2>/dev/null`+if [ "$CYGWIN" = "Cygwin" ]+then+ eval echo `gettext 'This script is not compatible with Cygwin. Please use the Wrapper batch files to control the Wrapper.'`+ exit 1+fi++if [ -n "$FIXED_COMMAND" ]+then+ COMMAND="$FIXED_COMMAND"+else+ COMMAND="$1"+fi++# check if there is a parameter "sysd"+SYSD=+if [ $# -gt 1 ] ; then+ if [ $2 = "sysd" ] ; then+ SYSD=1+ fi+fi++# default location for the service file+SYSTEMD_SERVICE_FILE="/etc/systemd/system/$APP_NAME.service"++# Required for HP-UX Startup+if [ `uname -s` = "HP-UX" -o `uname -s` = "HP-UX64" ] ; then+ PATH=$PATH:/usr/bin+fi++# Get the fully qualified path to the script+case $0 in+ /*)+ SCRIPT="$0"+ ;;+ *)+ PWD=`pwd`+ SCRIPT="$PWD/$0"+ ;;+esac++# Resolve the true real path without any sym links.+CHANGED=true+while [ "X$CHANGED" != "X" ]+do+ # Change spaces to ":" so the tokens can be parsed.+ SAFESCRIPT=`echo $SCRIPT | sed -e 's; ;:;g'`+ # Get the real path to this script, resolving any symbolic links+ TOKENS=`echo $SAFESCRIPT | sed -e 's;/; ;g'`+ REALPATH=+ for C in $TOKENS; do+ # Change any ":" in the token back to a space.+ C=`echo $C | sed -e 's;:; ;g'`+ REALPATH="$REALPATH/$C"+ # If REALPATH is a sym link, resolve it. Loop for nested links.+ while [ -h "$REALPATH" ] ; do+ LS="`ls -ld "$REALPATH"`"+ LINK="`expr "$LS" : '.*-> \(.*\)$'`"+ if expr "$LINK" : '/.*' > /dev/null; then+ # LINK is absolute.+ REALPATH="$LINK"+ else+ # LINK is relative.+ REALPATH="`dirname "$REALPATH"`""/$LINK"+ fi+ done+ done++ if [ "$REALPATH" = "$SCRIPT" ]+ then+ CHANGED=""+ else+ SCRIPT="$REALPATH"+ fi+done++# Get the location of the script.+REALDIR=`dirname "$REALPATH"`+# Normalize the path+REALDIR=`cd "${REALDIR}"; pwd`++# If the PIDDIR is relative, set its value relative to the full REALPATH to avoid problems if+# the working directory is later changed.+FIRST_CHAR=`echo $PIDDIR | cut -c1,1`+if [ "$FIRST_CHAR" != "/" ]+then+ PIDDIR=$REALDIR/$PIDDIR+fi+if [ ! -d "$PIDDIR" ]; then+ mkdir $PIDDIR+fi++# Same test for WRAPPER_CMD+FIRST_CHAR=`echo $WRAPPER_CMD | cut -c1,1`+if [ "$FIRST_CHAR" != "/" ]+then+ WRAPPER_CMD=$REALDIR/$WRAPPER_CMD+fi+# Same test for WRAPPER_CONF+FIRST_CHAR=`echo $WRAPPER_CONF | cut -c1,1`+if [ "$FIRST_CHAR" != "/" ]+then+ WRAPPER_CONF=$REALDIR/$WRAPPER_CONF+fi++# Process ID+ANCHORFILE="$PIDDIR/$APP_NAME.anchor"+COMMANDFILE="$PIDDIR/$APP_NAME.command"+STATUSFILE="$PIDDIR/$APP_NAME.status"+JAVASTATUSFILE="$PIDDIR/$APP_NAME.java.status"+PIDFILE="$PIDDIR/$APP_NAME.pid"+LOCKDIR="/var/lock/subsys"+LOCKFILE="$LOCKDIR/$APP_NAME"+pid=""++# Resolve the location of the 'ps' command+PS_BIN="/usr/ucb/ps"+ if [ ! -x "$PS_BIN" ]+ then+ PS_BIN="/usr/bin/ps"+ if [ ! -x "$PS_BIN" ]+ then+ PS_BIN="/bin/ps"+ if [ ! -x "$PS_BIN" ]+ then+ eval echo `gettext 'Unable to locate "ps".'`+ eval echo `gettext 'Please report this message along with the location of the command on your system.'`+ exit 1+ fi+ fi+ fi++TR_BIN="/usr/bin/tr"+if [ ! -x "$TR_BIN" ]+then+ TR_BIN="/bin/tr"+ if [ ! -x "$TR_BIN" ]+ then+ eval echo `gettext 'Unable to locate "tr".'`+ eval echo `gettext 'Please report this message along with the location of the command on your system.'`+ exit 1+ fi+fi+# Resolve the os+DIST_OS=`uname -s | $TR_BIN "[A-Z]" "[a-z]" | $TR_BIN -d ' '`+case "$DIST_OS" in+ 'sunos')+ DIST_OS="solaris"+ ;;+ 'hp-ux' | 'hp-ux64')+ # HP-UX needs the XPG4 version of ps (for -o args)+ DIST_OS="hpux"+ UNIX95=""+ export UNIX95+ ;;+ 'darwin')+ DIST_OS="macosx"+ ;;+ 'unix_sv')+ DIST_OS="unixware"+ ;;+ 'os/390')+ DIST_OS="zos"+ ;;+esac++# Compare Versions $1<$2=0, $1==$2=1, $1>$2=2+compareVersions () {+ if [ "$1" = "$2" ]+ then+ return 1+ else+ local i=1+ while true+ do+ local v1=`echo "$1" | cut -d '.' -f $i`+ local v2=`echo "$2" | cut -d '.' -f $i`+ if [ "X$v1" = "X" ]+ then+ if [ "X$v2" = "X" ]+ then+ return 1+ fi+ v1="0"+ elif [ "X$v2" = "X" ]+ then+ v2="0"+ fi+ if [ $v1 -lt $v2 ]+ then+ return 0+ elif [ $v1 -gt $v2 ]+ then+ return 2+ fi+ i=`expr $i + 1`+ done+ fi+}++# Resolve the architecture+if [ "$DIST_OS" = "macosx" ]+then+ OS_VER=`sw_vers | grep 'ProductVersion:' | grep -o '[0-9]*\.[0-9]*\.[0-9]*\|[0-9]*\.[0-9]*'`+ DIST_ARCH="universal"+ compareVersions "$OS_VER" "10.5.0"+ if [[ $? < 1 ]]+ then+ DIST_BITS="32"+ KEY_KEEP_ALIVE="OnDemand"+ else+ # Note: "OnDemand" has been deprecated and replaced from Mac OS X 10.5 by "KeepAlive"+ KEY_KEEP_ALIVE="KeepAlive"++ if [ "X`/usr/sbin/sysctl -n hw.cpu64bit_capable`" = "X1" ]+ then+ DIST_BITS="64"+ else+ DIST_BITS="32"+ fi+ fi+ APP_PLIST_BASE=${PLIST_DOMAIN}.${APP_NAME}+ APP_PLIST=${APP_PLIST_BASE}.plist+else+ if [ "$DIST_OS" = "linux" ]+ then+ DIST_ARCH=+ else+ DIST_ARCH=`uname -p 2>/dev/null | $TR_BIN "[A-Z]" "[a-z]" | $TR_BIN -d ' '`+ fi+ if [ "X$DIST_ARCH" = "X" ]+ then+ DIST_ARCH="unknown"+ fi+ if [ "$DIST_ARCH" = "unknown" ]+ then+ DIST_ARCH=`uname -m 2>/dev/null | $TR_BIN "[A-Z]" "[a-z]" | $TR_BIN -d ' '`+ fi+ case "$DIST_ARCH" in+ 'athlon' | 'i386' | 'i486' | 'i586' | 'i686')+ DIST_ARCH="x86"+ if [ "${DIST_OS}" = "solaris" ] ; then+ DIST_BITS=`isainfo -b`+ else+ DIST_BITS="32"+ fi+ ;;+ 'amd64' | 'x86_64')+ DIST_ARCH="x86"+ DIST_BITS="64"+ ;;+ 'ia32')+ DIST_ARCH="ia"+ DIST_BITS="32"+ ;;+ 'ia64' | 'ia64n' | 'ia64w')+ DIST_ARCH="ia"+ DIST_BITS="64"+ ;;+ 'ip27')+ DIST_ARCH="mips"+ DIST_BITS="32"+ ;;+ 'ppc64le')+ DIST_BITS="64"+ ;;+ 'power' | 'powerpc' | 'power_pc' | 'ppc64')+ if [ "${DIST_ARCH}" = "ppc64" ] ; then+ DIST_BITS="64"+ else+ DIST_BITS="32"+ fi+ DIST_ARCH="ppc"+ if [ "${DIST_OS}" = "aix" ] ; then+ if [ `getconf KERNEL_BITMODE` -eq 64 ]; then+ DIST_BITS="64"+ else+ DIST_BITS="32"+ fi+ fi+ ;;+ 'pa_risc' | 'pa-risc')+ DIST_ARCH="parisc"+ if [ `getconf KERNEL_BITS` -eq 64 ]; then+ DIST_BITS="64"+ else+ DIST_BITS="32"+ fi+ ;;+ 'sun4u' | 'sparcv9' | 'sparc')+ DIST_ARCH="sparc"+ DIST_BITS=`isainfo -b`+ ;;+ '9000/800' | '9000/785')+ DIST_ARCH="parisc"+ if [ `getconf KERNEL_BITS` -eq 64 ]; then+ DIST_BITS="64"+ else+ DIST_BITS="32"+ fi+ ;;+ '2064' | '2066' | '2084' | '2086' | '2094' | '2096' | '2097' | '2098' | '2817')+ DIST_ARCH="390"+ DIST_BITS="64"+ ;;+ armv*)+ if [ -z "`readelf -A /proc/self/exe | grep Tag_ABI_VFP_args`" ] ; then+ DIST_ARCH="armel"+ DIST_BITS="32"+ else+ DIST_ARCH="armhf"+ DIST_BITS="32"+ fi+ ;;+ esac+fi++# OSX always places Java in the same location so we can reliably set JAVA_HOME+if [ "$DIST_OS" = "macosx" ]+then+ if [ -z "$JAVA_HOME" ]; then+ if [ -x /usr/libexec/java_home ]; then+ JAVA_HOME=`/usr/libexec/java_home`; export JAVA_HOME+ else+ JAVA_HOME="/Library/Java/Home"; export JAVA_HOME+ fi+ fi+fi++# Test Echo+ECHOTEST=`echo -n "x"`+if [ "$ECHOTEST" = "x" ]+then+ ECHOOPT="-n "+ ECHOOPTC=""+else+ ECHOOPT=""+ ECHOOPTC="\c"+fi+++gettext() {+ "$WRAPPER_CMD" --translate "$1" "$WRAPPER_CONF" 2>/dev/null+ if [ $? != 0 ] ; then+ echo "$1"+ fi+}++outputFile() {+ if [ -f "$1" ]+ then+ eval echo `gettext ' $1 Found but not executable.'`;+ else+ echo " $1"+ fi+}++# Decide on the wrapper binary to use.+# If the bits of the OS could be detected, we will try to look for the+# binary with the correct bits value. If it doesn't exist, fall back+# and look for the 32-bit binary. If that doesn't exist either then+# look for the default.+WRAPPER_TEST_CMD=""+if [ -f "$WRAPPER_CMD-$DIST_OS-$DIST_ARCH-$DIST_BITS" ]+then+ WRAPPER_TEST_CMD="$WRAPPER_CMD-$DIST_OS-$DIST_ARCH-$DIST_BITS"+ if [ ! -x "$WRAPPER_TEST_CMD" ]+ then+ chmod +x "$WRAPPER_TEST_CMD" 2>/dev/null+ fi+ if [ -x "$WRAPPER_TEST_CMD" ]+ then+ WRAPPER_CMD="$WRAPPER_TEST_CMD"+ else+ outputFile "$WRAPPER_TEST_CMD"+ WRAPPER_TEST_CMD=""+ fi+fi+if [ -f "$WRAPPER_CMD-$DIST_OS-$DIST_ARCH-32" -a -z "$WRAPPER_TEST_CMD" ]+then+ WRAPPER_TEST_CMD="$WRAPPER_CMD-$DIST_OS-$DIST_ARCH-32"+ if [ ! -x "$WRAPPER_TEST_CMD" ]+ then+ chmod +x "$WRAPPER_TEST_CMD" 2>/dev/null+ fi+ if [ -x "$WRAPPER_TEST_CMD" ]+ then+ WRAPPER_CMD="$WRAPPER_TEST_CMD"+ else+ outputFile "$WRAPPER_TEST_CMD"+ WRAPPER_TEST_CMD=""+ fi+fi+if [ -f "$WRAPPER_CMD" -a -z "$WRAPPER_TEST_CMD" ]+then+ WRAPPER_TEST_CMD="$WRAPPER_CMD"+ if [ ! -x "$WRAPPER_TEST_CMD" ]+ then+ chmod +x "$WRAPPER_TEST_CMD" 2>/dev/null+ fi+ if [ -x "$WRAPPER_TEST_CMD" ]+ then+ WRAPPER_CMD="$WRAPPER_TEST_CMD"+ else+ outputFile "$WRAPPER_TEST_CMD"+ WRAPPER_TEST_CMD=""+ fi+fi+if [ -z "$WRAPPER_TEST_CMD" ]+then+ eval echo `gettext 'Unable to locate any of the following binaries:'`+ outputFile "$WRAPPER_CMD-$DIST_OS-$DIST_ARCH-$DIST_BITS"+ if [ ! "$DIST_BITS" = "32" ]+ then+ outputFile "$WRAPPER_CMD-$DIST_OS-$DIST_ARCH-32"+ fi+ outputFile "$WRAPPER_CMD"++ exit 1+fi+++# Build the nice clause+if [ "X$PRIORITY" = "X" ]+then+ CMDNICE=""+else+ CMDNICE="nice -$PRIORITY"+fi++# Build the anchor file clause.+if [ "X$IGNORE_SIGNALS" = "X" ]+then+ ANCHORPROP=+ IGNOREPROP=+else+ ANCHORPROP=wrapper.anchorfile=\"$ANCHORFILE\"+ IGNOREPROP=wrapper.ignore_signals=TRUE+fi++# Build the status file clause.+if [ "X$DETAIL_STATUS$WAIT_FOR_STARTED_STATUS" = "X" ]+then+ STATUSPROP=+else+ STATUSPROP="wrapper.statusfile=\"$STATUSFILE\" wrapper.java.statusfile=\"$JAVASTATUSFILE\""+fi++# Build the command file clause.+if [ -n "$PAUSABLE" ]+then+ COMMANDPROP="wrapper.commandfile=\"$COMMANDFILE\" wrapper.pausable=TRUE"+else+ COMMANDPROP=+fi++if [ ! -n "$WAIT_FOR_STARTED_STATUS" ]+then+ WAIT_FOR_STARTED_STATUS=true+fi++if [ $WAIT_FOR_STARTED_STATUS = true ] ; then+ DETAIL_STATUS=true+fi+++# Build the lock file clause. Only create a lock file if the lock directory exists on this platform.+LOCKPROP=+if [ -d $LOCKDIR ]+then+ if [ -w $LOCKDIR ]+ then+ LOCKPROP=wrapper.lockfile=\"$LOCKFILE\"+ fi+fi++# Build app name clause+if [ ! -n "$APP_NAME_PASS_TO_WRAPPER" ]+then+ APP_NAME_PASS_TO_WRAPPER=true+fi+if [ $APP_NAME_PASS_TO_WRAPPER = false ]+then+ APPNAMEPROP=+else+ APPNAMEPROP="wrapper.name=\"$APP_NAME\" wrapper.displayname=\"$APP_LONG_NAME\""+fi++# Decide on run levels.+RUN_LEVEL_S_DIST_OS_TMP=`eval "echo \$\{RUN_LEVEL_S_${DIST_OS}\}"`+RUN_LEVEL_S_DIST_OS=`eval "echo ${RUN_LEVEL_S_DIST_OS_TMP}"`+if [ "X${RUN_LEVEL_S_DIST_OS}" != "X" ] ; then+ APP_RUN_LEVEL_S=${RUN_LEVEL_S_DIST_OS}+elif [ "X$RUN_LEVEL_S" != "X" ] ; then+ APP_RUN_LEVEL_S=$RUN_LEVEL_S+else+ APP_RUN_LEVEL_S=$RUN_LEVEL+fi+APP_RUN_LEVEL_S_CHECK=`echo "$APP_RUN_LEVEL_S" | sed "s/[(0-9)*]/0/g"`+if [ "X${APP_RUN_LEVEL_S_CHECK}" != "X00" ] ; then+ eval echo `gettext 'Run level \"${APP_RUN_LEVEL_S}\" must be numeric and have a length of two \(00-99\).'`+ exit 1;+fi+RUN_LEVEL_K_DIST_OS_TMP=`eval "echo \$\{RUN_LEVEL_K_${DIST_OS}\}"`+RUN_LEVEL_K_DIST_OS=`eval "echo ${RUN_LEVEL_K_DIST_OS_TMP}"`+if [ "X${RUN_LEVEL_K_DIST_OS}" != "X" ] ; then+ APP_RUN_LEVEL_K=${RUN_LEVEL_K_DIST_OS}+elif [ "X$RUN_LEVEL_K" != "X" ] ; then+ APP_RUN_LEVEL_K=$RUN_LEVEL_K+else+ APP_RUN_LEVEL_K=$RUN_LEVEL+fi+APP_RUN_LEVEL_K_CHECK=`echo "$APP_RUN_LEVEL_K" | sed "s/[(0-9)*]/0/g"`+if [ "X${APP_RUN_LEVEL_K_CHECK}" != "X00" ] ; then+ eval echo `gettext 'Run level \"${APP_RUN_LEVEL_K}\" must be numeric and have a length of two \(00-99\).'`+ exit 1;+fi++prepAdditionalParams() {+ ADDITIONAL_PARA=""+ if [ ! -n "$PASS_THROUGH" ]+ then+ PASS_THROUGH=false+ fi+ if [ $PASS_THROUGH = true ] ; then+ ADDITIONAL_PARA="@properties_and_parameters@"+ while [ -n "$1" ] ; do+ ADDITIONAL_PARA="$ADDITIONAL_PARA \"$1\""+ shift+ done+ elif [ -n "$1" ] ; then+ eval echo `gettext "WARNING: Extra arguments will be ignored. Please run \'$0 help\' for usage."`+ fi+}++checkUser() {+ # $1 touchLock flag+ # $2.. [command] args++ # Check the configured user. If necessary rerun this script as the desired user.+ if [ "X$RUN_AS_USER" != "X" ]+ then+ # Resolve the location of the 'id' command+ ID_BIN="/usr/xpg4/bin/id"+ if [ ! -x "$ID_BIN" ]+ then+ ID_BIN="/usr/bin/id"+ if [ ! -x "$ID_BIN" ]+ then+ eval echo `gettext 'Unable to locate "id".'`+ eval echo `gettext 'Please report this message along with the location of the command on your system.'`+ exit 1+ fi+ fi++ if [ "`$ID_BIN -u -n`" = "$RUN_AS_USER" ]+ then+ # Already running as the configured user. Avoid password prompts by not calling su.+ RUN_AS_USER=""+ fi+ fi+ if [ "X$RUN_AS_USER" != "X" ]+ then+ if [ "`$ID_BIN -u -n "$RUN_AS_USER" 2>/dev/null`" != "$RUN_AS_USER" ]+ then+ eval echo `gettext 'User $RUN_AS_USER does not exist.'`+ exit 1+ fi++ # If LOCKPROP and $RUN_AS_USER are defined then the new user will most likely not be+ # able to create the lock file. The Wrapper will be able to update this file once it+ # is created but will not be able to delete it on shutdown. If $1 is set then+ # the lock file should be created for the current command+ if [ "X$LOCKPROP" != "X" ]+ then+ if [ "X$1" != "X" ]+ then+ # Resolve the primary group+ RUN_AS_GROUP=`groups $RUN_AS_USER | awk '{print $3}' | tail -1`+ if [ "X$RUN_AS_GROUP" = "X" ]+ then+ RUN_AS_GROUP=$RUN_AS_USER+ fi+ touch $LOCKFILE+ chown $RUN_AS_USER:$RUN_AS_GROUP $LOCKFILE+ fi+ fi++ # Still want to change users, recurse. This means that the user will only be+ # prompted for a password once. Variables shifted by 1+ shift++ # Wrap the parameters so they can be passed.+ ADDITIONAL_PARA=""+ while [ -n "$1" ] ; do+ if [ "$1" = 'installstart' ] ; then+ # At this point the service is already installed. When we will fork the process we only need to start the service.+ ADDITIONAL_PARA="$ADDITIONAL_PARA \"start\""+ else+ ADDITIONAL_PARA="$ADDITIONAL_PARA \"$1\""+ fi+ shift+ done++ # Use "runuser" if this exists.+ # runuser should be used on RedHat in preference to su.+ if test -f "/sbin/runuser"+ then+ /sbin/runuser - $RUN_AS_USER -c "\"$REALPATH\" $ADDITIONAL_PARA"+ else+ $SU_BIN - $RUN_AS_USER -c "\"$REALPATH\" $ADDITIONAL_PARA" $SU_OPTS+ fi+ RUN_AS_USER_EXITCODE=$?++ # we check if the previous command has failed+ if [ $RUN_AS_USER_EXITCODE -ne 0 ]+ then+ if [ $RUN_AS_USER_EXITCODE -eq 1 ]+ then+ checkForkCommand+ else+ eval echo `gettext 'Error executing the requested command with user \"$RUN_AS_USER\" \(error code $RUN_AS_USER_EXITCODE\).'`+ echo ""+ fi+ fi++ # Now that we are the original user again, we may need to clean up the lock file.+ if [ "X$LOCKPROP" != "X" ]+ then+ getpid+ if [ "X$pid" = "X" ]+ then+ # Wrapper is not running so make sure the lock file is deleted.+ if [ -f "$LOCKFILE" ]+ then+ rm "$LOCKFILE"+ fi+ fi+ fi++ exit $RUN_AS_USER_EXITCODE+ fi+}++# Try to fork by executing a simple command.+# With this function, we want to make sure we are able to fork.+checkForkCommand() {++ if test -f "/sbin/runuser"+ then+ /sbin/runuser - $RUN_AS_USER -c "ls \"$REALPATH\"" > /dev/null 2>&1 &+ else+ $SU_BIN - $RUN_AS_USER -c "ls \"$REALPATH\"" $SU_OPTS > /dev/null 2>&1 &+ fi+ CHECK_EXITCODE=$?++ if [ $CHECK_EXITCODE -ne 0 ]+ then+ # clearly a problem with forking+ eval echo `gettext 'Error: unable to create fork process.'`+ eval echo `gettext 'Advice:'`+ eval echo `gettext 'One possible cause of failure is when the user \(\"$RUN_AS_USER\"\) has no shell.'`+ eval echo `gettext 'In this case, two solutions are available by editing the script file:'`+ eval echo `gettext '1. Use \"SU_OPTS\" to set the shell for the user.'`+ eval echo `gettext '2. Use a OS service management tool (only available on some platforms).'`+ echo ""+ fi+}++getpid() {+ pid=""+ if [ -f "$PIDFILE" ]+ then+ if [ -r "$PIDFILE" ]+ then+ pid=`cat "$PIDFILE"`+ if [ "X$pid" != "X" ]+ then+ if [ "X$PIDFILE_CHECK_PID" != "X" ]+ then+ # It is possible that 'a' process with the pid exists but that it is not the+ # correct process. This can happen in a number of cases, but the most+ # common is during system startup after an unclean shutdown.+ # The ps statement below looks for the specific wrapper command running as+ # the pid. If it is not found then the pid file is considered to be stale.+ case "$DIST_OS" in+ 'freebsd')+ pidtest=`$PS_BIN -p $pid -o args | tail -1`+ if [ "X$pidtest" = "XCOMMAND" ]+ then+ pidtest=""+ fi+ ;;+ 'macosx')+ pidtest=`$PS_BIN -ww -p $pid -o command | grep -F "$WRAPPER_CMD" | tail -1`+ ;;+ 'solaris')+ if [ -f "/usr/bin/pargs" ]+ then+ pidtest=`pargs $pid | fgrep "$WRAPPER_CMD" | tail -1`+ else+ case "$PS_BIN" in+ '/usr/ucb/ps')+ pidtest=`$PS_BIN -auxww $pid | fgrep "$WRAPPER_CMD" | tail -1`+ ;;+ '/usr/bin/ps')+ TRUNCATED_CMD=`$PS_BIN -o comm -p $pid | tail -1`+ COUNT=`echo $TRUNCATED_CMD | wc -m`+ COUNT=`echo ${COUNT}`+ COUNT=`expr $COUNT - 1`+ TRUNCATED_CMD=`echo $WRAPPER_CMD | cut -c1-$COUNT`+ pidtest=`$PS_BIN -o comm -p $pid | fgrep "$TRUNCATED_CMD" | tail -1`+ ;;+ '/bin/ps')+ TRUNCATED_CMD=`$PS_BIN -o comm -p $pid | tail -1`+ COUNT=`echo $TRUNCATED_CMD | wc -m`+ COUNT=`echo ${COUNT}`+ COUNT=`expr $COUNT - 1`+ TRUNCATED_CMD=`echo $WRAPPER_CMD | cut -c1-$COUNT`+ pidtest=`$PS_BIN -o comm -p $pid | fgrep "$TRUNCATED_CMD" | tail -1`+ ;;+ *)+ echo "Unsupported ps command $PS_BIN"+ exit 1+ ;;+ esac+ fi+ ;;+ 'hpux')+ pidtest=`$PS_BIN -p $pid -x -o args | grep -F "$WRAPPER_CMD" | tail -1`+ ;;+ 'zos')+ TRUNCATED_CMD=`$PS_BIN -p $pid -o args | tail -1`+ COUNT=`echo $TRUNCATED_CMD | wc -m`+ COUNT=`echo ${COUNT}`+ COUNT=`expr $COUNT - 1`+ TRUNCATED_CMD=`echo $WRAPPER_CMD | cut -c1-$COUNT`+ pidtest=`$PS_BIN -p $pid -o args | grep -F "$TRUNCATED_CMD" | tail -1`+ ;;+ *)+ pidtest=`$PS_BIN -p $pid -o args | grep -F "$WRAPPER_CMD" | tail -1`+ ;;+ esac+ else+ # Check to see whether the pid exists as a running process, but in this mode, don't check what that pid is.+ case "$DIST_OS" in+ 'solaris')+ case "$PS_BIN" in+ '/usr/ucb/ps')+ pidtest=`$PS_BIN $pid | grep "$pid" | awk '{print $1}' | tail -1`+ ;;+ '/usr/bin/ps')+ pidtest=`$PS_BIN -p $pid -o pid | grep "$pid" | tail -1`+ ;;+ '/bin/ps')+ pidtest=`$PS_BIN -p $pid -o pid | grep "$pid" | tail -1`+ ;;+ *)+ echo "Unsupported ps command $PS_BIN"+ exit 1+ ;;+ esac+ ;;+ *)+ pidtest=`$PS_BIN -p $pid -o pid | grep "$pid" | tail -1`+ ;;+ esac+ fi++ if [ "X$pidtest" = "X" ]+ then+ # This is a stale pid file.+ rm -f "$PIDFILE"+ eval echo `gettext 'Removed stale pid file: $PIDFILE'`+ pid=""+ fi+ fi+ else+ eval echo `gettext 'Cannot read $PIDFILE.'`+ exit 1+ fi+ fi+}++getstatus() {+ STATUS=+ if [ -f "$STATUSFILE" ]+ then+ if [ -r "$STATUSFILE" ]+ then+ STATUS=`cat "$STATUSFILE"`+ fi+ fi+ if [ "X$STATUS" = "X" ]+ then+ STATUS="Unknown"+ fi++ JAVASTATUS=+ if [ -f "$JAVASTATUSFILE" ]+ then+ if [ -r "$JAVASTATUSFILE" ]+ then+ JAVASTATUS=`cat "$JAVASTATUSFILE"`+ fi+ fi+ if [ "X$JAVASTATUS" = "X" ]+ then+ JAVASTATUS="Unknown"+ fi+}++testpid() {+ case "$DIST_OS" in+ 'solaris')+ case "$PS_BIN" in+ '/usr/ucb/ps')+ pid=`$PS_BIN $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1`+ ;;+ '/usr/bin/ps')+ pid=`$PS_BIN -p $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1`+ ;;+ '/bin/ps')+ pid=`$PS_BIN -p $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1`+ ;;+ *)+ echo "Unsupported ps command $PS_BIN"+ exit 1+ ;;+ esac+ ;;+ *)+ pid=`$PS_BIN -p $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1` 2>/dev/null+ ;;+ esac+ if [ "X$pid" = "X" ]+ then+ # Process is gone so remove the pid file.+ rm -f "$PIDFILE"+ pid=""+ fi+}++launchdtrap() {+ stopit+ exit+}++waitforwrapperstop() {+ getpid+ while [ "X$pid" != "X" ] ; do+ sleep 1+ getpid+ done+}++launchinternal() {+ getpid+ trap launchdtrap TERM+ if [ "X$pid" = "X" ]+ then+ prepAdditionalParams "$@"++ # The string passed to eval must handles spaces in paths correctly.+ COMMAND_LINE="$CMDNICE \"$WRAPPER_CMD\" \"$WRAPPER_CONF\" wrapper.syslog.ident=\"$APP_NAME\" wrapper.pidfile=\"$PIDFILE\" wrapper.daemonize=TRUE $APPNAMEPROP $ANCHORPROP $IGNOREPROP $STATUSPROP $COMMANDPROP $LOCKPROP wrapper.script.version=3.5.29 $ADDITIONAL_PARA"+ eval $COMMAND_LINE+ else+ eval echo `gettext '$APP_LONG_NAME is already running.'`+ exit 1+ fi+ # launchd expects that this script stay up and running so we need to do our own monitoring of the Wrapper process.+ if [ $WAIT_FOR_STARTED_STATUS = true ]+ then+ waitforwrapperstop+ fi+}++console() {+ eval echo `gettext 'Running $APP_LONG_NAME...'`+ getpid+ if [ "X$pid" = "X" ]+ then+ trap '' 3++ prepAdditionalParams "$@"++ # The string passed to eval must handles spaces in paths correctly.+ COMMAND_LINE="$CMDNICE \"$WRAPPER_CMD\" \"$WRAPPER_CONF\" wrapper.syslog.ident=\"$APP_NAME\" wrapper.pidfile=\"$PIDFILE\" $APPNAMEPROP $ANCHORPROP $STATUSPROP $COMMANDPROP $LOCKPROP wrapper.script.version=3.5.29 $ADDITIONAL_PARA"+ eval $COMMAND_LINE+ else+ eval echo `gettext '$APP_LONG_NAME is already running.'`+ exit 1+ fi+}++waitforjavastartup() {+ getstatus+ eval echo $ECHOOPT `gettext 'Waiting for $APP_LONG_NAME...$ECHOOPTC'`++ # Wait until the timeout or we have something besides Unknown.+ counter=15+ while [ "$JAVASTATUS" = "Unknown" -a $counter -gt 0 -a -n "$JAVASTATUS" ] ; do+ echo $ECHOOPT".$ECHOOPTC"+ sleep 1+ getstatus+ counter=`expr $counter - 1`+ done++ if [ -n "$WAIT_FOR_STARTED_TIMEOUT" ] ; then+ counter=$WAIT_FOR_STARTED_TIMEOUT+ else+ counter=120+ fi+ while [ "$JAVASTATUS" != "STARTED" -a "$JAVASTATUS" != "Unknown" -a $counter -gt 0 -a -n "$JAVASTATUS" ] ; do+ echo $ECHOOPT".$ECHOOPTC"+ sleep 1+ getstatus+ counter=`expr $counter - 1`+ done+ echo ""+}++startwait() {+ if [ $WAIT_FOR_STARTED_STATUS = true ]+ then+ waitforjavastartup+ fi+ # Sleep for a few seconds to allow for intialization if required+ # then test to make sure we're still running.+ #+ i=0+ while [ $i -lt $WAIT_AFTER_STARTUP ]+ do+ sleep 1+ echo $ECHOOPT".$ECHOOPTC"+ i=`expr $i + 1`+ done+ if [ $WAIT_AFTER_STARTUP -gt 0 -o $WAIT_FOR_STARTED_STATUS = true ]+ then+ getpid+ if [ "X$pid" = "X" ]+ then+ eval echo `gettext ' WARNING: $APP_LONG_NAME may have failed to start.'`+ exit 1+ else+ eval echo `gettext ' running: PID:$pid'`+ fi+ else+ echo ""+ fi+}++mustBeRootOrExit() {+ if [ `id | sed 's/^uid=//;s/(.*$//'` != "0" ] ; then+ eval echo `gettext 'Must be root to perform this action.'`+ exit 1+ fi+}+++macosxStart() {+ # The daemon has been installed.+ eval echo `gettext 'Starting $APP_LONG_NAME. Detected Mac OSX and installed launchd daemon.'`+ mustBeRootOrExit++ getpid+ if [ "X$pid" != "X" ] ; then+ eval echo `gettext '$APP_LONG_NAME is already running.'`+ exit 1+ fi++ # If the daemon was just installed, it may not be loaded.+ LOADED_PLIST=`launchctl list | grep ${APP_PLIST_BASE}`+ if [ "X${LOADED_PLIST}" = "X" ] ; then+ launchctl load /Library/LaunchDaemons/${APP_PLIST}+ fi+ # If launchd is set to run the daemon already at Load, we don't need to call start+ getpid+ if [ "X$pid" = "X" ] ; then+ launchctl start ${APP_PLIST_BASE}+ fi++ startwait+}++macosxStop() {+ # The daemon should be running.+ eval echo `gettext 'Stopping $APP_LONG_NAME...'`+ mustBeRootOrExit++ getpid+ if [ "X$pid" = "X" ] ; then+ eval echo `gettext '$APP_LONG_NAME is not running.'`+ exit 1+ else+ if [ "$MACOSX_KEEP_RUNNING" = "true" ] ; then+ echo ""+ eval echo `gettext 'Daemon is set to be kept continuously running and it will be automatically restarted.'`+ eval echo `gettext 'To stop the daemon you need to uninstall it.'`+ eval echo `gettext 'If you want to use the \"stop\" argument, you need to find MACOSX_KEEP_RUNNING'`+ eval echo `gettext 'at the beginning of the script file and set it to \"false\".'`+ echo ""+ fi+ launchctl stop ${APP_PLIST_BASE}+ fi+}++macosxRestart() {+ # The daemon should be running.+ eval echo `gettext 'Restarting $APP_LONG_NAME...'`+ mustBeRootOrExit++ getpid+ if [ "X$pid" = "X" ] ; then+ eval echo `gettext '$APP_LONG_NAME is not running.'`+ exit 1+ else+ if [ "$MACOSX_KEEP_RUNNING" = "true" ] ; then+ # by stopping it, launchd will automatically restart it+ launchctl stop ${APP_PLIST_BASE}+ else+ launchctl unload "/Library/LaunchDaemons/${APP_PLIST}"+ sleep 1+ launchctl load "/Library/LaunchDaemons/${APP_PLIST}"+ fi+ fi++ startwait+}++upstartstart() {+ # The daemon has been installed.+ eval echo `gettext 'Starting $APP_LONG_NAME. Detected Linux and installed upstart.'`+ mustBeRootOrExit++ getpid+ if [ "X$pid" != "X" ] ; then+ eval echo `gettext '$APP_LONG_NAME is already running.'`+ exit 1+ fi++ /sbin/start ${APP_NAME}++ startwait+}++upstartStop() {+ # The daemon has been installed.+ eval echo `gettext 'Stopping $APP_LONG_NAME...'`+ mustBeRootOrExit++ getpid+ if [ "X$pid" = "X" ] ; then+ eval echo `gettext '$APP_LONG_NAME is not running.'`+ exit 1+ fi++ /sbin/stop ${APP_NAME}+}++upstartRestart() {+ # The daemon has been installed.+ eval echo `gettext 'Restarting $APP_LONG_NAME...'`+ mustBeRootOrExit++ getpid+ if [ "X$pid" = "X" ] ; then+ eval echo `gettext '$APP_LONG_NAME is not running.'`+ exit 1+ fi++ /sbin/restart ${APP_NAME}++ startwait+}++systemdInstall() {+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon using systemd...'`+ if [ -f "${REALDIR}/${APP_NAME}.service" ] ; then+ eval echo `gettext ' a custom service file ${APP_NAME}.service found'`+ cp "${REALDIR}/${APP_NAME}.service" "${SYSTEMD_SERVICE_FILE}"+ else+ eval echo `gettext ' creating default service file...'`+ echo "[Unit]" > "${SYSTEMD_SERVICE_FILE}"+ echo "Description=${APP_LONG_NAME}" >> "${SYSTEMD_SERVICE_FILE}"+ echo "After=syslog.target" >> "${SYSTEMD_SERVICE_FILE}"+ echo "" >> "${SYSTEMD_SERVICE_FILE}"+ echo "[Service]" >> "${SYSTEMD_SERVICE_FILE}"+ echo "Type=forking" >> "${SYSTEMD_SERVICE_FILE}"+ echo "ExecStart=${REALPATH} start sysd" >> "${SYSTEMD_SERVICE_FILE}"+ echo "ExecStop=${REALPATH} stop sysd" >> "${SYSTEMD_SERVICE_FILE}"+ if [ "X${RUN_AS_USER}" != "X" ] ; then+ echo "User=${RUN_AS_USER}" >> "${SYSTEMD_SERVICE_FILE}"+ fi+ echo "" >> "${SYSTEMD_SERVICE_FILE}"+ echo "[Install]" >> "${SYSTEMD_SERVICE_FILE}"+ echo "WantedBy=multi-user.target" >> "${SYSTEMD_SERVICE_FILE}"++ systemctl daemon-reload+ systemctl enable "${APP_NAME}"+ fi+}++systemdStart() {+ # check if the service file is present+ if [ -f "${SYSTEMD_SERVICE_FILE}" ] ; then+ eval echo `gettext 'Reading file ${SYSTEMD_SERVICE_FILE}'`+ else+ eval echo `gettext 'No service file detected. Did you install the service?'`+ exit 1+ fi++ systemctl start $APP_NAME+ if [ $? -ne 0 ] ; then+ eval echo `gettext 'Failed to start service $APP_NAME'`+ exit 1+ fi++ startwait+}++systemdStop() {+ systemctl stop $APP_NAME+ if [ $? -ne 0 ] ; then+ eval echo `gettext 'Failed to stop service $APP_NAME'`+ exit 1+ fi+}++systemdRestart() {+ systemctl restart $APP_NAME+ if [ $? -ne 0 ] ; then+ eval echo `gettext 'Failed to restart service $APP_NAME'`+ exit 1+ fi++ startwait+}++systemdRemove() {+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon from systemd...'`+ systemctl disable $APP_NAME+ rm "/etc/systemd/system/${APP_NAME}.service"+ systemctl daemon-reload+}++srcInstall() {+ if [ "X$RUN_AS_USER" = "X" ] ; then+ USERID="0"+ else+ USERID=`$ID_BIN -u "$RUN_AS_USER"`+ if [ $? -ne 0 ] ; then+ eval echo `gettext 'Failed to get user id for $RUN_AS_USER'`+ exit 1+ fi+ fi+ /usr/bin/mkssys -s "$APP_NAME" -p "$REALPATH" -a "launchdinternal" -u "$USERID" -f 9 -n 15 -S+ /usr/sbin/mkitab "$APP_NAME":2:once:"/usr/bin/startsrc -s \"${APP_NAME}\" >/dev/console 2>&1"++ if [ -n "$SKIP_SRC" ] ; then+ eval echo `gettext 'Please do not set SKIP_SRC to be able to use SRC features.'`+ fi+}++srcStart() {+ startsrc -s "${APP_NAME}"+ if [ $? -ne 0 ] ; then+ eval echo `gettext 'Failed to start service $APP_NAME'`+ exit 1+ fi++ startwait+}++srcStop() {+ stopsrc -s "${APP_NAME}"+ if [ $? -ne 0 ] ; then+ eval echo `gettext 'Failed to stop service $APP_NAME'`+ exit 1+ fi+}++srcRestart() {+ srcStop+ srcStart+}++start() {+ eval echo `gettext 'Starting $APP_LONG_NAME...'`+ getpid+ if [ "X$pid" = "X" ]+ then+ prepAdditionalParams "$@"++ # The string passed to eval must handles spaces in paths correctly.+ COMMAND_LINE="$CMDNICE \"$WRAPPER_CMD\" \"$WRAPPER_CONF\" wrapper.syslog.ident=\"$APP_NAME\" wrapper.pidfile=\"$PIDFILE\" wrapper.daemonize=TRUE $APPNAMEPROP $ANCHORPROP $IGNOREPROP $STATUSPROP $COMMANDPROP $LOCKPROP wrapper.script.version=3.5.29 $ADDITIONAL_PARA"+ eval $COMMAND_LINE+ else+ eval echo `gettext '$APP_LONG_NAME is already running.'`+ exit 1+ fi++ startwait+}++stopit() {+ # $1 exit if down flag++ eval echo `gettext 'Stopping $APP_LONG_NAME...'`+ getpid+ if [ "X$pid" = "X" ]+ then+ eval echo `gettext '$APP_LONG_NAME was not running.'`+ if [ "X$1" = "X1" ]+ then+ exit 1+ fi+ else+ if [ "X$IGNORE_SIGNALS" = "X" ]+ then+ # Running so try to stop it.+ kill $pid+ if [ $? -ne 0 ]+ then+ # An explanation for the failure should have been given+ eval echo `gettext 'Unable to stop $APP_LONG_NAME.'`+ exit 1+ fi+ else+ rm -f "$ANCHORFILE"+ if [ -f "$ANCHORFILE" ]+ then+ # An explanation for the failure should have been given+ eval echo `gettext 'Unable to stop $APP_LONG_NAME.'`+ exit 1+ fi+ fi++ # We can not predict how long it will take for the wrapper to+ # actually stop as it depends on settings in wrapper.conf.+ # Loop until it does.+ savepid=$pid+ CNT=0+ TOTCNT=0+ while [ "X$pid" != "X" ]+ do+ # Show a waiting message every 5 seconds.+ if [ "$CNT" -lt "5" ]+ then+ CNT=`expr $CNT + 1`+ else+ eval echo `gettext 'Waiting for $APP_LONG_NAME to exit...'`+ CNT=0+ fi+ TOTCNT=`expr $TOTCNT + 1`++ sleep 1++ testpid+ done++ pid=$savepid+ testpid+ if [ "X$pid" != "X" ]+ then+ eval echo `gettext 'Failed to stop $APP_LONG_NAME.'`+ exit 1+ else+ eval echo `gettext 'Stopped $APP_LONG_NAME.'`+ fi+ fi+}++pause() {+ eval echo `gettext 'Pausing $APP_LONG_NAME.'`+}++resume() {+ eval echo `gettext 'Resuming $APP_LONG_NAME.'`+}++status() {+ getpid+ if [ "X$pid" = "X" ]+ then+ eval echo `gettext '$APP_LONG_NAME is not running.'`+ exit 1+ else+ if [ "X$DETAIL_STATUS" = "X" ]+ then+ eval echo `gettext '$APP_LONG_NAME is running: PID:$pid'`+ else+ getstatus+ eval echo `gettext '$APP_LONG_NAME is running: PID:$pid, Wrapper:$STATUS, Java:$JAVASTATUS'`+ fi+ exit 0+ fi+}++# Make sure APP_NAME is less than 14 characters, otherwise in AIX, the commands+# "lsitab" or "lssrc" will fail+validateAppNameLength() {+ if [ ${#APP_NAME} -gt 14 ] ; then+ eval echo `gettext ' APP_NAME must be less than 14 characters long. Length of ${APP_NAME} is ${#APP_NAME}.'`+ exit 1+ fi+}++installUpstart() {+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon using upstart..'`+ if [ -f "${REALDIR}/${APP_NAME}.install" ] ; then+ eval echo `gettext ' a custom upstart conf file ${APP_NAME}.install found'`+ cp "${REALDIR}/${APP_NAME}.install" "/etc/init/${APP_NAME}.conf"+ else+ eval echo `gettext ' creating default upstart conf file..'`+ echo "# ${APP_NAME} - ${APP_LONG_NAME}" > "/etc/init/${APP_NAME}.conf"+ echo "description \"${APP_LONG_NAME}\"" >> "/etc/init/${APP_NAME}.conf"+ echo "author \"Tanuki Software Ltd. <[email protected]>\"" >> "/etc/init/${APP_NAME}.conf"+ echo "start on runlevel [2345]" >> "/etc/init/${APP_NAME}.conf"+ echo "stop on runlevel [!2345]" >> "/etc/init/${APP_NAME}.conf"+ echo "env LANG=${LANG}" >> "/etc/init/${APP_NAME}.conf"+ echo "exec \"${REALPATH}\" upstartinternal" >> "/etc/init/${APP_NAME}.conf"+ fi+}++installdaemon() {+ mustBeRootOrExit++ APP_NAME_LOWER=`echo "$APP_NAME" | $TR_BIN "[A-Z]" "[a-z]"`+ if [ "$DIST_OS" = "solaris" ] ; then+ eval echo `gettext 'Detected Solaris:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ ln -s "$REALPATH" "/etc/init.d/$APP_NAME"+ for i in `ls "/etc/rc3.d/K"??"$APP_NAME_LOWER" "/etc/rc3.d/S"??"$APP_NAME_LOWER" 2>/dev/null` ; do+ eval echo `gettext ' Removing unexpected file before proceeding: $i'`+ rm -f $i+ done+ ln -s "/etc/init.d/$APP_NAME" "/etc/rc3.d/K${APP_RUN_LEVEL_K}$APP_NAME_LOWER"+ ln -s "/etc/init.d/$APP_NAME" "/etc/rc3.d/S${APP_RUN_LEVEL_S}$APP_NAME_LOWER"+ fi+ elif [ "$DIST_OS" = "linux" ] ; then+ if [ -f /etc/redhat-release -o -f /etc/redhat_version -o -f /etc/fedora-release ] ; then+ eval echo `gettext 'Detected RHEL or Fedora:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" -o -f "/etc/init/${APP_NAME}.conf" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ elif [ -n "$USE_SYSTEMD" -a -d "/etc/systemd" ] ; then+ systemdInstall+ else+ if [ -n "$USE_UPSTART" -a -d "/etc/init" ] ; then+ installUpstart+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ ln -s "$REALPATH" "/etc/init.d/$APP_NAME"+ /sbin/chkconfig --add "$APP_NAME"+ /sbin/chkconfig "$APP_NAME" on+ fi+ fi+ elif [ -f /etc/SuSE-release ] ; then+ eval echo `gettext 'Detected SuSE or SLES:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ elif [ -n "$USE_SYSTEMD" -a -d "/etc/systemd" ] ; then+ systemdInstall+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ ln -s "$REALPATH" "/etc/init.d/$APP_NAME"+ insserv "/etc/init.d/$APP_NAME"+ fi+ elif [ -f /etc/lsb-release -o -f /etc/debian_version -o -f /etc/debian_release ] ; then+ eval echo `gettext 'Detected Ubuntu or Debian:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" -o -f "/etc/init/${APP_NAME}.conf" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ if [ -n "$USE_SYSTEMD" -a -d "/etc/systemd" ] ; then+ systemdInstall+ elif [ -n "$USE_UPSTART" -a -d "/etc/init" ] ; then+ installUpstart+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon using init.d..'`+ ln -s "$REALPATH" "/etc/init.d/$APP_NAME"+ update-rc.d "$APP_NAME" defaults+ fi+ fi+ else+ eval echo `gettext 'Detected Linux:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ ln -s "$REALPATH" /etc/init.d/$APP_NAME+ for i in `ls "/etc/rc3.d/K"??"$APP_NAME_LOWER" "/etc/rc5.d/K"??"$APP_NAME_LOWER" "/etc/rc3.d/S"??"$APP_NAME_LOWER" "/etc/rc5.d/S"??"$APP_NAME_LOWER" 2>/dev/null` ; do+ eval echo `gettext ' Removing unexpected file before proceeding: $i'`+ rm -f $i+ done+ ln -s "/etc/init.d/$APP_NAME" "/etc/rc3.d/K${APP_RUN_LEVEL_K}$APP_NAME_LOWER"+ ln -s "/etc/init.d/$APP_NAME" "/etc/rc3.d/S${APP_RUN_LEVEL_S}$APP_NAME_LOWER"+ ln -s "/etc/init.d/$APP_NAME" "/etc/rc5.d/S${APP_RUN_LEVEL_S}$APP_NAME_LOWER"+ ln -s "/etc/init.d/$APP_NAME" "/etc/rc5.d/K${APP_RUN_LEVEL_K}$APP_NAME_LOWER"+ fi+ fi+ elif [ "$DIST_OS" = "hpux" ] ; then+ eval echo `gettext 'Detected HP-UX:'`+ if [ -f "/sbin/init.d/$APP_NAME" -o -L "/sbin/init.d/$APP_NAME" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ ln -s "$REALPATH" "/sbin/init.d/$APP_NAME"+ for i in `ls "/sbin/rc3.d/K"??"$APP_NAME_LOWER" "/sbin/rc3.d/S"??"$APP_NAME_LOWER" 2>/dev/null` ; do+ eval echo `gettext ' Removing unexpected file before proceeding: $i'`+ rm -f $i+ done+ ln -s "/sbin/init.d/$APP_NAME" "/sbin/rc3.d/K${APP_RUN_LEVEL_K}$APP_NAME_LOWER"+ ln -s "/sbin/init.d/$APP_NAME" "/sbin/rc3.d/S${APP_RUN_LEVEL_S}$APP_NAME_LOWER"+ fi+ elif [ "$DIST_OS" = "aix" ] ; then+ eval echo `gettext 'Detected AIX:'`+ validateAppNameLength+ if [ -f "/etc/rc.d/init.d/$APP_NAME" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed as rc.d script.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ elif [ -n "`/usr/sbin/lsitab $APP_NAME`" -a -n "`/usr/bin/lssrc -S -s $APP_NAME`" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed as SRC service.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ if [ -n "`/usr/sbin/lsitab install_assist`" ] ; then+ eval echo `gettext ' The task /usr/sbin/install_assist was found in the inittab, this might cause problems for all subsequent tasks to launch at this process is known to block the init task. Please make sure this task is not needed anymore and remove/deactivate it.'`+ fi+ for i in `ls "/etc/rc.d/rc2.d/K"??"$APP_NAME_LOWER" "/etc/rc.d/rc2.d/S"??"$APP_NAME_LOWER" 2>/dev/null` ; do+ eval echo `gettext ' Removing unexpected file before proceeding: $i'`+ rm -f $i+ done+ srcInstall+ fi+ elif [ "$DIST_OS" = "freebsd" ] ; then+ eval echo `gettext 'Detected FreeBSD:'`+ if [ -f "/etc/rc.d/$APP_NAME" -o -L "/etc/rc.d/$APP_NAME" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ sed -i .bak "/${APP_NAME}_enable=\"YES\"/d" /etc/rc.conf+ if [ -f "${REALDIR}/${APP_NAME}.install" ] ; then+ ln -s "${REALDIR}/${APP_NAME}.install" "/etc/rc.d/$APP_NAME"+ else+ echo '#!/bin/sh' > "/etc/rc.d/$APP_NAME"+ echo "#" >> "/etc/rc.d/$APP_NAME"+ echo "# PROVIDE: $APP_NAME" >> "/etc/rc.d/$APP_NAME"+ echo "# REQUIRE: NETWORKING" >> "/etc/rc.d/$APP_NAME"+ echo "# KEYWORD: shutdown" >> "/etc/rc.d/$APP_NAME"+ echo ". /etc/rc.subr" >> "/etc/rc.d/$APP_NAME"+ echo "name=\"$APP_NAME\"" >> "/etc/rc.d/$APP_NAME"+ echo "rcvar=\`set_rcvar\`" >> "/etc/rc.d/$APP_NAME"+ echo "command=\"${REALPATH}\"" >> "/etc/rc.d/$APP_NAME"+ echo 'start_cmd="${name}_start"' >> "/etc/rc.d/$APP_NAME"+ echo 'load_rc_config $name' >> "/etc/rc.d/$APP_NAME"+ echo 'status_cmd="${name}_status"' >> "/etc/rc.d/$APP_NAME"+ echo 'stop_cmd="${name}_stop"' >> "/etc/rc.d/$APP_NAME"+ echo "${APP_NAME}_status() {" >> "/etc/rc.d/$APP_NAME"+ echo '${command} status' >> "/etc/rc.d/$APP_NAME"+ echo '}' >> "/etc/rc.d/$APP_NAME"+ echo "${APP_NAME}_stop() {" >> "/etc/rc.d/$APP_NAME"+ echo '${command} stop' >> "/etc/rc.d/$APP_NAME"+ echo '}' >> "/etc/rc.d/$APP_NAME"+ echo "${APP_NAME}_start() {" >> "/etc/rc.d/$APP_NAME"+ echo '${command} start' >> "/etc/rc.d/$APP_NAME"+ echo '}' >> "/etc/rc.d/$APP_NAME"+ echo 'run_rc_command "$1"' >> "/etc/rc.d/$APP_NAME"+ fi+ echo "${APP_NAME}_enable=\"YES\"" >> /etc/rc.conf+ chmod 555 "/etc/rc.d/$APP_NAME"+ fi+ elif [ "$DIST_OS" = "macosx" ] ; then+ eval echo `gettext 'Detected Mac OSX:'`+ if [ -f "/Library/LaunchDaemons/${APP_PLIST}" -o -L "/Library/LaunchDaemons/${APP_PLIST}" ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ if [ -f "${REALDIR}/${APP_PLIST}" ] ; then+ ln -s "${REALDIR}/${APP_PLIST}" "/Library/LaunchDaemons/${APP_PLIST}"+ else+ echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" > "/Library/LaunchDaemons/${APP_PLIST}"+ echo "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\"" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo "<plist version=\"1.0\">" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <dict>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <key>Label</key>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <string>${APP_PLIST_BASE}</string>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <key>ProgramArguments</key>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <array>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <string>${REALPATH}</string>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <string>launchdinternal</string>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " </array>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <key>${KEY_KEEP_ALIVE}</key>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <${MACOSX_KEEP_RUNNING}/>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <key>RunAtLoad</key>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <true/>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ if [ "X$RUN_AS_USER" != "X" ] ; then+ echo " <key>UserName</key>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo " <string>${RUN_AS_USER}</string>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ fi+ echo " </dict>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ echo "</plist>" >> "/Library/LaunchDaemons/${APP_PLIST}"+ fi+ chmod 555 "/Library/LaunchDaemons/${APP_PLIST}"+ fi+ elif [ "$DIST_OS" = "zos" ] ; then+ eval echo `gettext 'Detected z/OS:'`+ if [ -f /etc/rc.bak ] ; then+ eval echo `gettext ' The $APP_LONG_NAME daemon is already installed.'`+ if [ "$COMMAND" != 'installstart' ] ; then+ exit 1+ fi+ else+ eval echo `gettext ' Installing the $APP_LONG_NAME daemon..'`+ cp /etc/rc /etc/rc.bak+ sed "s:echo /etc/rc script executed, \`date\`::g" /etc/rc.bak > /etc/rc+ echo "_BPX_JOBNAME='${APP_NAME}' \"${REALDIR}/${APP_NAME}\" start" >>/etc/rc+ echo '/etc/rc script executed, `date`' >>/etc/rc+ fi+ else+ eval echo `gettext 'Install not currently supported for $DIST_OS'`+ exit 1+ fi+}++startdaemon() {+ if [ "$DIST_OS" = "macosx" -a -f "/Library/LaunchDaemons/${APP_PLIST}" ] ; then+ macosxStart+ elif [ "$DIST_OS" = "linux" -a -f "/etc/init/${APP_NAME}.conf" ] ; then+ upstartstart+ elif [ "$DIST_OS" = "linux" -a -n "$USE_SYSTEMD" -a -z "$SYSD" ] ; then+ systemdStart+ elif [ "$DIST_OS" = "aix" -a -z "$SKIP_SRC" ] && [ -n "`/usr/bin/lssrc -S -s $APP_NAME`" ] ; then+ srcStart+ else+ if [ -n "$SYSD" ] ; then+ shift+ fi++ checkUser touchlock "$@"+ if [ ! -n "$FIXED_COMMAND" ] ; then+ shift+ fi+ start "$@"+ fi+}++removedaemon() {+ mustBeRootOrExit++ APP_NAME_LOWER=`echo "$APP_NAME" | $TR_BIN "[A-Z]" "[a-z]"`+ if [ "$DIST_OS" = "solaris" ] ; then+ eval echo `gettext 'Detected Solaris:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ for i in `ls "/etc/rc3.d/K"??"$APP_NAME_LOWER" "/etc/rc3.d/S"??"$APP_NAME_LOWER" "/etc/init.d/$APP_NAME" 2>/dev/null` ; do+ rm -f $i+ done+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ "$DIST_OS" = "linux" ] ; then+ if [ -f /etc/redhat-release -o -f /etc/redhat_version -o -f /etc/fedora-release ] ; then+ eval echo `gettext 'Detected RHEL or Fedora:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ /sbin/chkconfig "$APP_NAME" off+ /sbin/chkconfig --del "$APP_NAME"+ rm -f "/etc/init.d/$APP_NAME"+ elif [ -n "$USE_SYSTEMD" -a -f "${SYSTEMD_SERVICE_FILE}" ] ; then+ systemdRemove+ elif [ -f "/etc/init/${APP_NAME}.conf" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon from upstart...'`+ rm "/etc/init/${APP_NAME}.conf"+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ -f /etc/SuSE-release ] ; then+ eval echo `gettext 'Detected SuSE or SLES:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ insserv -r "/etc/init.d/$APP_NAME"+ rm -f "/etc/init.d/$APP_NAME"+ elif [ -n "$USE_SYSTEMD" -a -f "${SYSTEMD_SERVICE_FILE}" ] ; then+ systemdRemove+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ -f /etc/lsb-release -o -f /etc/debian_version -o -f /etc/debian_release ] ; then+ eval echo `gettext 'Detected Ubuntu or Debian:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon from init.d...'`+ update-rc.d -f "$APP_NAME" remove+ rm -f "/etc/init.d/$APP_NAME"+ elif [ -n "$USE_SYSTEMD" -a -f "${SYSTEMD_SERVICE_FILE}" ] ; then+ systemdRemove+ elif [ -f "/etc/init/${APP_NAME}.conf" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon from upstart...'`+ rm "/etc/init/${APP_NAME}.conf"+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ else+ eval echo `gettext 'Detected Linux:'`+ if [ -f "/etc/init.d/$APP_NAME" -o -L "/etc/init.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ for i in `ls "/etc/rc3.d/K"??"$APP_NAME_LOWER" "/etc/rc5.d/K"??"$APP_NAME_LOWER" "/etc/rc3.d/S"??"$APP_NAME_LOWER" "/etc/rc5.d/S"??"$APP_NAME_LOWER" "/etc/init.d/$APP_NAME" 2>/dev/null` ; do+ rm -f $i+ done+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ fi+ elif [ "$DIST_OS" = "hpux" ] ; then+ eval echo `gettext 'Detected HP-UX:'`+ if [ -f "/sbin/init.d/$APP_NAME" -o -L "/sbin/init.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ for i in `ls "/sbin/rc3.d/K"??"$APP_NAME_LOWER" "/sbin/rc3.d/S"??"$APP_NAME_LOWER" "/sbin/init.d/$APP_NAME" 2>/dev/null` ; do+ rm -f $i+ done+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ "$DIST_OS" = "aix" ] ; then+ eval echo `gettext 'Detected AIX:'`+ validateAppNameLength+ if [ -f "/etc/rc.d/init.d/$APP_NAME" -o -L "/etc/rc.d/init.d/$APP_NAME" -o -n "`/usr/sbin/lsitab $APP_NAME`" -o -n "`/usr/bin/lssrc -S -s $APP_NAME`" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ if [ -f "/etc/rc.d/init.d/$APP_NAME" -o -L "/etc/rc.d/init.d/$APP_NAME" ] ; then+ for i in `ls "/etc/rc.d/rc2.d/K"??"$APP_NAME_LOWER" "/etc/rc.d/rc2.d/S"??"$APP_NAME_LOWER" "/etc/rc.d/init.d/$APP_NAME" 2>/dev/null` ; do+ rm -f $i+ done+ fi+ if [ -n "`/usr/sbin/lsitab $APP_NAME`" -o -n "`/usr/bin/lssrc -S -s $APP_NAME`" ] ; then+ /usr/sbin/rmitab $APP_NAME+ /usr/bin/rmssys -s $APP_NAME+ fi+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ "$DIST_OS" = "freebsd" ] ; then+ eval echo `gettext 'Detected FreeBSD:'`+ if [ -f "/etc/rc.d/$APP_NAME" -o -L "/etc/rc.d/$APP_NAME" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ for i in "/etc/rc.d/$APP_NAME"+ do+ rm -f $i+ done+ sed -i .bak "/${APP_NAME}_enable=\"YES\"/d" /etc/rc.conf+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ "$DIST_OS" = "macosx" ] ; then+ eval echo `gettext 'Detected Mac OSX:'`+ if [ -f "/Library/LaunchDaemons/${APP_PLIST}" -o -L "/Library/LaunchDaemons/${APP_PLIST}" ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ # Make sure the plist is installed+ LOADED_PLIST=`launchctl list | grep ${APP_PLIST_BASE}`+ if [ "X${LOADED_PLIST}" != "X" ] ; then+ launchctl unload "/Library/LaunchDaemons/${APP_PLIST}"+ fi+ rm -f "/Library/LaunchDaemons/${APP_PLIST}"+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ elif [ "$DIST_OS" = "zos" ] ; then+ eval echo `gettext 'Detected z/OS:'`+ if [ -f /etc/rc.bak ] ; then+ stopit "0"+ eval echo `gettext ' Removing $APP_LONG_NAME daemon...'`+ cp /etc/rc /etc/rc.bak+ sed "s/_BPX_JOBNAME=\'APP_NAME\'.*//g" /etc/rc.bak > /etc/rc+ rm /etc/rc.bak+ else+ eval echo `gettext ' The $APP_LONG_NAME daemon is not currently installed.'`+ exit 1+ fi+ else+ eval echo `gettext 'Remove not currently supported for $DIST_OS'`+ exit 1+ fi+}++dump() {+ eval echo `gettext 'Dumping $APP_LONG_NAME...'`+ getpid+ if [ "X$pid" = "X" ]+ then+ eval echo `gettext '$APP_LONG_NAME was not running.'`+ else+ kill -3 $pid++ if [ $? -ne 0 ]+ then+ eval echo `gettext 'Failed to dump $APP_LONG_NAME.'`+ exit 1+ else+ eval echo `gettext 'Dumped $APP_LONG_NAME.'`+ fi+ fi+}++# Used by HP-UX init scripts.+startmsg() {+ getpid+ if [ "X$pid" = "X" ]+ then+ eval echo `gettext 'Starting $APP_LONG_NAME... Wrapper:Stopped'`+ else+ if [ "X$DETAIL_STATUS" = "X" ]+ then+ eval echo `gettext 'Starting $APP_LONG_NAME... Wrapper:Running'`+ else+ getstatus+ eval echo `gettext 'Starting $APP_LONG_NAME... Wrapper:$STATUS, Java:$JAVASTATUS'`+ fi+ fi+}++# Used by HP-UX init scripts.+stopmsg() {+ getpid+ if [ "X$pid" = "X" ]+ then+ eval echo `gettext 'Stopping $APP_LONG_NAME... Wrapper:Stopped'`+ else+ if [ "X$DETAIL_STATUS" = "X" ]+ then+ eval echo `gettext 'Stopping $APP_LONG_NAME... Wrapper:Running'`+ else+ getstatus+ eval echo `gettext 'Stopping $APP_LONG_NAME... Wrapper:$STATUS, Java:$JAVASTATUS'`+ fi+ fi+}++showUsage() {+ # $1 bad command++ if [ -n "$1" ]+ then+ eval echo `gettext 'Unexpected command: $1'`+ echo "";+ fi++ eval MSG=`gettext 'Usage: '`+ if [ -n "$FIXED_COMMAND" ] ; then+ if [ -n "$PASS_THROUGH" ] ; then+ echo "${MSG} $0 {JavaAppArgs}"+ else+ echo "${MSG} $0"+ fi+ else+ if [ -n "$PAUSABLE" ] ; then+ if [ -n "$PASS_THROUGH" ] ; then+ echo "${MSG} $0 [ console {JavaAppArgs} | start {JavaAppArgs} | stop | restart {JavaAppArgs} | condrestart {JavaAppArgs} | pause | resume | status | install | installstart | remove | dump ]"+ else+ echo "${MSG} $0 [ console | start | stop | restart | condrestart | pause | resume | status | install | installstart | remove | dump ]"+ fi+ else+ if [ -n "$PASS_THROUGH" ] ; then+ echo "${MSG} $0 [ console {JavaAppArgs} | start {JavaAppArgs} | stop | restart {JavaAppArgs} | condrestart {JavaAppArgs} | status | install | installstart | remove | dump ]"+ else+ echo "${MSG} $0 [ console | start | stop | restart | condrestart | status | install | installstart | remove | dump ]"+ fi+ fi+ fi++ if [ ! -n "$BRIEF_USAGE" ]+ then+ echo "";+ if [ ! -n "$FIXED_COMMAND" ] ; then+ echo "`gettext 'Commands:'`"+ echo "`gettext ' console Launch in the current console.'`"+ echo "`gettext ' start Start in the background as a daemon process.'`"+ echo "`gettext ' stop Stop if running as a daemon or in another console.'`"+ echo "`gettext ' restart Stop if running and then start.'`"+ echo "`gettext ' condrestart Restart only if already running.'`"+ if [ -n "$PAUSABLE" ] ; then+ echo "`gettext ' pause Pause if running.'`"+ echo "`gettext ' resume Resume if paused.'`"+ fi+ echo "`gettext ' status Query the current status.'`"+ echo "`gettext ' install Install to start automatically when system boots.'`"+ echo "`gettext ' installstart Install and start running as a daemon process.'`"+ echo "`gettext ' remove Uninstall.'`"+ echo "`gettext ' dump Request a Java thread dump if running.'`"+ echo "";+ fi+ if [ -n "$PASS_THROUGH" ] ; then+ echo "`gettext 'JavaAppArgs: Zero or more arguments which will be passed to the Java application.'`"+ echo "";+ fi+ fi++ exit 1+}++docommand() {+ case "$COMMAND" in+ 'console')+ checkUser touchlock "$@"+ if [ ! -n "$FIXED_COMMAND" ] ; then+ shift+ fi+ console "$@"+ ;;++ 'start')+ startdaemon "$@"+ ;;++ 'stop')+ if [ "$DIST_OS" = "macosx" -a -f "/Library/LaunchDaemons/${APP_PLIST}" ] ; then+ macosxStop+ elif [ "$DIST_OS" = "linux" -a -f "/etc/init/${APP_NAME}.conf" ] ; then+ upstartStop+ elif [ "$DIST_OS" = "linux" -a -n "$USE_SYSTEMD" -a -z "$SYSD" ] ; then+ systemdStop+ elif [ "$DIST_OS" = "aix" -a -z "$SKIP_SRC" ] && [ "`/usr/bin/lssrc -S -s $APP_NAME`" ] ; then+ srcStop+ else+ checkUser "" "$COMMAND"+ stopit "0"+ fi+ ;;++ 'restart')+ if [ "$DIST_OS" = "macosx" -a -f "/Library/LaunchDaemons/${APP_PLIST}" ] ; then+ macosxRestart+ elif [ "$DIST_OS" = "linux" -a -f "/etc/init/${APP_NAME}.conf" ] ; then+ upstartRestart+ elif [ "$DIST_OS" = "linux" -a -n "$USE_SYSTEMD" -a -z "$SYSD" ] ; then+ systemdRestart+ elif [ "$DIST_OS" = "aix" -a -z "$SKIP_SRC" ] && [ "`/usr/bin/lssrc -S -s $APP_NAME`" ] ; then+ srcRestart+ else+ if [ -n "$SMF" ] ; then+ shift+ fi+ checkUser touchlock "$COMMAND"+ if [ ! -n "$FIXED_COMMAND" ] ; then+ shift+ fi+ stopit "0"+ start "$@"+ fi+ ;;++ 'condrestart')+ checkUser touchlock "$COMMAND"+ if [ ! -n "$FIXED_COMMAND" ] ; then+ shift+ fi+ stopit "1"+ start "$@"+ ;;++ 'pause')+ if [ -n "$PAUSABLE" ]+ then+ pause+ else+ showUsage "$COMMAND"+ fi+ ;;++ 'resume')+ if [ -n "$PAUSABLE" ]+ then+ resume+ else+ showUsage "$COMMAND"+ fi+ ;;++ 'status')+ status+ ;;++ 'install')+ installdaemon "$@"+ ;;++ 'installstart')+ installdaemon "$@"+ startdaemon "$@"+ ;;++ 'remove')+ removedaemon+ ;;++ 'dump')+ checkUser "" "$COMMAND"+ dump+ ;;++ 'start_msg')+ # Internal command called by launchd on HP-UX.+ checkUser "" "$COMMAND"+ startmsg+ ;;++ 'stop_msg')+ # Internal command called by launchd on HP-UX.+ checkUser "" "$COMMAND"+ stopmsg+ ;;++ 'launchdinternal' | 'upstartinternal')+ if [ ! "$DIST_OS" = "macosx" -o ! -f "/Library/LaunchDaemons/${APP_PLIST}" ] ; then+ checkUser touchlock "$@"+ fi+ # Internal command called by launchd on Max OSX.+ # We do not want to call checkUser here as it is handled in the launchd plist file. Doing it here would confuse launchd.+ if [ ! -n "$FIXED_COMMAND" ] ; then+ shift+ fi+ launchinternal "$@"+ ;;++ *)+ showUsage "$COMMAND"+ ;;+ esac+}++docommand "$@"++exit 0diff --git a/commons.jsw/wrapper/wrapper.conf b/commons.jsw/wrapper/customization/wrapper.confsimilarity index 100%rename from commons.jsw/wrapper/wrapper.confrename to commons.jsw/wrapper/customization/wrapper.confdiff --git a/commons.loader/src/main/java/com/pmease/commons/loader/AbstractPluginModule.java b/commons.loader/src/main/java/com/pmease/commons/loader/AbstractPluginModule.javaindex 36a57ade48..e473845fed 100644--- a/commons.loader/src/main/java/com/pmease/commons/loader/AbstractPluginModule.java+++ b/commons.loader/src/main/java/com/pmease/commons/loader/AbstractPluginModule.java@@ -30,7 +30,7 @@ public abstract class AbstractPluginModule extends AbstractModule implements Dep@Overrideprotected void configure() {- final Class<? extends Plugin> pluginClass = getPluginClass();+ Class<? extends Plugin> pluginClass = getPluginClass();if (pluginClass != null) {contribute(Plugin.class, pluginClass);diff --git a/commons.loader/src/main/java/com/pmease/commons/loader/AppLoader.java b/commons.loader/src/main/java/com/pmease/commons/loader/AppLoader.javaindex 61366df53e..007d3f52a0 100644--- a/commons.loader/src/main/java/com/pmease/commons/loader/AppLoader.java+++ b/commons.loader/src/main/java/com/pmease/commons/loader/AppLoader.java@@ -43,6 +43,15 @@ import javassist.bytecode.SignatureAttribute.TypeParameter;public class AppLoader implements Startable {+ // built-in command for database restore+ public static final String COMMAND_RESTORE = "restore";++ // built-in command for database upgrade+ public static final String COMMAND_UPGRADE = "upgrade";++ // built-in command for database constraint reapply+ public static final String COMMAND_REAPPLY_DB_CONSTRAINTS = "reapply_db_constraints";+private static final Logger logger = LoggerFactory.getLogger(AppLoader.class);public static Injector injector;@@ -62,7 +71,7 @@ public class AppLoader implements Startable {} catch (IOException e) {throw new RuntimeException(e);}- } else if (!tempDir.mkdir()) {+ } else if (!tempDir.mkdirs()) {throw new RuntimeException("Can not create directory '" + tempDir.getAbsolutePath() + "'.");}System.setProperty("java.io.tmpdir", tempDir.getAbsolutePath());@@ -90,7 +99,7 @@ public class AppLoader implements Startable {@Overridepublic void stop() {- logger.info("Shutting down general executor...");+ logger.info("Shutting down executor service...");injector.getInstance(ExecutorService.class).shutdown();logger.info("Stopping plugin manager...");diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDataManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDataManager.javaindex 5f05342f8d..640d88a3eb 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDataManager.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDataManager.java@@ -1,253 +1,253 @@-package com.pmease.gitplex.core.manager.impl;--import java.io.File;-import java.io.ObjectStreamException;-import java.io.Serializable;-import java.util.ArrayList;-import java.util.List;--import javax.inject.Inject;-import javax.inject.Singleton;-import javax.validation.Validator;--import org.joda.time.DateTime;-import org.joda.time.format.DateTimeFormat;-import org.quartz.CronScheduleBuilder;-import org.quartz.ScheduleBuilder;--import com.google.common.base.Throwables;-import com.google.common.collect.Lists;-import com.google.common.collect.Sets;-import com.pmease.commons.bootstrap.Bootstrap;-import com.pmease.commons.bootstrap.BootstrapUtils;-import com.pmease.commons.hibernate.IdManager;-import com.pmease.commons.hibernate.PersistManager;-import com.pmease.commons.hibernate.Sessional;-import com.pmease.commons.hibernate.Transactional;-import com.pmease.commons.loader.Listen;-import com.pmease.commons.loader.ManagedSerializedForm;-import com.pmease.commons.schedule.SchedulableTask;-import com.pmease.commons.schedule.TaskScheduler;-import com.pmease.commons.util.FileUtils;-import com.pmease.commons.util.init.ManualConfig;-import com.pmease.commons.util.init.Skippable;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.Account;-import com.pmease.gitplex.core.entity.Config;-import com.pmease.gitplex.core.entity.Config.Key;-import com.pmease.gitplex.core.event.lifecycle.SystemStarting;-import com.pmease.gitplex.core.manager.AccountManager;-import com.pmease.gitplex.core.manager.ConfigManager;-import com.pmease.gitplex.core.manager.DataManager;-import com.pmease.gitplex.core.manager.MailManager;-import com.pmease.gitplex.core.setting.BackupSetting;-import com.pmease.gitplex.core.setting.MailSetting;-import com.pmease.gitplex.core.setting.SystemSetting;--@Singleton-public class DefaultDataManager implements DataManager, Serializable {-- private static final String BACKUP_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss";-- private final AccountManager accountManager;-- private final ConfigManager configManager;-- private final IdManager idManager;-- private final TaskScheduler taskScheduler;-- private final Validator validator;-- private final PersistManager persistManager;-- private final MailManager mailManager;-- private String backupTaskId;-- @Inject- public DefaultDataManager(IdManager idManager, AccountManager accountManager,- ConfigManager configManager, TaskScheduler taskScheduler,- PersistManager persistManager, MailManager mailManager,- Validator validator) {- this.accountManager = accountManager;- this.configManager = configManager;- this.validator = validator;- this.idManager = idManager;- this.taskScheduler = taskScheduler;- this.persistManager = persistManager;- this.mailManager = mailManager;- }-- @SuppressWarnings("serial")- @Transactional- @Override- public List<ManualConfig> init() {- List<ManualConfig> manualConfigs = new ArrayList<ManualConfig>();- Account administrator = accountManager.get(Account.ADMINISTRATOR_ID);- if (administrator == null) {- administrator = new Account();- administrator.setId(Account.ADMINISTRATOR_ID);- manualConfigs.add(new ManualConfig("Create Administator Account", administrator,- Sets.newHashSet("description", "defaultPrivilege")) {-- @Override- public Skippable getSkippable() {- return null;- }-- @Override- public void complete() {- accountManager.save((Account) getSetting(), null);- idManager.init(Account.class);- }-- });- }-- Config systemConfig = configManager.getConfig(Key.SYSTEM);- SystemSetting systemSetting = null;-- if (systemConfig == null || systemConfig.getSetting() == null) {- systemSetting = new SystemSetting();- systemSetting.setServerUrl(GitPlex.getInstance().guessServerUrl());- } else {- if (!validator.validate(systemConfig.getSetting()).isEmpty())- systemSetting = (SystemSetting) systemConfig.getSetting();- }- if (systemSetting != null) {- manualConfigs.add(new ManualConfig("Specify System Setting", systemSetting) {-- @Override- public Skippable getSkippable() {- return null;- }-- @Override- public void complete() {- configManager.saveSystemSetting((SystemSetting) getSetting());- }-- });- }-- Config mailConfig = configManager.getConfig(Key.MAIL);- Serializable mailSetting = null;- if (mailConfig == null) {- mailSetting = new MailSetting();- } else if (mailConfig.getSetting() != null) {- if (!validator.validate(mailConfig.getSetting()).isEmpty())- mailSetting = mailConfig.getSetting();- }-- if (mailSetting != null) {- manualConfigs.add(new ManualConfig("Specify Mail Setting", mailSetting) {-- @Override- public Skippable getSkippable() {- return new Skippable() {-- @Override- public void skip() {- configManager.saveMailSetting(null);- }-- };- }-- @Override- public void complete() {- configManager.saveMailSetting((MailSetting) getSetting());- }-- });- }-- Config backupConfig = configManager.getConfig(Key.BACKUP);- if (backupConfig == null) {- configManager.saveBackupSetting(null);- } else if (backupConfig.getSetting() != null && !validator.validate(backupConfig.getSetting()).isEmpty()) {- Serializable backupSetting = backupConfig.getSetting();- manualConfigs.add(new ManualConfig("Specify Backup Setting", backupSetting) {-- @Override- public Skippable getSkippable() {- return null;- }-- @Override- public void complete() {- configManager.saveBackupSetting((BackupSetting) getSetting());- }-- });- }-- return manualConfigs;- }-- @Override- public void scheduleBackup(BackupSetting backupSetting) {- if (backupTaskId != null)- taskScheduler.unschedule(backupTaskId);- if (backupSetting != null) {- backupTaskId = taskScheduler.schedule(new SchedulableTask() {-- @Override- public void execute() {- File tempDir = null;- try {- File backupDir = new File(backupSetting.getFolder());- if (!backupDir.isAbsolute())- backupDir = new File(Bootstrap.installDir, backupSetting.getFolder());- if (!backupDir.exists()) {- throw new RuntimeException("Backup directory does not exist: " + backupDir.getAbsolutePath());- }- tempDir = FileUtils.createTempDir("backup");- persistManager.exportData(tempDir, BackupSetting.BATCH_SIZE);- File backupFile = new File(backupDir,- DateTimeFormat.forPattern(BACKUP_DATETIME_FORMAT).print(new DateTime()) + ".zip");- BootstrapUtils.zip(tempDir, backupFile);- } catch (Exception e) {- notifyBackupError(e);- throw Throwables.propagate(e);- } finally {- if (tempDir != null)- FileUtils.deleteDir(tempDir);- }- }-- @Override- public ScheduleBuilder<?> getScheduleBuilder() {- return CronScheduleBuilder.cronSchedule(backupSetting.getSchedule());- }-- });- }- }-- @Listen- public void on(SystemStarting event) {- scheduleBackup(configManager.getBackupSetting());- }-- @Sessional- protected void notifyBackupError(Exception e) {- Account root = accountManager.getRoot();- String url = configManager.getSystemSetting().getServerUrl();- String body = String.format(""- + "GitPlex url: <a href='%s'>%s</a>"- + "<p style='margin: 16px 0;'>"- + "<b>Error detail:</b>"- + "<pre style='font-family: monospace;'>%s</pre>"- + "<p style='margin: 16px 0;'>"- + "-- Sent by GitPlex",- url, url, Throwables.getStackTraceAsString(e));- mailManager.sendMail(Lists.newArrayList(root), "GitPlex database auto-backup failed", body);- }-- public Object writeReplace() throws ObjectStreamException {- return new ManagedSerializedForm(DataManager.class);- }--}+package com.pmease.gitplex.core.manager.impl;++import java.io.File;+import java.io.ObjectStreamException;+import java.io.Serializable;+import java.util.ArrayList;+import java.util.List;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.Validator;++import org.joda.time.DateTime;+import org.joda.time.format.DateTimeFormat;+import org.quartz.CronScheduleBuilder;+import org.quartz.ScheduleBuilder;++import com.google.common.base.Throwables;+import com.google.common.collect.Lists;+import com.google.common.collect.Sets;+import com.pmease.commons.bootstrap.Bootstrap;+import com.pmease.commons.bootstrap.BootstrapUtils;+import com.pmease.commons.hibernate.IdManager;+import com.pmease.commons.hibernate.PersistManager;+import com.pmease.commons.hibernate.Sessional;+import com.pmease.commons.hibernate.Transactional;+import com.pmease.commons.loader.Listen;+import com.pmease.commons.loader.ManagedSerializedForm;+import com.pmease.commons.schedule.SchedulableTask;+import com.pmease.commons.schedule.TaskScheduler;+import com.pmease.commons.util.FileUtils;+import com.pmease.commons.util.init.ManualConfig;+import com.pmease.commons.util.init.Skippable;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.Account;+import com.pmease.gitplex.core.entity.Config;+import com.pmease.gitplex.core.entity.Config.Key;+import com.pmease.gitplex.core.event.lifecycle.SystemStarting;+import com.pmease.gitplex.core.manager.AccountManager;+import com.pmease.gitplex.core.manager.ConfigManager;+import com.pmease.gitplex.core.manager.DataManager;+import com.pmease.gitplex.core.manager.MailManager;+import com.pmease.gitplex.core.setting.BackupSetting;+import com.pmease.gitplex.core.setting.MailSetting;+import com.pmease.gitplex.core.setting.SystemSetting;++@Singleton+public class DefaultDataManager implements DataManager, Serializable {++ private static final String BACKUP_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss";++ private final AccountManager accountManager;++ private final ConfigManager configManager;++ private final IdManager idManager;++ private final TaskScheduler taskScheduler;++ private final Validator validator;++ private final PersistManager persistManager;++ private final MailManager mailManager;++ private String backupTaskId;++ @Inject+ public DefaultDataManager(IdManager idManager, AccountManager accountManager,+ ConfigManager configManager, TaskScheduler taskScheduler,+ PersistManager persistManager, MailManager mailManager,+ Validator validator) {+ this.accountManager = accountManager;+ this.configManager = configManager;+ this.validator = validator;+ this.idManager = idManager;+ this.taskScheduler = taskScheduler;+ this.persistManager = persistManager;+ this.mailManager = mailManager;+ }++ @SuppressWarnings("serial")+ @Transactional+ @Override+ public List<ManualConfig> init() {+ List<ManualConfig> manualConfigs = new ArrayList<ManualConfig>();+ Account administrator = accountManager.get(Account.ADMINISTRATOR_ID);+ if (administrator == null) {+ administrator = new Account();+ administrator.setId(Account.ADMINISTRATOR_ID);+ manualConfigs.add(new ManualConfig("Create Administator Account", administrator,+ Sets.newHashSet("description", "defaultPrivilege")) {++ @Override+ public Skippable getSkippable() {+ return null;+ }++ @Override+ public void complete() {+ accountManager.save((Account) getSetting(), null);+ idManager.init(Account.class);+ }++ });+ }++ Config systemConfig = configManager.getConfig(Key.SYSTEM);+ SystemSetting systemSetting = null;++ if (systemConfig == null || systemConfig.getSetting() == null) {+ systemSetting = new SystemSetting();+ systemSetting.setServerUrl(GitPlex.getInstance().guessServerUrl());+ } else {+ if (!validator.validate(systemConfig.getSetting()).isEmpty())+ systemSetting = (SystemSetting) systemConfig.getSetting();+ }+ if (systemSetting != null) {+ manualConfigs.add(new ManualConfig("Specify System Setting", systemSetting) {++ @Override+ public Skippable getSkippable() {+ return null;+ }++ @Override+ public void complete() {+ configManager.saveSystemSetting((SystemSetting) getSetting());+ }++ });+ }++ Config mailConfig = configManager.getConfig(Key.MAIL);+ Serializable mailSetting = null;+ if (mailConfig == null) {+ mailSetting = new MailSetting();+ } else if (mailConfig.getSetting() != null) {+ if (!validator.validate(mailConfig.getSetting()).isEmpty())+ mailSetting = mailConfig.getSetting();+ }++ if (mailSetting != null) {+ manualConfigs.add(new ManualConfig("Specify Mail Setting", mailSetting) {++ @Override+ public Skippable getSkippable() {+ return new Skippable() {++ @Override+ public void skip() {+ configManager.saveMailSetting(null);+ }++ };+ }++ @Override+ public void complete() {+ configManager.saveMailSetting((MailSetting) getSetting());+ }++ });+ }++ Config backupConfig = configManager.getConfig(Key.BACKUP);+ if (backupConfig == null) {+ configManager.saveBackupSetting(null);+ } else if (backupConfig.getSetting() != null && !validator.validate(backupConfig.getSetting()).isEmpty()) {+ Serializable backupSetting = backupConfig.getSetting();+ manualConfigs.add(new ManualConfig("Specify Backup Setting", backupSetting) {++ @Override+ public Skippable getSkippable() {+ return null;+ }++ @Override+ public void complete() {+ configManager.saveBackupSetting((BackupSetting) getSetting());+ }++ });+ }++ return manualConfigs;+ }++ @Override+ public void scheduleBackup(BackupSetting backupSetting) {+ if (backupTaskId != null)+ taskScheduler.unschedule(backupTaskId);+ if (backupSetting != null) {+ backupTaskId = taskScheduler.schedule(new SchedulableTask() {++ @Override+ public void execute() {+ File tempDir = null;+ try {+ File backupDir = new File(backupSetting.getFolder());+ if (!backupDir.isAbsolute())+ backupDir = new File(Bootstrap.installDir, backupSetting.getFolder());+ if (!backupDir.exists()) {+ throw new RuntimeException("Backup directory does not exist: " + backupDir.getAbsolutePath());+ }+ tempDir = FileUtils.createTempDir("backup");+ persistManager.exportData(tempDir, BackupSetting.BATCH_SIZE);+ File backupFile = new File(backupDir,+ DateTimeFormat.forPattern(BACKUP_DATETIME_FORMAT).print(new DateTime()) + ".zip");+ BootstrapUtils.zip(tempDir, backupFile);+ } catch (Exception e) {+ notifyBackupError(e);+ throw Throwables.propagate(e);+ } finally {+ if (tempDir != null)+ FileUtils.deleteDir(tempDir);+ }+ }++ @Override+ public ScheduleBuilder<?> getScheduleBuilder() {+ return CronScheduleBuilder.cronSchedule(backupSetting.getSchedule());+ }++ });+ }+ }++ @Listen+ public void on(SystemStarting event) {+ scheduleBackup(configManager.getBackupSetting());+ }++ @Sessional+ protected void notifyBackupError(Exception e) {+ Account root = accountManager.getRoot();+ String url = configManager.getSystemSetting().getServerUrl();+ String body = String.format(""+ + "GitPlex url: <a href='%s'>%s</a>"+ + "<p style='margin: 16px 0;'>"+ + "<b>Error detail:</b>"+ + "<pre style='font-family: monospace;'>%s</pre>"+ + "<p style='margin: 16px 0;'>"+ + "-- Sent by GitPlex",+ url, url, Throwables.getStackTraceAsString(e));+ mailManager.sendMail(Lists.newArrayList(root), "GitPlex database auto-backup failed", body);+ }++ public Object writeReplace() throws ObjectStreamException {+ return new ManagedSerializedForm(DataManager.class);+ }++}diff --git a/gitplex.core/src/test/java/com/pmease/gitplex/core/model/PullRequestUpdateTest.java b/gitplex.core/src/test/java/com/pmease/gitplex/core/model/PullRequestUpdateTest.javaindex b8e1e8157d..a183fb3975 100644--- a/gitplex.core/src/test/java/com/pmease/gitplex/core/model/PullRequestUpdateTest.java+++ b/gitplex.core/src/test/java/com/pmease/gitplex/core/model/PullRequestUpdateTest.java@@ -43,6 +43,7 @@ public class PullRequestUpdateTest extends AbstractGitTest {public void testResolveChangedFilesWhenThereIsNoMerge() throws Exception {PullRequest request = new PullRequest();request.setTargetDepot(depot);+ request.setSourceDepot(depot);request.setTargetBranch("master");addFileAndCommit("a", "", "master:1");@@ -83,6 +84,7 @@ public class PullRequestUpdateTest extends AbstractGitTest {public void testResolveChangedFilesWhenThereIsMerge() throws Exception {PullRequest request = new PullRequest();request.setTargetDepot(depot);+ request.setSourceDepot(depot);request.setTargetBranch("master");addFileAndCommit("1", "", "master:1");@@ -123,6 +125,7 @@ public class PullRequestUpdateTest extends AbstractGitTest {public void testGetCommitsWhenTargetBranchIsMergedToSourceBranch() throws Exception {PullRequest request = new PullRequest();request.setTargetDepot(depot);+ request.setSourceDepot(depot);request.setTargetBranch("master");addFileAndCommit("0", "", "0");@@ -171,6 +174,7 @@ public class PullRequestUpdateTest extends AbstractGitTest {public void testGetCommitsWhenSourceBranchIsMergedToTargetBranch() throws Exception {PullRequest request = new PullRequest();request.setTargetDepot(depot);+ request.setSourceDepot(depot);request.setTargetBranch("master");addFileAndCommit("0", "", "0");diff --git a/gitplex.product/build/package.gant b/gitplex.product/build/package.gantindex d8c3482386..790d658fd4 100644--- a/gitplex.product/build/package.gant+++ b/gitplex.product/build/package.gant@@ -7,7 +7,7 @@ target(default:"package the product") {File destFile = new File(buildDir, "${packageName}.zip");zip(destfile: destFile) {- zipfileset(dir: sandboxDir, prefix: "${packageName}", excludes: "${executables}, bin/system.classpath")+ zipfileset(dir: sandboxDir, prefix: "${packageName}", excludes: "${executables}, boot/system.classpath")zipfileset(dir: sandboxDir, prefix: "${packageName}", includes: "${executables}", filemode: "755")}}diff --git a/gitplex.product/build/prepare_package.gant b/gitplex.product/build/prepare_package.gantindex 8feba296cd..1c988cd438 100644--- a/gitplex.product/build/prepare_package.gant+++ b/gitplex.product/build/prepare_package.gant@@ -9,12 +9,12 @@ target(default:"prepare to package the product") {jswLoc = extractTo}- File binDir = new File(sandboxDir, "bin")- copy(todir: binDir) {+ File binDir = new File(sandboxDir, "bin")+ File bootDir = new File(sandboxDir, "boot")+ copy(todir: bootDir) {fileset(dir: jswLoc.absolutePath + "/bin", includes: "wrapper-*")fileset(dir: jswLoc.absolutePath + "/lib", includes: "libwrapper-*, *.dll, wrapper.jar")}- copy(tofile: binDir.absolutePath + "/server.bat", file: jswLoc.absolutePath + "/src/bin/AppCommand.bat.in")filterset(id: "appFilterSet") {filter(token: "app.name", value: "${productId}")@@ -22,10 +22,85 @@ target(default:"prepare to package the product") {filter(token: "app.description", value: "${productName}")filter(token: "app.class", value: "${bootstrapClass}")}- copy(tofile: binDir.absolutePath + "/server.sh", file: jswLoc.absolutePath + "/src/bin/sh.script.in") {+ filterset(id: "batchCommandCommonFilterSet") {+ filter(token: "set_fixed_command", value: "set _FIXED_COMMAND=console")+ }+ filterset(id: "shellScriptCommonFilterSet") {+ filter(token: "set_fixed_command", value: "FIXED_COMMAND=console")+ filter(token: "set_pass_through", value: "PASS_THROUGH=true")+ }++ copy(tofile: binDir.absolutePath + "/server.bat", file: jswLoc.absolutePath + "/customization/AppCommand.bat.in") {+ filterset() {+ filter(token: "set_fixed_command", value: "")+ filter(token: "properties_and_parameters", value: "--")+ }+ }+ copy(tofile: binDir.absolutePath + "/restore.bat", file: jswLoc.absolutePath + "/customization/AppCommand.bat.in") {+ filterset(refid: "batchCommandCommonFilterSet")+ filterset() {+ filter(token: "properties_and_parameters", value: "wrapper.logfile.loglevel=NONE wrapper.console.title=\"${productName} Restore\" wrapper.name=${productId}_restore wrapper.displayname=\"${productName} Restore\" wrapper.description=\"${productName} Restore\" -- restore")+ }+ }+ copy(tofile: binDir.absolutePath + "/upgrade.bat", file: jswLoc.absolutePath + "/customization/AppCommand.bat.in") {+ filterset(refid: "batchCommandCommonFilterSet")+ filterset() {+ filter(token: "properties_and_parameters", value: "wrapper.logfile.loglevel=NONE wrapper.console.title=\"${productName} Upgrade\" wrapper.name=${productId}_upgrade wrapper.displayname=\"${productName} Upgrade\" wrapper.description=\"${productName} Upgrade\" -- upgrade")+ }+ }+ copy(tofile: binDir.absolutePath + "/reapply_db_constraints.bat", file: jswLoc.absolutePath + "/customization/AppCommand.bat.in") {+ filterset(refid: "batchCommandCommonFilterSet")+ filterset() {+ filter(token: "properties_and_parameters", value: "wrapper.logfile.loglevel=NONE wrapper.console.title=\"${productName} Reapply DB Constraints\" wrapper.name=${productId}_reapply_db_constraints wrapper.displayname=\"${productName} Reapply DB Constraints\" wrapper.description=\"${productName} Reapply DB Constraints\" -- reapply_db_constraints")+ }+ }++ copy(tofile: binDir.absolutePath + "/server.sh", file: jswLoc.absolutePath + "/customization/sh.script.in") {filterset(refid: "appFilterSet")+ filterset() {+ filter(token: "set_fixed_command", value: "")+ filter(token: "set_pass_through", value: "")+ filter(token: "properties_and_parameters", value: "--")+ }+ }+ copy(tofile: binDir.absolutePath + "/restore.sh", file: jswLoc.absolutePath + "/customization/sh.script.in") {+ filterset() {+ filter(token: "app.name", value: "${productId}_restore")+ filter(token: "app.long.name", value: "${productName} Restore")+ filter(token: "app.description", value: "${productName} Restore")+ filter(token: "app.class", value: "${bootstrapClass}")+ }+ filterset(refid: "shellScriptCommonFilterSet")+ filterset() {+ filter(token: "properties_and_parameters", value: "wrapper.logfile.loglevel=NONE wrapper.console.title='${productName} Restore' wrapper.name=${productId}_restore wrapper.displayname='${productName} Restore' wrapper.description='${productName} Restore' -- restore")+ }}- copy(tofile: sandboxDir.absolutePath + "/conf/wrapper.conf", file: jswLoc.absolutePath + "/wrapper.conf") {+ copy(tofile: binDir.absolutePath + "/upgrade.sh", file: jswLoc.absolutePath + "/customization/sh.script.in") {+ filterset() {+ filter(token: "app.name", value: "${productId}_upgrade")+ filter(token: "app.long.name", value: "${productName} Upgrade")+ filter(token: "app.description", value: "${productName} Upgrade")+ filter(token: "app.class", value: "${bootstrapClass}")+ }+ filterset(refid: "shellScriptCommonFilterSet")+ filterset() {+ filter(token: "properties_and_parameters", value: "wrapper.logfile.loglevel=NONE wrapper.console.title='${productName} Upgrade' wrapper.name=${productId}_upgrade wrapper.displayname='${productName} Upgrade' wrapper.description='${productName} Upgrade' -- upgrade")+ }+ }+ copy(tofile: binDir.absolutePath + "/reapply_db_constraints.sh", file: jswLoc.absolutePath + "/customization/sh.script.in") {+ filterset() {+ filter(token: "app.name", value: "${productId}_reapply_db_constraints")+ filter(token: "app.long.name", value: "${productName} Reapply DB Constraints")+ filter(token: "app.description", value: "${productName} Reapply DB Constraints")+ filter(token: "app.class", value: "${bootstrapClass}")+ }+ filterset(refid: "shellScriptCommonFilterSet")+ filterset() {+ filter(token: "properties_and_parameters", value: "wrapper.logfile.loglevel=NONE wrapper.console.title='${productName} Reapply DB Constraints' wrapper.name=${productId}_reapply_db_constraints wrapper.displayname='${productName} Reapply DB Constraints' wrapper.description='${productName} Reapply DB Constraints' -- reapply_db_constraints")+ }+ }++ copy(tofile: sandboxDir.absolutePath + "/conf/wrapper.conf", file: jswLoc.absolutePath + "/customization/wrapper.conf") {filterset(refid: "appFilterSet")}}\ No newline at end of filediff --git a/gitplex.product/pom.xml b/gitplex.product/pom.xmlindex ca5c17c81f..94f743ac2f 100644--- a/gitplex.product/pom.xml+++ b/gitplex.product/pom.xml@@ -1,168 +1,166 @@-<?xml version="1.0" encoding="UTF-8"?>--<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">- <modelVersion>4.0.0</modelVersion>- <artifactId>gitplex</artifactId>- <name>GitPlex</name>- <parent>- <groupId>com.pmease</groupId>- <artifactId>parent.general</artifactId>- <version>1.0.31</version>- </parent>- <build>- <plugins>- <plugin>- <artifactId>maven-archetype-plugin</artifactId>- </plugin>- <plugin>- <artifactId>maven-source-plugin</artifactId>- </plugin>- <plugin>- <artifactId>maven-javadoc-plugin</artifactId>- </plugin>- <plugin>- <groupId>com.pmease</groupId>- <artifactId>plugin.maven</artifactId>- <executions>- <execution>- <id>copy-product-resources</id>- <phase>compile</phase>- <goals>- <goal>run-ant</goal>- </goals>- <configuration>- <target>- <copy todir="${project.build.directory}/sandbox">- <fileset dir="system"- excludes="site/images/**, site/avatars/**, **/*.keystore" />- <filterset>- <filter token="dbName" value="${project.artifactId}" />- <filter token="productName" value="${project.name}" />- </filterset>- </copy>- <copy todir="${project.build.directory}/sandbox">- <fileset dir="system"- includes="site/images/**, site/avatars/**, **/*.keystore" />- </copy>- </target>- </configuration>- </execution>- </executions>- </plugin>- <plugin>- <artifactId>maven-antrun-plugin</artifactId>- <executions>- <execution>- <id>prepare-package</id>- <phase>prepare-package</phase>- <goals>- <goal>run</goal>- </goals>- <configuration>- <target>- <taskdef name="gant" classname="org.codehaus.gant.ant.Gant" />- <gant file="build/prepare_package.gant">- <definition name="buildDirectory" value="${project.build.directory}" />- <definition name="outputDirectory" value="${project.build.outputDirectory}" />- <definition name="jswPath" value="${com.pmease:commons.jsw:jar}" />- <definition name="productId" value="${project.artifactId}" />- <definition name="productName" value="${project.name}" />- <definition name="bootstrapClass" value="${bootstrapClass}" />- </gant>- </target>- </configuration>- </execution>- <execution>- <id>package</id>- <phase>package</phase>- <goals>- <goal>run</goal>- </goals>- <configuration>- <target>- <taskdef name="gant" classname="org.codehaus.gant.ant.Gant" />- <gant file="build/package.gant">- <definition name="buildDirectory" value="${project.build.directory}" />- <definition name="executables" value="${executables}" />- <definition name="packageName"- value="${project.artifactId}-${project.version}" />- </gant>- </target>- </configuration>- </execution>- </executions>- </plugin>- </plugins>- </build>- <dependencies>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>commons.jsw</artifactId>- <version>1.0.31</version>- <scope>provided</scope>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>gitplex.core</artifactId>- <version>1.0.31</version>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>gitplex.web</artifactId>- <version>1.0.0</version>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>commons.loader</artifactId>- <version>1.0.31</version>- <type>test-jar</type>- <scope>test</scope>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>commons.git</artifactId>- <version>1.0.0</version>- <type>test-jar</type>- <scope>test</scope>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>gitplex.rest</artifactId>- <version>1.0.0</version>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>gitplex.http</artifactId>- <version>1.0.0</version>- </dependency>- <dependency>- <groupId>com.pmease</groupId>- <artifactId>gitplex.search</artifactId>- <version>1.0.0</version>- </dependency>- </dependencies>- <repositories>- <repository>- <id>pmeaseRepo</id>- <name>PMEase Repository</name>- <releases>- <enabled>true</enabled>- <updatePolicy>never</updatePolicy>- <checksumPolicy>fail</checksumPolicy>- </releases>- <snapshots>- <enabled>true</enabled>- <updatePolicy>always</updatePolicy>- <checksumPolicy>fail</checksumPolicy>- </snapshots>- <url>http://artifact.pmease.com/</url>- </repository>- </repositories>- <properties>- <executables>bin/*.sh, bin/wrapper-*</executables>- <bootstrapClass>com.pmease.commons.bootstrap.Bootstrap</bootstrapClass>- <moduleClass>com.pmease.gitplex.product.ProductModule</moduleClass>- <aggregation>true</aggregation>- </properties>-</project>+<?xml version="1.0" encoding="UTF-8"?>++<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">+ <modelVersion>4.0.0</modelVersion>+ <artifactId>gitplex</artifactId>+ <name>GitPlex</name>+ <parent>+ <groupId>com.pmease</groupId>+ <artifactId>parent.general</artifactId>+ <version>1.0.31</version>+ </parent>+ <build>+ <plugins>+ <plugin>+ <artifactId>maven-archetype-plugin</artifactId>+ </plugin>+ <plugin>+ <artifactId>maven-source-plugin</artifactId>+ </plugin>+ <plugin>+ <artifactId>maven-javadoc-plugin</artifactId>+ </plugin>+ <plugin>+ <groupId>com.pmease</groupId>+ <artifactId>plugin.maven</artifactId>+ <executions>+ <execution>+ <id>copy-product-resources</id>+ <phase>compile</phase>+ <goals>+ <goal>run-ant</goal>+ </goals>+ <configuration>+ <target>+ <copy todir="${project.build.directory}/sandbox">+ <fileset dir="system" excludes="site/images/**, site/avatars/**, **/*.keystore" />+ <filterset>+ <filter token="dbName" value="${project.artifactId}" />+ <filter token="productName" value="${project.name}" />+ </filterset>+ </copy>+ <copy todir="${project.build.directory}/sandbox">+ <fileset dir="system"+ includes="site/images/**, site/avatars/**, **/*.keystore" />+ </copy>+ </target>+ </configuration>+ </execution>+ </executions>+ </plugin>+ <plugin>+ <artifactId>maven-antrun-plugin</artifactId>+ <executions>+ <execution>+ <id>prepare-package</id>+ <phase>prepare-package</phase>+ <goals>+ <goal>run</goal>+ </goals>+ <configuration>+ <target>+ <taskdef name="gant" classname="org.codehaus.gant.ant.Gant" />+ <gant file="build/prepare_package.gant">+ <definition name="buildDirectory" value="${project.build.directory}" />+ <definition name="outputDirectory" value="${project.build.outputDirectory}" />+ <definition name="jswPath" value="${com.pmease:commons.jsw:jar}" />+ <definition name="productId" value="${project.artifactId}" />+ <definition name="productName" value="${project.name}" />+ <definition name="bootstrapClass" value="${bootstrapClass}" />+ </gant>+ </target>+ </configuration>+ </execution>+ <execution>+ <id>package</id>+ <phase>package</phase>+ <goals>+ <goal>run</goal>+ </goals>+ <configuration>+ <target>+ <taskdef name="gant" classname="org.codehaus.gant.ant.Gant" />+ <gant file="build/package.gant">+ <definition name="buildDirectory" value="${project.build.directory}" />+ <definition name="executables" value="${executables}" />+ <definition name="packageName" value="${project.artifactId}-${project.version}" />+ </gant>+ </target>+ </configuration>+ </execution>+ </executions>+ </plugin>+ </plugins>+ </build>+ <dependencies>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>commons.jsw</artifactId>+ <version>1.0.31</version>+ <scope>provided</scope>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>gitplex.core</artifactId>+ <version>1.0.31</version>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>gitplex.web</artifactId>+ <version>1.0.0</version>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>commons.loader</artifactId>+ <version>1.0.31</version>+ <type>test-jar</type>+ <scope>test</scope>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>commons.git</artifactId>+ <version>1.0.0</version>+ <type>test-jar</type>+ <scope>test</scope>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>gitplex.rest</artifactId>+ <version>1.0.0</version>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>gitplex.http</artifactId>+ <version>1.0.0</version>+ </dependency>+ <dependency>+ <groupId>com.pmease</groupId>+ <artifactId>gitplex.search</artifactId>+ <version>1.0.0</version>+ </dependency>+ </dependencies>+ <repositories>+ <repository>+ <id>pmeaseRepo</id>+ <name>PMEase Repository</name>+ <releases>+ <enabled>true</enabled>+ <updatePolicy>never</updatePolicy>+ <checksumPolicy>fail</checksumPolicy>+ </releases>+ <snapshots>+ <enabled>true</enabled>+ <updatePolicy>always</updatePolicy>+ <checksumPolicy>fail</checksumPolicy>+ </snapshots>+ <url>http://artifact.pmease.com/</url>+ </repository>+ </repositories>+ <properties>+ <executables>bin/*.sh, boot/wrapper-*</executables>+ <bootstrapClass>com.pmease.commons.bootstrap.Bootstrap</bootstrapClass>+ <moduleClass>com.pmease.gitplex.product.ProductModule</moduleClass>+ <aggregation>true</aggregation>+ </properties>+</project>diff --git a/gitplex.product/src/test/java/gitplex/product/Test.java b/gitplex.product/src/test/java/gitplex/product/Test.javaindex 1dc75c4121..14bd1dbc05 100644--- a/gitplex.product/src/test/java/gitplex/product/Test.java+++ b/gitplex.product/src/test/java/gitplex/product/Test.java@@ -1,16 +1,9 @@package gitplex.product;-import java.lang.reflect.Field;--import com.pmease.commons.hibernate.migration.VersionTable;-public class Test {@org.junit.Testpublic void test() {- for (Field field: VersionTable.class.getFields()) {- System.out.println(field.getName());- }}}\ No newline at end of filediff --git a/gitplex.product/system/conf/logback.xml b/gitplex.product/system/conf/logback.xmlindex 70f309674a..d0e70f77a7 100644--- a/gitplex.product/system/conf/logback.xml+++ b/gitplex.product/system/conf/logback.xml@@ -1,42 +1,43 @@-<?xml version="1.0" encoding="UTF-8"?>--<configuration scan="true">- <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">- <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">- <pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>- </encoder>- </appender>-- <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">- <file>${installDir}/logs/server.log</file>- <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">- <pattern>%date %-5level [%thread] %logger{36} %msg%n</pattern>- </encoder>- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">- <maxIndex>3</maxIndex>- <FileNamePattern>${installDir}/logs/server.log.%i</FileNamePattern>- </rollingPolicy>- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">- <MaxFileSize>250KB</MaxFileSize>- </triggeringPolicy>- </appender>-- <logger name="org.apache.wicket" level="WARN" />- <logger name="org.eclipse" level="WARN" />- <logger name="org.hibernate" level="WARN" />- <logger name="java.sql.DatabaseMetaData" level="WARN"></logger>- <logger name="org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory" level="ERROR"></logger>- <logger name="com.jolbox.bonecp.BoneCPConfig" level="WARN" />- <logger name="com.sun.jersey" level="WARN" ></logger>- <logger name="org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl" level="ERROR"></logger>- <logger name="org.reflections" level="WARN"></logger>- <logger name="org.apache.shiro.realm.AuthorizingRealm" level="WARN"></logger>- <logger name="jetbrains.exodus" level="WARN"></logger>- <logger name="com.pmease" level="DEBUG"></logger>-- <root level="INFO">- <appender-ref ref="FILE" />- <appender-ref ref="CONSOLE" />- </root>-+<?xml version="1.0" encoding="UTF-8"?>++<configuration scan="true">+ <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">+ <pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>+ </encoder>+ </appender>++ <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">+ <file>${installDir}/logs/${bootstrapCommand}.log</file>+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">+ <pattern>%date %-5level [%thread] %logger{36} %msg%n</pattern>+ </encoder>+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">+ <maxIndex>3</maxIndex>+ <FileNamePattern>${installDir}/logs/${bootstrapCommand}.log.%i</FileNamePattern>+ </rollingPolicy>+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">+ <MaxFileSize>250KB</MaxFileSize>+ </triggeringPolicy>+ </appender>++ <logger name="org.apache.wicket" level="WARN" />+ <logger name="org.eclipse" level="WARN" />+ <logger name="org.hibernate" level="WARN" />+ <logger name="java.sql.DatabaseMetaData" level="WARN"></logger>+ <logger name="org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory" level="ERROR"></logger>+ <logger name="com.jolbox.bonecp.BoneCPConfig" level="WARN" />+ <logger name="com.sun.jersey" level="WARN" ></logger>+ <logger name="org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl" level="ERROR"></logger>+ <logger name="org.reflections" level="WARN"></logger>+ <logger name="org.apache.shiro.realm.AuthorizingRealm" level="WARN"></logger>+ <logger name="jetbrains.exodus" level="WARN"></logger>+ <logger name="com.zaxxer.hikari.HikariDataSource" level="ERROR"></logger>+ <logger name="com.pmease" level="DEBUG"></logger>++ <root level="WARN">+ <appender-ref ref="FILE" />+ <appender-ref ref="CONSOLE" />+ </root>+</configuration>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebAccountNameReservation.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebAccountNameReservation.javaindex d1bc4fcc81..0ff3c9e395 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebAccountNameReservation.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebAccountNameReservation.java@@ -1,87 +1,87 @@-package com.pmease.gitplex.web;--import java.lang.reflect.Field;-import java.util.Collections;-import java.util.HashSet;-import java.util.Set;--import javax.inject.Inject;--import org.apache.commons.lang3.StringUtils;-import org.apache.wicket.core.request.mapper.MountedMapper;-import org.apache.wicket.core.request.mapper.ResourceMapper;-import org.apache.wicket.request.IRequestMapper;-import org.apache.wicket.request.mapper.ICompoundRequestMapper;-import org.eclipse.jetty.servlet.ServletMapping;--import com.google.common.base.Preconditions;-import com.google.common.collect.Sets;-import com.pmease.commons.jetty.JettyPlugin;-import com.pmease.commons.util.ReflectionUtils;-import com.pmease.gitplex.core.util.validation.AccountNameReservation;--public class WebAccountNameReservation implements AccountNameReservation {-- private final JettyPlugin jettyPlugin;-- private final WicketConfig webApp;-- @Inject- public WebAccountNameReservation(JettyPlugin jettyPlugin, WicketConfig webApp) {- this.jettyPlugin = jettyPlugin;- this.webApp = webApp;- }-- @Override- public Set<String> getReserved() {- Set<String> reserved = new HashSet<String>();- for (ServletMapping mapping: jettyPlugin.getContextHandler().getServletHandler().getServletMappings()) {- for (String pathSpec: mapping.getPathSpecs()) {- pathSpec = StringUtils.stripStart(pathSpec, "/");- pathSpec = StringUtils.substringBefore(pathSpec, "/");- if (pathSpec.trim().length() != 0)- reserved.add(pathSpec.trim());- }- }-- reserved.add("wicket");- reserved.add("new");-- for (IRequestMapper mapper: webApp.getRequestMappers()) {- Set<String> set = getReservedNames(mapper);- reserved.addAll(set);- }-- return reserved;- }-- private Set<String> getReservedNames(IRequestMapper mapper) {- if (mapper instanceof MountedMapper || mapper instanceof ResourceMapper) {- try {- Field field = ReflectionUtils.findField(mapper.getClass(), "mountSegments");- Preconditions.checkNotNull(field);- field.setAccessible(true);- String[] mountSegments = (String[]) field.get(mapper);- if (mountSegments != null && mountSegments.length != 0 && mountSegments[0] != null)- return Collections.singleton(mountSegments[0]);- else- return Collections.emptySet();- } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {- throw new RuntimeException(e);- }- }-- if (mapper instanceof ICompoundRequestMapper) {- ICompoundRequestMapper m = (ICompoundRequestMapper) mapper;- Set<String> result = Sets.newHashSet();- for (IRequestMapper each : m) {- Set<String> set = getReservedNames(each);- result.addAll(set);- }-- return result;- }-- return Collections.emptySet();- }-}+package com.pmease.gitplex.web;++import java.lang.reflect.Field;+import java.util.Collections;+import java.util.HashSet;+import java.util.Set;++import javax.inject.Inject;++import org.apache.commons.lang3.StringUtils;+import org.apache.wicket.core.request.mapper.MountedMapper;+import org.apache.wicket.core.request.mapper.ResourceMapper;+import org.apache.wicket.request.IRequestMapper;+import org.apache.wicket.request.mapper.ICompoundRequestMapper;+import org.eclipse.jetty.servlet.ServletMapping;++import com.google.common.base.Preconditions;+import com.google.common.collect.Sets;+import com.pmease.commons.jetty.JettyManager;+import com.pmease.commons.util.ReflectionUtils;+import com.pmease.gitplex.core.util.validation.AccountNameReservation;++public class WebAccountNameReservation implements AccountNameReservation {++ private final JettyManager jettyManager;++ private final WicketConfig webApp;++ @Inject+ public WebAccountNameReservation(JettyManager jettyManager, WicketConfig webApp) {+ this.jettyManager = jettyManager;+ this.webApp = webApp;+ }++ @Override+ public Set<String> getReserved() {+ Set<String> reserved = new HashSet<String>();+ for (ServletMapping mapping: jettyManager.getContextHandler().getServletHandler().getServletMappings()) {+ for (String pathSpec: mapping.getPathSpecs()) {+ pathSpec = StringUtils.stripStart(pathSpec, "/");+ pathSpec = StringUtils.substringBefore(pathSpec, "/");+ if (pathSpec.trim().length() != 0)+ reserved.add(pathSpec.trim());+ }+ }++ reserved.add("wicket");+ reserved.add("new");++ for (IRequestMapper mapper: webApp.getRequestMappers()) {+ Set<String> set = getReservedNames(mapper);+ reserved.addAll(set);+ }++ return reserved;+ }++ private Set<String> getReservedNames(IRequestMapper mapper) {+ if (mapper instanceof MountedMapper || mapper instanceof ResourceMapper) {+ try {+ Field field = ReflectionUtils.findField(mapper.getClass(), "mountSegments");+ Preconditions.checkNotNull(field);+ field.setAccessible(true);+ String[] mountSegments = (String[]) field.get(mapper);+ if (mountSegments != null && mountSegments.length != 0 && mountSegments[0] != null)+ return Collections.singleton(mountSegments[0]);+ else+ return Collections.emptySet();+ } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {+ throw new RuntimeException(e);+ }+ }++ if (mapper instanceof ICompoundRequestMapper) {+ ICompoundRequestMapper m = (ICompoundRequestMapper) mapper;+ Set<String> result = Sets.newHashSet();+ for (IRequestMapper each : m) {+ Set<String> set = getReservedNames(each);+ result.addAll(set);+ }++ return result;+ }++ return Collections.emptySet();+ }+}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/DatabaseBackupPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/DatabaseBackupPage.javaindex 0c32faf915..62c354d4e3 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/DatabaseBackupPage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/DatabaseBackupPage.java@@ -1,72 +1,73 @@-package com.pmease.gitplex.web.page.admin;--import java.io.File;-import java.io.IOException;--import org.apache.tika.mime.MimeTypes;-import org.apache.wicket.markup.html.form.Form;-import org.apache.wicket.markup.html.link.ResourceLink;-import org.apache.wicket.request.resource.AbstractResource;--import com.pmease.commons.bootstrap.BootstrapUtils;-import com.pmease.commons.hibernate.PersistManager;-import com.pmease.commons.util.FileUtils;-import com.pmease.commons.wicket.editable.BeanContext;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.manager.ConfigManager;-import com.pmease.gitplex.core.setting.BackupSetting;--@SuppressWarnings("serial")-public class DatabaseBackupPage extends AdministrationPage {-- @Override- protected void onInitialize() {- super.onInitialize();-- BackupSettingHolder backupSettingHolder = new BackupSettingHolder();- backupSettingHolder.setBackupSetting(GitPlex.getInstance(ConfigManager.class).getBackupSetting());- Form<?> form = new Form<Void>("backupSetting") {-- @Override- protected void onSubmit() {- super.onSubmit();- GitPlex.getInstance(ConfigManager.class).saveBackupSetting(backupSettingHolder.getBackupSetting());- getSession().success("Backup setting has been updated");-- setResponsePage(DatabaseBackupPage.class);- }-- };- form.add(BeanContext.editBean("editor", backupSettingHolder));- form.add(new ResourceLink<Void>("backupNow", new AbstractResource() {-- @Override- protected ResourceResponse newResourceResponse(Attributes attributes) {- ResourceResponse response = new ResourceResponse();- response.setContentType(MimeTypes.OCTET_STREAM);- response.disableCaching();- response.setFileName("backup.zip");- response.setWriteCallback(new WriteCallback() {-- @Override- public void writeData(Attributes attributes) throws IOException {- File tempDir = FileUtils.createTempDir("backup");- try {- GitPlex.getInstance(PersistManager.class).exportData(tempDir, BackupSetting.BATCH_SIZE);- BootstrapUtils.zip(tempDir, attributes.getResponse().getOutputStream());- } finally {- FileUtils.deleteDir(tempDir);- }- }- });-- return response;-- }-- }));-- add(form);- }--}+package com.pmease.gitplex.web.page.admin;++import java.io.File;+import java.io.IOException;++import org.apache.tika.mime.MimeTypes;+import org.apache.wicket.markup.html.form.Form;+import org.apache.wicket.markup.html.link.ResourceLink;+import org.apache.wicket.request.resource.AbstractResource;++import com.pmease.commons.bootstrap.BootstrapUtils;+import com.pmease.commons.hibernate.PersistManager;+import com.pmease.commons.util.FileUtils;+import com.pmease.commons.wicket.editable.BeanContext;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.manager.ConfigManager;+import com.pmease.gitplex.core.setting.BackupSetting;++@SuppressWarnings("serial")+public class DatabaseBackupPage extends AdministrationPage {++ @Override+ protected void onInitialize() {+ super.onInitialize();++ BackupSettingHolder backupSettingHolder = new BackupSettingHolder();+ backupSettingHolder.setBackupSetting(GitPlex.getInstance(ConfigManager.class).getBackupSetting());+ Form<?> form = new Form<Void>("backupSetting") {++ @Override+ protected void onSubmit() {+ super.onSubmit();+ GitPlex.getInstance(ConfigManager.class).saveBackupSetting(backupSettingHolder.getBackupSetting());+ getSession().success("Backup setting has been updated");++ setResponsePage(DatabaseBackupPage.class);+ }++ };+ form.add(BeanContext.editBean("editor", backupSettingHolder));+ form.add(new ResourceLink<Void>("backupNow", new AbstractResource() {++ @Override+ protected ResourceResponse newResourceResponse(Attributes attributes) {+ ResourceResponse response = new ResourceResponse();+ response.setContentType(MimeTypes.OCTET_STREAM);+ response.disableCaching();+ response.setFileName("backup.zip");+ response.setWriteCallback(new WriteCallback() {++ @Override+ public void writeData(Attributes attributes) throws IOException {+ File tempDir = FileUtils.createTempDir("backup");+ try {+ PersistManager persistManager = GitPlex.getInstance(PersistManager.class);+ persistManager.exportData(tempDir, BackupSetting.BATCH_SIZE);+ BootstrapUtils.zip(tempDir, attributes.getResponse().getOutputStream());+ } finally {+ FileUtils.deleteDir(tempDir);+ }+ }+ });++ return response;++ }++ }));++ add(form);+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.htmlindex 795b443f3a..b47194918b 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html@@ -1,3 +1,2 @@<wicket:extend>- <a wicket:id="test">test</a></wicket:extend>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.javaindex 8148d762c8..c69c96280a 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java@@ -1,13 +1,8 @@package com.pmease.gitplex.web.page.test;-import javax.validation.Validator;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.html.link.Link;import com.pmease.commons.wicket.page.CommonPage;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.setting.BackupSetting;@SuppressWarnings("serial")public class TestPage extends CommonPage {@@ -15,18 +10,6 @@ public class TestPage extends CommonPage {@Overrideprotected void onInitialize() {super.onInitialize();-- add(new Link<Void>("test") {-- @Override- public void onClick() {- BackupSetting backupSetting = new BackupSetting();- backupSetting.setSchedule("0 * * * ?");- backupSetting.setFolder("w:\\temp");- System.out.println(GitPlex.getInstance(Validator.class).validate(backupSetting).size());- }-- });}@Overridediff --git a/plugin.maven/src/main/java/com/pmease/plugin/maven/CreateProductSandboxMojo.java b/plugin.maven/src/main/java/com/pmease/plugin/maven/CreateProductSandboxMojo.javaindex 7a29c03b4f..59ad7d7b2a 100644--- a/plugin.maven/src/main/java/com/pmease/plugin/maven/CreateProductSandboxMojo.java+++ b/plugin.maven/src/main/java/com/pmease/plugin/maven/CreateProductSandboxMojo.java@@ -88,7 +88,7 @@ public class CreateProductSandboxMojo extends AbstractMojo {File buildDir = new File(project.getBuild().getDirectory());File sandboxDir = new File(buildDir, PluginConstants.SANDBOX);- File classpathFile = new File(sandboxDir, "bin/" + PluginConstants.SYSTEM_CLASSPATH);+ File classpathFile = new File(sandboxDir, "boot/" + PluginConstants.SYSTEM_CLASSPATH);if (!classpathFile.exists()) {if (artifact.getFile().isFile()) {UnArchiver unArchiver;diff --git a/plugin.maven/src/main/java/com/pmease/plugin/maven/GenerateProductResourcesMojo.java b/plugin.maven/src/main/java/com/pmease/plugin/maven/GenerateProductResourcesMojo.javaindex 9bbb14cebf..bb448e3ad3 100644--- a/plugin.maven/src/main/java/com/pmease/plugin/maven/GenerateProductResourcesMojo.java+++ b/plugin.maven/src/main/java/com/pmease/plugin/maven/GenerateProductResourcesMojo.java@@ -61,9 +61,9 @@ public class GenerateProductResourcesMojo extends AbstractMojo {PluginUtils.checkResolvedArtifacts(project, true);- File binDir = new File(project.getBuild().getDirectory(), PluginConstants.SANDBOX + "/bin");- if (!binDir.exists())- binDir.mkdirs();+ File bootDir = new File(project.getBuild().getDirectory(), PluginConstants.SANDBOX + "/boot");+ if (!bootDir.exists())+ bootDir.mkdirs();Properties props = new Properties();props.put("executables", executables);@@ -76,9 +76,9 @@ public class GenerateProductResourcesMojo extends AbstractMojo {for (Artifact artifact: PluginUtils.getBootstrapArtifacts(project, repoSystem, repoSession, remoteRepos))bootstrapKeys.add(PluginUtils.getArtifactKey(artifact));- PluginUtils.writeObject(new File(binDir, PluginConstants.BOOTSTRAP_KEYS), bootstrapKeys);+ PluginUtils.writeObject(new File(bootDir, PluginConstants.BOOTSTRAP_KEYS), bootstrapKeys);- PluginUtils.writeClasspath(new File(binDir, PluginConstants.SYSTEM_CLASSPATH), project,+ PluginUtils.writeClasspath(new File(bootDir, PluginConstants.SYSTEM_CLASSPATH), project,repoSystem, repoSession, remoteRepos);}diff --git a/plugin.maven/src/main/java/com/pmease/plugin/maven/PluginUtils.java b/plugin.maven/src/main/java/com/pmease/plugin/maven/PluginUtils.javaindex 5a76e1ed69..eb846079a4 100644--- a/plugin.maven/src/main/java/com/pmease/plugin/maven/PluginUtils.java+++ b/plugin.maven/src/main/java/com/pmease/plugin/maven/PluginUtils.java@@ -186,16 +186,16 @@ public class PluginUtils {// copy necessary library files to sandbox so that sandbox can// be executed from command line- File binDir = new File(sandboxDir, "bin");+ File bootDir = new File(sandboxDir, "boot");File libDir = new File(sandboxDir, "lib");- if (!binDir.exists())- binDir.mkdirs();+ if (!bootDir.exists())+ bootDir.mkdirs();if (!libDir.exists())libDir.mkdirs();Set<String> bootstrapKeys = (Set<String>) readObject(- new File(binDir, PluginConstants.BOOTSTRAP_KEYS));+ new File(bootDir, PluginConstants.BOOTSTRAP_KEYS));Set<Artifact> artifacts = new HashSet<Artifact>();for (Artifact artifact: project.getArtifacts()) {@@ -211,7 +211,7 @@ public class PluginUtils {File destFile;if (bootstrapKeys.contains(artifactKey))- destFile = new File(binDir, artifactKey);+ destFile = new File(bootDir, artifactKey);elsedestFile = new File(libDir, artifactKey);copyArtifact(artifact.getFile(), destFile, archiverManager);