Example usage for java.sql Connection getMetaData

List of usage examples for java.sql Connection getMetaData

Introduction

In this page you can find the example usage for java.sql Connection getMetaData.

Prototype

DatabaseMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

Usage

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

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

    List dataSources = new ArrayList();

    try {//  w ww  .j a  v a2 s  . c om
        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:com.glaf.core.web.springmvc.MxSystemDbTableController.java

@ResponseBody
@RequestMapping("/json")
public byte[] json(HttpServletRequest request) throws IOException {
    JSONObject result = new JSONObject();
    JSONArray rowsJSON = new JSONArray();
    String[] types = { "TABLE" };
    Connection connection = null;
    try {/*w ww. j a  va2  s  . com*/
        connection = DBConnectionFactory.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rs = metaData.getTables(null, null, null, types);
        int startIndex = 1;
        while (rs.next()) {
            String tableName = rs.getObject("TABLE_NAME").toString();
            if (!DBUtils.isAllowedTable(tableName)) {
                continue;
            }
            if (tableName.toLowerCase().startsWith("cell_useradd")) {
                continue;
            }
            if (tableName.toLowerCase().startsWith("sys_data_log")) {
                continue;
            }
            if (tableName.toLowerCase().startsWith("temp")) {
                continue;
            }
            if (tableName.toLowerCase().startsWith("tmp")) {
                continue;
            }

            if (DBUtils.isTemoraryTable(tableName)) {
                continue;
            }
            JSONObject json = new JSONObject();
            json.put("startIndex", startIndex++);
            json.put("cat", rs.getObject("TABLE_CAT"));
            json.put("schem", rs.getObject("TABLE_SCHEM"));
            json.put("tablename", tableName);
            json.put("tableName_enc", RequestUtils.encodeString(tableName));
            rowsJSON.add(json);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(connection);
    }

    result.put("rows", rowsJSON);
    result.put("total", rowsJSON.size());
    return result.toJSONString().getBytes("UTF-8");
}

From source file:cn.com.xdays.xshop.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }//from   w ww . j  av  a  2 s  .  c o m
    if (StringUtils.isEmpty(databaseHost)) {
        return ajaxJsonErrorMessage("?!");
    }
    if (StringUtils.isEmpty(databasePort)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(databasePassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseName)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminPassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(installStatus)) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, "requiredCheckFinish");
        return ajaxJson(jsonMap);
    }

    String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName
            + "?useUnicode=true&characterEncoding=UTF-8";

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        // ?
        connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword);
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] types = { "TABLE" };
        resultSet = databaseMetaData.getTables(null, databaseName, "%", types);
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) {
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, "databaseCheckFinish");
            return ajaxJson(jsonMap);
        }

        // ?
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) {
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
            String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                    .getPath() + SQL_INSTALL_FILE_NAME;
            bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            String line = "";
            while (null != line) {
                line = bufferedReader.readLine();
                stringBuffer.append(line);
                if (null != line && line.endsWith(";")) {
                    System.out.println("[SHOP++?]SQL: " + line);
                    preparedStatement = connection.prepareStatement(stringBuffer.toString());
                    preparedStatement.executeUpdate();
                    stringBuffer = new StringBuffer();
                }
            }
            String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','"
                    + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');";
            String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');";
            preparedStatement = connection.prepareStatement(insertAdminSql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(insertAdminRoleSql);
            preparedStatement.executeUpdate();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return ajaxJsonErrorMessage("???!");
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ???
    String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
            + JDBC_CONFIG_FILE_NAME;
    Properties properties = new Properties();
    properties.put("jdbc.driver", "com.mysql.jdbc.Driver");
    properties.put("jdbc.url", jdbcUrl);
    properties.put("jdbc.username", databaseUsername);
    properties.put("jdbc.password", databasePassword);
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    OutputStream outputStream = new FileOutputStream(configFilePath);
    properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION);
    outputStream.close();

    // ??
    String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + BACKUP_WEB_CONFIG_FILE_NAME;
    String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    String webConfigFilePath = new File(
            Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/"
            + WEB_CONFIG_FILE_NAME;
    String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("")
            .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath));
    FileUtils.copyFile(new File(backupApplicationContextConfigFilePath),
            new File(applicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath),
            new File(compassApplicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath),
            new File(securityApplicationContextConfigFilePath));

    // ??
    String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
    File systemConfigFile = new File(systemConfigFilePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(systemConfigFile);
    Element rootElement = document.getRootElement();
    Element systemConfigElement = rootElement.element("systemConfig");
    Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
    if (isInstalledNode == null) {
        isInstalledNode = systemConfigElement.addElement("isInstalled");
    }
    isInstalledNode.setText("true");
    try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML?
        outputFormat.setEncoding("UTF-8");// XML?
        outputFormat.setIndent(true);// ?
        outputFormat.setIndent("   ");// TAB?
        outputFormat.setNewlines(true);// ??
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxJsonSuccessMessage("SHOP++?????");
}

From source file:org.tec.webapp.jdbc.service.impl.SystemSvcImpl.java

/**
 * {@inheritDoc}/*from  w  ww  .  j av a 2 s .c o m*/
 */
@Override()
public SerializableList<StatusBean> getStatus() {
    Connection conn = null;
    try {
        SerializableList<StatusBean> slist = new SerializableList<StatusBean>();

        // get java information
        slist.add(new StatusBean("java.version", System.getProperty("java.version")));

        //get Servlet information
        slist.add(new StatusBean("server.info", mServletContext.getServerInfo()));

        StringBuilder buff = new StringBuilder();

        buff.append(mServletContext.getMajorVersion());
        buff.append('.');
        buff.append(mServletContext.getMinorVersion());

        slist.add(new StatusBean("servlet.version", buff.toString()));

        // get database information
        conn = mDataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        slist.add(new StatusBean("database.server", dmd.getDatabaseProductName()));
        slist.add(new StatusBean("database.version", dmd.getDatabaseProductVersion()));
        slist.add(new StatusBean("jdbc.driver", dmd.getDriverName()));
        slist.add(new StatusBean("jdbc.driver.version", dmd.getDriverVersion()));

        // spring
        slist.add(new StatusBean("spring.version", SpringVersion.getVersion()));

        return slist;
    } catch (Throwable e) {
        throw new RuntimeException("failed to get system status", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Throwable e) {
                mLogger.error("failed to get system status", e);
            }
        }
    }
}

From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java

@Override
public boolean exists(String dbName) throws DAOException {

    ResultSet rs = null;/*from  w  w  w  .j a  va 2  s  .  c  o  m*/
    Connection conn = null;
    try {
        conn = getSQLConnection();
        DatabaseMetaData metaData = conn.getMetaData();
        rs = metaData.getTables(dbName, metaData.getUserName(), null, null);
        return rs != null && rs.next();
    } catch (SQLException e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(rs);
        SQLUtil.close(conn);
    }
}

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 www.j ava2  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:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

protected boolean checkSchema() throws Exception {
    Connection conn = getConnection(true);
    boolean found = false;
    try {/*w  w w .j  av a2 s .  c o  m*/
        DatabaseMetaData dbm = conn.getMetaData();
        Entity entity = DBVersion.class.getAnnotation(Entity.class);
        String table = entity.recordset();

        ResultSet rs = dbm.getTables(null, null, table, new String[] { "TABLE" });
        while (rs.next()) {
            found = true;
            break;
        }
        rs.close();

    } finally {
        if (conn != null) {
            releaseConnection(conn);
        }
    }
    return found;
}

From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java

@Override
public List<StagingDatabaseTableColumnDTO> getTablesColumns(String dbName) throws DAOException {

    ArrayList<StagingDatabaseTableColumnDTO> result = new ArrayList<StagingDatabaseTableColumnDTO>();

    ResultSet rs = null;/*from   w w w  .  j a  v  a  2  s.  c o m*/
    Connection conn = null;
    try {
        conn = getSQLConnection();
        DatabaseMetaData metaData = conn.getMetaData();
        rs = metaData.getColumns(dbName, null, null, null);
        while (rs.next()) {
            String table = rs.getString("TABLE_NAME");
            String column = rs.getString("COLUMN_NAME");
            String dataType = rs.getString("TYPE_NAME");
            StagingDatabaseTableColumnDTO dto = new StagingDatabaseTableColumnDTO(table, column, dataType);
            result.add(dto);
        }
    } catch (SQLException e) {
        throw new DAOException("Failure getting the tables and columns of database: " + dbName, e);
    } finally {
        SQLUtil.close(rs);
        SQLUtil.close(conn);
    }

    return result;
}

From source file:org.tec.webapp.orm.service.impl.SystemSvcImpl.java

/**
 * {@inheritDoc}/*from   w  ww  . j a  v a2 s  .  c o m*/
 */
@Override()
public SerializableList<StatusBean> getStatus() {
    Connection conn = null;
    try {
        SerializableList<StatusBean> slist = new SerializableList<StatusBean>();

        // get java information
        slist.add(new StatusBean("java.version", System.getProperty("java.version")));

        //get Servlet information
        slist.add(new StatusBean("server.info", mServletContext.getServerInfo()));

        StringBuilder buff = new StringBuilder();

        buff.append(mServletContext.getMajorVersion());
        buff.append('.');
        buff.append(mServletContext.getMinorVersion());

        slist.add(new StatusBean("servlet.version", buff.toString()));

        // get database information
        conn = mDataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        slist.add(new StatusBean("database.server", dmd.getDatabaseProductName()));
        slist.add(new StatusBean("database.version", dmd.getDatabaseProductVersion()));
        slist.add(new StatusBean("jdbc.driver", dmd.getDriverName()));
        slist.add(new StatusBean("jdbc.driver.version", dmd.getDriverVersion()));

        // spring
        slist.add(new StatusBean("spring.version", SpringVersion.getVersion()));

        // hibernate
        slist.add(new StatusBean("hibernate.version", Version.getVersionString()));
        slist.add(new StatusBean("hibernate.session.factory", mSessionFactory.getClass().getName()));

        return slist;
    } catch (Throwable e) {
        throw new RuntimeException("failed to get system status", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Throwable e) {
                mLogger.error("failed to get system status", e);
            }
        }
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static List<MetaDataColumn> getExistingMetaDataColumns(String channelId) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
    List<MetaDataColumn> metaDataColumns = new ArrayList<MetaDataColumn>();
    Connection connection = null;
    ResultSet columns = null;// w  ww  . j a va  2s. c  om

    try {
        connection = getConnection();
        columns = connection.getMetaData().getColumns(connection.getCatalog(), null, "d_mcm" + localChannelId,
                null);

        if (!columns.next()) {
            columns = connection.getMetaData().getColumns(connection.getCatalog(), null,
                    "D_MCM" + localChannelId, null);

            if (!columns.next()) {
                return metaDataColumns;
            }
        }

        do {
            String name = columns.getString("COLUMN_NAME");

            if (!name.toUpperCase().equals("METADATA_ID") && !name.toUpperCase().equals("MESSAGE_ID")) {
                int type = columns.getInt("DATA_TYPE");
                MetaDataColumnType metaDataColumnType = MetaDataColumnType.fromSqlType(type);

                if (metaDataColumnType == null) {
                    logger.error("Unsupported sql type: " + typeToString(type));
                } else {
                    metaDataColumns.add(new MetaDataColumn(name, metaDataColumnType, null));
                    logger.info(
                            String.format("Detected column '%s' with type '%s', using MetaDataColumnType: %s",
                                    name, typeToString(type), metaDataColumnType));
                }
            }
        } while (columns.next());
    } finally {
        close(columns);
        close(connection);
    }

    return metaDataColumns;
}