List of usage examples for java.sql DatabaseMetaData getUserName
String getUserName() throws SQLException;
From source file:com.netspective.axiom.connection.BasicConnectionProviderEntry.java
public void init(String dataSourceId, Connection conn) { this.dataSourceId = dataSourceId; try {/*from w ww. jav a 2 s . c om*/ try { DatabasePolicy policy = DatabasePolicies.getInstance().getDatabasePolicy(conn); put(KEYNAME_DATABASE_POLICY_CLASSNAME, policy.getClass().getName()); put(KEYNAME_DATABASE_POLICY_DBMSID, policy.getDbmsIdentifier()); } catch (Exception dpe) { put(KEYNAME_DATABASE_POLICY_CLASSNAME, dpe.toString()); } DatabaseMetaData dbmd = conn.getMetaData(); put(KEYNAME_DRIVER_NAME, dbmd.getDriverName()); put(KEYNAME_DATABASE_PRODUCT_NAME, dbmd.getDatabaseProductName()); put(KEYNAME_DATABASE_PRODUCT_VERSION, dbmd.getDatabaseProductVersion()); put(KEYNAME_DRIVER_VERSION, dbmd.getDriverVersion()); put(KEYNAME_URL, dbmd.getURL()); put(KEYNAME_USER_NAME, dbmd.getUserName()); String resultSetType = "unknown"; if (dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)) resultSetType = "scrollable (insensitive)"; else if (dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) resultSetType = "scrollable (sensitive)"; else if (dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY)) resultSetType = "non-scrollabe (forward only)"; put(KEYNAME_RESULTSET_TYPE, resultSetType); valid = true; } catch (Exception e) { exception = e; } finally { try { conn.close(); } catch (SQLException e) { log.error("SQL Exception while closing connection", e); } } }
From source file:jef.database.DbUtils.java
/** * ???/* ww w. j a v a2s . c o m*/ * * @param conn * @return * @throws SQLException */ public static ConnectInfo tryAnalyzeInfo(Connection conn) throws SQLException { DatabaseMetaData meta = conn.getMetaData(); ConnectInfo info = new ConnectInfo(); info.user = meta.getUserName(); info.url = meta.getURL(); info.parse();// ?profile, ????? return info; }
From source file:com.haulmont.cuba.core.sys.dbupdate.DbUpdaterEngine.java
public boolean dbInitialized() throws DbInitializationException { log.trace("Checking if the database is initialized"); Connection connection = null; try {/*from w w w .j a v a2 s .c o m*/ connection = getDataSource().getConnection(); DatabaseMetaData dbMetaData = connection.getMetaData(); DbProperties dbProperties = new DbProperties(getConnectionUrl(connection)); boolean isSchemaByUser = DbmsSpecificFactory.getDbmsFeatures().isSchemaByUser(); String schemaName = isSchemaByUser ? dbMetaData.getUserName() : dbProperties.getCurrentSchemaProperty(); ResultSet tables = dbMetaData.getTables(null, schemaName, null, null); boolean found = false; while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); if ("SYS_DB_CHANGELOG".equalsIgnoreCase(tableName)) { log.trace("Found SYS_DB_CHANGELOG table"); changelogTableExists = true; } if ("SEC_USER".equalsIgnoreCase(tableName)) { log.trace("Found SEC_USER table"); found = true; } } return found; } catch (SQLException e) { throw new DbInitializationException(true, "Error connecting to database: " + e.getMessage(), e); } finally { if (connection != null) try { connection.close(); } catch (SQLException ignored) { } } }
From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java
@Override public boolean exists(String dbName) throws DAOException { ResultSet rs = null;// w w w .ja v a 2 s . c om 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:com.qualogy.qafe.business.resource.rdb.query.enhancer.SQLQueryEnhancer.java
public Query enhance(Query query, DatabaseMetaData databaseMetaData) throws EnhancementFailedException { SQLQuery sqlQuery = (SQLQuery) query; ResultSet resultSet = null;/*w ww . j a va2 s . co m*/ try { if (StringUtils.isBlank(sqlQuery.getSqlAsAttribute()) && StringUtils.isBlank(sqlQuery.getSqlAsText()) && StringUtils.isNotBlank(sqlQuery.getTable())) { // The Oracle database stores its table names as Upper-Case, // if you pass a table name in lowercase characters, it will not work. // MySQL database does not care if table name is uppercase/lowercase. // // TODO:check if there is a way to catch table data // TODO: dialect needed for upper/lowercase String userName = databaseMetaData.getUserName(); resultSet = databaseMetaData.getTables(null, null, sqlQuery.getTable().toUpperCase(), null); String tableSchema = null; // Knowing schema name is not necessary but we gain performance // by using it during retrieving meta data. while (resultSet.next() && (null != userName)) { // some vendors like MySQL do not provide schema name // that's why we have to check whether the schema name is "null" if ((null != resultSet.getString("TABLE_SCHEM")) && resultSet.getString("TABLE_SCHEM").equals(userName)) { tableSchema = userName; break; } // TABLE_TYPE } try { sqlQuery.getMetaData().setSupportsGetGeneratedKeys(databaseMetaData.supportsGetGeneratedKeys()); } catch (AbstractMethodError e) { LOG.log(Level.WARNING, "On the database driver there is no support for Metadata reading (sqlquery: " + sqlQuery.getId() + ")", e); } // if you pass null values for the first two parameters, then // it might take too long to return the result. resultSet = databaseMetaData.getPrimaryKeys(null, tableSchema, sqlQuery.getTable().toUpperCase()); while (resultSet.next()) { sqlQuery.getMetaData().addPrimaryKey(resultSet.getString("COLUMN_NAME")); } // if no primarykeys found on a table, an update statement cannot be generated // so the query will be marked as error containing. sqlQuery.validate(); } } catch (SQLException e) { throw new EnhancementFailedException(e); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { throw new EnhancementFailedException(e); } } } return sqlQuery; }
From source file:com.amazon.carbonado.repo.jdbc.JDBCStorableIntrospector.java
/** * Uses the given database connection to query database metadata. This is * used to bind storables to tables, and properties to columns. Other * checks are performed to ensure that storable type matches well with the * definition in the database./*from w ww . ja v a2 s . co m*/ */ private static <S extends Storable> JDBCStorableInfo<S> examine(StorableInfo<S> mainInfo, Connection con, final String searchCatalog, final String searchSchema, SchemaResolver resolver, boolean primaryKeyCheckDisabled) throws SQLException, SupportException { final DatabaseMetaData meta = con.getMetaData(); final String databaseProductName = meta.getDatabaseProductName(); final String userName = meta.getUserName(); String[] tableAliases; if (mainInfo.getAliasCount() > 0) { tableAliases = mainInfo.getAliases(); } else { String name = mainInfo.getStorableType().getSimpleName(); tableAliases = generateAliases(name); } // Try to find matching table from aliases. String catalog = null, schema = null, tableName = null, tableType = null; findName: { // The call to getTables may return several matching tables. This // map defines the "best" table type we'd like to use. The higher // the number the better. Map<String, Integer> fitnessMap = new HashMap<String, Integer>(); fitnessMap.put("LOCAL TEMPORARY", 1); fitnessMap.put("GLOBAL TEMPORARY", 2); fitnessMap.put("VIEW", 3); fitnessMap.put("SYSTEM TABLE", 4); fitnessMap.put("TABLE", 5); fitnessMap.put("ALIAS", 6); fitnessMap.put("SYNONYM", 7); for (int i = 0; i < tableAliases.length; i++) { ResultSet rs = meta.getTables(searchCatalog, searchSchema, tableAliases[i], null); try { int bestFitness = 0; while (rs.next()) { String type = rs.getString("TABLE_TYPE"); Integer fitness = fitnessMap.get(type); if (fitness != null) { String rsSchema = rs.getString("TABLE_SCHEM"); if (searchSchema == null) { if (userName != null && userName.equalsIgnoreCase(rsSchema)) { // Favor entities whose schema name matches // the user name. fitness += 7; } } if (fitness > bestFitness) { bestFitness = fitness; catalog = rs.getString("TABLE_CAT"); schema = rsSchema; tableName = rs.getString("TABLE_NAME"); tableType = type; } } } } finally { rs.close(); } if (tableName != null) { // Found a match, so stop checking aliases. break; } } } if (tableName == null && !mainInfo.isIndependent()) { StringBuilder buf = new StringBuilder(); buf.append("Unable to find matching table name for type \""); buf.append(mainInfo.getStorableType().getName()); buf.append("\" by looking for "); appendToSentence(buf, tableAliases); buf.append(" with catalog " + searchCatalog + " and schema " + searchSchema); throw new MismatchException(buf.toString()); } String qualifiedTableName = tableName; String resolvedTableName = tableName; // Oracle specific stuff... // TODO: Migrate this to OracleSupportStrategy. if (tableName != null && databaseProductName.toUpperCase().contains("ORACLE")) { if ("TABLE".equals(tableType) && searchSchema != null) { // Qualified table name references the schema. Used by SQL statements. qualifiedTableName = searchSchema + '.' + tableName; } else if ("SYNONYM".equals(tableType)) { // Try to get the real schema. This call is Oracle specific, however. String select = "SELECT TABLE_OWNER,TABLE_NAME " + "FROM ALL_SYNONYMS " + "WHERE OWNER=? AND SYNONYM_NAME=?"; PreparedStatement ps = con.prepareStatement(select); ps.setString(1, schema); // in Oracle, schema is the owner ps.setString(2, tableName); try { ResultSet rs = ps.executeQuery(); try { if (rs.next()) { schema = rs.getString("TABLE_OWNER"); resolvedTableName = rs.getString("TABLE_NAME"); } } finally { rs.close(); } } finally { ps.close(); } } } // Gather information on all columns such that metadata only needs to // be retrieved once. Map<String, ColumnInfo> columnMap = new TreeMap<String, ColumnInfo>(String.CASE_INSENSITIVE_ORDER); if (resolvedTableName != null) { ResultSet rs = meta.getColumns(catalog, schema, resolvedTableName, null); rs.setFetchSize(1000); try { while (rs.next()) { ColumnInfo info = new ColumnInfo(rs); columnMap.put(info.columnName, info); } } finally { rs.close(); } } // Make sure that all properties have a corresponding column. Map<String, ? extends StorableProperty<S>> mainProperties = mainInfo.getAllProperties(); Map<String, String> columnToProperty = new HashMap<String, String>(); Map<String, JDBCStorableProperty<S>> jProperties = new LinkedHashMap<String, JDBCStorableProperty<S>>( mainProperties.size()); ArrayList<String> errorMessages = new ArrayList<String>(); for (StorableProperty<S> mainProperty : mainProperties.values()) { if (mainProperty.isDerived() || mainProperty.isJoin() || tableName == null) { jProperties.put(mainProperty.getName(), new JProperty<S>(mainProperty, primaryKeyCheckDisabled)); continue; } String[] columnAliases; if (mainProperty.getAliasCount() > 0) { columnAliases = mainProperty.getAliases(); } else { columnAliases = generateAliases(mainProperty.getName()); } JDBCStorableProperty<S> jProperty = null; boolean addedError = false; findName: for (int i = 0; i < columnAliases.length; i++) { ColumnInfo columnInfo = columnMap.get(columnAliases[i]); if (columnInfo != null) { AccessInfo accessInfo = getAccessInfo(mainProperty, columnInfo.dataType, columnInfo.dataTypeName, columnInfo.columnSize, columnInfo.decimalDigits); if (accessInfo == null) { TypeDesc propertyType = TypeDesc.forClass(mainProperty.getType()); String message = "Property \"" + mainProperty.getName() + "\" has type \"" + propertyType.getFullName() + "\" which is incompatible with database type \"" + columnInfo.dataTypeName + '"'; if (columnInfo.decimalDigits > 0) { message += " (decimal digits = " + columnInfo.decimalDigits + ')'; } errorMessages.add(message); addedError = true; break findName; } if (columnInfo.nullable) { if (!mainProperty.isNullable() && !mainProperty.isIndependent()) { errorMessages.add( "Property \"" + mainProperty.getName() + "\" must have a Nullable annotation"); } } else { if (mainProperty.isNullable() && !mainProperty.isIndependent()) { errorMessages.add("Property \"" + mainProperty.getName() + "\" must not have a Nullable annotation"); } } boolean autoIncrement = mainProperty.isAutomatic(); if (autoIncrement) { // Need to execute a little query to check if column is // auto-increment or not. This information is not available in // the regular database metadata prior to jdk1.6. PreparedStatement ps = con.prepareStatement( "SELECT " + columnInfo.columnName + " FROM " + tableName + " WHERE 1=0"); try { ResultSet rs = ps.executeQuery(); try { autoIncrement = rs.getMetaData().isAutoIncrement(1); } finally { rs.close(); } } finally { ps.close(); } } jProperty = new JProperty<S>(mainProperty, columnInfo, autoIncrement, primaryKeyCheckDisabled, accessInfo.mResultSetGet, accessInfo.mPreparedStatementSet, accessInfo.getAdapter()); break findName; } } if (jProperty != null) { jProperties.put(mainProperty.getName(), jProperty); columnToProperty.put(jProperty.getColumnName(), jProperty.getName()); } else { if (mainProperty.isIndependent()) { jProperties.put(mainProperty.getName(), new JProperty<S>(mainProperty, primaryKeyCheckDisabled)); } else if (!addedError) { StringBuilder buf = new StringBuilder(); buf.append("Unable to find matching database column for property \""); buf.append(mainProperty.getName()); buf.append("\" by looking for "); appendToSentence(buf, columnAliases); errorMessages.add(buf.toString()); } } } if (errorMessages.size() > 0) { throw new MismatchException(mainInfo.getStorableType(), errorMessages); } // Now verify that primary or alternate keys match. if (resolvedTableName != null) checkPrimaryKey: { ResultSet rs; try { rs = meta.getPrimaryKeys(catalog, schema, resolvedTableName); } catch (SQLException e) { getLog().info("Unable to get primary keys for table \"" + resolvedTableName + "\" with catalog " + catalog + " and schema " + schema + ": " + e); break checkPrimaryKey; } List<String> pkProps = new ArrayList<String>(); try { while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); String propertyName = columnToProperty.get(columnName); if (propertyName == null) { errorMessages .add("Column \"" + columnName + "\" must be part of primary or alternate key"); continue; } pkProps.add(propertyName); } } finally { rs.close(); } if (errorMessages.size() > 0) { // Skip any extra checks. break checkPrimaryKey; } if (pkProps.size() == 0) { // If no primary keys are reported, don't even bother checking. // There's no consistent way to get primary keys, and entities // like views and synonyms don't usually report primary keys. // A primary key might even be logically defined as a unique // constraint. break checkPrimaryKey; } if (matchesKey(pkProps, mainInfo.getPrimaryKey())) { // Good. Primary key in database is same as in Storable. break checkPrimaryKey; } // Check if Storable has an alternate key which matches the // database's primary key. boolean foundAnyAltKey = false; for (StorableKey<S> altKey : mainInfo.getAlternateKeys()) { if (matchesKey(pkProps, altKey)) { // Okay. Primary key in database matches a Storable // alternate key. foundAnyAltKey = true; // Also check that declared primary key is a strict subset // of the alternate key. If not, keep checking alt keys. if (matchesSubKey(pkProps, mainInfo.getPrimaryKey())) { break checkPrimaryKey; } } } if (foundAnyAltKey) { errorMessages.add("Actual primary key matches a declared alternate key, " + "but declared primary key must be a strict subset. " + mainInfo.getPrimaryKey().getProperties() + " is not a subset of " + pkProps); } else { errorMessages.add("Actual primary key does not match any " + "declared primary or alternate key: " + pkProps); } } if (errorMessages.size() > 0) { if (primaryKeyCheckDisabled) { for (String errorMessage : errorMessages) { getLog().warn("Suppressed error: " + errorMessage); } errorMessages.clear(); } else { throw new MismatchException(mainInfo.getStorableType(), errorMessages); } } // IndexInfo is empty, as querying for it tends to cause a table analyze to run. IndexInfo[] indexInfo = new IndexInfo[0]; if (needsQuotes(tableName)) { String quote = meta.getIdentifierQuoteString(); if (quote != null && !quote.equals(" ")) { tableName = quote + tableName + quote; qualifiedTableName = quote + qualifiedTableName + quote; } } return new JInfo<S>(mainInfo, catalog, schema, tableName, qualifiedTableName, indexInfo, jProperties); }
From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java
public String getDatasourceInfo() throws JdbcException { String dsinfo = null;//from w ww . jav a 2 s.com Connection conn = null; try { conn = getConnection(); DatabaseMetaData md = conn.getMetaData(); String product = md.getDatabaseProductName(); String productVersion = md.getDatabaseProductVersion(); String driver = md.getDriverName(); String driverVersion = md.getDriverVersion(); String url = md.getURL(); String user = md.getUserName(); if (getDatabaseType() == DbmsSupportFactory.DBMS_DB2 && "WAS".equals(IbisContext.getApplicationServerType()) && md.getResultSetHoldability() != ResultSet.HOLD_CURSORS_OVER_COMMIT) { // For (some?) combinations of WebShere and DB2 this seems to be // the default and result in the following exception when (for // example?) a ResultSetIteratingPipe is calling next() on the // ResultSet after it's sender has called a pipeline which // contains a GenericMessageSendingPipe using // transactionAttribute="NotSupported": // com.ibm.websphere.ce.cm.ObjectClosedException: DSRA9110E: ResultSet is closed. ConfigurationWarnings configWarnings = ConfigurationWarnings.getInstance(); configWarnings.add(log, "The database's default holdability for ResultSet objects is " + md.getResultSetHoldability() + " instead of " + ResultSet.HOLD_CURSORS_OVER_COMMIT + " (ResultSet.HOLD_CURSORS_OVER_COMMIT)"); } dsinfo = "user [" + user + "] url [" + url + "] product [" + product + "] version [" + productVersion + "] driver [" + driver + "] version [" + driverVersion + "]"; } catch (SQLException e) { log.warn("Exception determining databaseinfo", e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e1) { log.warn("exception closing connection for metadata", e1); } } } return dsinfo; }
From source file:org.alfresco.util.DatabaseMetaDataHelper.java
/** * Trys to determine the schema name from the DatabaseMetaData obtained from the Connection. * @param connection A database connection * @return String//from ww w . j av a 2s . c o m */ private String getSchemaFromConnection(Connection connection) { if (connection == null) { logger.error("Unable to determine schema due to null connection."); return null; } ResultSet schemas = null; try { final DatabaseMetaData dbmd = connection.getMetaData(); // Assume that if there are schemas, we want the one named after the connection user or the one called "dbo" (MS // SQL hack) String schema = null; schemas = dbmd.getSchemas(); while (schemas.next()) { final String thisSchema = schemas.getString("TABLE_SCHEM"); if (thisSchema.equals(dbmd.getUserName()) || thisSchema.equalsIgnoreCase("dbo")) { schema = thisSchema; break; } } return schema; } catch (Exception e) { logger.error("Unable to determine current schema.", e); } finally { if (schemas != null) { try { schemas.close(); } catch (Exception e) { //noop } } } return null; }
From source file:org.ambraproject.action.debug.DebugInfoAction.java
@Override public String execute() throws Exception { if (!checkAccess()) { return ERROR; }//from ww w . j a v a 2 s . c o m timestamp = new Date(System.currentTimeMillis()); Runtime rt = Runtime.getRuntime(); jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0); jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0); jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0); HttpServletRequest req = ServletActionContext.getRequest(); tomcatVersion = ServletActionContext.getServletContext().getServerInfo(); sessionCount = SessionCounter.getSessionCount(); host = req.getLocalName(); hostIp = req.getLocalAddr(); buildInfo = generateBuildInfo(); // The easiest way I found to get the URL and username for the DB. // It's not that easy and involves opening a connection... Context initialContext = new InitialContext(); Context context = (Context) initialContext.lookup("java:comp/env"); DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS"); Connection conn = null; try { conn = ds.getConnection(); DatabaseMetaData metadata = conn.getMetaData(); dbUrl = metadata.getURL(); dbUser = metadata.getUserName(); } finally { conn.close(); } Configuration config = ConfigurationStore.getInstance().getConfiguration(); FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore"); filestore = filestoreService.toString(); solrUrl = (String) config.getProperty("ambra.services.search.server.url"); configuration = dumpConfig(config); cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline")); return SUCCESS; }
From source file:org.apache.jackrabbit.core.fs.db.OracleFileSystem.java
/** * {@inheritDoc}/*w w w . jav a 2 s. c o m*/ * <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 + "FSENTRY"; 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 = OracleFileSystem.class.getResourceAsStream(schema + ".ddl"); 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(); } } finally { IOUtils.closeQuietly(in); closeStatement(stmt); } } }