Example usage for java.sql DatabaseMetaData getDatabaseProductVersion

List of usage examples for java.sql DatabaseMetaData getDatabaseProductVersion

Introduction

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

Prototype

String getDatabaseProductVersion() throws SQLException;

Source Link

Document

Retrieves the version number of this database product.

Usage

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}// w  ww .  j  ava 2 s. co  m
 */
public void init(PMContext context) throws Exception {
    if (initialized) {
        throw new IllegalStateException("already initialized");
    }

    // setup jdbc connection
    initConnection();

    DatabaseMetaData meta = con.getMetaData();
    try {
        log.info("Database: " + meta.getDatabaseProductName() + " / " + meta.getDatabaseProductVersion());
        log.info("Driver: " + meta.getDriverName() + " / " + meta.getDriverVersion());
    } catch (SQLException e) {
        log.warn("Can not retrieve database and driver name / version", e);
    }

    // make sure schemaObjectPrefix consists of legal name characters only
    prepareSchemaObjectPrefix();

    // check if schema objects exist and create them if necessary
    if (isSchemaCheckEnabled()) {
        checkSchema();
    }

    // build sql statements
    buildSQLStatements();

    // prepare statements
    initPreparedStatements();

    if (externalBLOBs) {
        /**
         * store BLOBs in local file system in a sub directory
         * of the workspace home directory
         */
        LocalFileSystem blobFS = new LocalFileSystem();
        blobFS.setRoot(new File(context.getHomeDir(), "blobs"));
        blobFS.init();
        this.blobFS = blobFS;
        blobStore = new FileSystemBLOBStore(blobFS);
    } else {
        /**
         * store BLOBs in db
         */
        blobStore = new DbBLOBStore();
    }

    initialized = true;
}

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.");
        }//  w w w  .jav a2 s .  com
        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:it.eng.spagobi.meta.initializer.PhysicalModelInitializer.java

private void addDatabase(DatabaseMetaData dbMeta, PhysicalModel model) {
    try {//from ww w .  j a  v a2s .  co m
        model.setDatabaseName(dbMeta.getDatabaseProductName());
        model.setDatabaseVersion(dbMeta.getDatabaseProductVersion());
    } catch (Throwable t) {
        throw new RuntimeException("Impossible to initialize database metadata", t);
    }
}

From source file:com.netspective.axiom.policy.AnsiDatabasePolicy.java

public void reverseEngineer(Writer writer, Connection conn, String catalog, String schemaPattern)
        throws IOException, SQLException {
    Map dataTypesMap = prepareJdbcTypeInfoMap();
    DatabaseMetaData dbmd = conn.getMetaData();
    TextUtils textUtils = TextUtils.getInstance();

    writer.write("<?xml version=\"1.0\"?>\n\n");
    writer.write("<!-- Reverse engineered by Axiom\n");
    writer.write("     driver: " + dbmd.getDriverName() + "\n");
    writer.write("     driver-version: " + dbmd.getDriverVersion() + "\n");
    writer.write("     product: " + dbmd.getDatabaseProductName() + "\n");
    writer.write("     product-version: " + dbmd.getDatabaseProductVersion() + "\n");

    writer.write("     available catalogs:");
    ResultSet rs = null;/*from   w ww.ja  v a 2  s.c  om*/
    try {
        rs = dbmd.getCatalogs();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }

    writer.write("\n");

    writer.write("     available schemas:");
    try {
        rs = dbmd.getSchemas();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }
    writer.write("\n");
    writer.write("-->\n\n");

    writer.write("<component xmlns:xdm=\"http://www.netspective.org/Framework/Commons/XMLDataModel\">\n");
    writer.write("    <xdm:include resource=\"com/netspective/axiom/conf/axiom.xml\"/>\n");
    writer.write("    <schema name=\"" + catalog + "." + schemaPattern + "\">\n");

    Map dbmdTypeInfoByName = new HashMap();
    Map dbmdTypeInfoByJdbcType = new HashMap();
    ResultSet typesRS = null;
    try {
        typesRS = dbmd.getTypeInfo();
        while (typesRS.next()) {
            int colCount = typesRS.getMetaData().getColumnCount();
            Object[] typeInfo = new Object[colCount];
            for (int i = 1; i <= colCount; i++)
                typeInfo[i - 1] = typesRS.getObject(i);
            dbmdTypeInfoByName.put(typesRS.getString(1), typeInfo);
            dbmdTypeInfoByJdbcType.put(new Integer(typesRS.getInt(2)), typeInfo);
        }
    } finally {
        if (typesRS != null)
            typesRS.close();
    }

    ResultSet tables = null;
    try {
        tables = dbmd.getTables(catalog, schemaPattern, null, new String[] { "TABLE" });
        while (tables.next()) {
            String tableNameOrig = tables.getString(3);
            String tableName = textUtils.fixupTableNameCase(tableNameOrig);

            writer.write("        <table name=\"" + tableName + "\">\n");

            Map primaryKeys = new HashMap();
            ResultSet pkRS = null;
            try {
                pkRS = dbmd.getPrimaryKeys(null, null, tableNameOrig);
                while (pkRS.next()) {
                    primaryKeys.put(pkRS.getString(4), pkRS.getString(5));
                }

            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (pkRS != null)
                    pkRS.close();
            }

            Map fKeys = new HashMap();
            ResultSet fkRS = null;
            try {
                fkRS = dbmd.getImportedKeys(null, null, tableNameOrig);
                while (fkRS.next()) {
                    fKeys.put(fkRS.getString(8), textUtils.fixupTableNameCase(fkRS.getString(3)) + "."
                            + fkRS.getString(4).toLowerCase());
                }
            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (fkRS != null)
                    fkRS.close();
            }

            // we keep track of processed columns so we don't duplicate them in the XML
            Set processedColsMap = new HashSet();
            ResultSet columns = null;
            try {
                columns = dbmd.getColumns(null, null, tableNameOrig, null);
                while (columns.next()) {
                    String columnNameOrig = columns.getString(4);
                    if (processedColsMap.contains(columnNameOrig))
                        continue;
                    processedColsMap.add(columnNameOrig);

                    String columnName = columnNameOrig.toLowerCase();

                    writer.write("            <column name=\"" + columnName + "\"");
                    try {
                        if (fKeys.containsKey(columnNameOrig))
                            writer.write(" lookup-ref=\"" + fKeys.get(columnNameOrig) + "\"");
                        else {
                            short jdbcType = columns.getShort(5);
                            String dataType = (String) dataTypesMap.get(new Integer(jdbcType));
                            if (dataType == null)
                                dataType = Short.toString(jdbcType);
                            writer.write(" type=\"" + dataType + "\"");
                        }

                        if (primaryKeys.containsKey(columnNameOrig))
                            writer.write(" primary-key=\"yes\"");

                        if (columns.getString(18).equals("NO"))
                            writer.write(" required=\"yes\"");

                        String defaultValue = columns.getString(13);
                        if (defaultValue != null)
                            writer.write(" default=\"" + defaultValue + "\"");

                        String remarks = columns.getString(12);
                        if (remarks != null)
                            writer.write(" descr=\"" + remarks + "\"");

                    } catch (Exception e) {
                    }

                    writer.write("/>\n");
                }
            } finally {
                if (columns != null)
                    columns.close();
            }

            writer.write("        </table>\n");
        }
    } finally {
        tables.close();
    }

    writer.write("    </schema>\n");
    writer.write("</component>");
}

From source file:org.schemaspy.SchemaAnalyzer.java

public Database analyze(String schema, Config config, File outputDir, ProgressListener progressListener)
        throws SQLException, IOException {
    try {//from   w  w w  .jav a2s.com
        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.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.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//from   www  .  ja  v  a 2s. c o  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:org.sakaiproject.warehouse.util.db.DbLoader.java

protected String getLocalDataTypeName(String genericDataTypeName) {

    String localDataTypeName = null;

    try {/*from  w  ww.ja  va 2  s.  c  o  m*/
        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.metis.push.PusherBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *//* w  ww  .  j  a v a2s . 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:net.hydromatic.optiq.test.JdbcTest.java

/**
 * Make sure that the properties look sane.
 *//*  ww w  . j a  v a  2 s.  co m*/
@Test
public void testVersion() throws ClassNotFoundException, SQLException {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    final DatabaseMetaData metaData = optiqConnection.getMetaData();
    assertEquals("Optiq JDBC Driver", metaData.getDriverName());

    final String driverVersion = metaData.getDriverVersion();
    final int driverMajorVersion = metaData.getDriverMajorVersion();
    final int driverMinorVersion = metaData.getDriverMinorVersion();
    assertEquals(0, driverMajorVersion);
    assertEquals(4, driverMinorVersion);

    assertEquals("Optiq", metaData.getDatabaseProductName());
    final String databaseProductVersion = metaData.getDatabaseProductVersion();
    final int databaseMajorVersion = metaData.getDatabaseMajorVersion();
    assertEquals(driverMajorVersion, databaseMajorVersion);
    final int databaseMinorVersion = metaData.getDatabaseMinorVersion();
    assertEquals(driverMinorVersion, databaseMinorVersion);

    // Check how version is composed of major and minor version. Note that
    // version is stored in pom.xml; major and minor version are
    // stored in net-hydromatic-optiq-jdbc.properties.
    if (!driverVersion.endsWith("-SNAPSHOT")) {
        assertTrue(driverVersion.startsWith("0."));
        String[] split = driverVersion.split("\\.");
        assertTrue(split.length >= 2);
        assertTrue(driverVersion.startsWith(driverMajorVersion + "." + driverMinorVersion + "."));
    }
    if (!databaseProductVersion.endsWith("-SNAPSHOT")) {
        assertTrue(databaseProductVersion.startsWith("0."));
        String[] split = databaseProductVersion.split("\\.");
        assertTrue(split.length >= 2);
        assertTrue(databaseProductVersion.startsWith(databaseMajorVersion + "." + databaseMinorVersion + "."));
    }

    connection.close();
}