Author: fdesbois Date: 2010-07-09 20:30:42 +0200 (Fri, 09 Jul 2010) New Revision: 2057 Url: http://nuiton.org/repositories/revision/topia/2057 Log: - Evo #766 : remove deprecated migration api Removed: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/DatabaseManager.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationCallback.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationEngine.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationService.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceDAOHelper.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceImpl.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersion.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionAbstract.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAO.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOAbstract.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOImpl.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionImpl.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationServiceImpl.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/callback/ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/common/ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/kernel/ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/transformation/ trunk/topia-service-migration/src/test/java/org/nuiton/topia/migration/common/ trunk/topia-service-migration/src/test/java/org/nuiton/topia/migration/kernel/ Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/DatabaseManager.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/DatabaseManager.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/DatabaseManager.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,435 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.migration; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.SQLQuery; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; -import org.hibernate.dialect.Dialect; -import org.hibernate.exception.JDBCConnectionException; -import org.hibernate.exception.SQLGrammarException; -import org.hibernate.mapping.ForeignKey; -import org.hibernate.mapping.Table; -import org.hibernate.tool.hbm2ddl.DatabaseMetadata; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.hibernate.tool.hbm2ddl.TableMetadata; -import org.nuiton.topia.migration.mappings.TMSVersion; -import org.nuiton.util.Version; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -/** - * DatabaseManager.java - * <p/> - * Cette classe sert à acceder a la base, pour la version notement - * creer les schemas, renommer et supprimer les tables. - * - * @author Chatellier Eric - * @author Chevallereau Benjamin - * @author Eon Sébastien - * @author Trève Vincent - * @version $Revision$ - * @deprecated since 2.3.4, please use now the simplify service {@link TopiaMigrationEngine} - */ -@Deprecated -public class DatabaseManager { - - /** Session factory */ - private SessionFactory sessionFactory; - - /** - * Configuration pour se connecter a la base - * et manipuler la table version seulement - */ - private Configuration dbConfiguration; - - /** Logger (common-logging) */ - private static Log logger = LogFactory.getLog(DatabaseManager.class); - - /** Suffix du nom des tables : _tms_v0 par exemple */ - private static String VERSIONNED_TABLES_SUFFIX = "_tmsv"; - - /** - * Constructeur - * - * @param pInfosConnexion Properties hibernate - */ - public DatabaseManager(Properties pInfosConnexion) { - // initie les proprietes - dbConfiguration = new Configuration(); - dbConfiguration.setProperties(pInfosConnexion); - - logger.debug("Configuration url : " + pInfosConnexion.getProperty(Environment.URL)); - logger.debug("Configuration driver : " + pInfosConnexion.getProperty(Environment.DRIVER)); - logger.debug("Configuration dialect : " + pInfosConnexion.getProperty(Environment.DIALECT)); - - // remplit la suite avec la liste de nos mappings... - logger.debug("Adding mappings for " + TMSVersion.class.getSimpleName()); - - // Hibernate will look for mapping files named - // /org/nuiton/topia/migration/mappings/TMSVersion.hbm.xml in the classpath. - // This approach eliminates any hardcoded filenames. - dbConfiguration.addClass(TMSVersion.class); - - // retourne une session factory - sessionFactory = dbConfiguration.buildSessionFactory(); - } - - /** - * Retourne la configuration Hibernate de la base. - * - * @return la configuration de la base - */ - public Configuration getDbConfiguration() { - return dbConfiguration; - } - - /** - * @return une {@link Connection}, charge a l'appelant de la fermer par la - * suite - */ - public Connection getConnection() { - Connection result = sessionFactory.openStatelessSession().connection(); - return result; - } - - /** - * Retourne la version de la base - * - * @return la version present en base, ou <tt>null</tt> si la version ne peut pas etre determinee - * @throws MigrationServiceException si un pb - */ - public Version getDataBaseVersion() throws MigrationServiceException { - Version version = null; - - logger.debug("Begin transaction to get version in database"); - - // get session - Session session = sessionFactory.openSession(); - - try { - - // debut d'une transaction - Transaction tx = session.beginTransaction(); - - // execute query - TMSVersion result = (TMSVersion) session.createCriteria(TMSVersion.class).uniqueResult(); - if (result != null) { - version = new Version(result.getVersion()); - logger.debug("Query executed, version found : " + version.getVersion()); - } else { - logger.debug("Query executed, no version found"); - } - - // commit - tx.commit(); - } catch (JDBCConnectionException e) { - throw new MigrationServiceException("Connection to database refused, check your configuration !"); - } catch (SQLGrammarException e) { - // si la table n'existe pas, on obtient une exception : base non versionnee - logger.debug("Exception on request : table not found"); - - // on retourn null - version = null; - } finally { - session.close(); - } - - return version; - } - - /** - * Renomme les tables en supprimant le suffixe - * - * @param vdbVersion Version a ajouter - * @param oldConfiguration Configuration contenant le schema - */ - public void renameTables(Configuration oldConfiguration, Version vdbVersion) { - - logger.debug("Renaming tables in configuration and database for version " + vdbVersion.getVersion()); - - // get session - Session session = sessionFactory.openSession(); - - // debut d'une transaction - Transaction tx = session.beginTransaction(); - - // DONE : voir si les relation *<->* sont listees par l'iterateur - // -> ok, normalement c bon, c gere - Iterator<?> i = oldConfiguration.getTableMappings(); - while (i.hasNext()) { - Table table = (Table) i.next(); - - String tableName = table.getName(); - String suffix = getTableSuffixForVersion(vdbVersion); - String newTableName = tableName; - if (tableName.endsWith(suffix)) { - newTableName = tableName.substring(0, tableName.length() - suffix.length()); - } - - // ALTER TABLE name RENAME TO newName - // marche normalement pour mysql, h2, postgres - - // TODO table existe pas - // TODO autre table existe deja - // TODO get sql string from dialect ... - - //Dialect dialect = Dialect.getDialect(oldConfiguration.getProperties()); - - logger.debug("Renaming table " + tableName + " to " + newTableName); - String sQuery = "ALTER TABLE " + tableName + " RENAME TO " + newTableName; - //logger.debug("Query : " + sQuery); - - SQLQuery sqlq = session.createSQLQuery(sQuery); - sqlq.executeUpdate(); - - // rennomage dans la config - table.setName(newTableName); - } - - // commit - tx.commit(); - - // close - session.close(); - } - - /** - * Renome les table dans la configuration hibernate - * - * @param oldConfiguration - * @param vdbVersion - * @return la nouvelle configuration - */ - public Configuration setRenamedTableSchema(Configuration oldConfiguration, Version vdbVersion) { - - logger.debug("Renaming tables in configuration for version " + vdbVersion.getVersion()); - - // voir si les relation *<->* sont listees par l'iterateur - // -> ok, normalement c bon, c gere - - // bug: sans cette ligne, les tables many-to-many ne sont pas list�es - oldConfiguration.buildMappings(); - - Iterator<?> i = oldConfiguration.getTableMappings(); - while (i.hasNext()) { - Table table = (Table) i.next(); - - if (table.isPhysicalTable()) { // hibernate utilse ca - - // rename constraints FK - Iterator<?> fKeys = table.getForeignKeyIterator(); - while (fKeys.hasNext()) { - ForeignKey fKey = (ForeignKey) fKeys.next(); - - if (logger.isTraceEnabled()) { - logger.trace("Changing constraints name : " + fKey.getName() + " to " + fKey.getName() + vdbVersion.getValidName()); - } - fKey.setName(fKey.getName() + vdbVersion.getValidName()); - } - - String tableName = table.getName(); - String newTableName = tableName + getTableSuffixForVersion(vdbVersion); - - // rennomage dans la config - logger.debug("Renaming table " + tableName + " to " + newTableName); - table.setName(newTableName); - } - } - - return oldConfiguration; - } - - /** - * Creer le nouveau schema pour l'application - * - * @param newConfiguration la configuration contenant le nouveau schema - */ - public void setApplicationSchemaInDatabase(Configuration newConfiguration) { - - // log - logger.debug("Creating new schema"); - - createSchema(newConfiguration); - - // log - logger.debug("Schema created"); - } - - /** - * Creer un schema - * - * @param configuration la configuration contenant les schemas - */ - protected void createSchema(Configuration configuration) { - // creer le schema en base - SchemaExport schemaExport = new SchemaExport(configuration); - schemaExport.execute(false/*script*/, true/*export*/, false/*justDrop*/, true/*justCreate*/); - } - - /** - * Supprimer un schema - * - * @param configuration la configuration contenant les schemas - */ - protected void dropSchema(Configuration configuration) { - // supprimer le schema en base - SchemaExport schemaExport = new SchemaExport(configuration); - schemaExport.drop(false, true); - } - - /** Creer le schema pour la table "tms_version" */ - public void createVersionTable() { - - logger.debug("Adding table to put version"); - - // creer le schema en base - // dans la configuration dbConfiguration, il n'y a que la table version - SchemaExport schemaExport = new SchemaExport(dbConfiguration); - schemaExport.create(false, true); - - logger.debug("Table for " + TMSVersion.class.getSimpleName() + " created"); - } - - /** - * Introduit la version du nouveau schema dans la base - * - * @param newVersion la version - */ - public void putVersionInDatabase(Version newVersion) { - - // get session - Session session = sessionFactory.openSession(); - - // debut d'une transaction - Transaction tx = session.beginTransaction(); - - logger.debug("Deleting existing versions"); - - // supprime les versions existants - // au pire, on pourrait remplacer la premiere - // execute query - List<?> lVersion = session.createCriteria(TMSVersion.class).list(); - for (Object o : lVersion) { - TMSVersion v = (TMSVersion) o; - logger.debug("Deleting version " + v.getVersion()); - - session.delete(v); - } - - // positionne la version - logger.debug("Setting database version to " + newVersion.getVersion()); - TMSVersion version = new TMSVersion(newVersion.getVersion()); - session.save(version); - - // commit - tx.commit(); - - // session close - session.close(); - } - - /** - * Supprime les tables des l'ancien mapping - * - * @param oldConfiguration configuration contenant le schema - */ - public void removeTablesFromOldMapping(Configuration oldConfiguration) { - - if (logger.isDebugEnabled()) { - logger.debug("Removing schema"); - } - dropSchema(oldConfiguration); - } - - /** - * Return table suffix name - * - * @param version version - * @return suffix name - */ - protected String getTableSuffixForVersion(Version version) { - String suffix = VERSIONNED_TABLES_SUFFIX + version.getValidName(); - return suffix; - } - - /** - * Test si les tables correspondant a une configuration existent. - * <p/> - * Test si au moins une table de la configuration existe. - * - * @param configuration la configuration - * @return <tt>true</tt> si le schema existe - */ - public boolean isSchemaExist(Configuration configuration) { - - boolean exist = false; - - Dialect dialect = Dialect.getDialect(configuration.getProperties()); - ConnectionProvider connectionProvider = ConnectionProviderFactory.newConnectionProvider(configuration.getProperties()); - - try { - - Iterator<?> tables = configuration.getTableMappings(); - - if (tables.hasNext()) { - Table testTable = (Table) tables.next(); - - Connection connection = connectionProvider.getConnection(); - - DatabaseMetadata meta = new DatabaseMetadata(connection, dialect); - - TableMetadata tmd = meta.getTableMetadata(testTable.getName(), testTable.getSchema(), testTable.getCatalog(), testTable.isQuoted()); - - if (tmd != null) { //table not found - exist = true; - } - } - - } catch (SQLException e) { - logger.error("Cant connect to database", e); - } - - return exist; - } - - /** Se deconnecte */ - public void disconnect() { - //nettoye - sessionFactory.close(); - } -} Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationCallback.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationCallback.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationCallback.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,250 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.migration; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.jdbc.Work; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.util.StringUtil; -import org.nuiton.util.Version; - -import java.lang.reflect.Method; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.List; - -import static org.nuiton.i18n.I18n._; - -/** - * ManualMigrationCallback - * - * @author tchemit <chemit@codelutin.com> - * @version $Revision$ - * @deprecated since 2.3.4, please use now the simplify service {@link TopiaMigrationCallback} - */ -@Deprecated -public abstract class ManualMigrationCallback { - - /** Logger */ - static private Log log = LogFactory.getLog(ManualMigrationCallback.class); - - /** CallbackHandler return type. */ - public enum MigrationChoice { - // no migration - - NO_MIGRATION, - // migration - MIGRATION, - // migration done by application, only version managed - CUSTOM_MIGRATION - } - - public abstract boolean askUser(Version dbVersion, - Version applicationVersion, - List<Version> versions); - - /** - * Tentative de migration depuis la version de la base version la version - * souhaitee. - * <p/> - * On applique toutes les migrations de version indiquee dans le parametre - * <code>version</code>. - * <p/> - * Pour chaque version, on cherche la methode migrateTo_XXX ou XXX est la - * version transforme en identifiant java via la methode - * {@link Version#getValidName()} et on l'execute. - * <p/> - * Note: pour chaque version a appliquer, on ouvre une nouvelle transaction. - * - * @param ctxt topia context de la transaction en cours - * @param dbVersion database version - * @param applicationVersion application version - * @param showSql drapeau pour afficher les requete sql - * @param showProgression drapeau pour afficher la progression - * @param versions all versions knwon by service @return migration a - * ggrement - * @return le choix de migration executee - */ - public MigrationChoice doMigration(TopiaContext ctxt, Version dbVersion, - Version applicationVersion, - boolean showSql, - boolean showProgression, - List<Version> versions) { - - MigrationChoice result = MigrationChoice.NO_MIGRATION; - - boolean doMigrate = askUser(dbVersion, applicationVersion, versions); - - if (doMigrate) { - TopiaContextImplementor tx; - - for (Version v : versions) { - // ouverture d'une connexion direct JDBC sur la base - try { - - tx = (TopiaContextImplementor) ctxt.beginTransaction(); - - try { - - String methodName = "migrateTo_" + v.getValidName(); - - Method m; - try { - m = getClass().getMethod(methodName, - TopiaContextImplementor.class, - boolean.class, - boolean.class); - - m.setAccessible(true); - - log.info(_("topia.migration.start.migrate", v)); - - if (log.isDebugEnabled()) { - log.debug("launch method " + methodName); - } - - m.invoke(this, tx, showSql, showProgression); - - - } catch (NoSuchMethodException e) { - // try with no boolean values (for legacy callbacks) - m = getClass().getMethod(methodName, - TopiaContextImplementor.class); - - m.setAccessible(true); - - log.info(_("topia.migration.start.migrate", v)); - - if (log.isDebugEnabled()) { - log.debug("launch method " + methodName); - } - - m.invoke(this, tx); - - } - - // commit des modifs - tx.commitTransaction(); - - // la migration a reussi, on dit que c fait - result = MigrationChoice.CUSTOM_MIGRATION; - } catch (Exception eee) { - // en cas d'erreur - log.error("Migration impossible de la base", eee); - // rollback du travail en cours - tx.rollbackTransaction(); - } finally { - // close database connexion - if (tx != null) { - tx.closeContext(); - } - } - - } catch (Exception eee) { - log.error("Error lors de la tentative de migration", eee); - } - } - } - return result; - } - - public void executeSQL(TopiaContextImplementor tx, String... sqls) - throws TopiaException { - executeSQL(tx, false, false, sqls); - } - - /** - * Executes the given {@code sqls} requests. - * - * @param tx the session - * @param showSql flag to see sql requests - * @param showProgression flag to see progession on console - * @param sqls requests to execute - * @throws TopiaException if any pb - * @since 2.3.0 - */ - public void executeSQL(TopiaContextImplementor tx, - final boolean showSql, - final boolean showProgression, - final String... sqls) throws TopiaException { - - if (log.isInfoEnabled()) { - - log.info(_("topia.migration.start.sqls", sqls.length)); - } - if (showSql) { - StringBuilder buffer = new StringBuilder(); - for (String s : sqls) { - buffer.append(s).append("\n"); - } - log.info("SQL TO EXECUTE :\n" + - "--------------------------------------------------------------------------------\n" + - "--------------------------------------------------------------------------------\n" + - buffer.toString() + - "--------------------------------------------------------------------------------\n" + - "--------------------------------------------------------------------------------\n" - ); - } - tx.getHibernate().doWork(new Work() { - - @Override - public void execute(Connection connection) throws SQLException { - int index = 0; - int max = sqls.length; - for (String sql : sqls) { - long t0 = System.nanoTime(); - if (log.isInfoEnabled()) { - String message = ""; - - if (showProgression) { - message = _("topia.migration.start.sql", ++index, max); - } - if (showSql) { - message += "\n" + sql; - } - if (showProgression || showSql) { - - log.info(message); - } - } - PreparedStatement sta = connection.prepareStatement(sql); - sta.executeUpdate(); - sta.close(); - if (log.isDebugEnabled()) { - String message; - message = _("topia.migration.end.sql", ++index, max, StringUtil.convertTime(System.nanoTime() - t0)); - log.debug(message); - } - } - } - }); - - } -} Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationEngine.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationEngine.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/ManualMigrationEngine.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,572 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.migration; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.cfg.Configuration; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaRuntimeException; -import org.nuiton.topia.event.TopiaContextEvent; -import org.nuiton.topia.event.TopiaContextListener; -import org.nuiton.topia.event.TopiaTransactionEvent; -import org.nuiton.topia.event.TopiaTransactionVetoable; -import org.nuiton.topia.framework.TopiaContextImpl; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.framework.TopiaUtil; -import org.nuiton.topia.migration.ManualMigrationCallback.MigrationChoice; -import org.nuiton.util.Resource; -import org.nuiton.util.Version; -import org.nuiton.util.VersionUtil; -import org.nuiton.util.VersionUtil.VersionComparator; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.List; -import java.util.Properties; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.nuiton.i18n.I18n._; - -/** - * TopiaMigrationServiceImpl.java - * <p/> - * Classe principale du projet. - * - * @author tchemit - * @deprecated since 2.3.4, please use now the simplify service {@link TopiaMigrationEngine} - */ -@Deprecated -public class ManualMigrationEngine //extends MigrationServiceImpl - implements TopiaMigrationService , TopiaContextListener, TopiaTransactionVetoable { - - // log - - private final static Log log = LogFactory.getLog(ManualMigrationEngine.class); - - /** La version de référence */ - static public final String MIGRATION_APPLICATION_VERSION = "topia.service.migration.version"; - - /** L'emplacement de tous les mappings */ - static public final String MIGRATION_MAPPING_DIRECTORY = "topia.service.migration.mappingdir"; - - /** Les noms des modèles connus */ - static public final String MIGRATION_MODEL_NAME = "topia.service.migration.modelname"; - - /** Configuration hibernate ne mappant que l'entite version (initialise en pre-init) */ - protected Configuration versionConfiguration; - - /** Chemin du dossier contenant les schemas de toutes les versions (initialise en pre-init) */ - protected String mappingsDirectory; - - /** ensemble des versions connues par le service */ - protected SortedSet<Version> versions; - - /** Version courante de l'application (initialise en pre-init) */ - protected Version applicationVersion; - - /** Un drapeau pour savoir si la table version existe en base (initialise en pre-init) */ - protected boolean versionTableExist; - - /** Version courante de la base (initialise en pre-init) */ - protected Version dbVersion; - - /** Drapeau pour savoir si la base est versionnée ou non */ - protected boolean dbNotVersioned; - - /** Un drapeau pour effectuer la migration au demarrage (initialise en pre-init) */ - protected boolean migrateOnInit; - - /** CallbackHandler list (initialise en pre-init) */ - protected ManualMigrationCallback callback; - - /** topia root context (initialise en pre-init) */ - protected TopiaContextImplementor rootContext; - - /** Un drapeau pour savoir si le service a bien ete initialise (i.e a bien fini la methode preInit) */ - protected boolean init; - - /** Un drapeau pour afficher les requetes sql executees */ - protected boolean showSql; - - /** Un drapeau pour afficher la progression des requetes sql executees */ - protected boolean showProgression; - - @Override - public Class<?>[] getPersistenceClasses() { - return new Class<?>[]{TMSVersionImpl.class}; - } - - @Override - public String getServiceName() { - return SERVICE_NAME; - } - - @Override - public boolean preInit(TopiaContextImplementor context) { - rootContext = context; - - Properties config = context.getConfig(); - - String mappingDirectory = config.getProperty(MIGRATION_MAPPING_DIRECTORY, null); - - String version = config.getProperty(MIGRATION_APPLICATION_VERSION, null); - String callbackStr = config.getProperty(MIGRATION_CALLBACK, ""); - String[] dirs = config.getProperty(TopiaContextImpl.TOPIA_PERSISTENCE_DIRECTORIES, "").split(","); - - migrateOnInit = Boolean.valueOf(config.getProperty(MIGRATION_MIGRATE_ON_INIT, "true")); - showSql = Boolean.valueOf(config.getProperty(MIGRATION_SHOW_SQL, "false")); - showProgression = Boolean.valueOf(config.getProperty(MIGRATION_SHOW_PROGRESSION, "false")); - String modelName = config.getProperty(MIGRATION_MODEL_NAME, null); - - if (version == null || version.trim().isEmpty()) { - throw new IllegalStateException("'" + MIGRATION_APPLICATION_VERSION + "' not set."); - } - if (modelName == null || modelName.trim().isEmpty()) { - throw new IllegalStateException("'" + MIGRATION_MODEL_NAME + "' not set."); - } - if (callbackStr == null || callbackStr.trim().isEmpty()) { - throw new IllegalStateException("'" + MIGRATION_CALLBACK + "' not set."); - } - if (mappingDirectory == null || mappingDirectory.trim().isEmpty()) { - throw new IllegalStateException("'" + MIGRATION_MAPPING_DIRECTORY + "' not set."); - } - - applicationVersion = VersionUtil.valueOf(version.trim()); - mappingsDirectory = mappingDirectory.trim() + "/" + modelName.trim(); - - // enregistrement du callback - try { - Class<?> clazz = Class.forName(callbackStr); - callback = (ManualMigrationCallback) clazz.newInstance(); - - } catch (ClassNotFoundException e) { - log.error("CallbackHandler Class " + callbackStr + " not found", e); - } catch (InstantiationException e) { - log.error("CallbackHandler class " + callbackStr + " cannot be instanciated", e); - } catch (IllegalAccessException e) { - log.error("CallbackHandler class " + callbackStr + " cannot be accessed", e); - } - - // creation de la configuration hibernate ne concernant que l'entite Version - // afin de pouvoir creer la table via un schemaExport si necessaire - - versionConfiguration = new Configuration(); - - // ajout des repertoires contenant les mappings hibernate - - for (String dir : dirs) { - dir = dir.trim(); - if (!dir.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("addDirectory " + dir); - } - versionConfiguration.addDirectory(new File(dir)); - } - } - - for (Class<?> clazz : getPersistenceClasses()) { - if (log.isDebugEnabled()) { - log.debug("addClass " + clazz); - } - versionConfiguration.addClass(clazz); - } - - Properties prop = new Properties(); - prop.putAll(versionConfiguration.getProperties()); - prop.putAll(config); - - versionConfiguration.setProperties(prop); - - init = true; - - // add topia context listener - context.addTopiaContextListener(this); - context.addTopiaTransactionVetoable(this); - - if (migrateOnInit) { - try { - - doMigrateSchema(); - - } catch (MigrationServiceException e) { - throw new TopiaRuntimeException("Can't migrate schema for reason " + e.getMessage(), e); - } - } else { - if (log.isDebugEnabled()) { - log.debug("migration service, skip migration on init"); - } - } - - return true; - } - - @Override - public boolean postInit(TopiaContextImplementor context) { - return true; - } - - @Override - public void preCreateSchema(TopiaContextEvent event) { - } - - @Override - public void preRestoreSchema(TopiaContextEvent event) { - } - - @Override - public void preUpdateSchema(TopiaContextEvent event) { - } - - @Override - public void postCreateSchema(TopiaContextEvent event) { - - if (log.isDebugEnabled()) { - log.debug("postCreateSchema event called : put version in database"); - } - - saveVersion(applicationVersion); - } - - @Override - public void postUpdateSchema(TopiaContextEvent event) { - if (log.isDebugEnabled()) { - log.debug("postUpdateSchema event called : put version in database"); - } - - saveVersion(applicationVersion); - } - - @Override - public void postRestoreSchema(TopiaContextEvent event) { - - if (log.isDebugEnabled()) { - log.debug("postRestoreSchema event detected, redo, schema migration"); - } - try { - - doMigrateSchema(); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("postRestoreSchema schema migration failed for reason " + e.getMessage(), e); - } - } - } - - @Override - public void beginTransaction(TopiaTransactionEvent event) { - - TopiaContextImplementor context = (TopiaContextImplementor) event.getSource(); - - // add topia context listener - context.addTopiaContextListener(this); - } - - public void doMigrateSchema() throws MigrationServiceException { - // migration - boolean complete = migrateSchema(); - if (!complete) { - if (log.isErrorEnabled()) { - log.error(_("topia.migration.migration.incomplete")); - } - throw new TopiaRuntimeException(_("topia.migration.migration.incomplete")); - } - } - - @Override - public boolean migrateSchema() throws MigrationServiceException { - - checkInit(); - - if (dbVersion == null || !migrateOnInit) { - detectDbVersion(); - } - - log.info(_("topia.migration.start.migration", applicationVersion.getVersion(), dbVersion.getVersion())); - - // tell if migration is needed - boolean bMigrationNeeded = false; - - if (log.isDebugEnabled()) { - log.debug("Migrate schema start version = " + dbVersion + - " _ not versioned = " + dbNotVersioned + - " _ TMSVersion exists = " + versionTableExist); - } - - if (versionTableExist && dbVersion.equals(applicationVersion)) { - log.info(_("topia.migration.skip.migration.db.is.up.to.date")); - // la base est a jour - return true; - } - - // Aucune version existante, la base de données est vierge - if (versionTableExist && dbNotVersioned && migrateOnInit) { - log.info(_("topia.migration.skip.migration.db.is.empty")); - // la base est vierge, aucune migration nécessaire - // mise à jour de la table tmsversion - saveVersion(applicationVersion); - return true; - } - - SortedSet<Version> allVersions = getVersions(); - log.info(_("topia.migration.available.versions", allVersions)); - - if (dbVersion.before(applicationVersion)) { - - // on filtre les versions a appliquer - List<Version> versionsToApply = VersionUtil.filterVersions(versions, dbVersion, applicationVersion, false, true); - //List<Version> versionsToApply = detectVersions(allVersions, dbVersion, applicationVersion); - - if (versionsToApply.isEmpty()) { - log.info(_("topia.migration.skip.migration.no.version.to.apply")); - } else { - bMigrationNeeded = true; - log.info(_("topia.migration.migrate.versions", versionsToApply)); - // ask handler for migration - MigrationChoice bMigrationWanted = callback.doMigration(rootContext, - dbVersion, - applicationVersion, - showSql, - showProgression, - versionsToApply); - - if (log.isDebugEnabled()) { - log.debug("Handler choose : " + bMigrationWanted); - } - if (bMigrationWanted == MigrationChoice.NO_MIGRATION) { - // l'utilisateur a annule la migration - return false; - } - } - } - - // on sauvegarde la version si necessaire (base non versionnee ou migration realisee) - if (!versionTableExist || bMigrationNeeded) { - - if (log.isDebugEnabled()) { - log.debug("Set application version in database to " + applicationVersion); - } - - // put version in database and create table if required - saveVersion(applicationVersion); - } - - // return succes flag - // - no migration needed - // - or migration needed and accepted - return true; - } - - /** - * Enregistre la version donnee en base avec creation de la table - * si elle n'existe pas. - * - * @param version la nouvelle version de la base - */ - public void saveVersion(Version version) { - checkInit(); - - if (log.isDebugEnabled()) { - log.debug("Save version = " + version + - " _ table exists = " + versionTableExist); - } - - if (dbVersion == null) { - detectDbVersion(); - } - - try { - - boolean createTable = !versionTableExist; - // update version even if database has not been migrated - // only case that database doesn't exist match this - if (createTable) { - // si la base n'etait pas versionnee, la table version n'existe pas - // creation - if (log.isDebugEnabled()) { - log.debug("Adding table to put version"); - } - - // creer le schema en base - // dans la configuration versionConfiguration, il n'y a que la table version - SchemaExport schemaExport = new SchemaExport(versionConfiguration); - schemaExport.create(log.isDebugEnabled(), true); - - if (log.isDebugEnabled()) { - log.debug("Table for " + TMSVersion.class.getSimpleName() + " created"); - } - - } - // Changement de la version en base - TopiaContext tx = null; - - try { - tx = rootContext.beginTransaction(); - - TMSVersionDAO dao = MigrationServiceDAOHelper.getTMSVersionDAO(tx); - - //FIXME on supprime toues les versions precedentes ??? - //FIXME il serait mieux de conserver toutes les versions je pense... - //FIXME on pourrait conserver l'information sur les date de mise a jour - List<TMSVersion> toDelete = dao.findAll(); - for (TMSVersion v : toDelete) { - dao.delete(v); - } - - log.info(_("topia.migration.saving.db.version", version)); - dao.create(TMSVersion.VERSION, version.getVersion()); - - tx.commitTransaction(); - } catch (TopiaException e) { - if (tx != null) { - tx.rollbackTransaction(); - } - throw e; - } finally { - if (tx != null) { - tx.closeContext(); - } - } - } catch (TopiaException e) { - throw new TopiaRuntimeException(e); - } - - // on change les etats internes du service - // ainsi cela empechera le redeclanchement de la migration - // suite a une creation de schema - versionTableExist = true; - dbVersion = version; - } - - /** - * Recupere toutes les versions prises en charge par le service de migration. - * - * @return l'ensemble triee (par ordre croissant) de toutes les versions - * detectees a partir du repertoire des mappings pour le modele donne. - * @throws MigrationServiceException pour tout probleme - */ - protected SortedSet<Version> getVersions() throws MigrationServiceException { - if (versions == null) { - checkInit(); - - // schema des noms de dossier de version - // FIX #38 : never use a File.separator for a class-path resource searching - Pattern MAPPING_PATTERN = Pattern.compile(mappingsDirectory + "/([0-9]+(\\.[0-9]+)*)"); - - if (log.isDebugEnabled()) { - log.debug("MAPPING_PATTERN : " + MAPPING_PATTERN); - } - ClassLoader classLoader = getClass().getClassLoader(); - - List<URL> urls = Resource.getURLs(".*" + mappingsDirectory + "/.*", classLoader instanceof URLClassLoader ? (URLClassLoader) classLoader : null); - - // ensemble ordonnee des version a charger apres - versions = new TreeSet<Version>(new VersionComparator()); - - if (urls != null && !urls.isEmpty()) { - - for (URL url : urls) { - if (log.isDebugEnabled()) { - log.debug("url to scan " + url); - } - Matcher matcher = MAPPING_PATTERN.matcher(url.getFile()); - if (matcher.find()) { - // group(1) est ce qui match entre le premier niveau de parentheses - String sVersion = matcher.group(1); - - versions.add(VersionUtil.valueOf(sVersion)); - } - } - } - } - return versions; - } - - /** - * Recupere depuis la base les états internes du service : - * <p/> - * <ul> - * <li>versionTableExist</li> - * <li>dbVersion</li> - * </ul> - */ - protected synchronized void detectDbVersion() { - - // on detecte si la table de versionning existe - versionTableExist = TopiaUtil.isSchemaExist(versionConfiguration, TMSVersionImpl.class.getName()); - - if (log.isDebugEnabled()) { - log.debug("Table TMSVersion exist = " + versionTableExist); - } - // recuperation de la version de la base - Version v = null; - try { - if (versionTableExist) { - TopiaContext tx = null; - try { - tx = rootContext.beginTransaction(); - TMSVersionDAO dao = MigrationServiceDAOHelper.getTMSVersionDAO(tx); - List<TMSVersion> versionsInDB = dao.findAll(); - if (!versionsInDB.isEmpty()) { - v = VersionUtil.valueOf(versionsInDB.get(0).getVersion()); - } - } finally { - if (tx != null) { - tx.closeContext(); - } - } - } - } catch (TopiaException e) { - throw new TopiaRuntimeException("Can't obtain dbVersion for reason " + e.getMessage(), e); - } - - if (v == null) { - // la base dans ce cas n'est pas versionee. - // On dit que la version de la base est 0 - // et les schema de cette version 0 doivent - // etre detenu en local - v = Version.VZERO; - dbNotVersioned = true; - log.info(_("topia.migration.db.not.versionned")); - } else { - log.info(_("topia.migration.detected.db.version", v)); - } - dbVersion = v; - } - - protected void checkInit() { - if (!init) { - throw new IllegalStateException("le service n'est pas initialisé!"); - } - } -} Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationService.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationService.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationService.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,103 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.migration; - -import org.nuiton.topia.migration.callback.MigrationCallbackHandler; -import org.hibernate.cfg.Configuration; - -/** - * MigrationService.java - * - * @author Chatellier Eric - * @author Chevallereau Benjamin - * @author Eon Sébastien - * @author Trève Vincent - * @version $Revision$ - * - * Last update : $Date$ - * @deprecated since 2.3.4, please use now the simplify service {@link TopiaMigrationEngine} - */ -@Deprecated -public interface MigrationService { - - /** - * Renvoie le chemin du ficier de configuration utilise - * @return Chemin du fichier de configuration - */ - String getConfigurationFile(); - - /** - * Modifie le fichier de configuration - * @param configurationFile Chemin du fichier de configuration d'hibernate - */ - void setConfigurationFile(String configurationFile); - - /** - * Retourne la configuration - * @return la configuration - * @see Configuration - */ - Configuration getConfiguration(); - - /** - * Renseigne la configuration - * @param configuration la configuration - * @see Configuration - */ - void setConfiguration(Configuration configuration); - - /** - * Retourne le repertoire des anciens schemas - * @return Le repertoire des anciens schemas - */ - String getMappingsDirectory(); - - /** - * Modifie le chemin du dossier des anciens schemas - * @param mappingsDirectory Le chemin du dossier des anciens schemas - */ - void setMappingsDirectory(String mappingsDirectory); - - /** - * Change la version courante - * @param version la version - */ - void setApplicationVersion(String version); - - /** - * Ajoute un callbackhandler pour la migration - * @param callbackHandler le controleur a ajouter - */ - void addMigrationCallbackHandler(MigrationCallbackHandler callbackHandler); - - /** - * Migrate the schema - * - * @return <tt>true</tt> si la migration a ete effectuee et s'est bien passee, <tt>false</tt> sinon - * @throws MigrationServiceException dans le cas ou le schema ne peut pas etre mis a jour - */ - boolean migrateSchema() throws MigrationServiceException; -} Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceDAOHelper.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceDAOHelper.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceDAOHelper.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,291 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - -import java.lang.reflect.Array; -import java.util.Arrays; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; - -@Deprecated -public class MigrationServiceDAOHelper { - - - - public enum MigrationServiceEntityEnum implements TopiaEntityEnum { - - TMSVersion(TMSVersion.class); - /** - * the contract of the entity - */ - protected Class<? extends TopiaEntity> contract; - /** - * the fully qualified name of the implementation of the entity - */ - protected String implementationFQN; - /** - * the implementation class of the entity (will be lazy computed at runtime) - */ - protected Class<? extends TopiaEntity> implementation; - /** - * MigrationServiceEntityEnum : - * @param contract - */ - - MigrationServiceEntityEnum(Class<? extends TopiaEntity > contract) { - this.contract = contract; - this.implementationFQN = contract.getName()+"Impl"; - } - - /** - * getContract : - * @return Class<? extends TopiaEntity> - */ - - public Class<? extends TopiaEntity> getContract() { - return contract; - } - - /** - * getImplementationFQN : - * @return String - */ - - public String getImplementationFQN() { - return implementationFQN; - } - - /** - * setImplementationFQN : - * @param implementationFQN - */ - - public void setImplementationFQN(String implementationFQN) { - this.implementationFQN = implementationFQN; - this.implementation = null; - } - - /** - * accept : - * @param klass - * @return boolean - */ - - public boolean accept(Class<? extends TopiaEntity> klass) { - return MigrationServiceDAOHelper.getContractClass(klass) == contract; - } - - /** - * getImplementation : - * @return Class<? extends TopiaEntity> - */ - - public Class<? extends TopiaEntity> getImplementation() { - if (implementation == null) { - try { - implementation = (Class<? extends TopiaEntity>) Class.forName(implementationFQN); - } catch (ClassNotFoundException e) { - throw new RuntimeException("could not find class " + implementationFQN); - } - } - return implementation; - } - - /** - * valueOf : - * @param entity - * @return MigrationServiceEntityEnum - */ - - public static MigrationServiceEntityEnum valueOf(TopiaEntity entity) { - return valueOf(entity.getClass()); - } - - /** - * valueOf : - * @param klass - * @return MigrationServiceEntityEnum - */ - - public static MigrationServiceEntityEnum valueOf(Class<?> klass) { - if (klass.isInterface()) { - return MigrationServiceEntityEnum.valueOf(klass.getSimpleName()); - } - for (MigrationServiceEntityEnum entityEnum : MigrationServiceEntityEnum.values()) { - if (entityEnum.getContract().isAssignableFrom(klass)) { - //todo check it works for inheritance - return entityEnum; - } - } - throw new IllegalArgumentException("no entity defined for the class " + klass + " in : " + Arrays.toString(MigrationServiceEntityEnum.values())); - } - - - } //MigrationServiceEntityEnum - /** - * MigrationServiceDAOHelper : - */ - - protected MigrationServiceDAOHelper() { } - - /** - * getModelVersion : - * @return String - */ - - public static String getModelVersion() { - return "1"; - } - - /** - * getModelName : - * @return String - */ - - public static String getModelName() { - return "MigrationService"; - } - - /** - * getTMSVersionDAO : - * @param context - * @return TMSVersionDAO - * @throws TopiaException - */ - - public static TMSVersionDAO getTMSVersionDAO(TopiaContext context) throws TopiaException { - TopiaContextImplementor ci = (TopiaContextImplementor) context; - TMSVersionDAO result = (TMSVersionDAO) ci.getDAO(TMSVersion.class); - return result; - } - - /** - * getDAO : - * @param context - * @param klass - * @return <T extends TopiaEntity, D extends TopiaDAO<? super T>> D - * @throws TopiaException - */ - - public static <T extends TopiaEntity, D extends TopiaDAO<? super T>> D getDAO(TopiaContext context, Class<T> klass) throws TopiaException { - TopiaContextImplementor ci = (TopiaContextImplementor) context; - MigrationServiceEntityEnum constant = MigrationServiceEntityEnum.valueOf(klass); - D dao = (D) ci.getDAO(constant.getContract()); - return dao; - } - - /** - * getDAO : - * @param context - * @param entity - * @return <T extends TopiaEntity, D extends TopiaDAO<? super T>> D - * @throws TopiaException - */ - - public static <T extends TopiaEntity, D extends TopiaDAO<? super T>> D getDAO(TopiaContext context, T entity) throws TopiaException { - TopiaContextImplementor ci = (TopiaContextImplementor) context; - MigrationServiceEntityEnum constant = MigrationServiceEntityEnum.valueOf(entity); - D dao = (D) ci.getDAO(constant.getContract()); - return dao; - } - - /** - * getContractClass : - * @param klass - * @return <T extends TopiaEntity> Class<T> - */ - - public static <T extends TopiaEntity> Class<T> getContractClass(Class<T> klass) { - MigrationServiceEntityEnum constant = MigrationServiceEntityEnum.valueOf(klass); - return (Class<T>) constant.getContract(); - } - - /** - * getImplementationClass : - * @param klass - * @return <T extends TopiaEntity> Class<T> - */ - - public static <T extends TopiaEntity> Class<T> getImplementationClass(Class<T> klass) { - MigrationServiceEntityEnum constant = MigrationServiceEntityEnum.valueOf(klass); - return (Class<T>) constant.getImplementation(); - } - - /** - * getContractClasses : - * @return Class<? extends TopiaEntity>[] - */ - - public static Class<? extends TopiaEntity>[] getContractClasses() { - MigrationServiceEntityEnum[] values = MigrationServiceEntityEnum.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getContract(); - } - return result; - } - - /** - * getImplementationClasses : - * @return Class<? extends TopiaEntity>[] - */ - - public static Class<? extends TopiaEntity>[] getImplementationClasses() { - MigrationServiceEntityEnum[] values = MigrationServiceEntityEnum.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getImplementation(); - } - return result; - } - - /** - * getImplementationClassesAsString : - * @return String - */ - - public static String getImplementationClassesAsString() { - StringBuilder buffer = new StringBuilder(); - for (Class<? extends TopiaEntity> aClass : getImplementationClasses()) { - buffer.append(',').append(aClass.getName()); - } - return buffer.substring(1); - } - - /** - * getContracts : - * @return MigrationServiceEntityEnum[] - */ - - public static MigrationServiceEntityEnum[] getContracts() { - return MigrationServiceEntityEnum.values(); - } - - - } //MigrationServiceDAOHelper Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceImpl.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceImpl.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/MigrationServiceImpl.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,555 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.migration; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.migration.callback.MigrationCallbackHandler; -import org.nuiton.topia.migration.callback.MigrationCallbackHandler.MigrationChoice; -import org.nuiton.util.Version; -import org.nuiton.topia.migration.kernel.ConfigurationAdapter; -import org.nuiton.topia.migration.kernel.ConfigurationHelper; -import org.nuiton.topia.migration.kernel.Transformer; -import org.nuiton.util.Resource; -import org.hibernate.cfg.Configuration; - -/** - * MigrationServiceImpl.java - * - * Classe principale du projet. - * - * @author Chatellier Eric - * @author Chevallereau Benjamin - * @author Eon S�bastien - * @author Tr�ve Vincent - * @deprecated since 2.3.4, please use now the simplify service {@link TopiaMigrationEngine} - */ -@Deprecated -public class MigrationServiceImpl implements MigrationService { - - /** - * Nom courant du fichier de configuration. - */ - protected String currentHibernateConfigurationFile; - - /** - * Configuration hibernate courante utilisee par l'application - */ - protected Configuration currentApplicationConfiguration; - - /** - * Chemin du dossier contenant les schema de touts les versions - */ - protected String mappingsDirectory; - - /** - * Version courante de l'application - */ - protected Version currentApplicationVersion; - - /** - * CallbackHandler list - */ - protected List<MigrationCallbackHandler> migrationCallBackHandlers; - - /** - * Logger (common-logging) - */ - private static Log logger = LogFactory.getLog(MigrationServiceImpl.class); - - /** - * Constructeur vide. - */ - public MigrationServiceImpl() { - - // init the configuration file - currentHibernateConfigurationFile = null; - // init configuration - currentApplicationConfiguration = null; - - // init callbask list - migrationCallBackHandlers = new LinkedList<MigrationCallbackHandler>(); - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#getConfigurationFile() - */ - @Override - public String getConfigurationFile() { - return currentHibernateConfigurationFile; - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#setConfigurationFile(java.lang.String) - */ - @Override - public void setConfigurationFile(String hibernateConfigurationFile) { - currentHibernateConfigurationFile = hibernateConfigurationFile; - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#getConfiguration() - */ - @Override - public Configuration getConfiguration() { - return currentApplicationConfiguration; - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#setConfiguration(org.hibernate.cfg.Configuration) - */ - @Override - public void setConfiguration(Configuration configuration) { - currentApplicationConfiguration = configuration; - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#getMappingsDirectory() - */ - @Override - public String getMappingsDirectory() { - return mappingsDirectory; - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#setMappingsDirectory(java.lang.String) - */ - @Override - public void setMappingsDirectory(String mappingsDirectory) { - this.mappingsDirectory = mappingsDirectory; - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#setApplicationVersion(java.lang.String) - */ - @Override - public void setApplicationVersion(String version) { - currentApplicationVersion = new Version(version); - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#addMigrationCallbackHandler(org.nuiton.topia.migration.callback.MigrationCallbackHandler) - */ - @Override - public void addMigrationCallbackHandler( - MigrationCallbackHandler callbackHandler) { - migrationCallBackHandlers.add(callbackHandler); - } - - /** - * Charge la configuration locale si elle n'est pas deja ete fournit - */ - protected void loadApplicationConfiguration() { - - // configuration pas deja fournit - if(currentApplicationConfiguration == null) { - // creation - currentApplicationConfiguration = new Configuration(); - - if (currentHibernateConfigurationFile != null ) { - logger.debug("Loading configuration file : " + currentHibernateConfigurationFile); - - // chargement via l'objet configuration dhibernate - currentApplicationConfiguration.configure(currentHibernateConfigurationFile); - } - else { - logger.debug("Loading configuration file : default hibernate configuration file"); - - // chargement via l'objet configuration dhibernate - currentApplicationConfiguration.configure(); - } - } - else { - // log - logger.debug("Configuration given, nothing to load"); - } - } - - /** - * Verifie si les information indispensable à la migration ont été - * renseignee. - * - * @throws MigrationServiceException - */ - protected void checkInformation() throws MigrationServiceException { - // check that version is set - if(currentApplicationVersion == null) { - throw new MigrationServiceException("No version set"); - } - - // check that shema location is set - if(mappingsDirectory == null) { - throw new MigrationServiceException("No old mapping directory set"); - } - } - - /* (non-Javadoc) - * @see org.nuiton.topia.migration.TopiaMigrationService#migrateSchema() - */ - @Override - public boolean migrateSchema() throws MigrationServiceException { - - // log - logger.info("Starting Topia Migration Service"); - - // check informations - checkInformation(); - - // chargement de la configuration de l'application - loadApplicationConfiguration(); - - // initie un DatabaseManager - // fournit les propietes de connection a la base (properties) - DatabaseManager dbManager = new DatabaseManager(currentApplicationConfiguration.getProperties()); - - // recupere la version de la base - Version vdbVersion = dbManager.getDataBaseVersion(); - - // si la version n'a pas ete trouvee - if(vdbVersion == null) { - // la base dans ce cas n'est pas versionee. - // On dit que la version de la base est 0 - // et les schema de cette version 0 doivent - // etre detenu en local - vdbVersion = Version.VZERO; - - logger.info("Database version not found, so database schema is considered as V0"); - } - - logger.info("Application version : " + currentApplicationVersion.getVersion() + ", database version : " + vdbVersion.getVersion()); - - // tel if migration is needed - boolean bMigrationNeeded = false; - // tel if migration is wanted - MigrationChoice bMigrationWanted = MigrationChoice.NO_MIGRATION; - - // test if schema exist in database... - // if not, the schema must be created - // and it will be created in version this.currentApplicationConfiguration - Configuration vdbConfiguration = getSingleConfiguration(vdbVersion); - vdbConfiguration.setProperties(currentApplicationConfiguration.getProperties()); - bMigrationNeeded = dbManager.isSchemaExist(vdbConfiguration); - if(logger.isDebugEnabled()) { - if(bMigrationNeeded) { - logger.debug("Schema for version " + vdbVersion.getVersion() + " found. Can do migration."); - } else { - logger.debug("Schema for version " + vdbVersion.getVersion() + " not found. No migration needed."); - } - } - - // vdbVersion < currentApplicationVersion - if(bMigrationNeeded && vdbVersion.compareTo(currentApplicationVersion) < 0) { - - logger.info("Database need update"); - - bMigrationNeeded = true; - // ask handler for migration - bMigrationWanted = askHandlerForMigration(dbManager, vdbVersion.getVersion(),currentApplicationVersion.getVersion()); - - logger.info("Handler choose : " + bMigrationWanted); - } - else { - bMigrationNeeded = false; - logger.info("Database is up to date, no migration needed."); - } - - // si la migration doit etre faite - if(bMigrationNeeded && bMigrationWanted.equals(MigrationChoice.MIGRATION)) { - - logger.info("Beginning database migration"); - - // ici, on charge toutes les configuration, entre > vdbVersion et < currentApplicationVersion - Map<Version, Configuration> mVersionAndConfigurationMap = loadIntermediateConfigurations(vdbVersion); - - // vdbVersion mapping has been loaded earlier - // on construit les ConfigurationAdpater - mVersionAndConfigurationMap.put(vdbVersion, vdbConfiguration); - - // Les configurationAdpater pour le kernel - SortedMap<Version,ConfigurationAdapter> smVersionAndConfigurationAdapterMap = new TreeMap<Version,ConfigurationAdapter>(); - - // les configurations sont chargees - // on doit : - // - pour la version vdbVersion, on utilise les tables deja en base - // - pour les autres, creer les tables (suffixees avec la version) - // - creation du schema courant - logger.debug("Set old database for old mappings"); - - // en meme temps, on construit les ConfigurationAdapter pour le noyau - for(Map.Entry<Version,Configuration> entry : mVersionAndConfigurationMap.entrySet()) { - Version vVersion = entry.getKey(); - Configuration cConfiguration = entry.getValue(); - - // la version vdbVersion a deja ses proprietes et ne doit pas etre renommee - if(!vdbVersion.equals(vVersion)) { - //ConfigurationHelper.getConfigurationForVersion(v) - // ne positionne pas les properties parce qu'elle n'en a pas connaissance - // on les met ici - cConfiguration.setProperties(currentApplicationConfiguration.getProperties()); - - // renommage des table - // et creation des schema intermediaires - cConfiguration = dbManager.setRenamedTableSchema(cConfiguration,vVersion); - logger.debug("Creating schema for version : " + vVersion.getVersion()); - dbManager.setApplicationSchemaInDatabase(cConfiguration); - } - - // on construit les ConfigurationAdpater - ConfigurationAdapter cfgAdpater = new ConfigurationAdapter(cConfiguration,vVersion); - smVersionAndConfigurationAdapterMap.put(vVersion, cfgAdpater); - } - - // enfin, il reste la configuration de l'application - // on va instancier le nouveau schema (le creer) - - // on renomme le nom des tables d'abord - currentApplicationConfiguration = dbManager.setRenamedTableSchema(currentApplicationConfiguration, currentApplicationVersion); - - logger.debug("Creating current application schema"); - dbManager.setApplicationSchemaInDatabase(currentApplicationConfiguration); - - ConfigurationAdapter appCfgAdpater = new ConfigurationAdapter(currentApplicationConfiguration, currentApplicationVersion); - smVersionAndConfigurationAdapterMap.put(currentApplicationVersion, appCfgAdpater); - - logger.info("Data migration"); - - // Ici, on a l'ancien schema deja present en base - // les schemas intermediaires creer et vides - // et le nouveau schema cree et vide - // on doit maintenant migrer les donnees - - // execute la transformation - Transformer trans = new Transformer(smVersionAndConfigurationAdapterMap); - - // migrate data - trans.execute(); - - // log - logger.info("Data migrated"); - - logger.debug("Deleting old database"); - - // suppresion des anciennes tables de toutes les configuration, sauf - // currentApplicationVersion - // (elle n'est pas dans mVersionAndConfigurationMap) - for(Configuration cfg : mVersionAndConfigurationMap.values()) { - dbManager.removeTablesFromOldMapping(cfg); - } - - // renommage correct du schema courant - dbManager.renameTables(currentApplicationConfiguration, currentApplicationVersion); - - // il faudrait ici valider les transactions et fermer les sessions - // vmvManager a sa propre gestion des transactions/session - // this.remoteConfiguration doit en avoir ouverte - // this.localConfiguration aussi - - // all done - logger.info("All done, migration complete"); - - // ferme la connexion a la base - dbManager.disconnect(); - } - else { - // ferme la connexion a la base - dbManager.disconnect(); - } - - // manage no migration, but shema version here - if(bMigrationNeeded && - ( bMigrationWanted.equals(MigrationChoice.MIGRATION) || - bMigrationWanted.equals(MigrationChoice.CUSTOM_MIGRATION))) { - - // put version - logger.info("Set application version in database to " + currentApplicationVersion); - - // put version in databse - putVersionInDatabase(currentApplicationConfiguration.getProperties(),currentApplicationVersion,vdbVersion.equals(Version.VZERO)); - } - - // return succes flag - // - no migration needed - // - or migration needed and accepted - return !bMigrationNeeded || (bMigrationNeeded && - ( bMigrationWanted.equals(MigrationChoice.MIGRATION) || - bMigrationWanted.equals(MigrationChoice.CUSTOM_MIGRATION))); - } - - /** - * Put version in database - * - * Single method because, version can be created alone... - * - * @param properties proprietes de connexion - * @param version version - * @param createTable - */ - protected void putVersionInDatabase(Properties properties, Version version, boolean createTable) { - - DatabaseManager dbManager = new DatabaseManager(properties); - - // update version even if database has not been migrated - // only case that database doesn't exist match this - if(createTable) { - // si la base n'etait pas versionnee, la table version n'existe pas - // creation - dbManager.createVersionTable(); - } - - // Changement de la version en base - dbManager.putVersionInDatabase(version); - - dbManager.disconnect(); - - } - - /** - * Ask handler for migration. - * - * Return true if all handler return true, or if there is no handler - * - * @param dbManager - * @param databaseVersion - * @param applicationVersion - * @return <tt>true</tt> or <tt>false</tt> - */ - protected MigrationChoice askHandlerForMigration(DatabaseManager dbManager, - String databaseVersion, String applicationVersion) { - - // true par defaut, s'il n'y a pas de handlers - MigrationChoice result = MigrationChoice.MIGRATION; - - for(MigrationCallbackHandler callback : migrationCallBackHandlers) { - MigrationChoice thiscallbackResult = callback.doMigration(dbManager, - databaseVersion, applicationVersion); - - // hack , si un des callback repond CUSTOM_MIGRATION - // ca sera CUSTOM_MIGRATION - - if(thiscallbackResult == MigrationChoice.NO_MIGRATION) { - if(!result.equals(MigrationChoice.CUSTOM_MIGRATION)) { - result = MigrationChoice.NO_MIGRATION; - } - } else if(thiscallbackResult == MigrationChoice.CUSTOM_MIGRATION) { - result = MigrationChoice.CUSTOM_MIGRATION; - } - else if(thiscallbackResult == MigrationChoice.MIGRATION) { - if(!result.equals(MigrationChoice.CUSTOM_MIGRATION)) { - result = MigrationChoice.MIGRATION; - } - } - } - - return result; - } - - /** - * Charge les configurations de version a partir de vdbVersion "non compris" - * jusqu'a currentApplicationVersion "non compris" - * @param vdbVersion la version de depart - * @return - */ - protected Map<Version, Configuration> loadIntermediateConfigurations(Version vdbVersion) { - // schema des noms de dossier de version - Pattern pattern = Pattern.compile(mappingsDirectory + File.separator + "([0-9]+(\\.[0-9]+)*)"); - - // instancie la map ordonee - Map<Version, Configuration> mVersionAndConfigurationMap = null; - - List<URL> urls = null; - // Don't use File.separator, don't work on windows - // EC-20090714 : fix class loader for maven tomcat launch - urls = Resource.getURLs(".*" + mappingsDirectory + "/.*", (URLClassLoader)MigrationServiceImpl.class.getClassLoader()); - - if (urls != null && urls.size() > 0) { - - mVersionAndConfigurationMap = new HashMap<Version, Configuration>(); - - // ensemble ordonnee des version a charger apres - TreeSet<Version> tsEnsembleVersionACharger = new TreeSet<Version>(); - - for(URL url : urls) { - Matcher matcher = pattern.matcher(url.getFile()); - - if(matcher.find()) { - // group(1) est ce qui match entre le premier niveau de parentheses - String sVersion = matcher.group(1); - //logger.debug("Directory " + fileInIt.getName() + " matches, version = " + sVersion); - - tsEnsembleVersionACharger.add(new Version(sVersion)); - } - } - - // charge les version qui conviennent - for(Version v : tsEnsembleVersionACharger) { - if(v.compareTo(vdbVersion) <= 0) { - logger.debug("No load needed for version " + v.getVersion()); - } - else { - logger.debug("Loading mapping for version " + v.getVersion()); - - Configuration cfgForVersion = getSingleConfiguration(v); - mVersionAndConfigurationMap.put(v, cfgForVersion); - } - } - } - else { - logger.error("No mapping found in classpath '" + mappingsDirectory + "'; can't load old mappings"); - } - - return mVersionAndConfigurationMap; - } - - /** - * Recupere une configuration sur disque pour une version. - * - * @param version version - * @return une configuration hibernate - */ - protected Configuration getSingleConfiguration(Version version) { - // Don't use File.separator, don't work on windows - String mappingVersionDir = mappingsDirectory + "/" + version.getVersion(); - - ConfigurationHelper cfgHelper = ConfigurationHelper.getInstance(); - Configuration cfgForVersion = cfgHelper.getConfigurationInDirectory(mappingVersionDir); - - return cfgForVersion; - } -} Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersion.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersion.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersion.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,46 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - -import org.nuiton.topia.persistence.TopiaEntity; - -@Deprecated -public interface TMSVersion extends TopiaEntity { String VERSION = "version"; - /** - * setVersion : - * @param version La valeur de l'attribut version à positionner. - */ - - void setVersion(String version); - - /** - * getVersion : - * @return String - */ - - String getVersion(); - - -} //TMSVersion Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionAbstract.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionAbstract.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionAbstract.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,143 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.EntityVisitor; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityAbstract; - -@Deprecated -public abstract class TMSVersionAbstract extends TopiaEntityAbstract implements TMSVersion { - - protected String version; - /** - * getVersion : - * @return String - */ - - public String getVersion() { - fireOnPreRead(VERSION, version); - java.lang.String result = this.version; - fireOnPostRead(VERSION, version); - return result; -} - - /** - * accept : - * Envoi via les methodes du visitor l'ensemble des champs de l'entity -avec leur nom, type et valeur. - * @param visitor le visiteur de l'entite. - * @throws TopiaException - */ - - @Override - public void accept(EntityVisitor visitor) throws TopiaException { - visitor.start(this); - visitor.visit(this, VERSION, String.class, version); - visitor.end(this); -} - - /** - * getAggregate : - * @return List<TopiaEntity> - * @throws TopiaException - */ - - @Override - public List<TopiaEntity> getAggregate() throws TopiaException { - List<TopiaEntity> tmp = new ArrayList<TopiaEntity>(); - - // pour tous les attributs rechecher les composites et les class d'asso - // on les ajoute dans tmp - - // on refait un tour sur chaque entity de tmp pour recuperer leur - // composite - List<TopiaEntity> result = new ArrayList<TopiaEntity>(); - for (TopiaEntity entity : tmp) { - result.add(entity); - result.addAll(entity.getAggregate()); - } - - return result; -} - - /** - * getComposite : - * @return List<TopiaEntity> - * @throws TopiaException - */ - - @Override - public List<TopiaEntity> getComposite() throws TopiaException { - List<TopiaEntity> tmp = new ArrayList<TopiaEntity>(); - - // pour tous les attributs rechecher les composites et les class d'asso - // on les ajoute dans tmp - - // on refait un tour sur chaque entity de tmp pour recuperer leur - // composite - List<TopiaEntity> result = new ArrayList<TopiaEntity>(); - for (TopiaEntity entity : tmp) { - if (entity != null) { - result.add(entity); - result.addAll(entity.getComposite()); - } - } - - return result; - } - - /** - * setVersion : - * @param value - */ - - public void setVersion(String value) { - String _oldValue = this.version; - fireOnPreWrite(VERSION, _oldValue, value); - this.version = value; - fireOnPostWrite(VERSION, _oldValue, value); -} - - /** - * toString : - * @return String - */ - - @Override - public String toString() { - String result = new ToStringBuilder(this). - append(VERSION, this.version). - toString(); - return result; -} - - -} //TMSVersionAbstract Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAO.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAO.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAO.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,32 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - - -@Deprecated -public class TMSVersionDAO extends TMSVersionDAOImpl<TMSVersion> { - - -} //TMSVersionDAO Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOAbstract.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOAbstract.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOAbstract.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,112 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaDAOImpl; -import org.nuiton.topia.persistence.TopiaEntity; - -@Deprecated -public abstract class TMSVersionDAOAbstract<E extends TMSVersion> extends TopiaDAOImpl<E> implements TopiaDAO<E> { - - /** - * getEntityClass : - * @return Class<E> - */ - - public Class<E> getEntityClass() { - return (Class<E>)TMSVersion.class; - } - - /** - * delete : - * @param entity - * @throws TopiaException - */ - - public void delete(E entity) throws TopiaException { - super.delete(entity); - } - - /** - * findByVersion : - * Retourne le premier élément trouvé ayant comme valeur pour l'attribut version le paramètre. - * @param v - * @return E - * @throws TopiaException - */ - - public E findByVersion(String v) throws TopiaException { - E result = findByProperty(TMSVersion.VERSION, v); - return result; - } - - /** - * findAllByVersion : - * Retourne les éléments ayant comme valeur pour l'attribut version le paramètre. - * @param v - * @return List<E> - * @throws TopiaException - */ - - public List<E> findAllByVersion(String v) throws TopiaException { - List<E> result = findAllByProperty(TMSVersion.VERSION, v); - return result; - } - - /** - * findUsages : - * @param type - * @param entity - * @return <U extends TopiaEntity> List<U> - * @throws TopiaException - */ - - @Override - public <U extends TopiaEntity> List<U> findUsages(Class<U> type, E entity) throws TopiaException { - return new ArrayList<U>(); - } - - /** - * findAllUsages : - * @param entity - * @return Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> - * @throws TopiaException - */ - - @Override - public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException { - return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(); - } - - -} //TMSVersionDAOAbstract<E extends TMSVersion> Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOImpl.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOImpl.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionDAOImpl.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,32 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - - -@Deprecated -public class TMSVersionDAOImpl<E extends TMSVersion> extends TMSVersionDAOAbstract<E> { - - -} //TMSVersionDAOImpl<E extends TMSVersion> Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionImpl.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionImpl.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TMSVersionImpl.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,32 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.migration; - - -@Deprecated -public class TMSVersionImpl extends TMSVersionAbstract { - - -} //TMSVersionImpl Deleted: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationServiceImpl.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationServiceImpl.java 2010-07-09 14:16:44 UTC (rev 2056) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationServiceImpl.java 2010-07-09 18:30:42 UTC (rev 2057) @@ -1,276 +0,0 @@ -/* - * #%L - * ToPIA :: Service Migration - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.migration; - -import java.io.File; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaRuntimeException; -import org.nuiton.topia.event.TopiaContextEvent; -import org.nuiton.topia.event.TopiaContextListener; -import org.nuiton.topia.event.TopiaTransactionEvent; -import org.nuiton.topia.event.TopiaTransactionVetoable; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.migration.callback.MigrationCallbackHandler; -import org.nuiton.util.Version; -import org.hibernate.cfg.Configuration; - -/** - * TopiaMigrationServiceImpl.java - * - * Classe principale du projet. - * - * @author Chatellier Eric - * @author Chevallereau Benjamin - * @author Eon S�bastien - * @author Tr�ve Vincent - * @deprecated since 2.3.4, please use now the simplify service {@link TopiaMigrationEngine} - */ -@Deprecated -public class TopiaMigrationServiceImpl extends MigrationServiceImpl implements TopiaMigrationService, TopiaContextListener, TopiaTransactionVetoable { - - // log - private final static Log log = LogFactory.getLog(TopiaMigrationServiceImpl.class); - /** - * Nom des proprietes - */ - static public final String MIGRATION_APPLICATION_VERSION = "topia.service.migration.version"; - static public final String MIGRATION_PREVIOUS_MAPPING_DIRECTORY = "topia.service.migration.mappingsdir"; - static public final String MIGRATION_MODEL_NAMES = "topia.service.migration.modelnames"; - static public final String MIGRATION_CALLBACKHANDLERS = "topia.service.migration.callbackhandlers"; - /** - * C'est la meme, mais ca vire des dependances - */ - static final protected String TOPIA_PERSISTENCE_DIRECTORIES = "topia.persistence.directories"; - static final protected String TOPIA_PERSISTENCE_CLASSES = "topia.persistence.classes"; - - public TopiaMigrationServiceImpl() { - } - - @Override - public Class<?>[] getPersistenceClasses() { - return null; - } - - @Override - public String getServiceName() { - return SERVICE_NAME; - } - - @Override - public boolean preInit(TopiaContextImplementor context) { - Properties config = context.getConfig(); - - String mappingdir = config.getProperty(MIGRATION_PREVIOUS_MAPPING_DIRECTORY, null); - String applicationversion = config.getProperty(MIGRATION_APPLICATION_VERSION, null); - - // Creer une nouvelle configuration a partir des fichiers speciaux - // de TOPIA - // il n'y a pas ici de hibernate.cfg.xml - Configuration hibernateConfiguration = new Configuration(); - - // ajout des repertoires contenant les mappings hibernate - String[] dirs = config.getProperty( - TOPIA_PERSISTENCE_DIRECTORIES, "").split(","); - for (String dir : dirs) { - dir = dir.trim(); - if (!"".equals(dir)) { - hibernateConfiguration.addDirectory(new File(dir)); - } - } - - // ajout des classes dites persistentes - String listPersistenceClasses = config.getProperty( - TOPIA_PERSISTENCE_CLASSES, ""); - - String[] classes = listPersistenceClasses.split(","); - for (String classname : classes) { - classname = classname.trim(); - if (!"".equals(classname)) { - Class<?> clazz; - try { - clazz = Class.forName(classname); - hibernateConfiguration.addClass(clazz); - } catch (ClassNotFoundException eee) { - log.error("Persistent class " + classname + " not found", eee); - } - } - } - - Properties prop = new Properties(); - prop.putAll(hibernateConfiguration.getProperties()); - prop.putAll(config); - /*TODO TOPIA_PERSISTENCE_PROPERTIES_FILE - try { - prop.putAll(TopiaUtil.getProperties(config.getProperty( - TOPIA_PERSISTENCE_PROPERTIES_FILE))); - } catch (TopiaNotFoundException e1) { - logger.error( - "Can't found property file",e1); - }*/ - hibernateConfiguration.setProperties(prop); - - // reseigne la configuration qui sera utilisee - setConfiguration(hibernateConfiguration); - - // test version null - if (applicationversion == null) { - log.error("'" + MIGRATION_APPLICATION_VERSION + "' not set."); - } else { - setApplicationVersion(applicationversion); - } - - - // ajout des callbackhandlers - String callbackHandlers = config.getProperty(MIGRATION_CALLBACKHANDLERS, ""); - - String[] tabCallbackHandlers = callbackHandlers.split(","); - for (String callbackHandler : tabCallbackHandlers) { - callbackHandler = callbackHandler.trim(); - if (!"".equals(callbackHandler)) { - Class<?> clazz; - try { - clazz = (Class<?>) Class.forName(callbackHandler); - MigrationCallbackHandler instance = (MigrationCallbackHandler) clazz.newInstance(); - addMigrationCallbackHandler(instance); - } catch (ClassNotFoundException e) { - log.error( - "CallbackHandler Class " + callbackHandler + " not found", e); - } catch (InstantiationException e) { - log.error( - "CallbackHandler class " + callbackHandler + " cannot be instanciated", e); - } catch (IllegalAccessException e) { - log.error( - "CallbackHandler class " + callbackHandler + " cannot be accessed", e); - } - } - } - - // add topia context listener - context.addTopiaContextListener(this); - context.addTopiaTransactionVetoable(this); - - // test mappingdir null - if (mappingdir == null) { - log.error("'" + MIGRATION_PREVIOUS_MAPPING_DIRECTORY + "' not set."); - } else { - - // test applicationversion null - if (applicationversion != null) { - // effectue la migration de tous les modeles - String modelnamesList = config.getProperty( - MIGRATION_MODEL_NAMES, ""); - String[] modelnames = modelnamesList.split(","); - - for (String modelname : modelnames) { - // Don't use File.separator, don't work on windows - setMappingsDirectory(mappingdir + "/" + modelname); - - boolean complete = false; - - try { - // migration - complete = migrateSchema(); - } catch (MigrationServiceException e) { - log.error("Can't migrate schema", e); - } - - if (!complete) { - if (log.isDebugEnabled()) { - log.error("Database migration not complete"); - } - throw new TopiaRuntimeException("Database migration not succesfully ended !"); - } - } - } - } - - return true; - } - - @Override - public boolean postInit(TopiaContextImplementor context) { - return true; - } - - @Override - public void postCreateSchema(TopiaContextEvent event) { - - if (log.isDebugEnabled()) { - log.debug("postCreateSchema event called : put version in database"); - } - - TopiaContextImplementor context = (TopiaContextImplementor) event.getSource(); - - String versionStr = context.getConfig().getProperty(MIGRATION_APPLICATION_VERSION, null); - - Version version = new Version(versionStr); - putVersionInDatabase(context.getConfig(), version, true); - } - - @Override - public void postUpdateSchema(TopiaContextEvent event) { - } - - @Override - public void preCreateSchema(TopiaContextEvent event) { - } - - @Override - public void preUpdateSchema(TopiaContextEvent event) { - } - - @Override - public void preRestoreSchema(TopiaContextEvent event) { - } - - @Override - public void postRestoreSchema(TopiaContextEvent event) { - - if (log.isInfoEnabled()) { - log.info("postRestoreSchema event detected, redo, schema migration"); - } - try { - migrateSchema(); - } catch (MigrationServiceException e) { - if (log.isErrorEnabled()) { - log.error("postRestoreSchema schema migration failed", e); - } - } - } - - @Override - public void beginTransaction(TopiaTransactionEvent event) { - - TopiaContextImplementor context = (TopiaContextImplementor) event.getSource(); - - // add topia context listener - context.addTopiaContextListener(this); - - } -}