List of usage examples for java.sql DatabaseMetaData getUserName
String getUserName() throws SQLException;
From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java
/** * Checks if the database table exist./* w ww . ja v a 2 s . c o m*/ * * @return <code>true</code> if the tables exist; * <code>false</code> otherwise. * * @throws SQLException if a database error occurs. * @throws RepositoryException if a repository exception occurs. */ protected boolean checkTablesExist() throws SQLException, RepositoryException { DatabaseMetaData metaData = connectionManager.getConnection().getMetaData(); String tableName = schemaObjectPrefix + "BUNDLE"; if (metaData.storesLowerCaseIdentifiers()) { tableName = tableName.toLowerCase(); } else if (metaData.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); } String userName = checkTablesWithUser() ? metaData.getUserName() : null; ResultSet rs = metaData.getTables(null, userName, tableName, null); try { return rs.next(); } finally { rs.close(); } }
From source file:org.apache.jackrabbit.core.persistence.db.OraclePersistenceManager.java
/** * {@inheritDoc}/*from ww w . j a v a 2s . c om*/ * <p/> * Overridden in order to support multiple oracle schemas. Note that * schema names in Oracle correspond to the username of the connection. * See http://issues.apache.org/jira/browse/JCR-582 * * @throws Exception if an error occurs */ protected void checkSchema() throws Exception { DatabaseMetaData metaData = con.getMetaData(); String tableName = schemaObjectPrefix + "NODE"; if (metaData.storesLowerCaseIdentifiers()) { tableName = tableName.toLowerCase(); } else if (metaData.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); } String userName = metaData.getUserName(); ResultSet rs = metaData.getTables(null, userName, tableName, null); boolean schemaExists; try { schemaExists = rs.next(); } finally { rs.close(); } if (!schemaExists) { // read ddl from resources InputStream in = getSchemaDDL(); if (in == null) { String msg = "Configuration error: unknown schema '" + schema + "'"; log.debug(msg); throw new RepositoryException(msg); } BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Statement stmt = con.createStatement(); try { String sql = reader.readLine(); while (sql != null) { // Skip comments and empty lines if (!sql.startsWith("#") && sql.length() > 0) { // replace prefix variable sql = Text.replace(sql, SCHEMA_OBJECT_PREFIX_VARIABLE, schemaObjectPrefix); // set the tablespace if it is defined String tspace; if (tableSpace == null || "".equals(tableSpace)) { tspace = ""; } else { tspace = "tablespace " + tableSpace; } sql = Text.replace(sql, TABLE_SPACE_VARIABLE, tspace).trim(); // execute sql stmt stmt.executeUpdate(sql); } // read next sql stmt sql = reader.readLine(); } // commit the changes con.commit(); } finally { IOUtils.closeQuietly(in); closeStatement(stmt); } } }
From source file:org.apache.openjpa.jdbc.sql.DBDictionaryFactory.java
/** * Return a string containing all the property values of the given * database metadata.// w w w .j av a 2 s . co m */ public static String toString(DatabaseMetaData meta) throws SQLException { String lineSep = J2DoPrivHelper.getLineSeparator(); StringBuilder buf = new StringBuilder(4096); try { buf.append("catalogSeparator: ").append(meta.getCatalogSeparator()).append(lineSep) .append("catalogTerm: ").append(meta.getCatalogTerm()).append(lineSep) .append("databaseProductName: ").append(meta.getDatabaseProductName()).append(lineSep) .append("databaseProductVersion: ").append(meta.getDatabaseProductVersion()).append(lineSep) .append("driverName: ").append(meta.getDriverName()).append(lineSep).append("driverVersion: ") .append(meta.getDriverVersion()).append(lineSep).append("extraNameCharacters: ") .append(meta.getExtraNameCharacters()).append(lineSep).append("identifierQuoteString: ") .append(meta.getIdentifierQuoteString()).append(lineSep).append("numericFunctions: ") .append(meta.getNumericFunctions()).append(lineSep).append("procedureTerm: ") .append(meta.getProcedureTerm()).append(lineSep).append("schemaTerm: ") .append(meta.getSchemaTerm()).append(lineSep).append("searchStringEscape: ") .append(meta.getSearchStringEscape()).append(lineSep).append("sqlKeywords: ") .append(meta.getSQLKeywords()).append(lineSep).append("stringFunctions: ") .append(meta.getStringFunctions()).append(lineSep).append("systemFunctions: ") .append(meta.getSystemFunctions()).append(lineSep).append("timeDateFunctions: ") .append(meta.getTimeDateFunctions()).append(lineSep).append("url: ").append(meta.getURL()) .append(lineSep).append("userName: ").append(meta.getUserName()).append(lineSep) .append("defaultTransactionIsolation: ").append(meta.getDefaultTransactionIsolation()) .append(lineSep).append("driverMajorVersion: ").append(meta.getDriverMajorVersion()) .append(lineSep).append("driverMinorVersion: ").append(meta.getDriverMinorVersion()) .append(lineSep).append("maxBinaryLiteralLength: ").append(meta.getMaxBinaryLiteralLength()) .append(lineSep).append("maxCatalogNameLength: ").append(meta.getMaxCatalogNameLength()) .append(lineSep).append("maxCharLiteralLength: ").append(meta.getMaxCharLiteralLength()) .append(lineSep).append("maxColumnNameLength: ").append(meta.getMaxColumnNameLength()) .append(lineSep).append("maxColumnsInGroupBy: ").append(meta.getMaxColumnsInGroupBy()) .append(lineSep).append("maxColumnsInIndex: ").append(meta.getMaxColumnsInIndex()) .append(lineSep).append("maxColumnsInOrderBy: ").append(meta.getMaxColumnsInOrderBy()) .append(lineSep).append("maxColumnsInSelect: ").append(meta.getMaxColumnsInSelect()) .append(lineSep).append("maxColumnsInTable: ").append(meta.getMaxColumnsInTable()) .append(lineSep).append("maxConnections: ").append(meta.getMaxConnections()).append(lineSep) .append("maxCursorNameLength: ").append(meta.getMaxCursorNameLength()).append(lineSep) .append("maxIndexLength: ").append(meta.getMaxIndexLength()).append(lineSep) .append("maxProcedureNameLength: ").append(meta.getMaxProcedureNameLength()).append(lineSep) .append("maxRowSize: ").append(meta.getMaxRowSize()).append(lineSep) .append("maxSchemaNameLength: ").append(meta.getMaxSchemaNameLength()).append(lineSep) .append("maxStatementLength: ").append(meta.getMaxStatementLength()).append(lineSep) .append("maxStatements: ").append(meta.getMaxStatements()).append(lineSep) .append("maxTableNameLength: ").append(meta.getMaxTableNameLength()).append(lineSep) .append("maxTablesInSelect: ").append(meta.getMaxTablesInSelect()).append(lineSep) .append("maxUserNameLength: ").append(meta.getMaxUserNameLength()).append(lineSep) .append("isCatalogAtStart: ").append(meta.isCatalogAtStart()).append(lineSep) .append("isReadOnly: ").append(meta.isReadOnly()).append(lineSep) .append("nullPlusNonNullIsNull: ").append(meta.nullPlusNonNullIsNull()).append(lineSep) .append("nullsAreSortedAtEnd: ").append(meta.nullsAreSortedAtEnd()).append(lineSep) .append("nullsAreSortedAtStart: ").append(meta.nullsAreSortedAtStart()).append(lineSep) .append("nullsAreSortedHigh: ").append(meta.nullsAreSortedHigh()).append(lineSep) .append("nullsAreSortedLow: ").append(meta.nullsAreSortedLow()).append(lineSep) .append("storesLowerCaseIdentifiers: ").append(meta.storesLowerCaseIdentifiers()) .append(lineSep).append("storesLowerCaseQuotedIdentifiers: ") .append(meta.storesLowerCaseQuotedIdentifiers()).append(lineSep) .append("storesMixedCaseIdentifiers: ").append(meta.storesMixedCaseIdentifiers()) .append(lineSep).append("storesMixedCaseQuotedIdentifiers: ") .append(meta.storesMixedCaseQuotedIdentifiers()).append(lineSep) .append("storesUpperCaseIdentifiers: ").append(meta.storesUpperCaseIdentifiers()) .append(lineSep).append("storesUpperCaseQuotedIdentifiers: ") .append(meta.storesUpperCaseQuotedIdentifiers()).append(lineSep) .append("supportsAlterTableWithAddColumn: ").append(meta.supportsAlterTableWithAddColumn()) .append(lineSep).append("supportsAlterTableWithDropColumn: ") .append(meta.supportsAlterTableWithDropColumn()).append(lineSep) .append("supportsANSI92EntryLevelSQL: ").append(meta.supportsANSI92EntryLevelSQL()) .append(lineSep).append("supportsANSI92FullSQL: ").append(meta.supportsANSI92FullSQL()) .append(lineSep).append("supportsANSI92IntermediateSQL: ") .append(meta.supportsANSI92IntermediateSQL()).append(lineSep) .append("supportsCatalogsInDataManipulation: ") .append(meta.supportsCatalogsInDataManipulation()).append(lineSep) .append("supportsCatalogsInIndexDefinitions: ") .append(meta.supportsCatalogsInIndexDefinitions()).append(lineSep) .append("supportsCatalogsInPrivilegeDefinitions: ") .append(meta.supportsCatalogsInPrivilegeDefinitions()).append(lineSep) .append("supportsCatalogsInProcedureCalls: ").append(meta.supportsCatalogsInProcedureCalls()) .append(lineSep).append("supportsCatalogsInTableDefinitions: ") .append(meta.supportsCatalogsInTableDefinitions()).append(lineSep) .append("supportsColumnAliasing: ").append(meta.supportsColumnAliasing()).append(lineSep) .append("supportsConvert: ").append(meta.supportsConvert()).append(lineSep) .append("supportsCoreSQLGrammar: ").append(meta.supportsCoreSQLGrammar()).append(lineSep) .append("supportsCorrelatedSubqueries: ").append(meta.supportsCorrelatedSubqueries()) .append(lineSep).append("supportsDataDefinitionAndDataManipulationTransactions: ") .append(meta.supportsDataDefinitionAndDataManipulationTransactions()).append(lineSep) .append("supportsDataManipulationTransactionsOnly: ") .append(meta.supportsDataManipulationTransactionsOnly()).append(lineSep) .append("supportsDifferentTableCorrelationNames: ") .append(meta.supportsDifferentTableCorrelationNames()).append(lineSep) .append("supportsExpressionsInOrderBy: ").append(meta.supportsExpressionsInOrderBy()) .append(lineSep).append("supportsExtendedSQLGrammar: ") .append(meta.supportsExtendedSQLGrammar()).append(lineSep).append("supportsFullOuterJoins: ") .append(meta.supportsFullOuterJoins()).append(lineSep).append("supportsGroupBy: ") .append(meta.supportsGroupBy()).append(lineSep).append("supportsGroupByBeyondSelect: ") .append(meta.supportsGroupByBeyondSelect()).append(lineSep).append("supportsGroupByUnrelated: ") .append(meta.supportsGroupByUnrelated()).append(lineSep) .append("supportsIntegrityEnhancementFacility: ") .append(meta.supportsIntegrityEnhancementFacility()).append(lineSep) .append("supportsLikeEscapeClause: ").append(meta.supportsLikeEscapeClause()).append(lineSep) .append("supportsLimitedOuterJoins: ").append(meta.supportsLimitedOuterJoins()).append(lineSep) .append("supportsMinimumSQLGrammar: ").append(meta.supportsMinimumSQLGrammar()).append(lineSep) .append("supportsMixedCaseIdentifiers: ").append(meta.supportsMixedCaseIdentifiers()) .append(lineSep).append("supportsMixedCaseQuotedIdentifiers: ") .append(meta.supportsMixedCaseQuotedIdentifiers()).append(lineSep) .append("supportsMultipleResultSets: ").append(meta.supportsMultipleResultSets()) .append(lineSep).append("supportsMultipleTransactions: ") .append(meta.supportsMultipleTransactions()).append(lineSep) .append("supportsNonNullableColumns: ").append(meta.supportsNonNullableColumns()) .append(lineSep).append("supportsOpenCursorsAcrossCommit: ") .append(meta.supportsOpenCursorsAcrossCommit()).append(lineSep) .append("supportsOpenCursorsAcrossRollback: ").append(meta.supportsOpenCursorsAcrossRollback()) .append(lineSep).append("supportsOpenStatementsAcrossCommit: ") .append(meta.supportsOpenStatementsAcrossCommit()).append(lineSep) .append("supportsOpenStatementsAcrossRollback: ") .append(meta.supportsOpenStatementsAcrossRollback()).append(lineSep) .append("supportsOrderByUnrelated: ").append(meta.supportsOrderByUnrelated()).append(lineSep) .append("supportsOuterJoins: ").append(meta.supportsOuterJoins()).append(lineSep) .append("supportsPositionedDelete: ").append(meta.supportsPositionedDelete()).append(lineSep) .append("supportsPositionedUpdate: ").append(meta.supportsPositionedUpdate()).append(lineSep) .append("supportsSchemasInDataManipulation: ").append(meta.supportsSchemasInDataManipulation()) .append(lineSep).append("supportsSchemasInIndexDefinitions: ") .append(meta.supportsSchemasInIndexDefinitions()).append(lineSep) .append("supportsSchemasInPrivilegeDefinitions: ") .append(meta.supportsSchemasInPrivilegeDefinitions()).append(lineSep) .append("supportsSchemasInProcedureCalls: ").append(meta.supportsSchemasInProcedureCalls()) .append(lineSep).append("supportsSchemasInTableDefinitions: ") .append(meta.supportsSchemasInTableDefinitions()).append(lineSep) .append("supportsSelectForUpdate: ").append(meta.supportsSelectForUpdate()).append(lineSep) .append("supportsStoredProcedures: ").append(meta.supportsStoredProcedures()).append(lineSep) .append("supportsSubqueriesInComparisons: ").append(meta.supportsSubqueriesInComparisons()) .append(lineSep).append("supportsSubqueriesInExists: ") .append(meta.supportsSubqueriesInExists()).append(lineSep).append("supportsSubqueriesInIns: ") .append(meta.supportsSubqueriesInIns()).append(lineSep) .append("supportsSubqueriesInQuantifieds: ").append(meta.supportsSubqueriesInQuantifieds()) .append(lineSep).append("supportsTableCorrelationNames: ") .append(meta.supportsTableCorrelationNames()).append(lineSep).append("supportsTransactions: ") .append(meta.supportsTransactions()).append(lineSep).append("supportsUnion: ") .append(meta.supportsUnion()).append(lineSep).append("supportsUnionAll: ") .append(meta.supportsUnionAll()).append(lineSep).append("usesLocalFilePerTable: ") .append(meta.usesLocalFilePerTable()).append(lineSep).append("usesLocalFiles: ") .append(meta.usesLocalFiles()).append(lineSep).append("allProceduresAreCallable: ") .append(meta.allProceduresAreCallable()).append(lineSep).append("allTablesAreSelectable: ") .append(meta.allTablesAreSelectable()).append(lineSep) .append("dataDefinitionCausesTransactionCommit: ") .append(meta.dataDefinitionCausesTransactionCommit()).append(lineSep) .append("dataDefinitionIgnoredInTransactions: ") .append(meta.dataDefinitionIgnoredInTransactions()).append(lineSep) .append("doesMaxRowSizeIncludeBlobs: ").append(meta.doesMaxRowSizeIncludeBlobs()) .append(lineSep).append("supportsBatchUpdates: ").append(meta.supportsBatchUpdates()); } catch (Throwable t) { // maybe abstract method error for jdbc 3 metadata method, or // other error buf.append(lineSep).append("Caught throwable: ").append(t); } return buf.toString(); }
From source file:org.apereo.portal.jdbc.DatabaseMetaDataImpl.java
/** * Gets meta data about the connection.//from w ww . j a v a 2s. co m */ private void getMetaData(final Connection conn) { try { final DatabaseMetaData dmd = conn.getMetaData(); this.databaseProductName = dmd.getDatabaseProductName(); this.databaseProductVersion = dmd.getDatabaseProductVersion(); this.driverName = dmd.getDriverName(); this.driverVersion = dmd.getDriverVersion(); this.userName = dmd.getUserName(); this.dbUrl = dmd.getURL(); this.dbmdSupportsOuterJoins = dmd.supportsOuterJoins(); } catch (SQLException sqle) { LOG.error("Error getting database meta data.", sqle); } }
From source file:org.bonitasoft.platform.setup.PlatformSetup.java
private void initDataSource() throws PlatformException { try {//from w w w.jav a2 s.c o m try (Connection connection = dataSource.getConnection()) { DatabaseMetaData metaData = connection.getMetaData(); LOGGER.info("Connected to '" + dbVendor + "' database with url: '" + metaData.getURL() + "' with user: '" + metaData.getUserName() + "'"); } } catch (SQLException e) { throw new PlatformException(e); } }
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 *//*ww w.ja va 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:org.dspace.storage.rdbms.DatabaseUtils.java
/** * Get the Database Schema Name in use by this Connection, so that it can * be used to limit queries in other methods (e.g. tableExists()). * * @param connection// www . j a v a 2 s. c om * Current Database Connection * @return Schema name as a string, or "null" if cannot be determined or unspecified * @throws SQLException * An exception that provides information on a database access error or other errors. */ public static String getSchemaName(Connection connection) throws SQLException { String schema = null; // Try to get the schema from the DB connection itself. // As long as the Database driver supports JDBC4.1, there should be a getSchema() method // If this method is unimplemented or doesn't exist, it will throw an exception (likely an AbstractMethodError) try { schema = connection.getSchema(); } catch (Exception | AbstractMethodError e) { } // If we don't know our schema, let's try the schema in the DSpace configuration if (StringUtils.isBlank(schema)) { schema = canonicalize(connection, DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("db.schema")); } // Still blank? Ok, we'll find a "sane" default based on the DB type if (StringUtils.isBlank(schema)) { String dbType = getDbType(connection); if (dbType.equals(DBMS_POSTGRES)) { // For PostgreSQL, the default schema is named "public" // See: http://www.postgresql.org/docs/9.0/static/ddl-schemas.html schema = "public"; } else if (dbType.equals(DBMS_ORACLE)) { // For Oracle, default schema is actually the user account // See: http://stackoverflow.com/a/13341390 DatabaseMetaData meta = connection.getMetaData(); schema = meta.getUserName(); } else // For H2 (in memory), there is no such thing as a schema schema = null; } return schema; }
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 *//* www . ja va 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.flywaydb.test.dbunit.DefaultDatabaseConnectionFactory.java
public IDatabaseConnection createConnection(final Connection con, final DatabaseMetaData databaseMetaData) throws SQLException, DatabaseUnitException { IDatabaseConnection connection = null; // FIXME not nice I found not a fast possibility to generate inside H2 // the tables inside a // schema as oracle do. final String driverName = databaseMetaData.getDriverName(); if (driverName.toLowerCase().contains("oracle")) { // oracle schema name is the user name connection = new DatabaseConnection(con, databaseMetaData.getUserName().toUpperCase()); } else {/*from ww w .ja v a2 s . c o m*/ if (driverName.contains("H2")) { // H2 connection = new DatabaseConnection(con); } else { // all other connection = new DatabaseConnection(con); } } // final DatabaseConfig config = connection.getConfig(); // // oracle 10g // // FIXME at the moment we have a hard coded oracle notation // config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new // Oracle10DataTypeFactory()); return connection; }
From source file:org.ralasafe.util.DBUtil.java
public static String getDefaultSchema(Connection conn) throws SQLException { String productName = getDatabaseProductName(conn); if (productName.equals(MYSQL) || productName.equals(SQLSERVER)) { return conn.getCatalog(); } else {//w w w . jav a 2s .c om DatabaseMetaData metaData = conn.getMetaData(); return metaData.getUserName(); } }