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: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 {/*from   w ww  .  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:org.gaixie.jibu.security.dao.SchemaCreate.java

/**
 * ?? dbscripts ? type???? sql /*from   w  ww  . j  av  a  2 s  .c o  m*/
 * <p>
 * @param type ? jibu.properties ?
 */
public void create(String type) {
    Connection conn = null;
    try {
        conn = ConnectionUtils.getConnection();
        DatabaseMetaData dbm = conn.getMetaData();

        ResultSet rs = dbm.getTables(null, null, "USERBASE", null);
        if (rs.next())
            throw new SQLException("Schema has been created!");

        String dpn = dbm.getDatabaseProductName();
        if (!"Apache Derby".equals(dpn))
            throw new SQLException("Database is not Apache Derby!");
        QueryRunner run = new QueryRunner();
        URL url = this.getClass().getResource("/dbscripts/" + type + "/");
        File dir = new File(url.toURI());
        File[] files = dir.listFiles();
        Arrays.sort(files);
        for (File file : files) {
            if (file.isFile()) {
                handleFile(run, conn, "/dbscripts/" + type + "/" + file.getName());
            }
        }
        DbUtils.commitAndClose(conn);
    } catch (SQLException se) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.warn("Schema create failed: " + se.getMessage());
    } catch (IOException ie) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.warn("Read SQL Scripts failed: " + ie.getMessage());
    } catch (URISyntaxException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.warn("Get SQL Scripts Directory failed: " + e.getMessage());
    }
}

From source file:org.nuxeo.ecm.directory.sql.SQLHelper.java

private boolean tableExists() throws DirectoryException {
    try {/*from w  ww . j  a  v  a2s .  c om*/
        // Check if table exists using metadata
        DatabaseMetaData metaData = connection.getMetaData();
        String schemaName = null;
        String productName = metaData.getDatabaseProductName();
        if ("Oracle".equals(productName)) {
            Statement st = connection.createStatement();
            String sql = "SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') FROM DUAL";
            log.trace("SQL: " + sql);
            ResultSet rs = st.executeQuery(sql);
            rs.next();
            schemaName = rs.getString(1);
            log.trace("checking existing tables for oracle database, schema: " + schemaName);
            rs.close();
            st.close();
        }
        ResultSet rs = metaData.getTables(null, schemaName, table.getPhysicalName(), new String[] { "TABLE" });
        boolean exists = rs.next();
        rs.close();
        log.debug(String.format("checking if table %s exists: %s", table.getPhysicalName(),
                Boolean.valueOf(exists)));
        return exists;
    } catch (SQLException e) {
        throw new DirectoryException(e);
    }
}

From source file:org.seasar.dbflute.helper.jdbc.connection.DfDataSourceHandler.java

protected void processConnectionMetaInfo(Connection conn) throws SQLException {
    if (_alreadySetupMeta) {
        return;//from w  w w  . jav a2s .  c o  m
    }
    try {
        final DfConnectionMetaInfo metaInfo = new DfConnectionMetaInfo();
        final DatabaseMetaData metaData = conn.getMetaData();
        metaInfo.setProductName(metaData.getDatabaseProductName());
        metaInfo.setProductVersion(metaData.getDatabaseProductVersion());
        metaInfo.setDriverName(metaData.getDriverName());
        metaInfo.setDriverVersion(metaData.getDriverVersion());
        final int majorVersion = metaData.getJDBCMajorVersion();
        final int minorVersion = metaData.getJDBCMinorVersion();
        metaInfo.setJdbcVersion(majorVersion + "." + minorVersion);
        _log.info("  product = " + metaInfo.getProductDisp());
        _log.info("  driver  = " + metaInfo.getDriverDisp());
        _connectionMetaInfo = metaInfo;
    } catch (SQLException continued) {
        _log.info("*Failed to get connection meta: " + continued.getMessage());
        _connectionMetaInfo = null;
    }
    _alreadySetupMeta = true;
}

From source file:binky.reportrunner.service.impl.DatasourceServiceImpl.java

@Override
public String testDataSource(RunnerDataSource runnerDs) {

    try {/*w  ww  . ja va  2s. c o  m*/
        //fix for issue 105 - when not editing password but just testing
        if (runnerDs.getPassword() == null || runnerDs.getPassword().trim().isEmpty()) {
            // see if ds already exists but we are hiding the password
            RunnerDataSource pwget = this.dataSourceDao.get(runnerDs.getDataSourceName());
            if (pwget != null) {
                logger.debug("supplied password was blank - using stored password (if any)");
                runnerDs.setPassword(pwget.getPassword());
            }
        } else {
            EncryptionUtil enc = new EncryptionUtil();
            runnerDs.setPassword(enc.encrpyt(this.secureKey, runnerDs.getPassword()));
        }

        DataSource ds = this.getDs(runnerDs);
        Connection conn = ds.getConnection();
        DatabaseMetaData meta = conn.getMetaData();
        String information = meta.getDatabaseProductName() + ", " + meta.getDatabaseProductVersion();
        conn.close();
        if (ds instanceof BasicDataSource) {
            ((BasicDataSource) ds).close();
        }
        return information;
    } catch (Exception e) {
        if (e instanceof NullPointerException) {
            logger.fatal(e.getMessage(), e);
        }
        logger.debug(e.getMessage());
        return "ERROR - " + e.getClass().getSimpleName() + ": " + e.getMessage();
    }
}

From source file:org.dashbuilder.dataprovider.sql.SQLDataSetTestBase.java

private void printDatabaseInfo() throws Exception {
    if (!_dbInfoPrinted) {
        DatabaseMetaData meta = conn.getMetaData();
        System.out.println(//from w  ww .  j  a va 2 s  . com
                "\n********************************************************************************************");
        System.out.println(String.format("Database: %s %s", meta.getDatabaseProductName(),
                meta.getDatabaseProductVersion()));
        System.out.println(String.format("Driver: %s %s", meta.getDriverName(), meta.getDriverVersion()));
        System.out.println(
                "*********************************************************************************************\n");
        _dbInfoPrinted = true;
    }
}

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 {//  w  w  w  . j  a  va 2 s . c om
        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:org.talend.metadata.managment.utils.MetadataConnectionUtils.java

public static boolean isSybase(DatabaseMetaData connectionMetadata) throws SQLException {
    if (connectionMetadata instanceof SybaseDatabaseMetaData) {
        return true;
    }//from  w  ww  .j  a v  a  2s  .  c  o  m
    if (connectionMetadata.getDriverName() != null && connectionMetadata.getDatabaseProductName() != null) {
        for (String keyString : getSybaseDBProductsName()) {
            if (keyString.trim().equals(connectionMetadata.getDatabaseProductName().trim())) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

public String getDatabaseType() {
    if (databaseType != null) {
        return databaseType;
    }/*from w w  w.j  av a 2s .  c o m*/
    try {
        @SuppressWarnings("deprecation")
        Connection connection = sessionFactory.getCurrentSession().connection();
        DatabaseMetaData metaData = connection.getMetaData();
        databaseType = metaData.getDatabaseProductName();
        if (databaseType.equals("Apache Derby")) {
            return databaseType = "derby";
        } else if (databaseType.equals("MySQL")) {
            return databaseType = "mysql";
        } else if (databaseType.equals("PostgreSQL")) {
            return databaseType = "postgres";
        } else if (databaseType.equals("Microsoft SQL Server")) {
            return databaseType = "mssql";
        } else {
            log.info(databaseType + " is not a supported database type");
        }
    } catch (HibernateException e) {
        log.error("Could not determine database type", e);
    } catch (SQLException e) {
        log.error("Could not determine database type", e);
    }
    return "unknown";
}

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;/*  ww  w  .  j a va2  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;
}