Example usage for java.sql DatabaseMetaData getURL

List of usage examples for java.sql DatabaseMetaData getURL

Introduction

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

Prototype

String getURL() throws SQLException;

Source Link

Document

Retrieves the URL for this DBMS.

Usage

From source file:org.easyrec.utils.spring.store.dao.DaoUtils.java

/**
 * @return the current database url and user name (for a given Datasource)
 * @throws RuntimeException when the database metadata cannot be retrieved
 *//*  w w  w.java  2 s  .  co m*/
public static String getDatabaseURLAndUserName(DataSource dataSource) {
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            String url = dbmd.getURL();
            String userName = dbmd.getUserName();

            StringBuilder s = new StringBuilder(url);
            s.append(" (userName='");
            s.append(userName);
            s.append("')");
            return s.toString();
        }
    };
    try {
        return (String) JdbcUtils.extractDatabaseMetaData(dataSource, callback);
    } catch (Exception e) {
        throw new RuntimeException("unable to read database metadata", e);
    }
}

From source file:org.eclipse.ecr.core.storage.sql.extensions.H2Fulltext.java

/**
 * Searches from the given full text index. The returned result set has a
 * single ID column which holds the keys for the matching rows.
 * <p>//from w  w  w  .j a v  a2s  .  co  m
 * Usually called through:
 *
 * <pre>
 *   SELECT * FROM NXFT_SEARCH(name, 'text');
 * </pre>
 *
 * @param conn the connection
 * @param indexName the index name
 * @param text the search query
 * @return the result set
 */
@SuppressWarnings("unchecked")
public static ResultSet search(Connection conn, String indexName, String text) throws SQLException {
    DatabaseMetaData meta = conn.getMetaData();
    if (indexName == null) {
        indexName = DEFAULT_INDEX_NAME;
    }

    // find schema, table and analyzer
    PreparedStatement ps = conn
            .prepareStatement("SELECT SCHEMA, TABLE, ANALYZER FROM " + FT_TABLE + " WHERE NAME = ?");
    ps.setString(1, indexName);
    ResultSet res = ps.executeQuery();
    if (!res.next()) {
        throw new SQLException("No such index: " + indexName);
    }
    String schema = res.getString(1);
    String table = res.getString(2);
    String analyzer = res.getString(3);
    ps.close();

    int type = getPrimaryKeyType(meta, schema, table);
    SimpleResultSet rs = new SimpleResultSet();
    rs.addColumn(COL_KEY, type, 0, 0);

    if (meta.getURL().startsWith("jdbc:columnlist:")) {
        // this is just to query the result set columns
        return rs;
    }

    String indexPath = getIndexPath(conn);
    try {
        BooleanQuery query = new BooleanQuery();
        QueryParser parser = new QueryParser(fieldForIndex(indexName), getAnalyzer(analyzer));
        query.add(parser.parse(text), BooleanClause.Occur.MUST);

        getIndexWriter(indexPath, analyzer).commit();
        Searcher searcher = new IndexSearcher(indexPath);
        Iterator<Hit> it = searcher.search(query).iterator();
        for (; it.hasNext();) {
            Hit hit = it.next();
            Object key = asObject(hit.get(FIELD_KEY), type);
            rs.addRow(new Object[] { key });
        }
        // TODO keep it open if possible
        searcher.close();
    } catch (Exception e) {
        throw convertException(e);
    }
    return rs;
}

From source file:org.eclipse.ecr.core.storage.sql.extensions.H2Functions.java

/**
 * Gets the invalidations for this cluster node.
 *
 * @return a result set with columns id, fragments, kind
 *///from ww  w .j a va 2s. c o m
public static ResultSet getClusterInvalidationsString(Connection conn) throws SQLException {
    DatabaseMetaData meta = conn.getMetaData();
    SimpleResultSet result = new SimpleResultSet();
    result.addColumn("ID", Types.VARCHAR, 0, 0); // String id
    result.addColumn("FRAGMENTS", Types.VARCHAR, 0, 0);
    result.addColumn("KIND", Types.INTEGER, 0, 0);
    if (meta.getURL().startsWith("jdbc:columnlist:")) {
        // this is just to query the result set columns
        return result;
    }

    PreparedStatement ps = null;
    Statement st = null;
    try {
        String sql = "SELECT \"ID\", \"FRAGMENTS\", \"KIND\" FROM \"CLUSTER_INVALS\" "
                + "WHERE \"NODEID\" = SESSION_ID()";
        if (isLogEnabled()) {
            logDebug(sql);
        }
        ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        List<Serializable> debugValues = null;
        if (isLogEnabled()) {
            debugValues = new LinkedList<Serializable>();
        }
        while (rs.next()) {
            String id = rs.getString(1);
            String fragments = rs.getString(2);
            long kind = rs.getLong(3);
            result.addRow(new Object[] { id, fragments, Long.valueOf(kind) });
            if (debugValues != null) {
                debugValues.add(id + ',' + fragments + ',' + kind);
            }
        }
        if (debugValues != null) {
            logDebug("  -> " + debugValues);
        }

        // remove processed invalidations
        sql = "DELETE FROM \"CLUSTER_INVALS\" WHERE \"NODEID\" = SESSION_ID()";
        if (isLogEnabled()) {
            logDebug(sql);
        }
        st = conn.createStatement();
        st.execute(sql);

        // return invalidations
        return result;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (st != null) {
            st.close();
        }
    }
}

From source file:org.hyperic.bootstrap.HQServer.java

boolean verifySchema() {
    final String sInconsistentStateErrorMsgTemplate = "HQ DB schema is in a bad state: '%s'."
            + " This is most likely due to a failed upgrade.  "
            + "Please either restore from backups and start your "
            + "previous version of HQ or contact HQ support.  "
            + "HQ cannot start while the current DB Schema version " + "is in this state";

    boolean isSuccessful = false;
    Statement stmt = null;//www. jav  a  2 s  .com
    ResultSet rs = null;
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        stmt = conn.createStatement();
        final String sql = "select propvalue from EAM_CONFIG_PROPS " + "WHERE propkey = '"
                + HQConstants.SchemaVersion + "'";
        rs = stmt.executeQuery(sql);
        if (rs.next()) {
            final String currSchema = rs.getString("propvalue");
            log.info("HQ DB schema: " + currSchema);
            if (currSchema.contains(HQConstants.SCHEMA_MOD_IN_PROGRESS)) {
                log.fatal(String.format(sInconsistentStateErrorMsgTemplate, currSchema));
            } else {
                isSuccessful = true;
            } //EO else if DB version is in a consistent state 
        } else {
            log.fatal(
                    String.format(sInconsistentStateErrorMsgTemplate, "No CAM_SCHEMA_VERSION property found"));
        } //EO else if there was no CAM_SCHEMA_VERSION proprety 

    } catch (SQLException e) {
        try {
            DatabaseMetaData metaData = (conn == null) ? null : conn.getMetaData();
            String url = (metaData == null) ? null : metaData.getURL();
            log.error("Error verifying if HQ schema is valid.  url= " + url + ", Cause: " + e, e);
        } catch (SQLException e1) {
            log.error(e, e);
        }
    } finally {
        DBUtil.closeJDBCObjects(HQServer.class.getName(), conn, stmt, rs);
    }
    return isSuccessful;
}

From source file:org.hyperic.util.jdbc.DBUtil.java

public boolean isBuiltinDB() {
    boolean isBuiltin = false;

    try {//from www.j av a 2s  . c om
        Connection conn = getConnection();
        DatabaseMetaData dbMetaData = conn.getMetaData();
        String url = dbMetaData.getURL();
        closeConnection(log, conn);

        if (url != null) {
            // built-in db url in the format of:
            // jdbc:postgresql://127.0.0.1:9432/hqdb?protocolVersion=2

            url = url.toLowerCase();
            isBuiltin = url.startsWith(BUILTIN_DB_JDBC_URL)
                    && url.indexOf(BUILTIN_DB_NAME) > BUILTIN_DB_JDBC_URL.length();
        }
    } catch (SQLException e) {
        log.warn("Error retrieving database meta data.", e);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("isBuiltinDB=" + isBuiltin);
        }
    }

    return isBuiltin;
}

From source file:org.jumpmind.db.platform.JdbcDatabasePlatformFactory.java

protected static String[] determineDatabaseNameVersionSubprotocol(DataSource dataSource) {
    Connection connection = null;
    String[] nameVersion = new String[3];
    try {//from  w ww . jav  a  2 s . co m
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        nameVersion[0] = metaData.getDatabaseProductName();
        nameVersion[1] = Integer.toString(metaData.getDatabaseMajorVersion());
        final String PREFIX = "jdbc:";
        String url = metaData.getURL();
        if (StringUtils.isNotBlank(url) && url.length() > PREFIX.length()) {
            url = url.substring(PREFIX.length());
            if (url.indexOf(":") > 0) {
                url = url.substring(0, url.indexOf(":"));
            }
        }
        nameVersion[2] = url;

        /*
         * if the productName is PostgreSQL, it could be either PostgreSQL
         * or Greenplum
         */
        /* query the metadata to determine which one it is */
        if (nameVersion[0].equalsIgnoreCase("PostgreSql")) {
            if (isGreenplumDatabase(connection)) {
                nameVersion[0] = DatabaseNamesConstants.GREENPLUM;
                nameVersion[1] = Integer.toString(getGreenplumVersion(connection));
            } else if (isRedshiftDatabase(connection)) {
                nameVersion[0] = DatabaseNamesConstants.REDSHIFT;
            }
        }

        /*
         * if the productName is MySQL, it could be either MysSQL or MariaDB
         * query the metadata to determine which one it is
         */
        if (nameVersion[0].equalsIgnoreCase(DatabaseNamesConstants.MYSQL)) {
            if (isMariaDBDatabase(connection)) {
                nameVersion[0] = DatabaseNamesConstants.MARIADB;
            }
        }

        if (nameVersion[0].toLowerCase().indexOf(DatabaseNamesConstants.DB2) != -1) {
            if (nameVersion[0].toUpperCase().indexOf("Z") != -1) {
                nameVersion[0] = DatabaseNamesConstants.DB2ZOS;
            } else if (nameVersion[0].indexOf("400") != -1) {
                nameVersion[0] = DatabaseNamesConstants.DB2AS400;
            } else {
                nameVersion[0] = DatabaseNamesConstants.DB2;
            }
        }
        if (nameVersion[0].equalsIgnoreCase("AS") && nameVersion[2].equalsIgnoreCase("db2")) {
            nameVersion[0] = DatabaseNamesConstants.DB2AS400;
        }

        if (nameVersion[0].toLowerCase().startsWith(DatabaseNamesConstants.FIREBIRD)) {
            if (isFirebirdDialect1(connection)) {
                nameVersion[0] = DatabaseNamesConstants.FIREBIRD_DIALECT1;
            }
        }

        log.info("Detected database '" + nameVersion[0] + "', version '" + nameVersion[1] + "', protocol '"
                + nameVersion[2] + "'");

        return nameVersion;
    } catch (SQLException ex) {
        throw new SqlException("Error while reading the database metadata: " + ex.getMessage(), ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                // we ignore this one
            }
        }
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.db.H2Fulltext.java

/**
 * Searches from the given full text index. The returned result set has a
 * single ID column which holds the keys for the matching rows.
 * <p>/*from   ww w. ja  v  a  2  s. c o m*/
 * Usually called through:
 *
 * <pre>
 *   SELECT * FROM NXFT_SEARCH(name, 'text');
 * </pre>
 *
 * @param conn the connection
 * @param indexName the index name
 * @param text the search query
 * @return the result set
 */
public static ResultSet search(Connection conn, String indexName, String text) throws SQLException {
    DatabaseMetaData meta = conn.getMetaData();
    if (indexName == null) {
        indexName = DEFAULT_INDEX_NAME;
    }

    String schema;
    String table;
    String analyzerName;

    // find schema, table and analyzer
    try (PreparedStatement ps = conn
            .prepareStatement("SELECT SCHEMA, TABLE, ANALYZER FROM " + FT_TABLE + " WHERE NAME = ?")) {
        ps.setString(1, indexName);
        try (ResultSet res = ps.executeQuery()) {
            if (!res.next()) {
                throw new SQLException("No such index: " + indexName);
            }
            schema = res.getString(1);
            table = res.getString(2);
            analyzerName = res.getString(3);
        }
    }

    int type = getPrimaryKeyType(meta, schema, table);
    SimpleResultSet rs = new SimpleResultSet();
    rs.addColumn(COL_KEY, type, 0, 0);

    if (meta.getURL().startsWith("jdbc:columnlist:")) {
        // this is just to query the result set columns
        return rs;
    }

    // flush changes
    final IndexWriter writer = getIndexWriter(getIndexName(conn), getIndexPath(conn), analyzerName);
    if (writer.hasUncommittedChanges()) {
        try {
            writer.commit();
        } catch (IOException cause) {
            throw convertException(cause);
        }
    }

    // search index
    try {
        BooleanQuery query = new BooleanQuery();
        String defaultField = fieldForIndex(indexName);
        Analyzer analyzer = getAnalyzer(analyzerName);
        QueryParser parser = new QueryParser(LUCENE_VERSION, defaultField, analyzer);
        query.add(parser.parse(text), BooleanClause.Occur.MUST);

        try (IndexReader reader = DirectoryReader.open(writer.getDirectory())) {
            IndexSearcher searcher = new IndexSearcher(reader);
            Collector collector = new ResultSetCollector(rs, reader, type);
            searcher.search(query, collector);
        }
    } catch (Exception e) {
        throw convertException(e);
    }
    return rs;
}

From source file:org.nuxeo.ecm.core.storage.sql.db.H2Functions.java

public static ResultSet getReadAclsFor(Connection conn, String principals) throws SQLException {
    DatabaseMetaData meta = conn.getMetaData();
    SimpleResultSet result = new SimpleResultSet();
    result.addColumn("ID", Types.VARCHAR, 0, 0); // String id
    if (meta.getURL().startsWith("jdbc:columnlist:")) {
        // this is just to query the result set columns
        return result;
    }//w w w .j a  va  2s  .c  o  m
    if (principals == null) {
        return result;
    }
    Set<String> principalsList = split(principals);
    Set<String> blackList = new HashSet<String>();
    for (String user : principalsList) {
        blackList.add('-' + user);
    }
    // log.debug("getReadAclFor " + principals);
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement("SELECT \"ID\", \"ACL\" FROM READ_ACLS");
        rs = ps.executeQuery();
        while (rs.next()) {
            String id = rs.getString(1);
            String[] acl = rs.getString(2).split(",");
            for (String ace : acl) {
                // log.debug("ace: " + ace);
                if (principalsList.contains(ace)) {
                    result.addRow(new Object[] { id });
                    // log.debug("allowed: " + id);
                } else if (blackList.contains(ace)) {
                    // log.debug("deny: " + id);
                    break;
                }
            }
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (ps != null) {
            ps.close();
        }
    }
    return result;
}

From source file:org.rhq.enterprise.server.util.SystemDatabaseInformation.java

private SystemDatabaseInformation() {
    DataSource ds = null;/*w  w w . j av  a  2  s  .co  m*/
    Connection conn = null;
    try {
        ds = LookupUtil.getDataSource();
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();

        String url = metadata.getURL();
        String productName = metadata.getDatabaseProductName();
        String productVersion = metadata.getDatabaseProductVersion();
        String driverName = metadata.getDriverName();
        String driverVersion = metadata.getDriverVersion();

        Map<Property, String> values = new HashMap<Property, String>();
        values.put(Property.DATABASE_CONNECTION_URL, url);
        values.put(Property.DATABASE_PRODUCT_NAME, productName);
        values.put(Property.DATABASE_PRODUCT_VERSION, productVersion);
        values.put(Property.DATABASE_DRIVER_NAME, driverName);
        values.put(Property.DATABASE_DRIVER_VERSION, driverVersion);

        values.put(Property.CURRENT_MEASUREMENT_TABLE, MeasurementDataManagerUtility.getCurrentRawTable());
        values.put(Property.NEXT_MEASUREMENT_TABLE_ROTATION,
                MeasurementDataManagerUtility.getNextRotationTime());

        properties = Collections.unmodifiableMap(values);

    } catch (Exception e) {
        log.error("Could not load properties for " + SystemDatabaseInformation.class.getSimpleName());
    } finally {
        if (properties == null) {
            Map<Property, String> values = new HashMap<Property, String>();
            for (Property prop : Property.values()) {
                values.put(prop, "unknown");
            }
            properties = Collections.unmodifiableMap(values);
        }
        JDBCUtil.safeClose(conn);
    }
}

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() + "'");
}