Java Code Examples for java.sql.DatabaseMetaData#getUserName()

The following examples show how to use java.sql.DatabaseMetaData#getUserName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JdbcFacade.java    From iaf with Apache License 2.0 6 votes vote down vote up
public String getDatasourceInfo() throws JdbcException {
	String dsinfo=null;
	try (Connection 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.add(this, 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);
	}
	return dsinfo;
}
 
Example 2
Source File: TestDatabaseMetaData.java    From evosql with Apache License 2.0 6 votes vote down vote up
/**
 * Basic test of DatabaseMetaData functions that access functions
 */
public void testThree() throws Exception {

    Connection conn = newConnection();
    int        updateCount;

    try {
        TestUtil.testScript(conn, "testrun/hsqldb/TestSelf.txt");

        DatabaseMetaData dbmeta     = conn.getMetaData();
        int txIsolation = dbmeta.getDefaultTransactionIsolation();
        String           userName   = dbmeta.getUserName();
        boolean          isReadOnly = dbmeta.isReadOnly();
    } catch (Exception e) {
        assertTrue("unable to prepare or execute DDL", false);
    } finally {
        conn.close();
    }
}
 
Example 3
Source File: DatabaseUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public String getSchemaName(DatabaseMetaData dbData) throws SQLException {
    if (!isLegacy && this.datasourceInfo.getUseSchemas() && dbData.supportsSchemasInTableDefinitions()) {
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getSchemaName())) {
            if (dbData.storesLowerCaseIdentifiers()) {
                return this.datasourceInfo.getSchemaName().toLowerCase();
            } else if (dbData.storesUpperCaseIdentifiers()) {
                return this.datasourceInfo.getSchemaName().toUpperCase();
            } else {
                return this.datasourceInfo.getSchemaName();
            }
        } else {
            return dbData.getUserName();
        }
    }
    return null;
}
 
Example 4
Source File: DataSourceValidator.java    From das with Apache License 2.0 5 votes vote down vote up
private PoolProperties getPoolProperties(Connection connection) {
    String url = null;
    String userName = null;
    try {
        DatabaseMetaData metaData = connection.getMetaData();
        url = metaData.getURL();
        userName = metaData.getUserName();
    } catch (Throwable e) {
        LOGGER.warn("DataSourceValidator getPoolProperties error", e);
        return null;
    }

    return PoolPropertiesHolder.getInstance().getPoolProperties(url, userName);
}
 
Example 5
Source File: ImportRecipientsDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, Map<String, Object>> getColumnInfoByColumnName(@VelocityCheck int companyId, String column) {
	LinkedHashMap<String, Map<String, Object>> list = new LinkedHashMap<>();
	try(final Connection connection = getDataSource().getConnection()) {

		DatabaseMetaData metaData = connection.getMetaData();

		boolean isOracle = isOracleDB();

		String tableName = "customer_" + companyId + "_tbl";

		String schemaPattern = isOracle ? metaData.getUserName() : null;
		String tableNamePattern = isOracle ? tableName.toUpperCase() : tableName.toLowerCase();
		String columnNamePattern = isOracle ? column.toUpperCase() : column;
		
		try(ResultSet resultSet = metaData.getColumns(null, schemaPattern, tableNamePattern, columnNamePattern)) {
			if (resultSet != null) {
				while (resultSet.next()) {
					Map<String, Object> mapping = new HashMap<>();
					mapping.put("column", resultSet.getString(4).toLowerCase());
					mapping.put("shortname", resultSet.getString(4).toLowerCase());
					mapping.put("type", ImportUtils.dbtype2string(resultSet.getInt(5)));
					mapping.put("length", resultSet.getInt(7));
					if (resultSet.getInt(11) == DatabaseMetaData.columnNullable) {
						mapping.put("nullable", 1);
					} else {
						mapping.put("nullable", 0);
					}

					list.put((String) mapping.get("shortname"), mapping);
				}
			}
		}
		
	} catch(Exception e) {
		logger.error(MessageFormat.format("Failed to get column ({0}) info for companyId ({1})", column, companyId), e);
	}
	
	return list;
}
 
Example 6
Source File: DBUtil.java    From ralasafe with MIT License 5 votes vote down vote up
public static String getDefaultSchema(Connection conn) throws SQLException {
	String productName = getDatabaseProductName(conn);
	if (productName.equals(MYSQL) || productName.equals(SQLSERVER)) {
		return conn.getCatalog();
	} else {
		DatabaseMetaData metaData = conn.getMetaData();
		return metaData.getUserName();
	}
}
 
Example 7
Source File: JdbcIntermediateFacade.java    From dekaf with Apache License 2.0 5 votes vote down vote up
private String getUserNameSafe(final DatabaseMetaData md) {
  try {
    return md.getUserName();
  }
  catch (Exception ignored) {
    return null;
  }
}
 
Example 8
Source File: DBInformation.java    From cloud-spring-boot-sample with Apache License 2.0 5 votes vote down vote up
public DBInformation(DatabaseMetaData metaData) throws SQLException
{
	url = metaData.getURL();
	dbName = metaData.getDatabaseProductName();
	dbMajorVersion = metaData.getDatabaseMajorVersion();
	dbMinorVersion = metaData.getDatabaseMinorVersion();

	driverName = metaData.getDriverName();
	driverVersion = metaData.getDriverVersion();

	userName = metaData.getUserName();
}
 
Example 9
Source File: TemporaryTableManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void readColumns(ResultSet resultSet, List<String> fields, DataSetTableDescriptor tableDescriptor, DatabaseMetaData dbMetadata,
		String schema) throws SQLException {
	int index = 0;
	do {
		// For oracle we have to check if the table exists in the right schema
		// If we set the schema name in the method dbMeta.getColumns in this way
		// dbMeta.getColumns(connection.getCatalog(), dbMeta.getUserName(), tableName, null);
		// the result contains all the tables for which the user has the select grant
		// also if they belong to other schema

		// if the schema is specified in input, it is the schema to be used;
		// in case the schema is not specified, the schema name is the user name
		String actualOracleSchema = schema != null ? schema : dbMetadata.getUserName();

		String tableSchema = resultSet.getString("TABLE_SCHEM");
		if (dbMetadata.getDriverName().contains("Oracle")) {
			if (!tableSchema.equalsIgnoreCase(actualOracleSchema)) {
				continue;
			}
		}
		String columnName = resultSet.getString("COLUMN_NAME");
		String fieldName = null;
		if (fields != null) {
			fieldName = fields.get(index);
		} else {
			fieldName = columnName;
		}
		short dataType = resultSet.getShort("DATA_TYPE");
		logger.debug("Data type of field [" + columnName + "] is equal to [" + dataType + "]");
		Class type = JDBCTypeMapper.getJavaType(dataType);
		logger.debug("Type class of field [" + columnName + "] is equal to [" + ((type == null) ? "null" : type.getName()) + "]");
		tableDescriptor.addField(fieldName, columnName, type);
		index++;
	} while (resultSet.next());// && (index<fields.size()));
}
 
Example 10
Source File: DatasourceServletAction.java    From ureport with Apache License 2.0 5 votes vote down vote up
public void buildDatabaseTables(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	Connection conn=null;
	ResultSet rs = null;
	try{
		conn=buildConnection(req);
		DatabaseMetaData metaData = conn.getMetaData();
		String url = metaData.getURL();
		String schema = null;
		if (url.toLowerCase().contains("oracle")) {
			schema = metaData.getUserName();
		}
		List<Map<String,String>> tables = new ArrayList<Map<String,String>>();
		rs = metaData.getTables(null, schema, "%", new String[] { "TABLE","VIEW" });
		while (rs.next()) {
			Map<String,String> table = new HashMap<String,String>();
			table.put("name",rs.getString("TABLE_NAME"));
			table.put("type",rs.getString("TABLE_TYPE"));
			tables.add(table);
		}
		writeObjectToJson(resp, tables);
	}catch(Exception ex){
		throw new ServletException(ex);
	}finally{
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 11
Source File: DbCommonServiceImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
public List<TableInfo> findTableInfos(String dbInfoId) throws Exception {
	List<TableInfo> tablesList = new ArrayList<TableInfo>();
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	Connection conn = null;
	ResultSet rs = null;
	try {
		conn = DataSourceUtils.getConnection(ds);
		DatabaseMetaData metaData = conn.getMetaData();
		String url = metaData.getURL();
		String schema = null;
		if (url.toLowerCase().contains("oracle")) {
			String value = Configure.getString("bdf2.default.schema");
			if (StringUtils.hasText(value)) {
				schema = value;
			} else {
				schema = metaData.getUserName();
			}
		}
		rs = metaData.getTables(null, schema, "%", new String[] { "TABLE" });
		TableInfo tableInfo = null;
		while (rs.next()) {
			tableInfo = new TableInfo();
			tableInfo.setTableName(rs.getString("TABLE_NAME"));
			tableInfo.setDbInfoId(dbInfoId);
			tablesList.add(tableInfo);
		}
		return tablesList;
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 12
Source File: TableMetaReader.java    From doma-gen with Apache License 2.0 4 votes vote down vote up
protected String getDefaultSchemaName(DatabaseMetaData metaData) throws SQLException {
  String userName = metaData.getUserName();
  return dialect.getDefaultSchemaName(userName);
}
 
Example 13
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Check whether the specified column of the specified table exists in the Identity database.
 *
 * @param tableName name of the table.
 * @param columnName name of the column.
 * @return true if column exists.
 */
public static boolean isTableColumnExists(String tableName, String columnName) {

    try (Connection connection = IdentityDatabaseUtil.getDBConnection()) {

        DatabaseMetaData metaData = connection.getMetaData();
        if (metaData.storesLowerCaseIdentifiers()) {
            tableName = tableName.toLowerCase();
            columnName = columnName.toLowerCase();
        }

        String schemaPattern = null;
        if (metaData.getDriverName().contains("Oracle")){
            if (log.isDebugEnabled()) {
                log.debug("DB type detected as Oracle. Setting schemaPattern to " + metaData.getUserName());
            }
            // Oracle checks the availability of the table column
            // in all users in the DB unless specified.
            schemaPattern = metaData.getUserName();
        }
        try (ResultSet resultSet = metaData.getColumns(null, schemaPattern, tableName, columnName)) {
            if (resultSet.next()) {
                if (log.isDebugEnabled()) {
                    log.debug("Column - " + columnName + " in table - " + tableName + " is available in the " +
                            "Identity database.");
                }
                IdentityDatabaseUtil.commitTransaction(connection);
                return true;
            }
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException ex) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            if (log.isDebugEnabled()) {
                log.debug("Column - " + columnName + " in table - " + tableName + " is not available in the " +
                        "Identity database.");
            }
            return false;
        }

    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Column - " + columnName + " in table - " + tableName + " is not available in the " +
                    "Identity database.");
        }
        return false;
    }
    if (log.isDebugEnabled()) {
        log.debug("Column - " + columnName + " in table - " + tableName + " is not available in the " +
                "Identity database.");
    }
    return false;
}
 
Example 14
Source File: GenericTableMetaDataProvider.java    From effectivejava with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta data.
 * @param databaseMetaData meta data to be used
 */
protected GenericTableMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}
 
Example 15
Source File: GenericTableMetaDataProvider.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta data.
 * @param databaseMetaData meta data to be used
 */
protected GenericTableMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}
 
Example 16
Source File: GenericCallMetaDataProvider.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta data.
 * @param databaseMetaData meta data to be used
 */
protected GenericCallMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}
 
Example 17
Source File: GenericCallMetaDataProvider.java    From effectivejava with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta data.
 * @param databaseMetaData meta data to be used
 */
protected GenericCallMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}
 
Example 18
Source File: GenericTableMetaDataProvider.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta-data.
 * @param databaseMetaData meta-data to be used
 */
protected GenericTableMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}
 
Example 19
Source File: GenericCallMetaDataProvider.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta-data.
 * @param databaseMetaData meta-data to be used
 */
protected GenericCallMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}
 
Example 20
Source File: GenericTableMetaDataProvider.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Constructor used to initialize with provided database meta-data.
 * @param databaseMetaData meta-data to be used
 */
protected GenericTableMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
	this.userName = databaseMetaData.getUserName();
}