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:com.eryansky.core.db.DbUtilsDao.java

/**
 * ?Catalog//from www.j av  a 2  s  .c o  m
 * @return String
 * @throws com.eryansky.common.exception.DaoException
 */
protected String GetCurrentCatalog() throws DaoException {
    //Microsoft SQL Server????SQL?
    //final String sql = "select db_name()";
    try {
        Connection conn = this.dataSource.getConnection();
        return conn.getCatalog();
    } catch (SQLException ex) {
        throw new DaoException(ex);
    }
}

From source file:net.sf.farrago.namespace.jdbc.MedJdbcColumnSet.java

protected RelNode optimizeLoopbackLink(RelOptCluster cluster, RelOptConnection connection, String[] actualName)
        throws SQLException {
    if (directory == null) {
        return null;
    }/*  w  w w .  j a va2  s. com*/
    if (directory.server == null) {
        return null;
    }
    if ((directory.server.schemaName != null) && !directory.server.useSchemaNameAsForeignQualifier) {
        // Schema name should never be specified for a connection to
        // Farrago; if it is, bail.
        return null;
    }

    Connection loopbackConnection = directory.server.getConnection();
    if (!(loopbackConnection instanceof FarragoJdbcEngineConnection)) {
        Connection conn = loopbackConnection;
        while ((conn != null) && (conn instanceof DelegatingConnection)) {
            conn = ((DelegatingConnection) conn).getDelegate();
        }
        if (!(conn instanceof FarragoJdbcEngineConnection)) {
            return null;
        }
    }

    String catalogName = directory.server.catalogName;
    if (catalogName == null) {
        // No catalog name specified, so try to query the connection for
        // it.
        catalogName = loopbackConnection.getCatalog();
        if (catalogName == null) {
            return null;
        }
    }

    if (actualName[0] == null) {
        actualName[0] = catalogName;
    }

    // REVIEW jvs 14-Aug-2006:  Security security security.
    RelOptTable realTable = getPreparingStmt().getTableForMember(actualName);
    if (realTable == null) {
        return null;
    }
    return realTable.toRel(cluster, connection);
}

From source file:com.taobao.itest.listener.ITestDataSetListener.java

private String getSchemaName(DataSource dataSource, Connection connection) throws SQLException {
    String schemaName = null;// ww w .  j av  a 2  s.  c o  m
    if (dataSource instanceof SchemaDataSource) {
        SchemaDataSource sds = (SchemaDataSource) dataSource;
        schemaName = sds.getSchemaName();
    }
    if (schemaName == null) {
        log.warn("No schemaName is specified, use db name as shcemaName defaultly");
        schemaName = connection.getCatalog();
    }
    return schemaName;
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static List<MetaDataColumn> getExistingMetaDataColumns(String channelId) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
    List<MetaDataColumn> metaDataColumns = new ArrayList<MetaDataColumn>();
    Connection connection = null;
    ResultSet columns = null;//www . j  a v a  2  s.c  o  m

    try {
        connection = getConnection();
        columns = connection.getMetaData().getColumns(connection.getCatalog(), null, "d_mcm" + localChannelId,
                null);

        if (!columns.next()) {
            columns = connection.getMetaData().getColumns(connection.getCatalog(), null,
                    "D_MCM" + localChannelId, null);

            if (!columns.next()) {
                return metaDataColumns;
            }
        }

        do {
            String name = columns.getString("COLUMN_NAME");

            if (!name.toUpperCase().equals("METADATA_ID") && !name.toUpperCase().equals("MESSAGE_ID")) {
                int type = columns.getInt("DATA_TYPE");
                MetaDataColumnType metaDataColumnType = MetaDataColumnType.fromSqlType(type);

                if (metaDataColumnType == null) {
                    logger.error("Unsupported sql type: " + typeToString(type));
                } else {
                    metaDataColumns.add(new MetaDataColumn(name, metaDataColumnType, null));
                    logger.info(
                            String.format("Detected column '%s' with type '%s', using MetaDataColumnType: %s",
                                    name, typeToString(type), metaDataColumnType));
                }
            }
        } while (columns.next());
    } finally {
        close(columns);
        close(connection);
    }

    return metaDataColumns;
}

From source file:org.syncope.core.util.ImportExport.java

private List<String> sortByForeignKeys(final Connection conn, final Set<String> tableNames)
        throws SQLException, CycleInMultiParentTreeException {

    MultiParentNode<String> root = new MultiParentNode<String>(ROOT_ELEMENT);

    for (String tableName : tableNames) {
        MultiParentNode<String> node = MultiParentNodeOp.findInTree(root, tableName);
        if (node == null) {
            node = new MultiParentNode<String>(tableName);
            root.addChild(node);/*from   w w  w . j a  v a2 s.c  om*/
        }

        ResultSet rs = null;
        try {
            rs = conn.getMetaData().getExportedKeys(conn.getCatalog(), readSchema(), tableName);
            while (rs.next()) {
                String fkTableName = rs.getString("FKTABLE_NAME");
                if (!tableName.equals(fkTableName)) {
                    MultiParentNode<String> fkNode = MultiParentNodeOp.findInTree(root, fkTableName);
                    if (fkNode == null) {
                        fkNode = new MultiParentNode<String>(fkTableName);
                        root.addChild(fkNode);
                    }
                    fkNode.addChild(node);
                    if (root.isParent(node)) {
                        root.removeChild(node);
                    }
                }
            }
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    LOG.error("While closing tables result set", e);
                }
            }
        }
    }

    List<String> sortedTableNames = new ArrayList<String>(tableNames.size());
    MultiParentNodeOp.traverseTree(root, sortedTableNames);
    return sortedTableNames.subList(0, sortedTableNames.size() - 1);
}

From source file:it.unibas.spicy.persistence.relational.DAORelational.java

@SuppressWarnings("unchecked")
public void loadInstanceSample(AccessConfiguration accessConfiguration, IDataSourceProxy dataSource,
        DBFragmentDescription dataDescription, IConnectionFactory dataSourceDB, String rootLabel,
        boolean translated) throws DAOException {
    String catalog = null;/*  w  w w. j a va2s  . c o  m*/
    INode root = null;
    String schemaName = accessConfiguration.getSchemaName();
    DatabaseMetaData databaseMetaData = null;
    Connection connection = dataSourceDB.getConnection(accessConfiguration);
    try {
        databaseMetaData = connection.getMetaData();
        catalog = connection.getCatalog();
        if (catalog == null) {
            catalog = accessConfiguration.getUri();
            if (logger.isDebugEnabled())
                logger.debug("Catalog is null. Catalog name will be: " + catalog);
        }
        if (logger.isDebugEnabled())
            logger.debug("Catalog: " + catalog);
        if (rootLabel == null) {
            root = new TupleNode(DAORelationalUtility.getNode(catalog).getLabel(), getOID());
        } else {
            this.dataDescription = dataDescription;
            root = new TupleNode(rootLabel, getOID());
        }
        root.setRoot(true);
        String[] tableTypes = new String[] { "TABLE" };
        ResultSet tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, tableTypes);
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            if (!this.dataDescription.checkLoadTable(tableName)) {
                continue;
            }
            SetNode setTable = new SetNode(DAORelationalUtility.getNode(tableName).getLabel(), getOID());
            ////INode setTable = new SetNode(tableName, getOID());
            //keep the number of instances as information on the Set node
            String tablePath;
            //mysql driver
            if (accessConfiguration.getDriver().equalsIgnoreCase(SpicyEngineConstants.MYSQL_DRIVER)) {
                tablePath = catalog + "." + tableName;
            } else {
                tablePath = "\"" + schemaName + "\".\"" + tableName + "\"";
            }
            Statement statement = connection.createStatement();
            ResultSet countResult = statement
                    .executeQuery("SELECT COUNT(*) AS instancesCount FROM " + tablePath + ";");
            int noOfRows = 0;
            while (countResult.next()) {
                noOfRows = countResult.getInt("instancesCount");
            }
            setTable.setFullSize(noOfRows);
            countResult.close();

            if (logger.isDebugEnabled())
                logger.debug("extracting value for table " + tableName + " ....");
            getInstanceByTable(dataSourceDB, connection, schemaName, tableName, setTable, dataSource,
                    translated);
            root.addChild(setTable);
        }
        int childrenNo = 0;
        for (INode setnode : root.getChildren()) {
            childrenNo = childrenNo + setnode.getChildren().size();
        }
        //if there are any instances
        if (childrenNo > 0) {
            //load only a sample of the instances to memory to show on MIPMap interface
            dataSource.addInstanceWithCheck(root);
        }
    } catch (SQLException | DAOException ex) {
        logger.error(ex);
        throw new DAOException(ex.getMessage());
    } finally {
        if (connection != null)
            dataSourceDB.close(connection);
    }
}

From source file:it.unibas.spicy.persistence.relational.DAORelational.java

public IDataSourceProxy loadSchemaForWeb(int scenarioNo, AccessConfiguration accessConfiguration,
        DBFragmentDescription dataDescription, IConnectionFactory dataSourceDB, boolean source)
        throws DAOException {
    this.dataDescription = dataDescription;
    INode root = null;// ww  w  . j  a  v a  2 s. c  o m
    String catalog = null;
    String schemaName = accessConfiguration.getSchemaName();
    DatabaseMetaData databaseMetaData = null;
    Connection connection = dataSourceDB.getConnection(accessConfiguration);
    IDataSourceProxy dataSource = null;
    try {
        databaseMetaData = connection.getMetaData();
        catalog = connection.getCatalog();
        if (catalog == null) {
            catalog = accessConfiguration.getUri();
            if (logger.isDebugEnabled())
                logger.debug("Catalog is null. Catalog name will be: " + catalog);
        }
        root = this.createRootNode(catalog);

        String[] tableTypes = new String[] { "TABLE" };
        ResultSet tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, tableTypes);
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            if (!this.dataDescription.checkLoadTable(tableName)) {
                continue;
            }
            INode setTable = new SetNode(tableName);
            setTable.addChild(getTuple(databaseMetaData, catalog, schemaName, tableName));
            setTable.setRequired(false);
            setTable.setNotNull(true);
            root.addChild(setTable);
            addNode(tableName, setTable);
        }
        dataSource = new ConstantDataSourceProxy(new DataSource(SpicyEngineConstants.TYPE_RELATIONAL, root));
        dataSource.addAnnotation(SpicyEngineConstants.ACCESS_CONFIGURATION, accessConfiguration);
        for (Map.Entry<String, String> entry : changedColumnNames.entrySet()) {
            dataSource.putChangedValue(entry.getKey(), entry.getValue());
        }
        loadPrimaryKeys(dataSource, databaseMetaData, catalog, schemaName, source, null, scenarioNo, true);
        loadForeignKeys(dataSource, databaseMetaData, catalog, schemaName, source, scenarioNo);
    } catch (Throwable ex) {
        logger.error(ex);
        throw new DAOException(ex.getMessage());
    } finally {
        if (connection != null)
            dataSourceDB.close(connection);
    }
    return dataSource;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Wrapper for {@link java.sql.DatabaseMetaData#getTables(String, String, String, String[])}
 *
 * @param connection open JDBC connection
 * @param schema schema name, can be null
 * @param tableName table name or pattern, optionally fully qualified in the form schema.tableName
 * @return ResultSet containing the table and view metadata
 *
 * @throws SQLException/*  www.  j av a  2  s  . c  o m*/
 */
public ResultSet getTableAndViewMetadata(Connection connection, String schema, String tableName)
        throws SQLException {
    return connection.getMetaData().getTables(connection.getCatalog(), schema, tableName,
            METADATA_TABLE_VIEW_TYPE);
}

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.AbstractDBExtractService.java

public final Catalog getCatalog() throws SQLException {
    Connection conn = null;
    try {//w  w w.  j a va2 s .  c o m
        conn = jdbcTemplate.getDataSource().getConnection();
        metaData = conn.getMetaData();
    } catch (SQLException e) {
        log.error("DB??SQL!DB????!", e);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR,
                "DB??SQL!DB????!");
        if (conn != null) {
            conn.close();
        }
        throw e;
    }
    log.info("???!");

    try {
        log.info("??.");

        String catalogName = conn.getCatalog();
        Catalog catalog = new Catalog();
        catalog.setName(catalogName);
        log.info("catalog Name:" + catalogName);
        catalog.setSchemas(internalGetSchemas());

        internalAfterHook(catalog);
        return catalog;
    } catch (SQLException e) {
        log.error("", e);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR, e.getMessage());
        throw e;
    } finally {
        // ??,???
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Wrapper for {@link java.sql.DatabaseMetaData#getTables(String, String, String, String[])}
 *
 * @param connection open JDBC connection
 * @param schema schema name, can be null
 * @param tableName table name or pattern, optionally fully qualified in the form schema.tableName
 * @return ResultSet containing the table metadata
 *
 * @throws SQLException/*www .  j ava2 s  .c  om*/
 */
public ResultSet getTableMetadata(Connection connection, String schema, String tableName) throws SQLException {
    DatabaseMetaData metadata = connection.getMetaData();
    return metadata.getTables(connection.getCatalog(), schema, tableName, METADATA_TABLE_TYPE);
}