Example usage for java.sql DatabaseMetaData getDriverName

List of usage examples for java.sql DatabaseMetaData getDriverName

Introduction

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

Prototype

String getDriverName() throws SQLException;

Source Link

Document

Retrieves the name of this JDBC driver.

Usage

From source file:com.googlecode.psiprobe.controllers.sql.ConnectionTestController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    DataSource dataSource = null;

    try {//  w  w  w.j  a v  a2 s  .com
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName,
                getContainerWrapper());
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        try {
            // TODO: use Spring's jdbc template?
            Connection conn = dataSource.getConnection();
            try {
                DatabaseMetaData md = conn.getMetaData();

                List dbMetaData = new ArrayList();

                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdName",
                        md.getDatabaseProductName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdVersion",
                        md.getDatabaseProductVersion());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverName",
                        md.getDriverName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverVersion",
                        md.getDriverVersion());
                //                    addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcVersion", String.valueOf(md.getJDBCMajorVersion()));

                return new ModelAndView(getViewName(), "dbMetaData", dbMetaData);
            } finally {
                conn.close();
            }
        } catch (SQLException e) {
            String message = getMessageSourceAccessor()
                    .getMessage("probe.src.dataSourceTest.connection.failure", new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:net.testdriven.psiprobe.controllers.sql.ConnectionTestController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    DataSource dataSource = null;

    try {//  www  .j av a 2 s  . c o m
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName);
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        try {
            // TODO: use Spring's jdbc template?
            try (Connection conn = dataSource.getConnection()) {
                DatabaseMetaData md = conn.getMetaData();

                List<Map<String, String>> dbMetaData = new ArrayList<>();

                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdName",
                        md.getDatabaseProductName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdVersion",
                        md.getDatabaseProductVersion());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverName",
                        md.getDriverName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverVersion",
                        md.getDriverVersion());
                //                    addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcVersion", String.valueOf(md.getJDBCMajorVersion()));

                return new ModelAndView(getViewName(), "dbMetaData", dbMetaData);
            }
        } catch (SQLException e) {
            String message = getMessageSourceAccessor()
                    .getMessage("probe.src.dataSourceTest.connection.failure", new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:psiprobe.controllers.sql.ConnectionTestController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    DataSource dataSource = null;

    try {/*  ww w.  j  a  va2s. co  m*/
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName,
                getContainerWrapper());
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
        logger.trace("", e);
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        try {
            // TODO: use Spring's jdbc template?
            try (Connection conn = dataSource.getConnection()) {
                DatabaseMetaData md = conn.getMetaData();

                List<Map<String, String>> dbMetaData = new ArrayList<>();

                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdName",
                        md.getDatabaseProductName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdVersion",
                        md.getDatabaseProductVersion());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverName",
                        md.getDriverName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverVersion",
                        md.getDriverVersion());
                // addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcVersion",
                // String.valueOf(md.getJDBCMajorVersion()));

                return new ModelAndView(getViewName(), "dbMetaData", dbMetaData);
            }
        } catch (SQLException e) {
            String message = getMessageSourceAccessor()
                    .getMessage("probe.src.dataSourceTest.connection.failure", new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java

public Connection getConnection() throws GVDBException {
    try {//from   w w w  .  j  a  v a  2s.c  o  m
        Connection conn = dataSource.getConnection();
        if (debugJDBCConn) {
            logger.debug("Created JDBC Connection [" + name + "]: [" + conn + "]");
            if (isFirst) {
                isFirst = false;
                DatabaseMetaData dbmd = conn.getMetaData();

                logger.debug("=====  Database info =====");
                logger.debug("DatabaseProductName: " + dbmd.getDatabaseProductName());
                logger.debug("DatabaseProductVersion: " + dbmd.getDatabaseProductVersion());
                logger.debug("DatabaseMajorVersion: " + dbmd.getDatabaseMajorVersion());
                logger.debug("DatabaseMinorVersion: " + dbmd.getDatabaseMinorVersion());
                logger.debug("=====  Driver info =====");
                logger.debug("DriverName: " + dbmd.getDriverName());
                logger.debug("DriverVersion: " + dbmd.getDriverVersion());
                logger.debug("DriverMajorVersion: " + dbmd.getDriverMajorVersion());
                logger.debug("DriverMinorVersion: " + dbmd.getDriverMinorVersion());
                logger.debug("=====  JDBC/DB attributes =====");
                if (dbmd.supportsGetGeneratedKeys())
                    logger.debug("Supports getGeneratedKeys(): true");
                else
                    logger.debug("Supports getGeneratedKeys(): false");
            }
        }

        return conn;
    } catch (Exception exc) {
        throw new GVDBException("DriverPoolConnectionBuilder - Error while creating Connection[" + name + "]",
                exc);
    }
}

From source file:info.magnolia.about.app.AboutPresenter.java

public AboutView start() {

    // magnolia information
    LicenseFileExtractor licenseProperties = LicenseFileExtractor.getInstance();
    String mgnlEdition = getEditionName();
    String mgnlVersion = licenseProperties.get(LicenseFileExtractor.VERSION_NUMBER);
    String authorInstance = serverConfiguration.isAdmin() ? i18n.translate("about.app.main.instance.author")
            : i18n.translate("about.app.main.instance.public");

    // system information
    String osInfo = String.format("%s %s (%s)", magnoliaProperties.getProperty("os.name"),
            magnoliaProperties.getProperty("os.version"), magnoliaProperties.getProperty("os.arch"));
    String javaInfo = String.format("%s (build %s)", magnoliaProperties.getProperty("java.version"),
            magnoliaProperties.getProperty("java.runtime.version"));
    String serverInfo = MgnlContext.getWebContext().getServletContext().getServerInfo();

    String dbInfo;/*from   w  w  w  .  j a  va  2  s .c  o m*/
    String dbDriverInfo;
    Connection connection = null;
    try {

        String connectionString[] = getConnectionString();

        String repoHome = magnoliaProperties.getProperty("magnolia.repositories.home");
        String repoName = getRepoName();
        connectionString[0] = StringUtils.replace(connectionString[0], "${wsp.home}",
                repoHome + "/" + repoName + "/workspaces/default");
        connection = DriverManager.getConnection(connectionString[0], connectionString[1], connectionString[2]);
        DatabaseMetaData meta = connection.getMetaData();
        dbInfo = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
        if (dbInfo.toLowerCase().indexOf("mysql") != -1) {
            String engine = getMySQLEngineInfo(connection, connectionString);
            if (engine != null) {
                dbInfo += engine;
            }
        }
        dbDriverInfo = meta.getDriverName() + " " + meta.getDriverVersion();

    } catch (SQLException e) {
        log.debug("Failed to read DB and driver info from connection with {}", e.getMessage(), e);
        dbInfo = i18n.translate("about.app.main.unknown");
        dbDriverInfo = dbInfo;
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // ignore, nothing we can do
            }
        }
    }

    String jcrInfo;
    try {
        Repository repo = JcrUtils.getRepository();
        jcrInfo = String.format("%s %s", repo.getDescriptor("jcr.repository.name"),
                repo.getDescriptor("jcr.repository.version"));
    } catch (RepositoryException e) {
        log.debug("JCR repository information is not available", e);
        jcrInfo = "-";
    }

    // Prepare information for the view
    viewData.addItemProperty(AboutView.MAGNOLIA_EDITION_KEY, new ObjectProperty<String>(mgnlEdition));
    viewData.addItemProperty(AboutView.MAGNOLIA_VERSION_KEY, new ObjectProperty<String>(mgnlVersion));
    viewData.addItemProperty(AboutView.MAGNOLIA_INSTANCE_KEY, new ObjectProperty<String>(authorInstance));
    viewData.addItemProperty(AboutView.OS_INFO_KEY, new ObjectProperty<String>(osInfo));
    viewData.addItemProperty(AboutView.JAVA_INFO_KEY, new ObjectProperty<String>(javaInfo));
    viewData.addItemProperty(AboutView.SERVER_INFO_KEY, new ObjectProperty<String>(serverInfo));
    viewData.addItemProperty(AboutView.JCR_INFO_KEY, new ObjectProperty<String>(jcrInfo));
    viewData.addItemProperty(AboutView.DB_INFO_KEY, new ObjectProperty<String>(dbInfo));
    viewData.addItemProperty(AboutView.DB_DRIVER_INFO_KEY, new ObjectProperty<String>(dbDriverInfo));
    view.setDataSource(viewData);

    return view;
}

From source file:net.risesoft.soa.asf.web.controller.SystemController.java

private List<SysInfo> getDBInfo() {
    List list = new ArrayList();
    String group = "4. ??";
    try {/*from w w w  . j  av  a2  s  .  c om*/
        Connection conn = this.basicDataSource.getConnection();
        try {
            DatabaseMetaData dbmd = conn.getMetaData();
            list.add(new SysInfo("DatabaseProductName", dbmd.getDatabaseProductName(), group));
            list.add(new SysInfo("DatabaseProductVersion", dbmd.getDatabaseProductVersion(), group));
            list.add(new SysInfo("DatabaseMajorVersion", Integer.valueOf(dbmd.getDatabaseMajorVersion()),
                    group));
            list.add(new SysInfo("DatabaseMinorVersion", Integer.valueOf(dbmd.getDatabaseMinorVersion()),
                    group));
            list.add(new SysInfo("DriverName", dbmd.getDriverName(), group));
            list.add(new SysInfo("DriverVersion", dbmd.getDriverVersion(), group));
            list.add(new SysInfo("DriverMajorVersion", Integer.valueOf(dbmd.getDriverMajorVersion()), group));
            list.add(new SysInfo("DriverMinorVersion", Integer.valueOf(dbmd.getDriverMinorVersion()), group));
        } finally {
            conn.close();
        }
        group = "5. ?";
        BasicDataSource bds = this.basicDataSource;
        list.add(new SysInfo("InitialSize", Integer.valueOf(bds.getInitialSize()), group));
        list.add(new SysInfo("MaxActive", Integer.valueOf(bds.getMaxActive()), group));
        list.add(new SysInfo("MaxIdle", Integer.valueOf(bds.getMaxIdle()), group));
        list.add(new SysInfo("MinIdle", Integer.valueOf(bds.getMinIdle()), group));
        list.add(new SysInfo("MaxWait", Long.valueOf(bds.getMaxWait()), group));
        list.add(new SysInfo("NumActive", Integer.valueOf(bds.getNumActive()), group));
        list.add(new SysInfo("NumIdle", Integer.valueOf(bds.getNumIdle()), group));
        list.add(new SysInfo("DriverClass", bds.getDriverClassName(), group));
        list.add(new SysInfo("URL", bds.getUrl(), group));
        list.add(new SysInfo("Username", bds.getUsername(), group));
        list.add(new SysInfo("Password", "******", group));
    } catch (Exception ex) {
        log.warn("???: " + ex.getMessage(), ex);
    }
    return list;
}

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

/**
 * {@inheritDoc}/*from   ww w. j  av  a2s . c om*/
 */
@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.metis.push.PusherBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *///  w  w w . jav  a 2 s  .co  m
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: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 a  v  a  2s .  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:net.certifi.audittablegen.AuditTableGen.java

/**
 * Validates the provided dataSource and gets a DataSourceDMR
 * object to manage database interaction.  Sets initialized flag
 * to true if initialization is successful.
 * @throws SQLException //from  w  w  w.j  av  a  2 s.com
 */
void initialize() throws SQLException {

    Connection connection = dataSource.getConnection();
    //Properties connectionProperties = connection.getClientInfo();
    DatabaseMetaData dmd = connection.getMetaData();

    logger.debug("DatabaseProduct: {}", dmd.getDatabaseProductName());

    try {
        catalog = connection.getCatalog();

        if (schema.isEmpty() || schema == null) {
            try {
                schema = connection.getSchema();
            } catch (AbstractMethodError e) {
                logger.error("Abstract method getSchema() not implemented", e);
                schema = "";
            }
        }
    } catch (SQLException e) {
        logger.error("Error getting catalog/schema", e);

    }

    if (dmd.getDriverName().toLowerCase().contains("postgresql")) {
        dmr = new PostgresqlDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else if (dmd.getDriverName().toLowerCase().contains("hsqldb")) {
        dmr = new HsqldbDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else {
        //generic implementation
        dmr = new GenericDMR(dataSource, schema);
        logger.info("attempting to run against unknown database product");
    }

    if (dmr != null) {
        this.initialized = true;
    }

    if (schema != null && !schema.isEmpty()) {
        dmr.setSchema(schema);

        if (dmr.getSchema() == null) {
            throw new RuntimeException("Schema could not be found.");
        }
    }

}