Example usage for org.springframework.jdbc.support JdbcUtils extractDatabaseMetaData

List of usage examples for org.springframework.jdbc.support JdbcUtils extractDatabaseMetaData

Introduction

In this page you can find the example usage for org.springframework.jdbc.support JdbcUtils extractDatabaseMetaData.

Prototype

@SuppressWarnings("unchecked")
public static <T> T extractDatabaseMetaData(DataSource dataSource, final String metaDataMethodName)
        throws MetaDataAccessException 

Source Link

Document

Call the specified method on DatabaseMetaData for the given DataSource, and extract the invocation result.

Usage

From source file:edu.upenn.cis.orchestra.repository.utils.dbConverter.SchemaConverterStatementsGen.java

/**
 * /*from  w w  w .  j  a va  2s.  co m*/
 * Returns a list of the db names of any tables which already exist in the
 * {@code Schema}.
 * 
 * @return a list of table names which exist in the {@code Schema}
 */
private List<String> getExistingTableNames() {
    _log.debug("Loading all the existing tables in memory");
    List<String> existingTables = new ArrayList<String>();
    Map<String, Set<String>> schemas = new HashMap<String, Set<String>>();
    for (Relation rel : _sc.getRelations()) {
        if (!schemas.containsKey(rel.getDbCatalog()))
            schemas.put(rel.getDbCatalog(), new HashSet<String>());
        Set<String> schemNames = schemas.get(rel.getDbCatalog());
        schemNames.add(rel.getDbSchema());
    }
    for (Map.Entry<String, Set<String>> entry : schemas.entrySet()) {
        for (String sc : entry.getValue()) {
            MetaExistTables loader = new MetaExistTables(entry.getKey(), sc, existingTables);
            try {
                JdbcUtils.extractDatabaseMetaData(_ds, loader);

            } catch (MetaDataAccessException ex) {
                // TODO: Actually deal with exceptions here!
                assert (false) : "not implemented yet";
            }

        }
    }
    _log.debug("Existing tables loaded. " + existingTables.size() + " found");
    return existingTables;
}

From source file:edu.upenn.cis.orchestra.repository.utils.dbConverter.SchemaConverterStatementsGen.java

/**
 * For each column in the relation, add a new column to contain the labeled
 * null id./*  w  w  w. j  av  a  2s  . c om*/
 * 
 * @param rel Relation for which labeled null columns must be added
 * @param statements List to which new statements must be added
 * @return List of labeled null columns already defined but incorrect
 */
@SuppressWarnings("unchecked")
private List<String> addLabeledNullColumns(Relation rel, List<String> statements, boolean withNoLogging,
        SqlDb db) throws MetaDataAccessException {
    List<String> labNulls = new ArrayList<String>();
    MetaLoadColumns loader = new MetaLoadColumns(rel.getDbCatalog(), rel.getDbSchema(), rel.getDbRelName(),
            labNulls);
    List<String> errors = null;
    // try
    // {
    errors = (List<String>) JdbcUtils.extractDatabaseMetaData(_ds, loader);
    /*
     * } catch (MetaDataAccessException ex) { //TODO: Actually deal with
     * exceptions here! assert (errors!=null) : "not implemented yet"; }
     */

    // String extra = "";
    // if (_jdbcDriver.contains("db2")) {
    // if (withNoLogging)
    // extra = ALTER_NO_LOGGING;
    // }

    List<ISqlColumnDef> cols = newArrayList();
    int inx = 0;
    for (RelationField fld : rel.getFields()) {
        // Add null column if this attribute is not the key
        // boolean fldInKey = rel.getPrimaryKey().getFields().contains(fld);

        // if(!fldInKey){
        if ((!Config.useCompactNulls() || rel.isNullable(inx))
                && !labNulls.contains(fld.getName() + RelationField.LABELED_NULL_EXT))
            cols.add(_sqlFactory.newColumnDef(fld.getName() + RelationField.LABELED_NULL_EXT, "INTEGER",
                    Integer.toString(SqlEngine.LABELED_NULL_NONVALUE)));
        // statements.add ("ALTER TABLE " + rel.getFullQualifiedDbId()
        // + " ADD " + fld.getName() + ModelConstants.LABEL_NULL_EXT
        // //+ " NUMERIC (2, 0) WITH DEFAULT 1" + extra
        // + " INTEGER DEFAULT 1" + extra
        // //TODO: Fix pb: if create table as select it doesn't copy default
        // value!!!
        // /*+ " DEFAULT -1"
        // + " NOT NULL"*/);
        // // }
        inx++;
    }
    statements.addAll(db.getSqlTranslator().addColsToTable(rel.getFullQualifiedDbId(), cols, withNoLogging));
    return errors;
}

From source file:net.urosk.mifss.core.lib.db.PaginationHelper.java

public String getDatabaseProductName(final DataSource dataSource) {

    String dbName = null;/*from   w  w w  . ja  v a2  s.c  o m*/

    try {

        dbName = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");

    } catch (MetaDataAccessException e) {
        logger.error("getDatabaseProductName" + e, e);
    }

    return dbName;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean.java

public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null) {
        throw new IllegalStateException("Data source is not set!");
    }/*from  w ww . j  a v  a 2 s.c  o m*/
    if (this.vendorNameDialectMappings == null) {
        throw new IllegalStateException("Vendor name/dialect mappings are not set!");
    }

    String dbName = (String) JdbcUtils.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName");
    Integer majorVersion = (Integer) JdbcUtils.extractDatabaseMetaData(this.dataSource,
            "getDatabaseMajorVersion");

    try {
        this.hibernateDialect = DialectFactory.determineDialect(dbName, majorVersion.intValue());
        this.hibernateDialectClassName = this.hibernateDialect.getClass().getName();
    } catch (HibernateException e) {
        this.hibernateDialectClassName = this.vendorNameDialectMappings.getProperty(dbName);
    }

    if (StringUtils.isBlank(this.hibernateDialectClassName)) {
        throw new CouldNotDetermineHibernateDialectException(
                "Could not determine Hibernate dialect for database name [" + dbName + "]!");
    }
}

From source file:org.easyrec.store.dao.web.impl.LoaderDAOMysqlImpl.java

@Override
public void testConnection(String url, String username, String password) throws Exception {

    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    config.setJdbcUrl(url);/*from   ww w.j ava2 s.  co m*/
    config.setUsername(username);
    config.setPassword(password);
    config.setPoolName("easyrecPool");
    config.addDataSourceProperty("url", url);
    HikariDataSource ds = new HikariDataSource(config);

    setDataSource(ds);
    sqlScriptService.setDataSource(ds);

    boolean tablesOk = false;

    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getTables(null, null, "operator", null);
            return rs.next();
        }
    };

    tablesOk = (Boolean) JdbcUtils.extractDatabaseMetaData(ds, callback);
}

From source file:org.easyrec.store.dao.web.impl.LoaderDAOMysqlImpl.java

@Override
public void createDB() throws Exception {

    HikariDataSource bds = (HikariDataSource) getDataSource();
    boolean tablesOk = false;

    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getTables(null, null, "operator", null);
            return rs.next();
        }//from w  ww  .jav  a2  s  . c o m
    };

    tablesOk = (Boolean) JdbcUtils.extractDatabaseMetaData(bds, callback);
    sqlScriptService.executeSqlScript(dbCreationFile.getInputStream());
}

From source file:org.easyrec.store.dao.web.impl.LoaderDAOMysqlImpl.java

@Override
public void migrateDB() throws Exception {

    HikariDataSource bds = (HikariDataSource) getDataSource();
    boolean tablesOk = false;

    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getTables(null, null, "operator", null);
            return rs.next();
        }/*from  w ww  .  j a  v a2s.  co m*/
    };

    tablesOk = (Boolean) JdbcUtils.extractDatabaseMetaData(bds, callback);
    Float installedVersion = checkVersion();

    for (String migrateFile : migrateFiles) {
        logger.info("migrate File: " + migrateFile);
        Float scriptVersion = Float.parseFloat(migrateFile.substring(migrateFile.lastIndexOf("_") + 1));
        logger.info("scriptVersion: " + scriptVersion);
        if (installedVersion < scriptVersion) {
            File f = new File(dbMigrateFolder.getFile(), migrateFile + ".sql");
            if (f.exists()) {
                logger.info("Executing migrate script: " + f.getName());
                sqlScriptService.executeSqlScript(new FileSystemResource(f).getInputStream());
            }
            if (scriptVersion == 0.96) {
                update_0_96f();
            }
            if (scriptVersion == 0.98) {
                update_0_98();
            }
            if (scriptVersion == 1.00) {
                update_1_00();
            }
        }
    }

    //        if (installedVersion < 0.96f) {
    //            update_0_96f();
    //            // logs are not converted from ruleminerlog -> plugin_log
    //        }
    //
    //        if (installedVersion < 0.98) {
    //            update_0_98();
    //        }

    //updateVersion(); // done in migrate script!
}

From source file:org.easyrec.store.dao.web.impl.LoaderDAOMysqlImpl.java

/**
 * This function returns the current version of easyrec,
 * depending on the presence of a version table. If
 * no version table is present return the inital version
 *
 *
 *//*from   w  ww  .  jav a2  s  .c  om*/
@Override
public Float checkVersion() throws Exception {

    HikariDataSource bds = (HikariDataSource) getDataSource();
    float tableCount;

    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getTables(null, null, null, null);
            float f = 0;
            while (rs.next()) {
                f++;
            }
            return f;
        }
    };

    tableCount = (Float) JdbcUtils.extractDatabaseMetaData(bds, callback);

    if (tableCount != 0) {
        try {
            return getJdbcTemplate().queryForObject("SELECT MAX(VERSION) FROM easyrec ", Float.class);
        } catch (Exception e) {
            // else return initial version 0.9
            return INITIAL_VERSION;
        }
    } else {
        return tableCount;
    }
}

From source file:org.easyrec.utils.spring.store.dao.DaoUtils.java

/**
 * Checks if a given database table is found in the given <code>DataSource</code>.
 *
 * @param dataSource//w  w  w.j ava 2 s.  c  om
 * @param tableName
 * @return true if table exists, false if not
 */
public static boolean existsTable(DataSource dataSource, final String tableName) {
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getTables(null, null, tableName, null);
            return rs.next();
        }
    };
    try {
        return (Boolean) JdbcUtils.extractDatabaseMetaData(dataSource, callback);
    } catch (Exception e) {
        throw new RuntimeException("unable to read database metadata", e);
    }
}

From source file:org.easyrec.utils.spring.store.dao.DaoUtils.java

/**
 * @return the current database url and user name (for a given Datasource)
 * @throws RuntimeException when the database metadata cannot be retrieved
 */// w  w w .  j  av  a2  s .co m
public static String getDatabaseURLAndUserName(DataSource dataSource) {
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            String url = dbmd.getURL();
            String userName = dbmd.getUserName();

            StringBuilder s = new StringBuilder(url);
            s.append(" (userName='");
            s.append(userName);
            s.append("')");
            return s.toString();
        }
    };
    try {
        return (String) JdbcUtils.extractDatabaseMetaData(dataSource, callback);
    } catch (Exception e) {
        throw new RuntimeException("unable to read database metadata", e);
    }
}