Author: chatellier Date: 2008-11-14 11:04:45 +0000 (Fri, 14 Nov 2008) New Revision: 1220 Added: topia-service/tags/topia-service-0.9.1/ topia-service/tags/topia-service-0.9.1/changelog topia-service/tags/topia-service-0.9.1/pom.xml topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml Removed: topia-service/tags/topia-service-0.9.1/changelog topia-service/tags/topia-service-0.9.1/pom.xml topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml Log: [maven-release-plugin] copy for tag topia-service-0.9.1 Copied: topia-service/tags/topia-service-0.9.1 (from rev 1207, topia-service/trunk) Deleted: topia-service/tags/topia-service-0.9.1/changelog =================================================================== --- topia-service/trunk/changelog 2008-11-02 20:08:40 UTC (rev 1207) +++ topia-service/tags/topia-service-0.9.1/changelog 2008-11-14 11:04:45 UTC (rev 1220) @@ -1,28 +0,0 @@ -0.9 - * <chemit> use lutinproject 3.0 + clean pom + use topia 2.0.27 - * <poussin> modif dans service de migration pour permettre a l'app de - faire la migration via le callback - -0.8 - - * 20071120 [chatellier] update topia-service site - * 20071115 [chatellier] apply hibernate code style to open/close session and - transaction - * 20071115 [chatellier] refractoring separate specifique topia service - and real migration code - * 20071115 [chatellier] add schema existance detection support - and dont migrate if there is no table - * 20071111 [chatellier] add support for callback handler - * 20071111 [chatellier] use cascade to calculate dependencies order - * 20071109 [chatellier] change schema creation process to - correct duplicate foreign key creation - * 20071109 [chatellier] add inherit support to calculate dependancies - -0.6 ??? ??? - - * 20070426 [chatellier] use lutinutil.Resources.getUrls() to get mappings - * 20070426 [chatellier] change finder migration to use Class.forName() - * 20070420 [chatellier] remove the 'V' letter in old mapping directories name - * 20070420 [chatellier] add support to look for hibernate mapping in a tree - structure of directories - * 20070418 [chatellier] add migration service \ No newline at end of file Copied: topia-service/tags/topia-service-0.9.1/changelog (from rev 1218, topia-service/trunk/changelog) =================================================================== --- topia-service/tags/topia-service-0.9.1/changelog (rev 0) +++ topia-service/tags/topia-service-0.9.1/changelog 2008-11-14 11:04:45 UTC (rev 1220) @@ -0,0 +1,31 @@ +0.9.1 + * [chatellier] Correction d'un bug de recherche de mapping sous windows (\) + +0.9 + * <chemit> use lutinproject 3.0 + clean pom + use topia 2.0.27 + * <poussin> modif dans service de migration pour permettre a l'app de + faire la migration via le callback + +0.8 + + * 20071120 [chatellier] update topia-service site + * 20071115 [chatellier] apply hibernate code style to open/close session and + transaction + * 20071115 [chatellier] refractoring separate specifique topia service + and real migration code + * 20071115 [chatellier] add schema existance detection support + and dont migrate if there is no table + * 20071111 [chatellier] add support for callback handler + * 20071111 [chatellier] use cascade to calculate dependencies order + * 20071109 [chatellier] change schema creation process to + correct duplicate foreign key creation + * 20071109 [chatellier] add inherit support to calculate dependancies + +0.6 ??? ??? + + * 20070426 [chatellier] use lutinutil.Resources.getUrls() to get mappings + * 20070426 [chatellier] change finder migration to use Class.forName() + * 20070420 [chatellier] remove the 'V' letter in old mapping directories name + * 20070420 [chatellier] add support to look for hibernate mapping in a tree + structure of directories + * 20070418 [chatellier] add migration service \ No newline at end of file Deleted: topia-service/tags/topia-service-0.9.1/pom.xml =================================================================== --- topia-service/trunk/pom.xml 2008-11-02 20:08:40 UTC (rev 1207) +++ topia-service/tags/topia-service-0.9.1/pom.xml 2008-11-14 11:04:45 UTC (rev 1220) @@ -1,143 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - - <modelVersion>4.0.0</modelVersion> - - <!-- ************************************************************* --> - <!-- *** POM Relationships *************************************** --> - <!-- ************************************************************* --> - <parent> - <groupId>org.codelutin</groupId> - <artifactId>lutinproject</artifactId> - <version>3.0</version> - </parent> - - <artifactId>topia-service</artifactId> - - <dependencies> - - <!--Compile--> - <dependency> - <groupId>org.codelutin</groupId> - <artifactId>topia</artifactId> - <version>${topia.version}</version> - <scope>compile</scope> - </dependency> - - <dependency> - <groupId>org.codelutin</groupId> - <artifactId>lutinutil</artifactId> - <version>0.31</version> - <scope>compile</scope> - </dependency> - - <dependency> - <groupId>org.apache.lucene</groupId> - <artifactId>lucene-core</artifactId> - <version>2.3.2</version> - <scope>compile</scope> - </dependency> - - <!--BD H2 pour le test--> - <dependency> - <groupId>com.h2database</groupId> - <artifactId>h2</artifactId> - <version>1.0.79</version> - <scope>test</scope> - </dependency> - - </dependencies> - - <!-- ************************************************************* --> - <!-- *** Project Information ************************************* --> - <!-- ************************************************************* --> - - <name>ToPIA Service</name> - <version>0.10-SNAPSHOT</version> - <description> - ToPIA Service est une librairie de ToPIA pour la gestion de sercices. - </description> - <inceptionYear>2006</inceptionYear> - - <!-- ************************************************************* --> - <!-- *** Build Settings ****************************************** --> - <!-- ************************************************************* --> - - <packaging>jar</packaging> - - <properties> - <!-- id du projet du labs --> - <labs.id>21</labs.id> - - <!-- nom du projet sur le labs --> - <labs.project>topia</labs.project> - - <!-- topia version --> - <topia.version>2.0.27</topia.version> - - <!-- Test FIXME : should be ok --> - <maven.test.skip>true</maven.test.skip> - </properties> - - <build> - - <plugins> - - <plugin> - <groupId>org.codelutin</groupId> - <artifactId>maven-generator-plugin</artifactId> - <version>0.60</version> - <executions> - <execution> - <phase>process-sources</phase> - <!--Configuration of model generator--> - <configuration> - <addCompileDirectory>true</addCompileDirectory> - <srcDirZuml>${maven.src.dir}/main/xmi</srcDirZuml> - <srcXmiDest>${maven.gen.dir}/xmi/</srcXmiDest> - <srcGenDest>${maven.gen.dir}/objectmodel/</srcGenDest> - <includes>**/*.objectmodel</includes> - <templates>org.codelutin.topia.generator.TopiaMetaGenerator</templates> - <destDirGen>${maven.gen.dir}/java</destDirGen> - <defaultPackage>org.codelutin.topia</defaultPackage> - <extractedPackages>org.codelutin.topia.tass</extractedPackages> - - <copyVersionDir>src/main/resources/oldmappings/%MODELNAME%</copyVersionDir> - <copyVersionFiles>**/*.hbm.xml</copyVersionFiles> - <copyOverwrite>true</copyOverwrite> - </configuration> - <goals> - <goal>zargo2xmi</goal> - <goal>xmi2objectmodel</goal> - <goal>generate</goal> - <goal>copyVersionFiles</goal> - </goals> - </execution> - </executions> - <dependencies> - <dependency> - <groupId>org.codelutin</groupId> - <artifactId>topia</artifactId> - <version>${topia.version}</version> - <scope>compile</scope> - </dependency> - </dependencies> - </plugin> - - <plugin> - <artifactId>maven-javadoc-plugin</artifactId> - </plugin> - - </plugins> - </build> - - <!-- ************************************************************* --> - <!-- *** Build Environment ************************************** --> - <!-- ************************************************************* --> - <scm> - <connection>${maven.scm.connection}</connection> - <developerConnection>${maven.scm.developerConnection}</developerConnection> - <url>${maven.scm.url}</url> - </scm> - -</project> Copied: topia-service/tags/topia-service-0.9.1/pom.xml (from rev 1219, topia-service/trunk/pom.xml) =================================================================== --- topia-service/tags/topia-service-0.9.1/pom.xml (rev 0) +++ topia-service/tags/topia-service-0.9.1/pom.xml 2008-11-14 11:04:45 UTC (rev 1220) @@ -0,0 +1,150 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <!-- ************************************************************* --> + <!-- *** POM Relationships *************************************** --> + <!-- ************************************************************* --> + <parent> + <groupId>org.codelutin</groupId> + <artifactId>lutinproject</artifactId> + <version>3.0</version> + </parent> + + <artifactId>topia-service</artifactId> + + <dependencies> + + <!--Compile--> + <dependency> + <groupId>org.codelutin</groupId> + <artifactId>topia</artifactId> + <version>${topia.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.codelutin</groupId> + <artifactId>lutinutil</artifactId> + <version>0.31</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.lucene</groupId> + <artifactId>lucene-core</artifactId> + <version>2.3.2</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>commons-lang</groupId> + <artifactId>commons-lang</artifactId> + <version>2.4</version> + <scope>compile</scope> + </dependency> + + <!--BD H2 pour le test--> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <version>1.0.79</version> + <scope>test</scope> + </dependency> + + </dependencies> + + <!-- ************************************************************* --> + <!-- *** Project Information ************************************* --> + <!-- ************************************************************* --> + + <name>ToPIA Service</name> + <version>0.9.1</version> + <description> + ToPIA Service est une librairie de ToPIA pour la gestion de sercices. + </description> + <inceptionYear>2006</inceptionYear> + + <!-- ************************************************************* --> + <!-- *** Build Settings ****************************************** --> + <!-- ************************************************************* --> + + <packaging>jar</packaging> + + <properties> + <!-- id du projet du labs --> + <labs.id>21</labs.id> + + <!-- nom du projet sur le labs --> + <labs.project>topia</labs.project> + + <!-- topia version --> + <topia.version>2.0.28</topia.version> + + <!-- Test FIXME : should be ok --> + <maven.test.skip>true</maven.test.skip> + </properties> + + <build> + + <plugins> + + <plugin> + <groupId>org.codelutin</groupId> + <artifactId>maven-generator-plugin</artifactId> + <version>0.61</version> + <executions> + <execution> + <phase>process-sources</phase> + <!--Configuration of model generator--> + <configuration> + <addCompileDirectory>true</addCompileDirectory> + <srcDirZuml>${maven.src.dir}/main/xmi</srcDirZuml> + <srcXmiDest>${maven.gen.dir}/xmi/</srcXmiDest> + <srcGenDest>${maven.gen.dir}/objectmodel/</srcGenDest> + <includes>**/*.objectmodel</includes> + <templates>org.codelutin.topia.generator.TopiaMetaGenerator</templates> + <destDirGen>${maven.gen.dir}/java</destDirGen> + <defaultPackage>org.codelutin.topia</defaultPackage> + <extractedPackages>org.codelutin.topia.tass</extractedPackages> + + <copyVersionDir>src/main/resources/oldmappings/%MODELNAME%</copyVersionDir> + <copyVersionFiles>**/*.hbm.xml</copyVersionFiles> + <copyOverwrite>true</copyOverwrite> + </configuration> + <goals> + <goal>zargo2xmi</goal> + <goal>xmi2objectmodel</goal> + <goal>generate</goal> + <goal>copyVersionFiles</goal> + </goals> + </execution> + </executions> + <dependencies> + <dependency> + <groupId>org.codelutin</groupId> + <artifactId>topia</artifactId> + <version>${topia.version}</version> + <scope>compile</scope> + </dependency> + </dependencies> + </plugin> + + <plugin> + <artifactId>maven-javadoc-plugin</artifactId> + </plugin> + + </plugins> + </build> + + <!-- ************************************************************* --> + <!-- *** Build Environment ************************************** --> + <!-- ************************************************************* --> + <scm> + <connection>scm:svn:svn://anonymous@labs.libre-entreprise.org/svnroot/topia/topia-service/tags/topia-service-0.9.1</connection> + <developerConnection>scm:svn:svn+ssh://chatellier@labs.libre-entreprise.org/svnroot/topia/topia-service/tags/topia-service-0.9.1</developerConnection> + <url>http://labs.libre-entreprise.org/plugins/scmsvn/viewcvs.php/topia-service/tags/topia-service-0.9.1?root=topia</url> + </scm> + +</project> Deleted: topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java =================================================================== --- topia-service/trunk/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java 2008-11-02 20:08:40 UTC (rev 1207) +++ topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java 2008-11-14 11:04:45 UTC (rev 1220) @@ -1,531 +0,0 @@ -/* *##% ToPIA Service - * Copyright (C) 2006 - 2008 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>. ##%*/ - -package org.codelutin.topia.migration; - -import java.io.File; -import java.net.URL; -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.codelutin.topia.migration.callback.MigrationCallbackHandler; -import org.codelutin.topia.migration.callback.MigrationCallbackHandler.MigrationChoice; -import org.codelutin.topia.migration.common.Version; -import org.codelutin.topia.migration.kernel.ConfigurationAdapter; -import org.codelutin.topia.migration.kernel.ConfigurationHelper; -import org.codelutin.topia.migration.kernel.Transformer; -import org.codelutin.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 - * @version $Revision$ - * - * Last update : $Date$ - */ -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() { - super(); - - // init the configuration file - currentHibernateConfigurationFile = null; - // init configuration - currentApplicationConfiguration = null; - - // init callbask list - migrationCallBackHandlers = new LinkedList<MigrationCallbackHandler>(); - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#getConfigurationFile() - */ - public String getConfigurationFile() { - return currentHibernateConfigurationFile; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#setConfigurationFile(java.lang.String) - */ - public void setConfigurationFile(String hibernateConfigurationFile) { - this.currentHibernateConfigurationFile = hibernateConfigurationFile; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#getConfiguration() - */ - public Configuration getConfiguration() { - return currentApplicationConfiguration; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#setConfiguration(org.hibernate.cfg.Configuration) - */ - public void setConfiguration(Configuration configuration) { - this.currentApplicationConfiguration = configuration; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#getMappingsDirectory() - */ - public String getMappingsDirectory() { - return mappingsDirectory; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#setMappingsDirectory(java.lang.String) - */ - public void setMappingsDirectory(String mappingsDirectory) { - this.mappingsDirectory = mappingsDirectory; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#setApplicationVersion(java.lang.String) - */ - public void setApplicationVersion(String version) { - currentApplicationVersion = new Version(version); - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#addMigrationCallbackHandler(org.codelutin.topia.migration.callback.MigrationCallbackHandler) - */ - 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(this.currentApplicationConfiguration == null) { - // creation - this.currentApplicationConfiguration = new Configuration(); - - if ( this.currentHibernateConfigurationFile != null ) { - logger.debug("Loading configuration file : " + this.currentHibernateConfigurationFile); - - // chargement via l'objet configuration dhibernate - currentApplicationConfiguration.configure(this.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(this.currentApplicationVersion == null) { - throw new MigrationServiceException("No version set"); - } - - // check that shema location is set - if(this.mappingsDirectory == null) { - throw new MigrationServiceException("No old mapping directory set"); - } - } - - /* (non-Javadoc) - * @see org.codelutin.topia.migration.TopiaMigrationService#migrateSchema() - */ - 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(this.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(this.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 - this.currentApplicationConfiguration = dbManager.setRenamedTableSchema(this.currentApplicationConfiguration,this.currentApplicationVersion); - - logger.debug("Creating current application schema"); - dbManager.setApplicationSchemaInDatabase(this.currentApplicationConfiguration); - - ConfigurationAdapter appCfgAdpater = new ConfigurationAdapter(this.currentApplicationConfiguration,this.currentApplicationVersion); - smVersionAndConfigurationAdapterMap.put(this.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(this.currentApplicationConfiguration, this.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 - */ - 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 - * - * @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 - */ - protected Map<Version, Configuration> loadIntermediateConfigurations(Version vdbVersion) { - // schema des noms de dossier de version - final Pattern pattern = Pattern.compile(mappingsDirectory + File.separator + "([0-9]+(\\.[0-9]+)*)"); - - // instancie la map ordonee - Map<Version, Configuration> mVersionAndConfigurationMap = null; - - List<URL> urls = null; - urls = Resource.getURLs(".*" + mappingsDirectory + File.separator + ".*"); - - 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) { - String mappingVersionDir = mappingsDirectory + File.separator + version.getVersion(); - - ConfigurationHelper cfgHelper = ConfigurationHelper.getInstance(); - Configuration cfgForVersion = cfgHelper.getConfigurationInDirectory(mappingVersionDir); - - return cfgForVersion; - } -} Copied: topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java (from rev 1218, topia-service/trunk/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java) =================================================================== --- topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java (rev 0) +++ topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/MigrationServiceImpl.java 2008-11-14 11:04:45 UTC (rev 1220) @@ -0,0 +1,533 @@ +/* *##% ToPIA Service + * Copyright (C) 2006 - 2008 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>. ##%*/ + +package org.codelutin.topia.migration; + +import java.io.File; +import java.net.URL; +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.codelutin.topia.migration.callback.MigrationCallbackHandler; +import org.codelutin.topia.migration.callback.MigrationCallbackHandler.MigrationChoice; +import org.codelutin.topia.migration.common.Version; +import org.codelutin.topia.migration.kernel.ConfigurationAdapter; +import org.codelutin.topia.migration.kernel.ConfigurationHelper; +import org.codelutin.topia.migration.kernel.Transformer; +import org.codelutin.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 + * @version $Revision$ + * + * Last update : $Date$ + */ +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() { + super(); + + // init the configuration file + currentHibernateConfigurationFile = null; + // init configuration + currentApplicationConfiguration = null; + + // init callbask list + migrationCallBackHandlers = new LinkedList<MigrationCallbackHandler>(); + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#getConfigurationFile() + */ + public String getConfigurationFile() { + return currentHibernateConfigurationFile; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#setConfigurationFile(java.lang.String) + */ + public void setConfigurationFile(String hibernateConfigurationFile) { + this.currentHibernateConfigurationFile = hibernateConfigurationFile; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#getConfiguration() + */ + public Configuration getConfiguration() { + return currentApplicationConfiguration; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#setConfiguration(org.hibernate.cfg.Configuration) + */ + public void setConfiguration(Configuration configuration) { + this.currentApplicationConfiguration = configuration; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#getMappingsDirectory() + */ + public String getMappingsDirectory() { + return mappingsDirectory; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#setMappingsDirectory(java.lang.String) + */ + public void setMappingsDirectory(String mappingsDirectory) { + this.mappingsDirectory = mappingsDirectory; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#setApplicationVersion(java.lang.String) + */ + public void setApplicationVersion(String version) { + currentApplicationVersion = new Version(version); + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#addMigrationCallbackHandler(org.codelutin.topia.migration.callback.MigrationCallbackHandler) + */ + 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(this.currentApplicationConfiguration == null) { + // creation + this.currentApplicationConfiguration = new Configuration(); + + if ( this.currentHibernateConfigurationFile != null ) { + logger.debug("Loading configuration file : " + this.currentHibernateConfigurationFile); + + // chargement via l'objet configuration dhibernate + currentApplicationConfiguration.configure(this.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(this.currentApplicationVersion == null) { + throw new MigrationServiceException("No version set"); + } + + // check that shema location is set + if(this.mappingsDirectory == null) { + throw new MigrationServiceException("No old mapping directory set"); + } + } + + /* (non-Javadoc) + * @see org.codelutin.topia.migration.TopiaMigrationService#migrateSchema() + */ + 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(this.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(this.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 + this.currentApplicationConfiguration = dbManager.setRenamedTableSchema(this.currentApplicationConfiguration,this.currentApplicationVersion); + + logger.debug("Creating current application schema"); + dbManager.setApplicationSchemaInDatabase(this.currentApplicationConfiguration); + + ConfigurationAdapter appCfgAdpater = new ConfigurationAdapter(this.currentApplicationConfiguration,this.currentApplicationVersion); + smVersionAndConfigurationAdapterMap.put(this.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(this.currentApplicationConfiguration, this.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 + */ + 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 + * + * @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 + */ + protected Map<Version, Configuration> loadIntermediateConfigurations(Version vdbVersion) { + // schema des noms de dossier de version + final 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 + urls = Resource.getURLs(".*" + mappingsDirectory + "/.*"); + + 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: topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java =================================================================== --- topia-service/trunk/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java 2008-11-02 20:08:40 UTC (rev 1207) +++ topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java 2008-11-14 11:04:45 UTC (rev 1220) @@ -1,310 +0,0 @@ -/* *##% ToPIA Service - * Copyright (C) 2006 - 2008 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>. ##%*/ - -package org.codelutin.topia.migration; - -import java.io.File; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codelutin.topia.TopiaRuntimeException; -import org.codelutin.topia.event.TopiaContextEvent; -import org.codelutin.topia.event.TopiaTransactionEvent; -import org.codelutin.topia.framework.TopiaContextImplementor; -import org.codelutin.topia.migration.callback.MigrationCallbackHandler; -import org.codelutin.topia.migration.common.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 - * @version $Revision$ - * - * Last update : $Date$ - */ -public class TopiaMigrationServiceImpl extends MigrationServiceImpl implements TopiaMigrationService { - - // 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"; - - /** - * Logger (common-logging) - */ - private static Log logger = LogFactory.getLog(TopiaMigrationServiceImpl.class); - - /** - * Constructeur vide. - */ - public TopiaMigrationServiceImpl() { - super(); - } - - /* (non-Javadoc) - * @see org.codelutin.topia.framework.TopiaService#getPersistenceClasses() - */ - public Class [] getPersistenceClasses() { - return null; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.framework.TopiaService#getServiceName() - */ - public String getServiceName() { - return TopiaMigrationService.SERVICE_NAME; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.framework.TopiaService#preInit(org.codelutin.topia.framework.TopiaContextImplementor) - */ - 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) { - logger.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 - this.setConfiguration(hibernateConfiguration); - - // test version null - if(applicationversion == null) { - logger.error("'" + MIGRATION_APPLICATION_VERSION +"' not set."); - } - else { - this.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<MigrationCallbackHandler> clazz; - try { - clazz = (Class<MigrationCallbackHandler>)Class.forName(callbackHandler); - MigrationCallbackHandler instance = clazz.newInstance(); - addMigrationCallbackHandler(instance); - } catch (ClassNotFoundException e) { - logger.error( - "CallbackHandler Class " + callbackHandler - + " not found",e); - } catch (InstantiationException e) { - logger.error( - "CallbackHandler class " + callbackHandler - + " cannot be instanciated",e); - } catch (IllegalAccessException e) { - logger.error( - "CallbackHandler class " + callbackHandler - + " cannot be accessed",e); - } - } - } - - // add topia context listener - context.addTopiaContextListener(this); - context.addTopiaTransactionVetoable(this); - - // test mappingdir null - if(mappingdir == null) { - logger.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) { - this.setMappingsDirectory(mappingdir + File.separator + modelname); - - boolean complete = false; - - try { - // migration - complete = migrateSchema(); - } - catch(MigrationServiceException e) { - logger.error("Can't migrate schema", e); - } - - - if(!complete) { - if(logger.isDebugEnabled()) { - logger.error("Database migration not complete"); - } - throw new TopiaRuntimeException("Database migration not succesfully ended !"); - } - } - } - } - - return true; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.framework.TopiaService#postInit(org.codelutin.topia.framework.TopiaContextImplementor) - */ - public boolean postInit(TopiaContextImplementor context) { - return true; - } - - /* (non-Javadoc) - * @see org.codelutin.topia.event.TopiaContextListener#postCreateSchema(org.codelutin.topia.event.TopiaContextEvent) - */ - public void postCreateSchema(TopiaContextEvent event) { - - if(logger.isDebugEnabled()) { - logger.debug("postCreateSchema event called : put version in database"); - } - - TopiaContextImplementor context = (TopiaContextImplementor)event.getSource(); - - Version version = new Version(context.getConfig().getProperty(MIGRATION_APPLICATION_VERSION, null)); - putVersionInDatabase(context.getConfig(), version , true); - } - - /* (non-Javadoc) - * @see org.codelutin.topia.event.TopiaContextListener#postUpdateSchema(org.codelutin.topia.event.TopiaContextEvent) - */ - public void postUpdateSchema(TopiaContextEvent event) { - - } - - /* (non-Javadoc) - * @see org.codelutin.topia.event.TopiaContextListener#preCreateSchema(org.codelutin.topia.event.TopiaContextEvent) - */ - public void preCreateSchema(TopiaContextEvent event) { - - } - - /* (non-Javadoc) - * @see org.codelutin.topia.event.TopiaContextListener#preUpdateSchema(org.codelutin.topia.event.TopiaContextEvent) - */ - public void preUpdateSchema(TopiaContextEvent event) { - - } - - /* - * @see org.codelutin.topia.event.TopiaContextListener#preRestoreSchema(org.codelutin.topia.event.TopiaContextEvent) - */ - public void preRestoreSchema(TopiaContextEvent event) { - - } - - /* - * @see org.codelutin.topia.event.TopiaContextListener#postRestoreSchema(org.codelutin.topia.event.TopiaContextEvent) - */ - 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); - } - } - } - - /* - * @see org.codelutin.topia.event.TopiaTransactionVetoable#beginTransaction(org.codelutin.topia.event.TopiaTransactionEvent) - */ - public void beginTransaction(TopiaTransactionEvent event) { - - TopiaContextImplementor context = (TopiaContextImplementor)event.getSource(); - - // add topia context listener - context.addTopiaContextListener(this); - - } -} Copied: topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java (from rev 1218, topia-service/trunk/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java) =================================================================== --- topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java (rev 0) +++ topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/TopiaMigrationServiceImpl.java 2008-11-14 11:04:45 UTC (rev 1220) @@ -0,0 +1,311 @@ +/* *##% ToPIA Service + * Copyright (C) 2006 - 2008 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>. ##%*/ + +package org.codelutin.topia.migration; + +import java.io.File; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.topia.TopiaRuntimeException; +import org.codelutin.topia.event.TopiaContextEvent; +import org.codelutin.topia.event.TopiaTransactionEvent; +import org.codelutin.topia.framework.TopiaContextImplementor; +import org.codelutin.topia.migration.callback.MigrationCallbackHandler; +import org.codelutin.topia.migration.common.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 + * @version $Revision$ + * + * Last update : $Date$ + */ +public class TopiaMigrationServiceImpl extends MigrationServiceImpl implements TopiaMigrationService { + + // 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"; + + /** + * Logger (common-logging) + */ + private static Log logger = LogFactory.getLog(TopiaMigrationServiceImpl.class); + + /** + * Constructeur vide. + */ + public TopiaMigrationServiceImpl() { + super(); + } + + /* (non-Javadoc) + * @see org.codelutin.topia.framework.TopiaService#getPersistenceClasses() + */ + public Class [] getPersistenceClasses() { + return null; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.framework.TopiaService#getServiceName() + */ + public String getServiceName() { + return TopiaMigrationService.SERVICE_NAME; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.framework.TopiaService#preInit(org.codelutin.topia.framework.TopiaContextImplementor) + */ + 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) { + logger.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 + this.setConfiguration(hibernateConfiguration); + + // test version null + if(applicationversion == null) { + logger.error("'" + MIGRATION_APPLICATION_VERSION +"' not set."); + } + else { + this.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<MigrationCallbackHandler> clazz; + try { + clazz = (Class<MigrationCallbackHandler>)Class.forName(callbackHandler); + MigrationCallbackHandler instance = clazz.newInstance(); + addMigrationCallbackHandler(instance); + } catch (ClassNotFoundException e) { + logger.error( + "CallbackHandler Class " + callbackHandler + + " not found",e); + } catch (InstantiationException e) { + logger.error( + "CallbackHandler class " + callbackHandler + + " cannot be instanciated",e); + } catch (IllegalAccessException e) { + logger.error( + "CallbackHandler class " + callbackHandler + + " cannot be accessed",e); + } + } + } + + // add topia context listener + context.addTopiaContextListener(this); + context.addTopiaTransactionVetoable(this); + + // test mappingdir null + if(mappingdir == null) { + logger.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 + this.setMappingsDirectory(mappingdir + "/" + modelname); + + boolean complete = false; + + try { + // migration + complete = migrateSchema(); + } + catch(MigrationServiceException e) { + logger.error("Can't migrate schema", e); + } + + + if(!complete) { + if(logger.isDebugEnabled()) { + logger.error("Database migration not complete"); + } + throw new TopiaRuntimeException("Database migration not succesfully ended !"); + } + } + } + } + + return true; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.framework.TopiaService#postInit(org.codelutin.topia.framework.TopiaContextImplementor) + */ + public boolean postInit(TopiaContextImplementor context) { + return true; + } + + /* (non-Javadoc) + * @see org.codelutin.topia.event.TopiaContextListener#postCreateSchema(org.codelutin.topia.event.TopiaContextEvent) + */ + public void postCreateSchema(TopiaContextEvent event) { + + if(logger.isDebugEnabled()) { + logger.debug("postCreateSchema event called : put version in database"); + } + + TopiaContextImplementor context = (TopiaContextImplementor)event.getSource(); + + Version version = new Version(context.getConfig().getProperty(MIGRATION_APPLICATION_VERSION, null)); + putVersionInDatabase(context.getConfig(), version , true); + } + + /* (non-Javadoc) + * @see org.codelutin.topia.event.TopiaContextListener#postUpdateSchema(org.codelutin.topia.event.TopiaContextEvent) + */ + public void postUpdateSchema(TopiaContextEvent event) { + + } + + /* (non-Javadoc) + * @see org.codelutin.topia.event.TopiaContextListener#preCreateSchema(org.codelutin.topia.event.TopiaContextEvent) + */ + public void preCreateSchema(TopiaContextEvent event) { + + } + + /* (non-Javadoc) + * @see org.codelutin.topia.event.TopiaContextListener#preUpdateSchema(org.codelutin.topia.event.TopiaContextEvent) + */ + public void preUpdateSchema(TopiaContextEvent event) { + + } + + /* + * @see org.codelutin.topia.event.TopiaContextListener#preRestoreSchema(org.codelutin.topia.event.TopiaContextEvent) + */ + public void preRestoreSchema(TopiaContextEvent event) { + + } + + /* + * @see org.codelutin.topia.event.TopiaContextListener#postRestoreSchema(org.codelutin.topia.event.TopiaContextEvent) + */ + 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); + } + } + } + + /* + * @see org.codelutin.topia.event.TopiaTransactionVetoable#beginTransaction(org.codelutin.topia.event.TopiaTransactionEvent) + */ + public void beginTransaction(TopiaTransactionEvent event) { + + TopiaContextImplementor context = (TopiaContextImplementor)event.getSource(); + + // add topia context listener + context.addTopiaContextListener(this); + + } +} Deleted: topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java =================================================================== --- topia-service/trunk/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java 2008-11-02 20:08:40 UTC (rev 1207) +++ topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java 2008-11-14 11:04:45 UTC (rev 1220) @@ -1,261 +0,0 @@ -/* *##% ToPIA Service - * Copyright (C) 2006 - 2008 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>. ##%*/ - -package org.codelutin.topia.migration.kernel; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.net.URL; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codelutin.util.Resource; -import org.dom4j.Attribute; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.hibernate.cfg.Configuration; -import org.hibernate.util.DTDEntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * ConfigurationHelper.java - * - * Charge des configuration en mode "dynamic-map". - * - * @author Chatellier Eric - * @author Chevallereau Benjamin - * @author Eon Sébastien - * @author Trève Vincent - * @version $Revision$ - * - * Last update : $Date$ - */ -public class ConfigurationHelper { - - /** - * Logger (common-logging) - */ - private static Log logger = LogFactory.getLog(ConfigurationHelper.class); - - /** - * Single instance - */ - protected static ConfigurationHelper instance = new ConfigurationHelper(); - - /** - * Constructeur - */ - protected ConfigurationHelper() {} - - /** - * Get single instance - */ - public static ConfigurationHelper getInstance() { - return instance; - } - - /** - * Retourne une configuration correspondant au chargement - * de tous les mappings du dossier specifie. - * - * Ici, on pourrait utiliser configuration.addDirectory - * mais on modifie les mappings version "entity-map" - * - * @param pathDirectory Le dossier ou se trouvent les mappings (contient - * la version souhaitee) - * @return La configuration associee - */ - public Configuration getConfigurationInDirectory(String pathDirectory) { - - // schema des noms de fichier a lire - final String regexFilename = ".*\\.hbm\\.xml"; - - // nouvelle configuration en retour - Configuration configuration = null; - - // FIXME faire deux cas ici. Soit on est sur le filesystem comme deja - // code. Soit on est dans un jar (a faire). Dans tous les cas, il faut - // ensuite travailler avec des URLs et non pas des Strings. - // - // si mappingDir n'est pas un repertoire, rechercher avec - // ResourceUtil.getUrls(String pattern): List<URL> ou equivalent. - - // mappingDir est toujours dans le classpath et Resource.getURLs doit - // le trouver, donc que ce soit un dossier ou un jar ici importe peu - - List<URL> urls = null; - urls = Resource.getURLs(".*" + pathDirectory + File.separator + regexFilename); - - logger.debug("Loading mappings in " + pathDirectory); - - if (urls != null && urls.size() > 0) { - // s'il y a des fichier a charger - configuration = new Configuration(); - - for(URL url : urls) { - String xmlmapping = ConfigurationHelper.getEntityMappingFromFile(url); - - // lit le fichier avec lutin xml - org.w3c.dom.Document domDoc = getDocumentResolvedByHibernate(xmlmapping); - - configuration.addDocument(domDoc); - - logger.debug("Local mapping added : " + url); - } - } - else { - logger.error("No mappings files found in directory " + pathDirectory); - } - - return configuration; - } - - /** - * Charge un fichier et retourne un mapping valide pour etre manipule via les map - * - * @param fichier le nom du fichier - * @return le mapping en forme xml - */ - protected static String getEntityMappingFromFile(URL fichier) { - String sXml = null; - - // charge le document en representation dom4j - Document domDoc = getDom4jDocument(fichier); - - // transforme en entity - domDoc = transformAsValidHibernateMapConfigFile(domDoc); - - // transforme le document en chaine - sXml = domDoc.asXML(); - - return sXml; - } - - /** - * Transforme en ajoutant des info de mappings. - * - * Ajoute un entity-name avec la valeur de name. - * Supprime name , sinon hibernate l'utilise encore. - * - * @param dom4jdoc le document - * @return un document mapping entite - */ - protected static Document transformAsValidHibernateMapConfigFile(Document dom4jdoc) { - Element rootElem = dom4jdoc.getRootElement(); - - List<Element> childElements = rootElem.elements("class"); - - for(Element eChild : childElements) { - - // suivant si l'attribut est deja la ou pas - String entityname = eChild.attributeValue("entity-name"); - String odlClassName = eChild.attributeValue("name"); - - if(entityname == null) { - // on l'ajoute alors - eChild.addAttribute("entity-name", odlClassName); - } - - // et supprime l'attribut name (sinon, hibernate continue de l'utiliser) - Attribute attName = eChild.attribute("name"); - if(attName != null) { - eChild.remove(attName); - } - } - - return dom4jdoc; - } - - /** - * Charge un document dom4j - * - * @param fichier le nom du fichier - * @return un document dom4j - */ - protected static Document getDom4jDocument(URL fichier) { - SAXReader reader = new SAXReader(); - reader.setValidation(false); - //DTDEntityResolver = celui d'hibernate - reader.setEntityResolver(new DTDEntityResolver()); - org.dom4j.Document document = null; - try { - document = reader.read(fichier); - } catch (DocumentException e) { - e.printStackTrace(); - } - return document; - } - - - // a partir d'ici, on reprend du code de lutin xml - // mais on doit le modifier pour specifier un DTDResolver , celui d'hibernate - - /** - * Construit un nouveau document a partir du flux - */ - protected static org.w3c.dom.Document getDocumentResolvedByHibernate(String xmlString) { - DocumentBuilder domBuild = ConfigurationHelper.getDocumentBuilder(); - // resolver hibernate - domBuild.setEntityResolver(new DTDEntityResolver()); - - org.w3c.dom.Document domDoc = null; - try { - domDoc = domBuild.parse(new InputSource(new BufferedReader(new StringReader(xmlString)))); - } catch (IOException eee) { - logger.error("Error while reading xml mapping"); - } catch (SAXException eee) { - logger.error("Error while parsing xml mapping"); - } - - return domDoc; - } - - /** - * Recopie, elle est protected dans lutin xml - * @return un DocumentBuilder - */ - protected static DocumentBuilder getDocumentBuilder() { - DocumentBuilderFactory builderFactory = - DocumentBuilderFactory.newInstance(); - - // on configure le builder - builderFactory.setCoalescing(true); - builderFactory.setExpandEntityReferences(true); - builderFactory.setIgnoringComments(true); - builderFactory.setNamespaceAware(true); - builderFactory.setValidating(false); - - DocumentBuilder builder = null; - try { - builder = builderFactory.newDocumentBuilder(); - } catch (ParserConfigurationException eee) { - logger.error("Error while parsing xml mapping"); - } - - return builder; - } -} Copied: topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java (from rev 1218, topia-service/trunk/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java) =================================================================== --- topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java (rev 0) +++ topia-service/tags/topia-service-0.9.1/src/main/java/org/codelutin/topia/migration/kernel/ConfigurationHelper.java 2008-11-14 11:04:45 UTC (rev 1220) @@ -0,0 +1,266 @@ +/* *##% ToPIA Service + * Copyright (C) 2006 - 2008 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>. ##%*/ + +package org.codelutin.topia.migration.kernel; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.net.URL; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.util.Resource; +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; +import org.hibernate.cfg.Configuration; +import org.hibernate.util.DTDEntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * ConfigurationHelper.java + * + * Charge des configuration en mode "dynamic-map". + * + * @author Chatellier Eric + * @author Chevallereau Benjamin + * @author Eon Sébastien + * @author Trève Vincent + * @version $Revision$ + * + * Last update : $Date$ + */ +public class ConfigurationHelper { + + /** + * Logger (common-logging) + */ + private static Log logger = LogFactory.getLog(ConfigurationHelper.class); + + /** + * Single instance + */ + protected static ConfigurationHelper instance = new ConfigurationHelper(); + + /** + * Constructeur + */ + protected ConfigurationHelper() {} + + /** + * Get single instance + */ + public static ConfigurationHelper getInstance() { + return instance; + } + + /** + * Retourne une configuration correspondant au chargement + * de tous les mappings du dossier specifie. + * + * Ici, on pourrait utiliser configuration.addDirectory + * mais on modifie les mappings version "entity-map" + * + * @param pathDirectory Le dossier ou se trouvent les mappings (contient + * la version souhaitee) + * @return La configuration associee + */ + public Configuration getConfigurationInDirectory(String pathDirectory) { + + // schema des noms de fichier a lire + final String regexFilename = ".*\\.hbm\\.xml"; + + // nouvelle configuration en retour + Configuration configuration = null; + + // FIXME faire deux cas ici. Soit on est sur le filesystem comme deja + // code. Soit on est dans un jar (a faire). Dans tous les cas, il faut + // ensuite travailler avec des URLs et non pas des Strings. + // + // si mappingDir n'est pas un repertoire, rechercher avec + // ResourceUtil.getUrls(String pattern): List<URL> ou equivalent. + + // mappingDir est toujours dans le classpath et Resource.getURLs doit + // le trouver, donc que ce soit un dossier ou un jar ici importe peu + + List<URL> urls = null; + + // Don't use File.separator, don't work on windows + String pattern = ".*" + pathDirectory + "/" + regexFilename; + + // find all mapping + urls = Resource.getURLs(pattern); + + logger.debug("Loading mappings in " + pathDirectory); + + if (urls != null && urls.size() > 0) { + // s'il y a des fichier a charger + configuration = new Configuration(); + + for(URL url : urls) { + String xmlmapping = ConfigurationHelper.getEntityMappingFromFile(url); + + // lit le fichier avec lutin xml + org.w3c.dom.Document domDoc = getDocumentResolvedByHibernate(xmlmapping); + + configuration.addDocument(domDoc); + + logger.debug("Local mapping added : " + url); + } + } + else { + logger.error("No mappings files found in directory " + pathDirectory); + } + + return configuration; + } + + /** + * Charge un fichier et retourne un mapping valide pour etre manipule via les map + * + * @param fichier le nom du fichier + * @return le mapping en forme xml + */ + protected static String getEntityMappingFromFile(URL fichier) { + String sXml = null; + + // charge le document en representation dom4j + Document domDoc = getDom4jDocument(fichier); + + // transforme en entity + domDoc = transformAsValidHibernateMapConfigFile(domDoc); + + // transforme le document en chaine + sXml = domDoc.asXML(); + + return sXml; + } + + /** + * Transforme en ajoutant des info de mappings. + * + * Ajoute un entity-name avec la valeur de name. + * Supprime name , sinon hibernate l'utilise encore. + * + * @param dom4jdoc le document + * @return un document mapping entite + */ + protected static Document transformAsValidHibernateMapConfigFile(Document dom4jdoc) { + Element rootElem = dom4jdoc.getRootElement(); + + List<Element> childElements = rootElem.elements("class"); + + for(Element eChild : childElements) { + + // suivant si l'attribut est deja la ou pas + String entityname = eChild.attributeValue("entity-name"); + String odlClassName = eChild.attributeValue("name"); + + if(entityname == null) { + // on l'ajoute alors + eChild.addAttribute("entity-name", odlClassName); + } + + // et supprime l'attribut name (sinon, hibernate continue de l'utiliser) + Attribute attName = eChild.attribute("name"); + if(attName != null) { + eChild.remove(attName); + } + } + + return dom4jdoc; + } + + /** + * Charge un document dom4j + * + * @param fichier le nom du fichier + * @return un document dom4j + */ + protected static Document getDom4jDocument(URL fichier) { + SAXReader reader = new SAXReader(); + reader.setValidation(false); + //DTDEntityResolver = celui d'hibernate + reader.setEntityResolver(new DTDEntityResolver()); + org.dom4j.Document document = null; + try { + document = reader.read(fichier); + } catch (DocumentException e) { + e.printStackTrace(); + } + return document; + } + + + // a partir d'ici, on reprend du code de lutin xml + // mais on doit le modifier pour specifier un DTDResolver , celui d'hibernate + + /** + * Construit un nouveau document a partir du flux + */ + protected static org.w3c.dom.Document getDocumentResolvedByHibernate(String xmlString) { + DocumentBuilder domBuild = ConfigurationHelper.getDocumentBuilder(); + // resolver hibernate + domBuild.setEntityResolver(new DTDEntityResolver()); + + org.w3c.dom.Document domDoc = null; + try { + domDoc = domBuild.parse(new InputSource(new BufferedReader(new StringReader(xmlString)))); + } catch (IOException eee) { + logger.error("Error while reading xml mapping"); + } catch (SAXException eee) { + logger.error("Error while parsing xml mapping"); + } + + return domDoc; + } + + /** + * Recopie, elle est protected dans lutin xml + * @return un DocumentBuilder + */ + protected static DocumentBuilder getDocumentBuilder() { + DocumentBuilderFactory builderFactory = + DocumentBuilderFactory.newInstance(); + + // on configure le builder + builderFactory.setCoalescing(true); + builderFactory.setExpandEntityReferences(true); + builderFactory.setIgnoringComments(true); + builderFactory.setNamespaceAware(true); + builderFactory.setValidating(false); + + DocumentBuilder builder = null; + try { + builder = builderFactory.newDocumentBuilder(); + } catch (ParserConfigurationException eee) { + logger.error("Error while parsing xml mapping"); + } + + return builder; + } +} Deleted: topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml =================================================================== --- topia-service/trunk/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml 2008-11-02 20:08:40 UTC (rev 1207) +++ topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml 2008-11-14 11:04:45 UTC (rev 1220) @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> -<hibernate-mapping default-access="field" auto-import="true" package="org.codelutin.topia.security.entities.user"> - <class name="org.codelutin.topia.security.entities.user.TopiaUserImpl" table="topiaUser" node="org.codelutin.topia.security.entities.user.TopiaUserImpl" abstract="false" proxy="org.codelutin.topia.security.entities.user.TopiaUser" > - <id name="topiaId" type="string" length="255" node="@topiaId"/> - <version name="topiaVersion" type="long" node="@topiaVersion"/> - <property name="topiaCreateDate" type="date" node="@topiaCreateDate"/> - <property name="login" type="text" access="field" column="login" node="login"/> - <property name="email" type="text" access="field" column="email" node="email"/> - <property name="password" type="text" access="field" column="password" node="password"/> - <property name="note" type="text" access="field" column="note" node="note"/> - <property name="linkApplication" type="text" access="field" column="linkApplication" node="linkApplication"/> - <bag name="topiaGroup" table="topiagroup_topiauser" lazy="true" node="topiaGroup" embed-xml="true"> - <key column="topiaUser"/> - <many-to-many class="org.codelutin.topia.security.entities.user.TopiaGroupImpl" column="topiaGroup" node="topiaId"/> - </bag> - </class> -</hibernate-mapping> Copied: topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml (from rev 1218, topia-service/trunk/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml) =================================================================== --- topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml (rev 0) +++ topia-service/tags/topia-service-0.9.1/src/main/resources/oldmappings/TopiaService/0/org/codelutin/topia/security/entities/user/TopiaUserImpl.hbm.xml 2008-11-14 11:04:45 UTC (rev 1220) @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> +<hibernate-mapping default-access="field" auto-import="true" package="org.codelutin.topia.security.entities.user"> + <class name="org.codelutin.topia.security.entities.user.TopiaUserImpl" table="topiaUser" node="org.codelutin.topia.security.entities.user.TopiaUserImpl" abstract="false" proxy="org.codelutin.topia.security.entities.user.TopiaUser" > + <id name="topiaId" type="string" length="255" node="@topiaId"/> + <version name="topiaVersion" type="long" node="@topiaVersion"/> + <property name="topiaCreateDate" type="date" node="@topiaCreateDate"/> + <property name="login" type="text" access="field" column="login" node="login"/> + <property name="email" type="text" access="field" column="email" node="email"/> + <property name="password" type="text" access="field" column="password" node="password"/> + <property name="note" type="text" access="field" column="note" node="note"/> + <property name="linkApplication" type="text" access="field" column="linkApplication" node="linkApplication"/> + <bag name="topiaGroup" table="topiagroup_topiauser" inverse="true" lazy="true" node="topiaGroup" embed-xml="true"> + <key column="topiaUser"/> + <many-to-many class="org.codelutin.topia.security.entities.user.TopiaGroupImpl" column="topiaGroup" node="topiaId"/> + </bag> + </class> +</hibernate-mapping>