All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nuiton.topia.service.migration.version.TMSVersionHibernateDao Maven / Gradle / Ivy

The newest version!
package org.nuiton.topia.service.migration.version;

/*
 * #%L
 * ObServe Toolkit :: ToPIA Migration service
 * %%
 * Copyright (C) 2017 - 2018 IRD, Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.nuiton.topia.persistence.TopiaApplicationContext;
import org.nuiton.topia.persistence.TopiaConfiguration;
import org.nuiton.topia.persistence.TopiaException;
import org.nuiton.topia.persistence.internal.AbstractTopiaApplicationContext;
import org.nuiton.topia.persistence.internal.HibernateProvider;
import org.nuiton.topia.persistence.jdbc.JdbcHelper;
import org.nuiton.topia.persistence.util.TopiaUtil;

import java.util.Collections;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Properties;

/**
 * @author Tony Chemit - [email protected]
 */
public class TMSVersionHibernateDao {

    public static final String TABLE_NAME = "tms_version";
    private final static Log log = LogFactory.getLog(TMSVersionHibernateDao.class);

    private final Configuration hibernateConfiguration;
    private final String tableName;
    private final JdbcHelper jdbcHelper;
    private final HibernateProvider hibernateProvider;

    public TMSVersionHibernateDao(TopiaApplicationContext topiaApplicationContext) {
        TopiaConfiguration topiaConfiguration = topiaApplicationContext.getConfiguration();
        hibernateProvider = ((AbstractTopiaApplicationContext) topiaApplicationContext).getHibernateProvider();
        this.jdbcHelper = new JdbcHelper(topiaConfiguration);
        Properties prop = new Properties();

        prop.put(AvailableSettings.URL, topiaConfiguration.getJdbcConnectionUrl());
        prop.put(AvailableSettings.USER, topiaConfiguration.getJdbcConnectionUser());
        prop.put(AvailableSettings.PASS, topiaConfiguration.getJdbcConnectionPassword());
        prop.put(AvailableSettings.DRIVER, topiaConfiguration.getJdbcDriverClass().getName());
        prop.put(AvailableSettings.DIALECT, HibernateProvider.getHibernateDialect(topiaConfiguration));
        prop.putAll(topiaConfiguration.getHibernateExtraConfiguration());

        hibernateConfiguration = new Configuration();
        hibernateConfiguration.setProperties(prop);
        hibernateConfiguration.addClass(TMSVersion.class);

        hibernateConfiguration.getProperties().remove(AvailableSettings.HBM2DDL_AUTO); // Make sure schema is not created by Hibernate

        String schemaName = TopiaUtil.getSchemaName(hibernateConfiguration);
        this.tableName = (schemaName == null ? "" : schemaName + ".") + TABLE_NAME;

    }

    public void save(String version) {
        try {
            jdbcHelper.runUpdate(String.format("DELETE FROM %1$s; INSERT INTO %1$s (version) VALUES('%2$s')", tableName, version));
        } catch (Exception e) {
            throw new TopiaException(String.format("Could not save version %s", version), e);
        }
    }

    public Optional getVersion() {
        return getVersion(jdbcHelper, tableName);
    }

    public static Optional getVersion(JdbcHelper jdbcHelper, String tableName) {
        try {
            String version = jdbcHelper.runSelectOnString(String.format("select version from %s", tableName));
            return Optional.ofNullable(version == null ? null : new TMSVersion(version));
        } catch (Exception e) {
            throw new TopiaException("Could not obtain version", e);
        }
    }

    public boolean isTableExists() {
        try (SessionFactory sessionFactory = newSessionFactory()) {
            Metadata metaData = hibernateProvider.newMetaData(hibernateConfiguration, sessionFactory, Collections.singleton(TMSVersion.class));
            return TopiaUtil.isSchemaExist(hibernateConfiguration, metaData, TMSVersion.class.getName());
        }
    }

    public void createSchemaIfNotExist() {
        try (SessionFactory sessionFactory = newSessionFactory()) {
            Metadata metaData = hibernateProvider.newMetaData(hibernateConfiguration, sessionFactory, Collections.singleton(TMSVersion.class));
            createSchemaIfNotExist(metaData);
        }
    }

    public SessionFactory newSessionFactory() {
        return TopiaUtil.newSessionFactory(hibernateConfiguration);
    }

    private void createTMSSchema(Metadata metadata) {
        // creer le schema en base
        // dans la configuration il n'y a que la table version
        SchemaExport schemaExport = new SchemaExport();
        EnumSet targetTypes = EnumSet.of(TargetType.DATABASE);
        if (log.isDebugEnabled()) {
            targetTypes.add(TargetType.STDOUT);
        }
        schemaExport.create(targetTypes, metadata);
    }

    private void createSchemaIfNotExist(Metadata metaData) {
        if (TopiaUtil.isSchemaEmpty(hibernateConfiguration, metaData)) {
            createTMSSchema(metaData);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy