Example usage for java.sql DatabaseMetaData getDatabaseProductName

List of usage examples for java.sql DatabaseMetaData getDatabaseProductName

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getDatabaseProductName.

Prototype

String getDatabaseProductName() throws SQLException;

Source Link

Document

Retrieves the name of this database product.

Usage

From source file:org.schemaspy.SchemaAnalyzer.java

public Database analyze(String schema, Config config, File outputDir, ProgressListener progressListener)
        throws SQLException, IOException {
    try {/*from ww w  .  j  ava  2s.  co  m*/
        LOGGER.info("Starting schema analysis");

        FileUtils.forceMkdir(outputDir);

        String dbName = config.getDb();

        String catalog = commandLineArguments.getCatalog();

        DatabaseMetaData meta = sqlService.connect(config);

        LOGGER.debug("supportsSchemasInTableDefinitions: {}", meta.supportsSchemasInTableDefinitions());
        LOGGER.debug("supportsCatalogsInTableDefinitions: {}", meta.supportsCatalogsInTableDefinitions());

        // set default Catalog and Schema of the connection
        if (schema == null)
            schema = meta.getConnection().getSchema();
        if (catalog == null)
            catalog = meta.getConnection().getCatalog();

        SchemaMeta schemaMeta = config.getMeta() == null ? null
                : new SchemaMeta(config.getMeta(), dbName, schema);
        if (config.isHtmlGenerationEnabled()) {
            FileUtils.forceMkdir(new File(outputDir, "tables"));
            FileUtils.forceMkdir(new File(outputDir, "diagrams/summary"));

            LOGGER.info("Connected to {} - {}", meta.getDatabaseProductName(),
                    meta.getDatabaseProductVersion());

            if (schemaMeta != null && schemaMeta.getFile() != null) {
                LOGGER.info("Using additional metadata from {}", schemaMeta.getFile());
            }
        }

        //
        // create our representation of the database
        //
        Database db = new Database(config, meta, dbName, catalog, schema, schemaMeta, progressListener);
        databaseService.gatheringSchemaDetails(config, db, progressListener);

        long duration = progressListener.startedGraphingSummaries();

        Collection<Table> tables = new ArrayList<>(db.getTables());
        tables.addAll(db.getViews());

        if (tables.isEmpty()) {
            dumpNoTablesMessage(schema, config.getUser(), meta, config.getTableInclusions() != null);
            if (!config.isOneOfMultipleSchemas()) // don't bail if we're doing the whole enchilada
                throw new EmptySchemaException();
        }

        if (config.isHtmlGenerationEnabled()) {
            generateHtmlDoc(config, progressListener, outputDir, db, duration, tables);
        }

        outputProducers.forEach(outputProducer -> {
            try {
                outputProducer.generate(db, outputDir);
            } catch (OutputException oe) {
                if (config.isOneOfMultipleSchemas()) {
                    LOGGER.warn("Failed to produce output", oe);
                } else {
                    throw oe;
                }
            }
        });

        List<ForeignKeyConstraint> recursiveConstraints = new ArrayList<>();

        // create an orderer to be able to determine insertion and deletion ordering of tables
        TableOrderer orderer = new TableOrderer();

        // side effect is that the RI relationships get trashed
        // also populates the recursiveConstraints collection
        List<Table> orderedTables = orderer.getTablesOrderedByRI(db.getTables(), recursiveConstraints);

        writeOrders(outputDir, orderedTables);

        duration = progressListener.finishedGatheringDetails();
        long overallDuration = progressListener.finished(tables, config);

        if (config.isHtmlGenerationEnabled()) {
            LOGGER.info("Wrote table details in {} seconds", duration / 1000);

            LOGGER.info("Wrote relationship details of {} tables/views to directory '{}' in {} seconds.",
                    tables.size(), outputDir, overallDuration / 1000);
            LOGGER.info("View the results by opening {}", new File(outputDir, "index.html"));
        }

        return db;
    } catch (Config.MissingRequiredParameterException missingParam) {
        config.dumpUsage(missingParam.getMessage(), missingParam.isDbTypeSpecific());
        return null;
    }
}

From source file:org.openbizview.util.Sgc012.java

/**
 * Leer Datos de paises/*w w  w.  j a v a2  s . c o  m*/
 * @throws NamingException 
* @throws IOException 
 **/
public void select(int first, int pageSize, String sortField, Object filterValue)
        throws SQLException, ClassNotFoundException, NamingException {

    //System.out.println("entre al metodo SELECT");   
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    con = ds.getConnection();
    //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
    DatabaseMetaData databaseMetaData = con.getMetaData();
    productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

    String validar = "1";
    String querycon = "SELECT BI_SGC014('" + login.toUpperCase() + "') AS VALIDAR FROM DUAL";

    //System.out.println(querycon);
    //System.out.println(JNDI);

    consulta.selectPntGenerica(querycon, JNDI);

    rows = consulta.getRows();
    tabla = consulta.getArray();
    //System.out.println(tabla[0][0]);

    if (tabla[0][0].equals(validar)) {

        if (comp == null) {
            comp = " - ";
        }
        if (comp == "") {
            comp = " - ";
        }
        if (area == null) {
            area = " - ";
        }
        if (area == "") {
            area = " - ";
        }
        if (codigo == null) {
            codigo = " - ";
        }
        if (codigo == "") {
            codigo = " - ";
        }
        String[] veccomp = comp.split("\\ - ", -1);
        String[] vecarea = area.split("\\ - ", -1);
        String[] veccod = codigo.split("\\ - ", -1);

        String query = " SELECT ";
        query += " *  ";
        query += " FROM (select  ";
        query += "       query.*, rownum as rn  ";
        query += "       from (SELECT  ";
        query += "             A.COMP, A.AREA, A.CODIGO, A.ANOCAL, A.MESCAL, A.INVANA, A.RRHH, A.SUPERV,  ";
        query += "             A.MEDAMB, A.EQUIPO, A.INFSTR, A.PROCED, A.OTROS, A.USRCRE, TO_CHAR(A.FECCRE,'DD/MM/YYYY') AS FECCRE,  ";
        query += "             B.NOMIND AS DESC1, C.DESCR AS DESC2, D.DESCR AS DESC3   ";
        query += "             FROM  ";
        query += "             SGC012 A, SGC001 B, SGC005 C, SGC006 D ";
        query += "             WHERE  ";
        query += "             A.CODIGO = B.CODIGO ";
        query += "             AND A.COMP = C.CODIGO ";
        query += "             AND A.AREA = D.CODIGO ";
        query += "             AND C.CODIGO = D.COMP ";
        query += "            ) query ";
        query += "            WHERE ";
        query += "            TRIM(query.COMP) LIKE TRIM('%" + veccomp[0] + "%')";
        query += "            AND TRIM(query.AREA) LIKE TRIM('%" + vecarea[0] + "%')";
        query += "            AND TRIM(query.CODIGO) LIKE TRIM('%" + veccod[0] + "%')";
        query += "      )   ";
        query += " WHERE  ";
        query += " ROWNUM <=" + pageSize;
        query += " AND rn > (" + first + ")";
        query += " ORDER BY COMP, AREA, CODIGO, ANOCAL, MESCAL ";

        pstmt = con.prepareStatement(query);
        //System.out.println(query);
        //System.out.println("***ADMINISTRADOR***");

        r = pstmt.executeQuery();

        while (r.next()) {
            Sgc012 select = new Sgc012();
            select.setZcomp(r.getString(1) + " - " + r.getString(17));
            select.setZarea(r.getString(2) + " - " + r.getString(18));
            select.setZcodigo(r.getString(3) + " - " + r.getString(16));
            select.setZanocal(r.getString(4));
            select.setZmescal(r.getString(5));
            select.setZinvana(r.getString(6));
            select.setZrrhh(r.getString(7));
            select.setZsuperv(r.getString(8));
            select.setZmedamb(r.getString(9));
            select.setZequipo(r.getString(10));
            select.setZinfstr(r.getString(11));
            select.setZproced(r.getString(12));
            select.setZotros(r.getString(13));
            select.setZcoddel(r.getString(1) + "" + r.getString(2) + "" + r.getString(3) + "" + r.getString(4)
                    + "" + r.getString(5));
            select.setZorderby(r.getString(1) + ", " + r.getString(2) + ", " + r.getString(3) + ", "
                    + r.getString(4) + ", " + r.getString(5));
            select.setZusrcre(r.getString(14));
            select.setZfeccre(r.getString(15));

            //Agrega la lista
            list.add(select);
        }
        //Cierra las conecciones
        pstmt.close();
        con.close();
    } else {

        if (comp == null) {
            comp = " - ";
        }
        if (comp == "") {
            comp = " - ";
        }
        if (area == null) {
            area = " - ";
        }
        if (area == "") {
            area = " - ";
        }
        if (codigo == null) {
            codigo = " - ";
        }
        if (codigo == "") {
            codigo = " - ";
        }
        String[] veccomp = comp.split("\\ - ", -1);
        String[] vecarea = area.split("\\ - ", -1);
        String[] veccod = codigo.split("\\ - ", -1);

        String query = " SELECT ";
        query += " *  ";
        query += " FROM (select  ";
        query += "       DISTINCT query.* ";
        query += "       from (SELECT  ";
        query += "             A.COMP, A.AREA, A.CODIGO, A.ANOCAL, A.MESCAL, A.INVANA, A.RRHH, A.SUPERV,  ";
        query += "             A.MEDAMB, A.EQUIPO, A.INFSTR, A.PROCED, A.OTROS, A.USRCRE, TO_CHAR(A.FECCRE,'DD/MM/YYYY') AS FECCRE,  ";
        query += "             B.NOMIND AS DESC1, C.DESCR AS DESC2, D.DESCR AS DESC3   ";
        query += "             FROM  ";
        query += "             SGC012 A, SGC001 B, SGC005 C, SGC006 D, SGC009 E ";
        query += "             WHERE  ";
        query += "             A.CODIGO = B.CODIGO   ";
        query += "             AND A.COMP = C.CODIGO   ";
        query += "             AND A.AREA = D.CODIGO   ";
        query += "             AND C.CODIGO = D.COMP             ";
        query += "             AND A.COMP = E.COMP ";
        query += "             AND A.AREA = E.AREA ";
        query += "             AND A.CODIGO = E.INDICA ";
        query += "             AND E.CODUSER = '" + login.toUpperCase() + "'";
        query += "             UNION ALL ";
        query += "             SELECT  ";
        query += "             A.COMP, A.AREA, A.CODIGO, A.ANOCAL, A.MESCAL, A.INVANA, A.RRHH, A.SUPERV,  ";
        query += "             A.MEDAMB, A.EQUIPO, A.INFSTR, A.PROCED, A.OTROS, A.USRCRE, TO_CHAR(A.FECCRE,'DD/MM/YYYY') AS FECCRE,  ";
        query += "             B.NOMIND AS DESC1, C.DESCR AS DESC2, D.DESCR AS DESC3   ";
        query += "             FROM  ";
        query += "             SGC012 A, SGC001 B, SGC005 C, SGC006 D ";
        query += "             WHERE  ";
        query += "             A.CODIGO = B.CODIGO   ";
        query += "             AND A.COMP = C.CODIGO   ";
        query += "             AND A.AREA = D.CODIGO   ";
        query += "             AND C.CODIGO = D.COMP             ";
        query += "             AND A.COMP||A.AREA IN (SELECT COMP||AREA FROM SGC008 WHERE CODUSER = '"
                + login.toUpperCase() + "'AND DUEPRO = '1')";
        query += "            ) query ";
        query += "            WHERE ";
        query += "            TRIM(query.COMP) LIKE TRIM('%" + veccomp[0] + "%')";
        query += "            AND TRIM(query.AREA) LIKE TRIM('%" + vecarea[0] + "%')";
        query += "            AND TRIM(query.CODIGO) LIKE TRIM('%" + veccod[0] + "%')";
        query += "      )   ";
        query += " WHERE  ";
        query += " ROWNUM <=" + pageSize;
        query += " AND ROWNUM > (" + first + ")";
        query += " ORDER BY COMP, AREA, CODIGO, ANOCAL, MESCAL ";

        pstmt = con.prepareStatement(query);
        //System.out.println(query);
        //System.out.println("***NO ADMINISTRADOR***");

        r = pstmt.executeQuery();

        while (r.next()) {
            Sgc012 select = new Sgc012();
            select.setZcomp(r.getString(1) + " - " + r.getString(17));
            select.setZarea(r.getString(2) + " - " + r.getString(18));
            select.setZcodigo(r.getString(3) + " - " + r.getString(16));
            select.setZanocal(r.getString(4));
            select.setZmescal(r.getString(5));
            select.setZinvana(r.getString(6));
            select.setZrrhh(r.getString(7));
            select.setZsuperv(r.getString(8));
            select.setZmedamb(r.getString(9));
            select.setZequipo(r.getString(10));
            select.setZinfstr(r.getString(11));
            select.setZproced(r.getString(12));
            select.setZotros(r.getString(13));
            select.setZcoddel(r.getString(1) + "" + r.getString(2) + "" + r.getString(3) + "" + r.getString(4)
                    + "" + r.getString(5));
            select.setZorderby(r.getString(1) + ", " + r.getString(2) + ", " + r.getString(3) + ", "
                    + r.getString(4) + ", " + r.getString(5));
            select.setZusrcre(r.getString(14));
            select.setZfeccre(r.getString(15));

            //Agrega la lista
            list.add(select);
        }
        //Cierra las conecciones
        pstmt.close();
        con.close();
    }
}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

/**
 * Test simple DatabaseMetaData calls.  getColumns is tested elsewhere, as we need to call
 * that on a valid table.  Same with getFunctions.
 *
 * @throws SQLException/*  w  w w. ja v a2 s .co m*/
 */
@Test
public void databaseMetaDataCalls() throws SQLException {
    DatabaseMetaData md = conn.getMetaData();

    boolean boolrc = md.allTablesAreSelectable();
    LOG.debug("All tables are selectable? " + boolrc);

    String strrc = md.getCatalogSeparator();
    LOG.debug("Catalog separator " + strrc);

    strrc = md.getCatalogTerm();
    LOG.debug("Catalog term " + strrc);

    ResultSet rs = md.getCatalogs();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found catalog " + strrc);
    }

    Connection c = md.getConnection();

    int intrc = md.getDatabaseMajorVersion();
    LOG.debug("DB major version is " + intrc);

    intrc = md.getDatabaseMinorVersion();
    LOG.debug("DB minor version is " + intrc);

    strrc = md.getDatabaseProductName();
    LOG.debug("DB product name is " + strrc);

    strrc = md.getDatabaseProductVersion();
    LOG.debug("DB product version is " + strrc);

    intrc = md.getDefaultTransactionIsolation();
    LOG.debug("Default transaction isolation is " + intrc);

    intrc = md.getDriverMajorVersion();
    LOG.debug("Driver major version is " + intrc);

    intrc = md.getDriverMinorVersion();
    LOG.debug("Driver minor version is " + intrc);

    strrc = md.getDriverName();
    LOG.debug("Driver name is " + strrc);

    strrc = md.getDriverVersion();
    LOG.debug("Driver version is " + strrc);

    strrc = md.getExtraNameCharacters();
    LOG.debug("Extra name characters is " + strrc);

    strrc = md.getIdentifierQuoteString();
    LOG.debug("Identifier quote string is " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getImportedKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getIndexInfo("a", "b", "d", true, true);

    intrc = md.getJDBCMajorVersion();
    LOG.debug("JDBC major version is " + intrc);

    intrc = md.getJDBCMinorVersion();
    LOG.debug("JDBC minor version is " + intrc);

    intrc = md.getMaxColumnNameLength();
    LOG.debug("Maximum column name length is " + intrc);

    strrc = md.getNumericFunctions();
    LOG.debug("Numeric functions are " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getPrimaryKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedureColumns("a", "b", "d", "e");

    strrc = md.getProcedureTerm();
    LOG.debug("Procedures are called " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedures("a", "b", "d");

    strrc = md.getSchemaTerm();
    LOG.debug("Schemas are called " + strrc);

    rs = md.getSchemas();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found schema " + strrc);
    }

    strrc = md.getSearchStringEscape();
    LOG.debug("Search string escape is " + strrc);

    strrc = md.getStringFunctions();
    LOG.debug("String functions are " + strrc);

    strrc = md.getSystemFunctions();
    LOG.debug("System functions are " + strrc);

    rs = md.getTableTypes();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found table type " + strrc);
    }

    strrc = md.getTimeDateFunctions();
    LOG.debug("Time/date functions are " + strrc);

    rs = md.getTypeInfo();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found type " + strrc);
    }

    // In Hive 1.2 this always returns an empty RS
    rs = md.getUDTs("a", "b", "d", null);

    boolrc = md.supportsAlterTableWithAddColumn();
    LOG.debug("Supports alter table with add column? " + boolrc);

    boolrc = md.supportsAlterTableWithDropColumn();
    LOG.debug("Supports alter table with drop column? " + boolrc);

    boolrc = md.supportsBatchUpdates();
    LOG.debug("Supports batch updates? " + boolrc);

    boolrc = md.supportsCatalogsInDataManipulation();
    LOG.debug("Supports catalogs in data manipulation? " + boolrc);

    boolrc = md.supportsCatalogsInIndexDefinitions();
    LOG.debug("Supports catalogs in index definition? " + boolrc);

    boolrc = md.supportsCatalogsInPrivilegeDefinitions();
    LOG.debug("Supports catalogs in privilege definition? " + boolrc);

    boolrc = md.supportsCatalogsInProcedureCalls();
    LOG.debug("Supports catalogs in procedure calls? " + boolrc);

    boolrc = md.supportsCatalogsInTableDefinitions();
    LOG.debug("Supports catalogs in table definition? " + boolrc);

    boolrc = md.supportsColumnAliasing();
    LOG.debug("Supports column aliasing? " + boolrc);

    boolrc = md.supportsFullOuterJoins();
    LOG.debug("Supports full outer joins? " + boolrc);

    boolrc = md.supportsGroupBy();
    LOG.debug("Supports group by? " + boolrc);

    boolrc = md.supportsLimitedOuterJoins();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsMultipleResultSets();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsNonNullableColumns();
    LOG.debug("Supports non-nullable columns? " + boolrc);

    boolrc = md.supportsOuterJoins();
    LOG.debug("Supports outer joins? " + boolrc);

    boolrc = md.supportsPositionedDelete();
    LOG.debug("Supports positioned delete? " + boolrc);

    boolrc = md.supportsPositionedUpdate();
    LOG.debug("Supports positioned update? " + boolrc);

    boolrc = md.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set holdability? " + boolrc);

    boolrc = md.supportsResultSetType(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set type? " + boolrc);

    boolrc = md.supportsSavepoints();
    LOG.debug("Supports savepoints? " + boolrc);

    boolrc = md.supportsSchemasInDataManipulation();
    LOG.debug("Supports schemas in data manipulation? " + boolrc);

    boolrc = md.supportsSchemasInIndexDefinitions();
    LOG.debug("Supports schemas in index definitions? " + boolrc);

    boolrc = md.supportsSchemasInPrivilegeDefinitions();
    LOG.debug("Supports schemas in privilege definitions? " + boolrc);

    boolrc = md.supportsSchemasInProcedureCalls();
    LOG.debug("Supports schemas in procedure calls? " + boolrc);

    boolrc = md.supportsSchemasInTableDefinitions();
    LOG.debug("Supports schemas in table definitions? " + boolrc);

    boolrc = md.supportsSelectForUpdate();
    LOG.debug("Supports select for update? " + boolrc);

    boolrc = md.supportsStoredProcedures();
    LOG.debug("Supports stored procedures? " + boolrc);

    boolrc = md.supportsTransactions();
    LOG.debug("Supports transactions? " + boolrc);

    boolrc = md.supportsUnion();
    LOG.debug("Supports union? " + boolrc);

    boolrc = md.supportsUnionAll();
    LOG.debug("Supports union all? " + boolrc);

}

From source file:annis.dao.SpringAnnisDao.java

@Override
public boolean checkDatabaseVersion() throws AnnisException {
    try (Connection conn = getJdbcTemplate().getDataSource().getConnection();) {

        DatabaseMetaData meta = conn.getMetaData();

        log.debug("database info [major: " + meta.getDatabaseMajorVersion() + " minor: "
                + meta.getDatabaseMinorVersion() + " complete: " + meta.getDatabaseProductVersion() + " name: "
                + meta.getDatabaseProductName() + "]");

        if (!"PostgreSQL".equalsIgnoreCase(meta.getDatabaseProductName())) {
            throw new AnnisException("You did provide a database connection to a "
                    + "database that is not PostgreSQL. Please note that this will " + "not work.");
        }//from   w  w w.  j a  v a 2s. c om
        if (meta.getDatabaseMajorVersion() < 9
                || (meta.getDatabaseMajorVersion() == 9 && meta.getDatabaseMinorVersion() < 1)) // we urge people to use 9.2, but 9.1 should be valid as well
        {
            throw new AnnisException("Wrong PostgreSQL version installed. Please "
                    + "install at least PostgreSQL 9.2 (current installed version is "
                    + meta.getDatabaseProductVersion() + ")");
        }
    } catch (SQLException ex) {
        log.error("could not get database version", ex);
    }

    return false;
}

From source file:org.activiti.idm.engine.IdmEngineConfiguration.java

public void initDatabaseType() {
    Connection connection = null;
    try {// w  w w.  ja v a  2 s . c o  m
        connection = dataSource.getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String databaseProductName = databaseMetaData.getDatabaseProductName();
        logger.debug("database product name: '{}'", databaseProductName);
        databaseType = databaseTypeMappings.getProperty(databaseProductName);
        if (databaseType == null) {
            throw new ActivitiIdmException(
                    "couldn't deduct database type from database product name '" + databaseProductName + "'");
        }
        logger.debug("using database type: {}", databaseType);

    } catch (SQLException e) {
        logger.error("Exception while initializing Database connection", e);
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            logger.error("Exception while closing the Database connection", e);
        }
    }
}

From source file:org.sakaiproject.warehouse.util.db.DbLoader.java

protected void printInfo() throws SQLException {
    DatabaseMetaData dbMetaData = con.getMetaData();
    dbName = dbMetaData.getDatabaseProductName();
    dbVersion = dbMetaData.getDatabaseProductVersion();
    driverName = dbMetaData.getDriverName();
    driverVersion = dbMetaData.getDriverVersion();

    logger.debug("Starting DbLoader...");
    logger.debug("Database name: '" + dbName + "'");
    logger.debug("Database version: '" + dbVersion + "'");
    logger.debug("Driver name: '" + driverName + "'");
    logger.debug("Driver version: '" + driverVersion + "'");
    logger.debug("Database url: '" + dbMetaData.getURL() + "'");
}

From source file:org.talend.core.model.metadata.builder.database.ExtractMetaDataUtils.java

/**
 * /*from   w  w  w .  ja  va 2  s .co m*/
 * 
 * @param conn
 * @return
 * @throws SQLException
 * 
 * this method will pass a mistake databaseType to get DatabaseMetDdata(e.x. db2->db2 for zos) if you can, you
 * should use getDatabaseMetaData() instead of this method
 * 
 */
public DatabaseMetaData getConnectionMetadata(java.sql.Connection conn) throws SQLException {
    if (conn != null) {
        DatabaseMetaData dbMetaData = conn.getMetaData();
        // MOD xqliu 2009-11-17 bug 7888
        if (dbMetaData != null && dbMetaData.getDatabaseProductName() != null) {
            // because there is no sqlMode and the database arguments. so sqlMode is false, database is null.
            return getDatabaseMetaData(conn, dbMetaData.getDatabaseProductName(), false, null);
        }

        return dbMetaData;
    }
    return null;
}

From source file:org.metis.push.PusherBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *//*from   w w w  . j  a v  a  2  s.com*/
public void afterPropertiesSet() throws Exception {

    // create the session registry
    setWdsSessions(new Hashtable<String, WdsSocketSession>(getInitCapacity()));

    // log info for the jdbc driver being used
    // this will also attempt to open connection
    // with jdbc driver
    try {
        Connection con = getDataSource().getConnection();
        if (con != null) {
            DatabaseMetaData dbmd = con.getMetaData();
            setDbConnectionAcquired(true);
            if (dbmd != null) {
                setDriverName(dbmd.getDriverName().trim().toLowerCase());
                // record the URL to the DB
                setDbUrl(dbmd.getURL().trim());
                isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false;
                LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle);
                LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName());
                LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim());
                LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim());
                LOG.info(getBeanName() + ":JDBC URL = " + getDbUrl());
                LOG.info(getBeanName() + ":JDBC Driver database product version = "
                        + dbmd.getDatabaseProductVersion().trim());
                con.close();
            } else {
                LOG.info(getBeanName() + ": Unable to get JDBC driver meta data");
            }
        } else {
            LOG.info(getBeanName() + ": Unable to get JDBC connection");
        }
    } catch (SQLException exc) {
        LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
        LOG.error(getBeanName() + ": causing exception stack trace follows:");
        dumpStackTrace(exc.getCause().getStackTrace());
    }

    // bean must be assigned a JDBC DataSource
    if (getDataSource() == null) {
        throw new Exception(
                getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource");
    }

    // do some validation
    if (getSqls4Get() == null) {
        throw new Exception("The PusherBean must be assigned at least one SQL statement");
    }

    // create and validate the injected SQL statements

    sqlStmnts4Get = new ArrayList<SqlStmnt>();
    for (String sql : getSqls4Get()) {
        // get the frequency settings
        Map<String, Long> map = Utils.parseTimeInterval(sql);
        sql = Utils.stripTimeInterval(sql);
        sql = Utils.stripCall(sql);
        SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());

        if (stmt.isEqual(sqlStmnts4Get)) {
            throw new Exception("Injected SQL statements for GET are not distinct");
        }
        // set the frequency
        stmt.setIntervalTime(map.get(TIME_INTERVAL));
        if (map.get(TIME_INTERVAL_MAX) != null) {
            stmt.setIntervalMax(map.get(TIME_INTERVAL_MAX));
        }
        if (map.get(TIME_INTERVAL_STEP) != null) {
            stmt.setIntervalStep(map.get(TIME_INTERVAL_STEP));
        }
        sqlStmnts4Get.add(stmt);
    }
    if (LOG.isDebugEnabled()) {
        for (SqlStmnt sqlstmnt : sqlStmnts4Get) {
            LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal());
            LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared());
        }
    }

    if (getHazelcastInstance() != null) {
        LOG.debug(getBeanName() + ": My Hazelcast Instance Name = " + getHazelcastInstance().getName());
        ;
    }
}

From source file:org.sakaiproject.warehouse.util.db.DbLoader.java

protected String getLocalDataTypeName(String genericDataTypeName) {

    String localDataTypeName = null;

    try {//  www  . j  av a2 s. c  om
        DatabaseMetaData dbmd = con.getMetaData();
        String dbName = dbmd.getDatabaseProductName();
        String dbVersion = dbmd.getDatabaseProductVersion();
        String driverName = dbmd.getDriverName();
        String driverVersion = dbmd.getDriverVersion();

        // Check for a mapping in DbLoader.xml
        localDataTypeName = propertiesHandler.properties.getMappedDataTypeName(dbName, dbVersion, driverName,
                driverVersion, genericDataTypeName);

        if (localDataTypeName != null)
            return localDataTypeName;

        // Find the type code for this generic type name
        int dataTypeCode = getJavaSqlType(genericDataTypeName);

        // Find the first local type name matching the type code
        ResultSet rs = dbmd.getTypeInfo();
        try {
            while (rs.next()) {
                int localDataTypeCode = rs.getInt("DATA_TYPE");

                if (dataTypeCode == localDataTypeCode) {
                    try {
                        localDataTypeName = rs.getString("TYPE_NAME");
                    } catch (SQLException sqle) {
                    }
                    break;
                }
            }
        } finally {
            rs.close();
        }

        if (localDataTypeName != null)
            return localDataTypeName;

        // No matching type found, report an error
        logger.error("Error in DbLoader.getLocalDataTypeName()");
        logger.error("Your database driver, '" + driverName + "', version '" + driverVersion
                + "', was unable to find a local type name that matches the generic type name, '"
                + genericDataTypeName + "'.");
        logger.error("Please add a mapped type for database '" + dbName + "', version '" + dbVersion
                + "' inside your properties file and run this program again.");
        logger.error("Exiting...");
    } catch (Exception e) {
        logger.error("Error in DbLoader.getLocalDataTypeName()", e);
    }

    return null;
}

From source file:org.kawanfw.test.api.client.DatabaseMetaDataTest.java

public void test(Connection connection) throws Exception {
    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Test that getMetaData() will return value from cache
    databaseMetaData = connection.getMetaData();

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("Java Version : " + System.getProperty("java.version"));
        MessageDisplayer.display("AceQL Version: " + ((RemoteConnection) connection).getVersion());
        MessageDisplayer.display("AceQL Url    : " + ((RemoteConnection) connection).getUrl());
        MessageDisplayer.display("");
    }/*from   www  .j a va2 s.  c  om*/

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("((RemoteConnection)connection).clone();");
        Connection connection2 = ((RemoteConnection) connection).clone();
        @SuppressWarnings("unused")
        DatabaseMetaData databaseMetaData2 = connection2.getMetaData();
        connection2.close();
    }

    MessageDisplayer.display("General info (no Assert done):");

    MessageDisplayer.display("connection.getCatalog()                     : " + connection.getCatalog());

    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductVersion(): " + databaseMetaData.getDatabaseProductVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMajorVersion()  : " + databaseMetaData.getDatabaseMajorVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMinorVersion()  : " + databaseMetaData.getDatabaseMinorVersion());
    MessageDisplayer.display(
            "databaseMetaData.allProceduresAreCallable() : " + databaseMetaData.allProceduresAreCallable());
    // SystemOutHandle.display(DatabaseMetaData.bestRowSession);
    MessageDisplayer.display("");

    // SystemOutHandle.display(databaseMetaData.autoCommitFailureClosesAllResultSets());

    MessageDisplayer.display("databaseMetaData.getCatalogTerm(): " + databaseMetaData.getCatalogTerm());

    try {

        MessageDisplayer.display(
                "databaseMetaData.supportsStoredProcedures(): " + databaseMetaData.supportsStoredProcedures());

        MessageDisplayer.display("databaseMetaData.supportsStoredFunctionsUsingCallSyntax(): "
                + databaseMetaData.supportsStoredFunctionsUsingCallSyntax());

    } catch (Throwable e) {
        MessageDisplayer.display(e.toString());
    }

    MessageDisplayer.display("connection.getAutoCommit(): " + connection.getAutoCommit());

    MessageDisplayer.display("databaseMetaData.getDefaultTransactionIsolation()    : "
            + databaseMetaData.getDefaultTransactionIsolation());

    MessageDisplayer
            .display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED): "
                    + databaseMetaData
                            .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

    MessageDisplayer
            .display("databaseMetaData.supportsBatchUpdates()    : " + databaseMetaData.supportsBatchUpdates());
    MessageDisplayer
            .display("databaseMetaData.supportsSavepoints()      : " + databaseMetaData.supportsSavepoints());
    MessageDisplayer.display(
            "databaseMetaData.supportsGetGeneratedKeys(): " + databaseMetaData.supportsGetGeneratedKeys());

    if (!new SqlUtil(connection).isTeradata() && !new SqlUtil(connection).isInformix()) {
        Assert.assertEquals(true,
                databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
    }

    Assert.assertEquals("databaseMetaData.supportsBatchUpdates()", true,
            databaseMetaData.supportsBatchUpdates());

    if (!new SqlUtil(connection).isSQLAnywhere() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals("databaseMetaData.supportsGetGeneratedKeys()", true,
                databaseMetaData.supportsGetGeneratedKeys());
    }
    // Informix does not support savepoints
    SqlUtil sqlUtil = new SqlUtil(connection);
    if (!sqlUtil.isInformix() && !sqlUtil.isTeradata() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals(true, databaseMetaData.supportsSavepoints());
    }

    MessageDisplayer.display("");

    String catalog = null;
    String schema = null;
    String table = "customer";

    // Table name must be uppercase for Oracle & DB2, lowercase for MySQL
    // and PostgreSQL
    if (new SqlUtil(connection).isOracle() || new SqlUtil(connection).isHSQLDB()
            || new SqlUtil(connection).isDB2()) {
        table = table.toUpperCase();
    }

    ResultSet rs = null;

    if (!new SqlUtil(connection).isAccess()) {

        rs = databaseMetaData.getPrimaryKeys(catalog, schema, table);

        printResultSet(rs);

        boolean rsNext = false;

        while (rs.next()) {
            rsNext = true;
            String keyColumnName = rs.getString("COLUMN_NAME");
            MessageDisplayer.display("Primary Key is: " + keyColumnName + " for Table: " + table);
            Assert.assertEquals("customer_id", keyColumnName.toLowerCase());
        }

        if (!new SqlUtil(connection).isH2()) {
            Assert.assertEquals(true, rsNext);
        }

        rs.close();
    }

    // boolean returnNow = true;
    // if (returnNow) return;

    String[] types = { "TABLE", "VIEW" };
    rs = databaseMetaData.getTables(null, null, null, types);

    Set<String> tablesSet = new HashSet<String>();

    Set<String> ourTables = new HashSet<String>();
    ourTables.add("banned_usernames");
    ourTables.add("customer");
    ourTables.add("customer_auto");
    ourTables.add("orderlog");
    ourTables.add("user_login");

    MessageDisplayer.display("");
    while (rs.next()) {
        table = rs.getString("TABLE_NAME");

        if (ourTables.contains(table.toLowerCase())) {
            MessageDisplayer.display("Table: " + table);
        }

        tablesSet.add(table.toLowerCase());
    }

    // printResultSet(rs);

    testTable("banned_usernames", tablesSet);
    testTable("customer", tablesSet);
    testTable("orderlog", tablesSet);
    testTable("user_login", tablesSet);

    rs.close();
}