Example usage for java.sql DatabaseMetaData getURL

List of usage examples for java.sql DatabaseMetaData getURL

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getURL.

Prototype

String getURL() throws SQLException;

Source Link

Document

Retrieves the URL for this DBMS.

Usage

From source file:org.apache.nifi.processors.standard.AbstractQueryDatabaseTable.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory)
        throws ProcessException {
    // Fetch the column/table info once
    if (!setupComplete.get()) {
        super.setup(context);
    }/*from  w ww  .  j  a  v a 2 s . co  m*/
    ProcessSession session = sessionFactory.createSession();
    final List<FlowFile> resultSetFlowFiles = new ArrayList<>();

    final ComponentLog logger = getLogger();

    final DBCPService dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class);
    final DatabaseAdapter dbAdapter = dbAdapters.get(context.getProperty(DB_TYPE).getValue());
    final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions().getValue();
    final String columnNames = context.getProperty(COLUMN_NAMES).evaluateAttributeExpressions().getValue();
    final String sqlQuery = context.getProperty(SQL_QUERY).evaluateAttributeExpressions().getValue();
    final String maxValueColumnNames = context.getProperty(MAX_VALUE_COLUMN_NAMES)
            .evaluateAttributeExpressions().getValue();
    final String customWhereClause = context.getProperty(WHERE_CLAUSE).evaluateAttributeExpressions()
            .getValue();
    final Integer fetchSize = context.getProperty(FETCH_SIZE).evaluateAttributeExpressions().asInteger();
    final Integer maxRowsPerFlowFile = context.getProperty(MAX_ROWS_PER_FLOW_FILE)
            .evaluateAttributeExpressions().asInteger();
    final Integer outputBatchSizeField = context.getProperty(OUTPUT_BATCH_SIZE).evaluateAttributeExpressions()
            .asInteger();
    final int outputBatchSize = outputBatchSizeField == null ? 0 : outputBatchSizeField;
    final Integer maxFragments = context.getProperty(MAX_FRAGMENTS).isSet()
            ? context.getProperty(MAX_FRAGMENTS).evaluateAttributeExpressions().asInteger()
            : 0;

    SqlWriter sqlWriter = configureSqlWriter(session, context);

    final StateManager stateManager = context.getStateManager();
    final StateMap stateMap;

    try {
        stateMap = stateManager.getState(Scope.CLUSTER);
    } catch (final IOException ioe) {
        getLogger().error("Failed to retrieve observed maximum values from the State Manager. Will not perform "
                + "query until this is accomplished.", ioe);
        context.yield();
        return;
    }
    // Make a mutable copy of the current state property map. This will be updated by the result row callback, and eventually
    // set as the current state map (after the session has been committed)
    final Map<String, String> statePropertyMap = new HashMap<>(stateMap.toMap());

    //If an initial max value for column(s) has been specified using properties, and this column is not in the state manager, sync them to the state property map
    for (final Map.Entry<String, String> maxProp : maxValueProperties.entrySet()) {
        String maxPropKey = maxProp.getKey().toLowerCase();
        String fullyQualifiedMaxPropKey = getStateKey(tableName, maxPropKey, dbAdapter);
        if (!statePropertyMap.containsKey(fullyQualifiedMaxPropKey)) {
            String newMaxPropValue;
            // If we can't find the value at the fully-qualified key name, it is possible (under a previous scheme)
            // the value has been stored under a key that is only the column name. Fall back to check the column name,
            // but store the new initial max value under the fully-qualified key.
            if (statePropertyMap.containsKey(maxPropKey)) {
                newMaxPropValue = statePropertyMap.get(maxPropKey);
            } else {
                newMaxPropValue = maxProp.getValue();
            }
            statePropertyMap.put(fullyQualifiedMaxPropKey, newMaxPropValue);

        }
    }

    List<String> maxValueColumnNameList = StringUtils.isEmpty(maxValueColumnNames) ? null
            : Arrays.asList(maxValueColumnNames.split("\\s*,\\s*"));
    final String selectQuery = getQuery(dbAdapter, tableName, sqlQuery, columnNames, maxValueColumnNameList,
            customWhereClause, statePropertyMap);
    final StopWatch stopWatch = new StopWatch(true);
    final String fragmentIdentifier = UUID.randomUUID().toString();

    try (final Connection con = dbcpService.getConnection(Collections.emptyMap());
            final Statement st = con.createStatement()) {

        if (fetchSize != null && fetchSize > 0) {
            try {
                st.setFetchSize(fetchSize);
            } catch (SQLException se) {
                // Not all drivers support this, just log the error (at debug level) and move on
                logger.debug("Cannot set fetch size to {} due to {}",
                        new Object[] { fetchSize, se.getLocalizedMessage() }, se);
            }
        }

        String jdbcURL = "DBCPService";
        try {
            DatabaseMetaData databaseMetaData = con.getMetaData();
            if (databaseMetaData != null) {
                jdbcURL = databaseMetaData.getURL();
            }
        } catch (SQLException se) {
            // Ignore and use default JDBC URL. This shouldn't happen unless the driver doesn't implement getMetaData() properly
        }

        final Integer queryTimeout = context.getProperty(QUERY_TIMEOUT).evaluateAttributeExpressions()
                .asTimePeriod(TimeUnit.SECONDS).intValue();
        st.setQueryTimeout(queryTimeout); // timeout in seconds
        if (logger.isDebugEnabled()) {
            logger.debug("Executing query {}", new Object[] { selectQuery });
        }
        try (final ResultSet resultSet = st.executeQuery(selectQuery)) {
            int fragmentIndex = 0;
            // Max values will be updated in the state property map by the callback
            final MaxValueResultSetRowCollector maxValCollector = new MaxValueResultSetRowCollector(tableName,
                    statePropertyMap, dbAdapter);

            while (true) {
                final AtomicLong nrOfRows = new AtomicLong(0L);

                FlowFile fileToProcess = session.create();
                try {
                    fileToProcess = session.write(fileToProcess, out -> {
                        try {
                            nrOfRows.set(
                                    sqlWriter.writeResultSet(resultSet, out, getLogger(), maxValCollector));
                        } catch (Exception e) {
                            throw new ProcessException("Error during database query or conversion of records.",
                                    e);
                        }
                    });
                } catch (ProcessException e) {
                    // Add flowfile to results before rethrowing so it will be removed from session in outer catch
                    resultSetFlowFiles.add(fileToProcess);
                    throw e;
                }

                if (nrOfRows.get() > 0) {
                    // set attributes
                    final Map<String, String> attributesToAdd = new HashMap<>();
                    attributesToAdd.put(RESULT_ROW_COUNT, String.valueOf(nrOfRows.get()));
                    attributesToAdd.put(RESULT_TABLENAME, tableName);

                    if (maxRowsPerFlowFile > 0) {
                        attributesToAdd.put(FRAGMENT_ID, fragmentIdentifier);
                        attributesToAdd.put(FRAGMENT_INDEX, String.valueOf(fragmentIndex));
                    }

                    attributesToAdd.putAll(sqlWriter.getAttributesToAdd());
                    fileToProcess = session.putAllAttributes(fileToProcess, attributesToAdd);
                    sqlWriter.updateCounters(session);

                    logger.info("{} contains {} records; transferring to 'success'",
                            new Object[] { fileToProcess, nrOfRows.get() });

                    session.getProvenanceReporter().receive(fileToProcess, jdbcURL,
                            stopWatch.getElapsed(TimeUnit.MILLISECONDS));
                    resultSetFlowFiles.add(fileToProcess);
                    // If we've reached the batch size, send out the flow files
                    if (outputBatchSize > 0 && resultSetFlowFiles.size() >= outputBatchSize) {
                        session.transfer(resultSetFlowFiles, REL_SUCCESS);
                        session.commit();
                        resultSetFlowFiles.clear();
                    }
                } else {
                    // If there were no rows returned, don't send the flowfile
                    session.remove(fileToProcess);
                    // If no rows and this was first FlowFile, yield
                    if (fragmentIndex == 0) {
                        context.yield();
                    }
                    break;
                }

                fragmentIndex++;
                if (maxFragments > 0 && fragmentIndex >= maxFragments) {
                    break;
                }

                // If we aren't splitting up the data into flow files or fragments, then the result set has been entirely fetched so don't loop back around
                if (maxFragments == 0 && maxRowsPerFlowFile == 0) {
                    break;
                }

                // If we are splitting up the data into flow files, don't loop back around if we've gotten all results
                if (maxRowsPerFlowFile > 0 && nrOfRows.get() < maxRowsPerFlowFile) {
                    break;
                }
            }

            // Apply state changes from the Max Value tracker
            maxValCollector.applyStateChanges();

            // Even though the maximum value and total count are known at this point, to maintain consistent behavior if Output Batch Size is set, do not store the attributes
            if (outputBatchSize == 0) {
                for (int i = 0; i < resultSetFlowFiles.size(); i++) {
                    // Add maximum values as attributes
                    for (Map.Entry<String, String> entry : statePropertyMap.entrySet()) {
                        // Get just the column name from the key
                        String key = entry.getKey();
                        String colName = key
                                .substring(key.lastIndexOf(NAMESPACE_DELIMITER) + NAMESPACE_DELIMITER.length());
                        resultSetFlowFiles.set(i, session.putAttribute(resultSetFlowFiles.get(i),
                                "maxvalue." + colName, entry.getValue()));
                    }

                    //set count on all FlowFiles
                    if (maxRowsPerFlowFile > 0) {
                        resultSetFlowFiles.set(i, session.putAttribute(resultSetFlowFiles.get(i),
                                FRAGMENT_COUNT, Integer.toString(fragmentIndex)));
                    }
                }
            }
        } catch (final SQLException e) {
            throw e;
        }

        session.transfer(resultSetFlowFiles, REL_SUCCESS);

    } catch (final ProcessException | SQLException e) {
        logger.error("Unable to execute SQL select query {} due to {}", new Object[] { selectQuery, e });
        if (!resultSetFlowFiles.isEmpty()) {
            session.remove(resultSetFlowFiles);
        }
        context.yield();
    } finally {
        session.commit();
        try {
            // Update the state
            stateManager.setState(statePropertyMap, Scope.CLUSTER);
        } catch (IOException ioe) {
            getLogger().error("{} failed to update State Manager, maximum observed values will not be recorded",
                    new Object[] { this, ioe });
        }
    }
}

From source file:org.apache.nifi.processors.standard.QueryDatabaseTable.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory)
        throws ProcessException {
    ProcessSession session = sessionFactory.createSession();
    final List<FlowFile> resultSetFlowFiles = new ArrayList<>();

    final ComponentLog logger = getLogger();

    final DBCPService dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class);
    final DatabaseAdapter dbAdapter = dbAdapters.get(context.getProperty(DB_TYPE).getValue());
    final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions().getValue();
    final String columnNames = context.getProperty(COLUMN_NAMES).evaluateAttributeExpressions().getValue();
    final String maxValueColumnNames = context.getProperty(MAX_VALUE_COLUMN_NAMES)
            .evaluateAttributeExpressions().getValue();
    final Integer fetchSize = context.getProperty(FETCH_SIZE).evaluateAttributeExpressions().asInteger();
    final Integer maxRowsPerFlowFile = context.getProperty(MAX_ROWS_PER_FLOW_FILE)
            .evaluateAttributeExpressions().asInteger();
    final Integer maxFragments = context.getProperty(MAX_FRAGMENTS).isSet()
            ? context.getProperty(MAX_FRAGMENTS).evaluateAttributeExpressions().asInteger()
            : 0;// ww w  .  j  av  a 2s. co m
    final boolean convertNamesForAvro = context.getProperty(NORMALIZE_NAMES_FOR_AVRO).asBoolean();

    final Map<String, String> maxValueProperties = getDefaultMaxValueProperties(context.getProperties());

    final StateManager stateManager = context.getStateManager();
    final StateMap stateMap;

    try {
        stateMap = stateManager.getState(Scope.CLUSTER);
    } catch (final IOException ioe) {
        getLogger().error("Failed to retrieve observed maximum values from the State Manager. Will not perform "
                + "query until this is accomplished.", ioe);
        context.yield();
        return;
    }
    // Make a mutable copy of the current state property map. This will be updated by the result row callback, and eventually
    // set as the current state map (after the session has been committed)
    final Map<String, String> statePropertyMap = new HashMap<>(stateMap.toMap());

    //If an initial max value for column(s) has been specified using properties, and this column is not in the state manager, sync them to the state property map
    for (final Map.Entry<String, String> maxProp : maxValueProperties.entrySet()) {
        String maxPropKey = maxProp.getKey().toLowerCase();
        String fullyQualifiedMaxPropKey = getStateKey(tableName, maxPropKey);
        if (!statePropertyMap.containsKey(fullyQualifiedMaxPropKey)) {
            String newMaxPropValue;
            // If we can't find the value at the fully-qualified key name, it is possible (under a previous scheme)
            // the value has been stored under a key that is only the column name. Fall back to check the column name,
            // but store the new initial max value under the fully-qualified key.
            if (statePropertyMap.containsKey(maxPropKey)) {
                newMaxPropValue = statePropertyMap.get(maxPropKey);
            } else {
                newMaxPropValue = maxProp.getValue();
            }
            statePropertyMap.put(fullyQualifiedMaxPropKey, newMaxPropValue);

        }
    }

    List<String> maxValueColumnNameList = StringUtils.isEmpty(maxValueColumnNames) ? null
            : Arrays.asList(maxValueColumnNames.split("\\s*,\\s*"));
    final String selectQuery = getQuery(dbAdapter, tableName, columnNames, maxValueColumnNameList,
            statePropertyMap);
    final StopWatch stopWatch = new StopWatch(true);
    final String fragmentIdentifier = UUID.randomUUID().toString();

    try (final Connection con = dbcpService.getConnection(); final Statement st = con.createStatement()) {

        if (fetchSize != null && fetchSize > 0) {
            try {
                st.setFetchSize(fetchSize);
            } catch (SQLException se) {
                // Not all drivers support this, just log the error (at debug level) and move on
                logger.debug("Cannot set fetch size to {} due to {}",
                        new Object[] { fetchSize, se.getLocalizedMessage() }, se);
            }
        }

        String jdbcURL = "DBCPService";
        try {
            DatabaseMetaData databaseMetaData = con.getMetaData();
            if (databaseMetaData != null) {
                jdbcURL = databaseMetaData.getURL();
            }
        } catch (SQLException se) {
            // Ignore and use default JDBC URL. This shouldn't happen unless the driver doesn't implement getMetaData() properly
        }

        final Integer queryTimeout = context.getProperty(QUERY_TIMEOUT).evaluateAttributeExpressions()
                .asTimePeriod(TimeUnit.SECONDS).intValue();
        st.setQueryTimeout(queryTimeout); // timeout in seconds
        try {
            logger.debug("Executing query {}", new Object[] { selectQuery });
            final ResultSet resultSet = st.executeQuery(selectQuery);
            int fragmentIndex = 0;
            while (true) {
                final AtomicLong nrOfRows = new AtomicLong(0L);

                FlowFile fileToProcess = session.create();
                try {
                    fileToProcess = session.write(fileToProcess, out -> {
                        // Max values will be updated in the state property map by the callback
                        final MaxValueResultSetRowCollector maxValCollector = new MaxValueResultSetRowCollector(
                                tableName, statePropertyMap, dbAdapter);
                        try {
                            nrOfRows.set(JdbcCommon.convertToAvroStream(resultSet, out, tableName,
                                    maxValCollector, maxRowsPerFlowFile, convertNamesForAvro));
                        } catch (SQLException | RuntimeException e) {
                            throw new ProcessException(
                                    "Error during database query or conversion of records to Avro.", e);
                        }
                    });
                } catch (ProcessException e) {
                    // Add flowfile to results before rethrowing so it will be removed from session in outer catch
                    resultSetFlowFiles.add(fileToProcess);
                    throw e;
                }

                if (nrOfRows.get() > 0) {
                    // set attribute how many rows were selected
                    fileToProcess = session.putAttribute(fileToProcess, RESULT_ROW_COUNT,
                            String.valueOf(nrOfRows.get()));
                    fileToProcess = session.putAttribute(fileToProcess, RESULT_TABLENAME, tableName);
                    if (maxRowsPerFlowFile > 0) {
                        fileToProcess = session.putAttribute(fileToProcess, "fragment.identifier",
                                fragmentIdentifier);
                        fileToProcess = session.putAttribute(fileToProcess, "fragment.index",
                                String.valueOf(fragmentIndex));
                    }

                    logger.info("{} contains {} Avro records; transferring to 'success'",
                            new Object[] { fileToProcess, nrOfRows.get() });

                    session.getProvenanceReporter().receive(fileToProcess, jdbcURL,
                            stopWatch.getElapsed(TimeUnit.MILLISECONDS));
                    resultSetFlowFiles.add(fileToProcess);
                } else {
                    // If there were no rows returned, don't send the flowfile
                    session.remove(fileToProcess);
                    context.yield();
                    break;
                }

                fragmentIndex++;
                if (maxFragments > 0 && fragmentIndex >= maxFragments) {
                    break;
                }
            }

            for (int i = 0; i < resultSetFlowFiles.size(); i++) {
                // Add maximum values as attributes
                for (Map.Entry<String, String> entry : statePropertyMap.entrySet()) {
                    // Get just the column name from the key
                    String key = entry.getKey();
                    String colName = key
                            .substring(key.lastIndexOf(NAMESPACE_DELIMITER) + NAMESPACE_DELIMITER.length());
                    resultSetFlowFiles.set(i, session.putAttribute(resultSetFlowFiles.get(i),
                            "maxvalue." + colName, entry.getValue()));
                }

                //set count on all FlowFiles
                if (maxRowsPerFlowFile > 0) {
                    resultSetFlowFiles.set(i, session.putAttribute(resultSetFlowFiles.get(i), "fragment.count",
                            Integer.toString(fragmentIndex)));
                }
            }

        } catch (final SQLException e) {
            throw e;
        }

        session.transfer(resultSetFlowFiles, REL_SUCCESS);

    } catch (final ProcessException | SQLException e) {
        logger.error("Unable to execute SQL select query {} due to {}", new Object[] { selectQuery, e });
        if (!resultSetFlowFiles.isEmpty()) {
            session.remove(resultSetFlowFiles);
        }
        context.yield();
    } finally {
        session.commit();
        try {
            // Update the state
            stateManager.setState(statePropertyMap, Scope.CLUSTER);
        } catch (IOException ioe) {
            getLogger().error("{} failed to update State Manager, maximum observed values will not be recorded",
                    new Object[] { this, ioe });
        }
    }
}

From source file:org.apache.ojb.broker.metadata.JdbcMetadataUtils.java

/**
 * Fills parameters of the given {@link JdbcConnectionDescriptor} with metadata
 * extracted from the given datasource.//from  w w  w.j  a va2 s .  c om
 * 
 * @param jcd        The jdbc connection descriptor to fill
 * @param dataSource The data source
 * @param username   The username required to establish a connection via the data source
 *                   Can be empty if the data source does not require it or if one
 *                   is specified in the jdbc connection descriptor
 * @param password   The username required to establish a connection via the data source
 *                   Can be empty if the data source or username does not require it or if one
 *                   is specified in the jdbc connection descriptor
 */
public void fillJCDFromDataSource(JdbcConnectionDescriptor jcd, DataSource dataSource, String username,
        String password) throws MetadataException {
    String realUsername = (jcd.getUserName() != null ? jcd.getUserName() : username);
    String realPassword = (jcd.getPassWord() != null ? jcd.getPassWord() : password);
    Connection connection = null;
    DatabaseMetaData metadata = null;

    try {
        // we have to open a connection to be able to retrieve metadata
        if (realUsername != null) {
            connection = dataSource.getConnection(realUsername, realPassword);
        } else {
            connection = dataSource.getConnection();
        }

        metadata = connection.getMetaData();
    } catch (Throwable t) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
            }
        }
        throw new MetadataException("Could not get the metadata from the given datasource", t);
    }

    try {
        HashMap urlComponents = parseConnectionUrl(metadata.getURL());

        if (urlComponents.containsKey(PROPERTY_DBALIAS)) {
            jcd.setProtocol((String) urlComponents.get(PROPERTY_PROTOCOL));
            jcd.setSubProtocol((String) urlComponents.get(PROPERTY_SUBPROTOCOL));
            jcd.setDbAlias((String) urlComponents.get(PROPERTY_DBALIAS));
            if (jdbcSubProtocolToPlatform.containsKey(jcd.getSubProtocol())) {
                // TODO: We might be able to use this: metadata.getDatabaseProductName();
                jcd.setDbms((String) jdbcSubProtocolToPlatform.get(jcd.getSubProtocol()));
            }
        }
    } catch (Throwable t) {
        try {
            connection.close();
        } catch (SQLException ex) {
        }
        throw new MetadataException("Could not get the metadata from the given datasource", t);
    }
    try {
        // this will only work with JDK >= 1.4 and only with some jdbc drivers
        Integer majorVersion = (Integer) PropertyUtils.getProperty(metadata, "JDBCMajorVersion");
        Integer minorVersion = (Integer) PropertyUtils.getProperty(metadata, "JDBCMinorVersion");

        jcd.setJdbcLevel(Double.parseDouble(majorVersion.toString() + "." + minorVersion.toString()));
    } catch (Throwable t) {
        // otherwise we're assuming JDBC 2.0 compliance
        jcd.setJdbcLevel(2.0);
    }
    try {
        connection.close();
    } catch (SQLException ex) {
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionaryFactory.java

/**
 * Create the dictionary using connection metadata to determine its type.
 *///from   www.j a  va2 s .  c  om
public static DBDictionary newDBDictionary(JDBCConfiguration conf, DataSource ds, String props) {
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData meta = conn.getMetaData();
        String dclass = dictionaryClassForString(meta.getDatabaseProductName(), conf);
        if (dclass == null)
            dclass = dictionaryClassForString(getProtocol(meta.getURL()), conf);
        if (dclass == null)
            dclass = DBDictionary.class.getName();
        return newDBDictionary(conf, dclass, props, conn);
    } catch (SQLException se) {
        throw new StoreException(se).setFatal(true);
    } finally {
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException se) {
            }
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionaryFactory.java

/**
 * Return a string containing all the property values of the given
 * database metadata./*ww w .  ja  va  2 s  . com*/
 */
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  .  ja  v a  2 s.  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.artifactory.storage.db.DbServiceImpl.java

private void printConnectionInfo() throws SQLException {
    Connection connection = jdbcHelper.getDataSource().getConnection();
    try {//from  ww w . j a  v  a2  s  . c o  m
        DatabaseMetaData meta = connection.getMetaData();
        log.info("Database: {} {}. Driver: {} {}", meta.getDatabaseProductName(),
                meta.getDatabaseProductVersion(), meta.getDriverName(), meta.getDriverVersion());
        log.info("Connection URL: {}", meta.getURL());
    } catch (SQLException e) {
        log.warn("Can not retrieve database and driver name / version", e);
    } finally {
        DbUtils.close(connection);
    }
}

From source file:org.bonitasoft.platform.setup.PlatformSetup.java

private void initDataSource() throws PlatformException {
    try {/*from   ww  w .  j av a  2 s .  co  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.dashbuilder.dataprovider.backend.sql.JDBCUtils.java

public static Dialect dialect(Connection connection) {
    try {//  w  ww .jav  a 2s  .  c  om
        DatabaseMetaData m = connection.getMetaData();
        String url = m.getURL();
        if (!StringUtils.isBlank(url)) {
            return dialect(url, m.getDatabaseMajorVersion());
        }
        String dbName = m.getDatabaseProductName();
        return dialect(dbName.toLowerCase());
    } catch (SQLException e) {
        e.printStackTrace();
        return DEFAULT;
    }
}

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
 *///from  w w  w.j av a2  s.com
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)"));
    }
}