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.dspace.storage.rdbms.DatabaseUtils.java

/**
 * Print basic information about the current database to System.out.
 * This is utilized by both the 'test' and 'info' commandline options.
 * @param connection current database connection
 * @throws SQLException if database error occurs
 *//*from   w w w  .jav  a 2  s  .  c om*/
private static void printDBInfo(Connection connection) throws SQLException {
    // Get basic Database info from connection
    DatabaseMetaData meta = connection.getMetaData();
    String dbType = getDbType(connection);
    System.out.println("\nDatabase Type: " + dbType);
    System.out.println("Database URL: " + meta.getURL());
    System.out.println("Database Schema: " + getSchemaName(connection));
    System.out.println("Database Username: " + meta.getUserName());
    System.out.println("Database Software: " + meta.getDatabaseProductName() + " version "
            + meta.getDatabaseProductVersion());
    System.out.println("Database Driver: " + meta.getDriverName() + " version " + meta.getDriverVersion());

    // For Postgres, report whether pgcrypto is installed
    // (If it isn't, we'll also write out warnings...see below)
    if (dbType.equals(DBMS_POSTGRES)) {
        boolean pgcryptoUpToDate = PostgresUtils.isPgcryptoUpToDate();
        Double pgcryptoVersion = PostgresUtils.getPgcryptoInstalledVersion(connection);
        System.out.println("PostgreSQL '" + PostgresUtils.PGCRYPTO + "' extension installed/up-to-date? "
                + pgcryptoUpToDate + " "
                + ((pgcryptoVersion != null) ? "(version=" + pgcryptoVersion + ")" : "(not installed)"));
    }
}

From source file:com.jaxio.celerio.configuration.database.support.MetadataExtractor.java

private DatabaseInfo extractDatabaseInfo(DatabaseMetaData databaseMetaData) {
    DatabaseInfo database = new DatabaseInfo();

    // database/*from   w  w  w .j a v a  2 s. c o  m*/
    try {
        database.setDatabaseProductName(databaseMetaData.getDatabaseProductName());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDatabaseProductVersion(databaseMetaData.getDatabaseProductVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDatabaseMajorVersion(databaseMetaData.getDatabaseMajorVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDatabaseMinorVersion(databaseMetaData.getDatabaseMinorVersion());
    } catch (Exception e) { /* ignore */
    }

    // driver
    try {
        database.setDriverName(databaseMetaData.getDriverName());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDriverVersion(databaseMetaData.getDriverVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDriverMajorVersion(databaseMetaData.getDriverMajorVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDriverMinorVersion(databaseMetaData.getDriverMinorVersion());
    } catch (Exception e) { /* ignore */
    }

    return database;
}

From source file:com.flexive.ejb.beans.configuration.GlobalConfigurationEngineBean.java

/**
 * {@inheritDoc}//from w w  w  .j  av a2  s . com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public DivisionData createDivisionData(int divisionId, String dataSource, String domainRegEx) {
    String dbVendor = "unknown";
    String dbVersion = "unknown";
    String dbDriverVersion = "unknown";
    boolean available = false;
    Connection con = null;
    try {
        // lookup non-transactional datasource to avoid issues with the default JEE6 data source in Glassfish
        con = Database.getDataSource(dataSource + "NoTX").getConnection();
        DatabaseMetaData dbmd = con.getMetaData();
        dbVendor = dbmd.getDatabaseProductName();
        dbVersion = dbmd.getDatabaseProductVersion();
        dbDriverVersion = dbmd.getDriverName() + " " + dbmd.getDriverVersion();
        available = true;
    } catch (NamingException e) {
        LOG.error("Failed to get datasource " + dataSource + " (flagged inactive)");
    } catch (SQLException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to get database meta information: " + e.getMessage(), e);
        }
    } finally {
        Database.closeObjects(GlobalConfigurationEngineBean.class, con, null);
    }
    return new DivisionData(divisionId, available, dataSource, domainRegEx, dbVendor, dbVersion,
            dbDriverVersion);
}

From source file:org.apache.openjpa.jdbc.sql.MySQLDictionary.java

@Override
public void connectedConfiguration(Connection conn) throws SQLException {
    super.connectedConfiguration(conn);

    DatabaseMetaData metaData = conn.getMetaData();
    int maj = 0;/*from   w  ww  .  j  a va  2 s  .  c  o  m*/
    int min = 0;
    if (isJDBC3) {
        maj = metaData.getDatabaseMajorVersion();
        min = metaData.getDatabaseMinorVersion();
    } else {
        try {
            // The product version looks like 4.1.3-nt or 5.1.30
            String productVersion = metaData.getDatabaseProductVersion();
            int[] versions = getMajorMinorVersions(productVersion);
            maj = versions[0];
            min = versions[1];
        } catch (IllegalArgumentException e) {
            // we don't understand the version format.
            // That is ok. We just take the default values.
            if (log.isWarnEnabled())
                log.warn(e.toString(), e);
        }
    }
    if (maj < 4 || (maj == 4 && min < 1)) {
        supportsSubselect = false;
        allowsAliasInBulkClause = false;
        supportsForeignKeysComposite = false;
    }
    if (maj > 5 || (maj == 5 && min >= 1))
        supportsXMLColumn = true;

    if (metaData.getDriverMajorVersion() < 5)
        driverDeserializesBlobs = true;
}

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

private void initHeartbeat() {
    osName = System.getProperty("os.name");
    osVersion = System.getProperty("os.version");
    javaVendor = System.getProperty("java.vendor");
    javaVersion = System.getProperty("java.version");
    serverInfo = servletContext.getServerInfo();
    location = servletContext.getRealPath("/");
    dbName = null;/*from  w w w.ja v a  2  s  . c om*/
    dbVersion = null;

    Connection connection = null;

    try {
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();

        dbName = metaData.getDatabaseProductName();
        dbVersion = metaData.getDatabaseProductVersion();
    } catch (SQLException e) {
        if (log.isDebugEnabled())
            log.debug("Getting database metadata failed.", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }

    String idSource =
            //javaVendor + "|" 
            //+ javaVersion + "|" 
            serverInfo + "|" + productName + "|"
            //+ productVersion + "|" 
                    + (location == null ? "" : location);

    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        //heartbeat is always silent
    }

    if (messageDigest == null) {
        localId = String.valueOf(idSource.hashCode());
    } else {
        byte[] idBytes = messageDigest.digest(idSource.getBytes());
        StringBuffer idBuffer = new StringBuffer(2 * idBytes.length);
        for (int i = 0; i < idBytes.length; i++) {
            String hexa = Integer.toHexString(128 + idBytes[i]).toUpperCase();
            hexa = ("00" + hexa).substring(hexa.length());
            idBuffer.append(hexa);
        }
        localId = idBuffer.toString();
    }

    /*   */
    File localIdFile = getLocalIdFile();
    if (localIdFile.exists() && localIdFile.isFile()) {
        localIdProperties = new Properties();

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(localIdFile);
            localIdProperties.load(fis);
        } catch (IOException e) {
            if (log.isDebugEnabled())
                log.debug("Loading heartbeat local ID properties file failed.", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
    }
    heartbeatId = localIdProperties.getProperty(PROPERTY_HEARTBEAT_ID);

    /*   */
    File clientInfoCacheFile = getClientInfoCacheFile();
    if (clientInfoCacheFile.exists() && clientInfoCacheFile.isFile()) {
        try {
            clientInfoCache = (HeartbeatInfoCache) JRLoader.loadObject(clientInfoCacheFile);
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("Loading heartbeat cache from serialized file failed.", e);
        }
    }
    lastCacheSaveTime = System.currentTimeMillis();
}

From source file:com.atlassian.jira.startup.JiraSystemInfo.java

/**
 * Obtains database configuration information.  This should be called after the database has been checked for sanity
 * and hence we can safely do some entityengine.xml and database connection test. But this is before the database is
 * auto-created and hence the support team can get valuable configuration information before a real DB cockup is
 * encountered.//from   w  ww  .  j  av a2 s.  c o  m
 */
public void obtainDatabaseConfigurationInfo() {
    logMsg.outputHeader("Database Configuration");
    final URL entityEngineURL = ClassLoaderUtils.getResource("entityengine.xml", getClass());
    logMsg.outputProperty("Loading entityengine.xml from", entityEngineURL.toString());

    final DatasourceInfo datasourceInfo = connectionFactory.getDatasourceInfo();
    if (datasourceInfo != null) {
        logMsg.outputProperty("Entity model field type name", datasourceInfo.getFieldTypeName());
        logMsg.outputProperty("Entity model schema name", datasourceInfo.getSchemaName());
    }

    Connection connection = null;
    try {
        connection = connectionFactory.getConnection();
        final DatabaseMetaData metaData = connection.getMetaData();
        final SystemInfoUtils jiraSysInfo = new SystemInfoUtilsImpl();

        logMsg.outputProperty("Database Version",
                metaData.getDatabaseProductName() + " - " + metaData.getDatabaseProductVersion());
        logMsg.outputProperty("Database Driver",
                metaData.getDriverName() + " - " + metaData.getDriverVersion());
        logMsg.outputProperty("Database URL", maskURL(metaData.getURL()));
        logMsg.outputProperty(jiraSysInfo.getDbDescriptorLabel(), jiraSysInfo.getDbDescriptorValue());
    } catch (final SQLException e) {
        // dont worry about this exception here. Code later one will barf on the same problem and do more appropriate actions.
        // We are just trying to get startup information for support purposes for now.
        log.debug(e);
    } finally {
        silentlyClose(connection);
    }

}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

/**
 * Create a column group and confirm that the {@code ResultSetMetaData} works.
 *///  w ww.  j  a v a  2 s.  c  o m
@Test
public void testResultSetMetaData() throws Exception {

    Statement stmt = con.createStatement();

    // Create the target Column family
    String createCF = "CREATE COLUMNFAMILY t33 (k int PRIMARY KEY," + "c text " + ") ;";

    stmt.execute(createCF);
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    // paraphrase of the snippet from the ISSUE #33 provided test
    PreparedStatement statement = con.prepareStatement("update t33 set c=? where k=123");
    statement.setString(1, "mark");
    statement.executeUpdate();

    ResultSet result = statement.executeQuery("SELECT k, c FROM t33;");

    ResultSetMetaData metadata = result.getMetaData();

    int colCount = metadata.getColumnCount();

    System.out.println("Test Issue #33");
    DatabaseMetaData md = con.getMetaData();
    System.out.println();
    System.out.println("--------------");
    System.out.println("Driver Version :   " + md.getDriverVersion());
    System.out.println("DB Version     :   " + md.getDatabaseProductVersion());
    System.out.println("Catalog term   :   " + md.getCatalogTerm());
    System.out.println("Catalog        :   " + con.getCatalog());
    System.out.println("Schema term    :   " + md.getSchemaTerm());

    System.out.println("--------------");
    while (result.next()) {
        metadata = result.getMetaData();
        colCount = metadata.getColumnCount();

        assertEquals("Total column count should match schema for t33", 2, metadata.getColumnCount());

        System.out.printf("(%d) ", result.getRow());
        for (int i = 1; i <= colCount; i++) {
            System.out.print(showColumn(i, result) + " ");

            switch (i) {
            case 1:
                assertEquals("First Column: k", "k", metadata.getColumnName(1));
                assertEquals("First Column Type: int", Types.INTEGER, metadata.getColumnType(1));
                break;
            case 2:
                assertEquals("Second Column: c", "c", metadata.getColumnName(2));
                assertEquals("Second Column Type: text", Types.NVARCHAR, metadata.getColumnType(2));
                break;
            }
        }
        System.out.println();
    }
}

From source file:net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.java

/**
 * /*w  w w  .j a va2s.  c  om*/
 */
public JRJdbcQueryExecuter(JasperReportsContext jasperReportsContext, JRDataset dataset,
        Map<String, ? extends JRValueParameter> parameters) {
    super(jasperReportsContext, dataset, parameters);

    connection = (Connection) getParameterValue(JRParameter.REPORT_CONNECTION);
    if (connection == null) {
        if (log.isWarnEnabled()) {
            log.warn("The supplied java.sql.Connection object is null.");
        }
    } else if (log.isDebugEnabled()) {
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            log.debug("DB is " + metaData.getDatabaseProductName() + " version "
                    + metaData.getDatabaseProductVersion() + " (" + metaData.getDatabaseMajorVersion() + "/"
                    + metaData.getDatabaseMinorVersion() + ")");
            log.debug("driver is " + metaData.getDriverName() + " version " + metaData.getDriverVersion() + " ("
                    + metaData.getDriverMajorVersion() + "/" + metaData.getDriverMinorVersion() + ")");
            log.debug("jdbc " + metaData.getJDBCMajorVersion() + "/" + metaData.getJDBCMinorVersion());
            log.debug("connection URL is " + metaData.getURL());
        } catch (SQLException e) {
            log.debug("failed to read connection metadata", e);
        }
    }

    isCachedRowSet = getBooleanParameterOrProperty(JRJdbcQueryExecuterFactory.PROPERTY_CACHED_ROWSET, false);

    setTimeZone();

    registerFunctions();

    parseQuery();
}

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

public void createDatabaseInfoCache() {
    databaseInfoCache = new HeartbeatInfoCache();

    List dataSources = new ArrayList();

    try {/*from  w  ww  .ja v  a  2s.  co m*/
        List jdbcDataSources = repositoryService
                .loadClientResources(FilterCriteria.createFilter(JdbcReportDataSource.class));
        if (jdbcDataSources != null)
            dataSources.addAll(jdbcDataSources);
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Getting JDBC data sources list failed.", e);
    }

    try {
        List jndiDataSources = repositoryService
                .loadClientResources(FilterCriteria.createFilter(JndiJdbcReportDataSource.class));
        if (jndiDataSources != null)
            dataSources.addAll(jndiDataSources);
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Getting JNDI data sources list failed.", e);
    }

    for (Iterator it = dataSources.iterator(); it.hasNext();) {
        ReportDataSource dataSource = (ReportDataSource) it.next();

        Map paramValues = new HashMap();

        try {
            ReportDataSourceService dataSourceService = engineService.createDataSourceService(dataSource);
            dataSourceService.setReportParameterValues(paramValues);
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("Getting connection to data source failed.", e);
        }

        Connection connection = (Connection) paramValues.get(JRParameter.REPORT_CONNECTION);
        if (connection != null) {
            try {
                DatabaseMetaData metaData = connection.getMetaData();

                HeartbeatDatabaseInfo dbInfo = new HeartbeatDatabaseInfo();
                dbInfo.setDatabaseName(metaData.getDatabaseProductName());
                dbInfo.setDatabaseVersion(metaData.getDatabaseProductVersion());
                databaseInfoCache.update(dbInfo);
            } catch (SQLException e) {
                if (log.isDebugEnabled())
                    log.debug("Getting database metadata failed.", e);
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                    }
                }
            }
        }
    }
}

From source file:org.acmsl.queryj.tools.handlers.DatabaseMetaDataRetrievalHandler.java

/**
 * Retrieves the product version.//from  w  w w .  j  av a  2s .  co  m
 * @param metaData the database metadata.
 * @return the product version.
 */
@NotNull
protected String retrieveProductVersion(@NotNull final DatabaseMetaData metaData) {
    @NotNull
    String result = "";

    try {
        result = metaData.getDatabaseProductVersion();
    } catch (@NotNull final SQLException sqlException) {
        @Nullable
        final Log t_Log = UniqueLogFactory.getLog(DatabaseMetaDataRetrievalHandler.class);

        if (t_Log != null) {
            t_Log.error("Cannot retrieve database vendor's product version.", sqlException);
        }
    }

    return result;
}