Example usage for java.sql Connection getCatalog

List of usage examples for java.sql Connection getCatalog

Introduction

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

Prototype

String getCatalog() throws SQLException;

Source Link

Document

Retrieves this Connection object's current catalog name.

Usage

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * @param connection//w ww  .  j  a v  a2  s. co  m
 * @return
 */
public static List<String> getTableNames(final Connection connection) {
    try {
        ArrayList<String> fields = new ArrayList<String>();

        DatabaseMetaData mdm = connection.getMetaData();
        ResultSet rs = mdm.getTables(connection.getCatalog(), connection.getCatalog(), null,
                new String[] { "TABLE" });
        while (rs.next()) {
            /*System.out.println("-------- " + rs.getString("TABLE_NAME")+" ----------");
            for (int i=1;i<=rs.getMetaData().getColumnCount();i++)
            {
            System.out.println(rs.getMetaData().getColumnName(i)+"="+rs.getObject(i));
                    
            }*/
            fields.add(rs.getString("TABLE_NAME"));
        }
        rs.close();
        return fields;

    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

public static List<String> getFieldNamesFromSchema(final Connection connection, final String tableName) {
    try {/*www. ja  va  2s  .  c  o m*/
        ArrayList<String> fields = new ArrayList<String>();

        DatabaseMetaData mdm = connection.getMetaData();
        ResultSet rs = mdm.getColumns(connection.getCatalog(), connection.getCatalog(), tableName, null);
        while (rs.next()) {
            fields.add(rs.getString("COLUMN_NAME"));
        }
        rs.close();
        return fields;

    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * @param connection/*from   w w  w  .  j a  va2s . co m*/
 * @param tableName
 * @return
 */
public static List<FieldMetaData> getFieldMetaDataFromSchema(final Connection connection,
        final String tableName) {
    try {
        ArrayList<FieldMetaData> fields = new ArrayList<FieldMetaData>();

        DatabaseMetaData mdm = connection.getMetaData();
        ResultSet rs = mdm.getColumns(connection.getCatalog(), connection.getCatalog(), tableName, null);
        while (rs.next()) {
            /*System.out.println("-------- " + rs.getString("COLUMN_NAME")+" ----------");
            for (int i=1;i<=rs.getMetaData().getColumnCount();i++)
            {
            System.out.println(rs.getMetaData().getColumnName(i)+"="+rs.getObject(i));
                    
            }*/

            String typeStr = rs.getString("TYPE_NAME");
            FieldMetaData fmd = new FieldMetaData(rs.getString("COLUMN_NAME"), typeStr,
                    typeStr.startsWith("DATE"), false, StringUtils.contains(typeStr.toLowerCase(), "varchar"));
            fmd.setSqlType(rs.getInt("DATA_TYPE"));
            fields.add(fmd);
        }
        rs.close();
        return fields;

    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

public static String getDatabaseName(final Connection connection) {
    // List<String> names = new Vector<String>();
    String databaseName = null;/*from www.j  ava 2 s  . co  m*/
    try {
        //Statement  stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

        //ResultSet rs1 = stmt.executeQuery("select name from sysfiles");

        //if (rs1.first())
        //{
        databaseName = connection.getCatalog();
        //log.debug("GETTING db NAME: " + databaseName);
        return databaseName;
        //}

    } catch (SQLException ex) {
        edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex);
        log.error(ex);
        ex.printStackTrace();
    }
    return databaseName;
}

From source file:net.sourceforge.squirrel_sql.fw.sql.SQLConnection.java

/**
 * @see net.sourceforge.squirrel_sql.fw.sql.ISQLConnection#setCatalog(java.lang.String)
 *///from  w  ww  .j  a v a2s  . co  m
public void setCatalog(String catalogName) throws SQLException {
    validateConnection();
    final Connection conn = getConnection();
    final String oldValue = conn.getCatalog();
    final DialectType dialectType = DialectFactory.getDialectType(metaData);
    if (!StringUtils.equals(oldValue, catalogName)) {
        setDbSpecificCatalog(dialectType, catalogName);
        getPropertyChangeReporter().firePropertyChange(IPropertyNames.CATALOG, oldValue, catalogName);
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java

/**
 * Returns the name and location of the database that this objects operates on.
 *  /*from   w ww.  j  av a2s . c  om*/
 * @see nl.nn.adapterframework.core.HasPhysicalDestination#getPhysicalDestinationName()
 */
public String getPhysicalDestinationName() {
    String result = "unknown";
    try {
        Connection connection = getConnection();
        DatabaseMetaData metadata = connection.getMetaData();
        result = metadata.getURL();

        String catalog = null;
        catalog = connection.getCatalog();
        result += catalog != null ? ("/" + catalog) : "";

        connection.close();
    } catch (Exception e) {
        log.warn(getLogPrefix() + "exception retrieving PhysicalDestinationName", e);
    }
    return result;
}

From source file:org.apache.cayenne.modeler.dialog.db.DbLoaderHelper.java

public DbLoaderHelper(ProjectController mediator, Connection connection, DbAdapter adapter, String dbUserName) {
    this.dbUserName = dbUserName;
    this.mediator = mediator;
    try {/*from  w w  w . ja v a2s.  co m*/
        this.dbCatalog = connection.getCatalog();
    } catch (SQLException e) {
        logObj.warn("Error getting catalog.", e);
    }
    this.adapter = adapter;
    this.loader = new DbLoader(connection, adapter, new LoaderDelegate());
}

From source file:org.apache.ddlutils.platform.JdbcModelReader.java

/**
 * Reads the database model from the given connection.
 * /*www . j  ava 2 s  . c  o  m*/
 * @param connection The connection
 * @param name       The name of the resulting database; <code>null</code> when the default name (the catalog)
 *                   is desired which might be <code>null</code> itself though
 * @param catalog    The catalog to acess in the database; use <code>null</code> for the default value
 * @param schema     The schema to acess in the database; use <code>null</code> for the default value
 * @param tableTypes The table types to process; use <code>null</code> or an empty list for the default ones
 * @return The database model
 */
public Database getDatabase(Connection connection, String name, String catalog, String schema,
        String[] tableTypes) throws SQLException {
    Database db = new Database();

    if (name == null) {
        try {
            db.setName(connection.getCatalog());
            if (catalog == null) {
                catalog = db.getName();
            }
        } catch (Exception ex) {
            _log.info("Cannot determine the catalog name from connection.", ex);
        }
    } else {
        db.setName(name);
    }
    try {
        _connection = connection;
        db.addTables(readTables(catalog, schema, tableTypes));
        // Note that we do this here instead of in readTable since platforms may redefine the
        // readTable method whereas it is highly unlikely that this method gets redefined
        if (getPlatform().isForeignKeysSorted()) {
            sortForeignKeys(db);
        }
    } finally {
        _connection = null;
    }
    db.initialize();
    return db;
}

From source file:org.apache.hawq.ranger.service.HawqClient.java

/**
 * Uses the connectionProperties and attempts to connect to Hawq.
 * Returns a message depending on success or failure.
 *
 * @param connectionProperties Map which contains hostname, port, username, and password
 * @return Map which contains connectivityStatus, message, description, objectId, and fieldName
 *//*from  w ww .  ja  v  a  2  s. c o m*/

public HashMap<String, Object> checkConnection(Map<String, String> connectionProperties) throws Exception {

    boolean isConnected = false;
    HashMap<String, Object> result = new HashMap<>();

    String description = CONNECTION_FAILURE_MESSAGE;

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== HawqClient.checkConnection Starting connection to hawq");
    }

    Connection conn = null;
    try {
        conn = getConnection(connectionProperties);
        if (conn.getCatalog() != null) {
            isConnected = true;
            description = CONNECTION_SUCCESSFUL_MESSAGE;
        }
    } catch (SQLException e) {
        LOG.error("<== HawqClient.checkConnection Error: Failed to connect" + e);
        description = e.getMessage();
    } finally {
        closeConnection(conn);
    }

    String message = isConnected ? CONNECTION_SUCCESSFUL_MESSAGE : CONNECTION_FAILURE_MESSAGE;
    generateResponseDataMap(isConnected, message, description, null, null, result);

    return result;
}

From source file:org.apache.oozie.command.SchemaCheckXCommand.java

@Override
protected Void execute() throws CommandException {
    Connection conn = null;
    LOG.info("About to check database schema");
    Date startTime = new Date();
    boolean problem = false;
    try {/*from w w  w  . j a v  a 2 s  . co  m*/
        conn = DriverManager.getConnection(url, user, pass);
        String catalog = conn.getCatalog();
        DatabaseMetaData metaData = conn.getMetaData();

        Map<String, Class<? extends JsonBean>> tableClasses = new HashMap<String, Class<? extends JsonBean>>();
        tableClasses.put(getTableName(BundleActionBean.class), BundleActionBean.class);
        tableClasses.put(getTableName(BundleJobBean.class), BundleJobBean.class);
        tableClasses.put(getTableName(CoordinatorActionBean.class), CoordinatorActionBean.class);
        tableClasses.put(getTableName(CoordinatorJobBean.class), CoordinatorJobBean.class);
        tableClasses.put(getTableName(JsonSLAEvent.class), JsonSLAEvent.class);
        tableClasses.put(getTableName(SLARegistrationBean.class), SLARegistrationBean.class);
        tableClasses.put(getTableName(SLASummaryBean.class), SLASummaryBean.class);
        tableClasses.put(getTableName(WorkflowActionBean.class), WorkflowActionBean.class);
        tableClasses.put(getTableName(WorkflowJobBean.class), WorkflowJobBean.class);

        boolean tableProblem = checkTables(metaData, catalog, tableClasses.keySet());
        problem = problem | tableProblem;
        if (!tableProblem) {
            for (Map.Entry<String, Class<? extends JsonBean>> table : tableClasses.entrySet()) {
                TableInfo ti = new TableInfo(table.getValue(), dbType);
                boolean columnProblem = checkColumns(metaData, catalog, table.getKey(), ti.columnTypes);
                problem = problem | columnProblem;
                if (!columnProblem) {
                    boolean primaryKeyProblem = checkPrimaryKey(metaData, catalog, table.getKey(),
                            ti.primaryKeyColumn);
                    problem = problem | primaryKeyProblem;
                    boolean indexProblem = checkIndexes(metaData, catalog, table.getKey(), ti.indexedColumns);
                    problem = problem | indexProblem;
                }
            }
        }
        if (problem) {
            LOG.error("Database schema is BAD! Check previous error log messages for details");
        } else {
            LOG.info("Database schema is GOOD");
        }
    } catch (SQLException sqle) {
        LOG.error("An Exception occurred while talking to the database: " + sqle.getMessage(), sqle);
        problem = true;
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                LOG.error("An Exception occurred while disconnecting from the database: " + e.getMessage(), e);
            }
        }
        Services.get().get(SchemaCheckerService.class).updateInstrumentation(problem, startTime);
    }
    return null;
}