Example usage for java.sql DatabaseMetaData getDriverName

List of usage examples for java.sql DatabaseMetaData getDriverName

Introduction

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

Prototype

String getDriverName() throws SQLException;

Source Link

Document

Retrieves the name of this JDBC driver.

Usage

From source file:jef.database.DbMetaData.java

/**
 * ??// w  ww .  j a  v  a 2 s.co m
 * 
 * @return Map<String,String> [key] is
 *         <ul>
 *         <li>DatabaseProductName</li>
 *         <li>DatabaseProductVersion</li>
 *         <li>DriverName</li>
 *         <li>DriverVersion</li>
 *         </ul>
 */
public Map<String, String> getDbVersion() throws SQLException {
    Connection conn = getConnection(false);
    DatabaseMetaData databaseMetaData = conn.getMetaData();
    Map<String, String> map = new SimpleMap<String, String>();
    map.put("DriverName", databaseMetaData.getDriverName());
    map.put("DriverVersion",
            databaseMetaData.getDriverVersion() + " " + databaseMetaData.getDatabaseMinorVersion());
    map.put("DatabaseProductName", databaseMetaData.getDatabaseProductName());
    map.put("DatabaseProductVersion",
            databaseMetaData.getDatabaseProductVersion() + " " + databaseMetaData.getDatabaseMinorVersion());

    String otherVersionSQL = info.profile.getProperty(DbProperty.OTHER_VERSION_SQL);
    if (otherVersionSQL != null) {
        for (String sql : StringUtils.split(otherVersionSQL, ";")) {
            if (StringUtils.isBlank(sql))
                continue;
            Statement st = conn.createStatement();
            ResultSet rs = null;
            try {
                rs = st.executeQuery(sql);
                while (rs.next()) {
                    map.put(rs.getString(1), rs.getString(2));
                }
            } finally {
                DbUtils.close(rs);
                DbUtils.close(st);
            }
        }
    }
    releaseConnection(conn);
    return map;
}

From source file:jef.database.DbMetaData.java

private List<Function> innerGetFunctions(String schema, String name) throws SQLException {
    if (schema == null) {
        schema = this.schema;
    }/*from   w  w  w  . j  a  v  a  2 s  .  c  om*/

    Connection conn = getConnection(false);
    DatabaseDialect profile = getProfile();
    if (profile.has(Feature.NOT_SUPPORT_USER_FUNCTION)) {
        return Collections.emptyList();
    }
    List<Function> result = new ArrayList<Function>();
    DatabaseMetaData databaseMetaData = conn.getMetaData();
    ResultSet rs = null;
    try {
        rs = databaseMetaData.getFunctions(profile.getCatlog(schema), profile.getSchema(schema), name);
        while (rs.next()) {
            Function function = new Function();
            function.setCatalog(rs.getString(1));
            function.setSchema(rs.getString(2));
            function.setName(rs.getString(3));
            function.setRemarks(rs.getString(4));
            function.setType(rs.getShort(5));
            function.setSpecificName(rs.getString(6));
            result.add(function);
        }
    } catch (java.sql.SQLFeatureNotSupportedException e) {
        LogUtil.warn(databaseMetaData.getDriverName() + " doesn't supprt getFunctions() defined in JDDBC 4.0.");
    } catch (AbstractMethodError e) { // Driver version is too old...
        StringBuilder sb = new StringBuilder("The driver ").append(databaseMetaData.getDriverName());
        sb.append(' ').append(databaseMetaData.getDriverVersion()).append(' ')
                .append(databaseMetaData.getDatabaseMinorVersion());
        sb.append(" not implements JDBC 4.0, please upgrade you JDBC Driver.");
        throw new SQLException(sb.toString());
    } finally {
        DbUtils.close(rs);
        releaseConnection(conn);
    }
    return result;
}

From source file:net.tradelib.misc.StrategyText.java

public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date, String csvPath,
        char csvSep) throws Exception {
    // public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date) throws Exception {
    ArrayList<InstrumentText> result = new ArrayList<InstrumentText>();

    CSVPrinter printer = null;//from ww w .  j  a va  2s  .  c o  m
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(csvSep).print(new BufferedWriter(new FileWriter(csvPath)));
    }

    int numCsvColumns = 12;

    int rollMethod = 2;

    DatabaseMetaData dmd = con.getMetaData();
    String driverName = dmd.getDriverName();
    String query = "";
    if (driverName.startsWith("MySQL")) {
        query = STRATEGY_QUERY_MYSQL;
    } else {
        query = STRATEGY_QUERY;
    }

    String prevCategory = "";
    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setString(1, strategy);
    pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay()));
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
        String category = rs.getString(2);
        if (!category.equals(prevCategory)) {
            result.add(InstrumentText.makeSection(category));
            prevCategory = category;

            if (printer != null) {
                printer.print(category);
                for (int ii = 1; ii < numCsvColumns; ++ii) {
                    printer.print("");
                }
                printer.println();
            }
        }
        String name = rs.getString(3);
        String symbol = rs.getString(4);
        String contract = "";
        if (rollMethod == 1) {
            // Uses current_contract and trading_days
            int ndays = rs.getInt(12);
            if (ndays > 1) {
                contract = rs.getString(10);
            } else {
                contract = "Roll to " + rs.getString(11);
            }
        } else if (rollMethod == 2) {
            // Uses current_contract2 and roll_today
            int rollToday = rs.getInt(14);
            if (rollToday == 0) {
                contract = rs.getString(13);
            } else {
                contract = "Roll to " + rs.getString(13);
            }
        }

        if (printer != null) {
            printer.print(name);
            printer.print(symbol);
            printer.print(contract);
        }

        String signal;
        long position = (long) rs.getDouble(5);
        JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class);
        if (position > 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(Double.MIN_VALUE);
                pnl = Double.MIN_VALUE;
            }
            signal = String.format("Long [%d] since %s [at %s].", position, rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else if (position < 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(-1);
                pnl = -1;
            }
            signal = String.format("Short [%d] since %s [at %s].", Math.abs(position), rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else {
            signal = "Out.";
            if (printer != null) {
                printer.print(signal);
                // An empty column follows the status if there is no position - there is no profit.
                printer.print("");
            }
        }

        boolean hasOrder = false;
        JsonArray ja = jo.get("orders").getAsJsonArray();
        double entryRisk;
        try {
            entryRisk = jo.get("entry_risk").getAsDouble();
        } catch (Exception ee) {
            entryRisk = Double.NaN;
        }
        String profitTarget;
        Double profitTargetDbl;
        try {
            profitTarget = formatBigDecimal(jo.get("profit_target").getAsBigDecimal());
            profitTargetDbl = jo.get("profit_target").getAsDouble();
        } catch (Exception ee) {
            profitTarget = null;
            profitTargetDbl = null;
        }
        String stopLoss;
        Double stopLossDbl;
        try {
            stopLoss = formatBigDecimal(jo.get("stop_loss").getAsBigDecimal());
            stopLossDbl = jo.get("stop_loss").getAsDouble();
        } catch (Exception ee) {
            stopLoss = null;
            stopLossDbl = null;
        }

        Double lastClose;
        try {
            lastClose = jo.get("last_close").getAsDouble();
        } catch (Exception ee) {
            lastClose = null;
        }

        // Currently maximum one entry and maximum one exit are supported.
        String entryStr = "";
        String exitStr = "";
        String contractRiskStr = "";

        for (int ii = 0; ii < ja.size(); ++ii) {
            JsonObject jorder = ja.get(ii).getAsJsonObject();

            switch (jorder.get("type").getAsString()) {
            case "EXIT_LONG_STOP":
                exitStr = "Exit long at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP":
                exitStr = "Exit short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "ENTER_LONG":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter long at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter long at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_SHORT":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter short at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter short at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_LONG_STOP":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at stop %s [%s%%].", position,
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_LONG_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at limit %s, stop at %s [%s%%].", position,
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP":
                // signal += " Enter short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + ".";
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at stop %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at limit %s, stop at %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "EXIT_LONG":
                exitStr = "Exit long at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT":
                exitStr = "Exit short at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP_LIMIT":
                exitStr = "Exit short at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_LONG_STOP_LIMIT":
                exitStr = "Exit long at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;
            }
            hasOrder = true;
        }

        String lastCloseStr = "Last close at " + formatBigDecimal(jo.get("last_close").getAsBigDecimal()) + ".";
        String stopLossStr = "";
        String profitTargetStr = "";

        if (hasOrder) {
            signal += " " + lastCloseStr;
        }

        if (stopLoss != null) {
            stopLossStr = "Stop loss at " + stopLoss;
            if (lastClose != null && stopLossDbl != null) {
                stopLossStr += " [" + formatPercentage(stopLossDbl / lastClose * 100 - 100) + "%]";
            }
            stopLossStr += ".";
            signal += " " + stopLossStr;
        }

        if (profitTarget != null) {
            profitTargetStr = "Profit target at about " + profitTarget;
            if (profitTargetDbl != null && lastClose != null) {
                profitTargetStr += " [" + formatPercentage(profitTargetDbl / lastClose * 100 - 100) + "%]";
            }
            profitTargetStr += ".";
            signal += " " + profitTargetStr;
        }

        if (printer != null) {
            printer.print(exitStr);
            printer.print(entryStr);
            printer.print(contractRiskStr);
            printer.print(lastCloseStr);
            printer.print(stopLossStr);
            printer.print(profitTargetStr);
            printer.println();
        }

        result.add(InstrumentText.make(name, symbol, contract, signal));
    }

    rs.close();
    pstmt.close();

    if (printer != null)
        printer.flush();

    return result;
}

From source file:net.tradelib.misc.StrategyText.java

public static void buildOrdersCsv(String dbUrl, String strategy, LocalDate date, String csvPath)
        throws Exception {
    Connection con = DriverManager.getConnection(dbUrl);

    CSVPrinter printer = null;//w w w.  j av  a  2  s.  c  o  m
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(',').withHeader(CSV_HEADER)
                .print(new BufferedWriter(new FileWriter(csvPath)));
    }

    int rollMethod = 2;

    DatabaseMetaData dmd = con.getMetaData();
    String driverName = dmd.getDriverName();
    String query = "";
    if (driverName.startsWith("MySQL")) {
        query = STRATEGY_ORDER_QUERY_MYSQL;
    } else {
        query = STRATEGY_ORDER_QUERY;
    }

    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setString(1, strategy);
    pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay()));
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
        JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class);
        JsonArray ja = jo.get("orders").getAsJsonArray();

        int ndays = rs.getInt(12);
        String contract = "";
        if (rollMethod == 1) {
            if (ndays > 1) {
                contract = rs.getString(10);
            } else {
                contract = rs.getString(11);
            }
        } else if (rollMethod == 2) {
            contract = rs.getString(15);
        }

        for (int ii = 0; ii < ja.size(); ++ii) {
            JsonObject jorder = ja.get(ii).getAsJsonObject();

            switch (jorder.get("type").getAsString()) {
            case "EXIT_LONG_STOP":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "EXIT_SHORT_STOP":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_LONG":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "ENTER_SHORT":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "ENTER_LONG_STOP":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_LONG_STOP_LIMIT":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_SHORT_STOP":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_SHORT_STOP_LIMIT":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "EXIT_LONG":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "EXIT_SHORT":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "EXIT_SHORT_STOP_LIMIT":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "EXIT_LONG_STOP_LIMIT":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;
            }
        }

        if (printer != null)
            printer.flush();
    }
}

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

public String getDatasourceInfo() throws JdbcException {
    String dsinfo = null;/*from  w  w w . ja va 2 s  .  co  m*/
    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.apache.bigtop.itest.hive.TestJdbc.java

/**
 * Test simple DatabaseMetaData calls.  getColumns is tested elsewhere, as we need to call
 * that on a valid table.  Same with getFunctions.
 *
 * @throws SQLException/*from  w w w  .  jav  a2  s  .c  om*/
 */
@Test
public void databaseMetaDataCalls() throws SQLException {
    DatabaseMetaData md = conn.getMetaData();

    boolean boolrc = md.allTablesAreSelectable();
    LOG.debug("All tables are selectable? " + boolrc);

    String strrc = md.getCatalogSeparator();
    LOG.debug("Catalog separator " + strrc);

    strrc = md.getCatalogTerm();
    LOG.debug("Catalog term " + strrc);

    ResultSet rs = md.getCatalogs();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found catalog " + strrc);
    }

    Connection c = md.getConnection();

    int intrc = md.getDatabaseMajorVersion();
    LOG.debug("DB major version is " + intrc);

    intrc = md.getDatabaseMinorVersion();
    LOG.debug("DB minor version is " + intrc);

    strrc = md.getDatabaseProductName();
    LOG.debug("DB product name is " + strrc);

    strrc = md.getDatabaseProductVersion();
    LOG.debug("DB product version is " + strrc);

    intrc = md.getDefaultTransactionIsolation();
    LOG.debug("Default transaction isolation is " + intrc);

    intrc = md.getDriverMajorVersion();
    LOG.debug("Driver major version is " + intrc);

    intrc = md.getDriverMinorVersion();
    LOG.debug("Driver minor version is " + intrc);

    strrc = md.getDriverName();
    LOG.debug("Driver name is " + strrc);

    strrc = md.getDriverVersion();
    LOG.debug("Driver version is " + strrc);

    strrc = md.getExtraNameCharacters();
    LOG.debug("Extra name characters is " + strrc);

    strrc = md.getIdentifierQuoteString();
    LOG.debug("Identifier quote string is " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getImportedKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getIndexInfo("a", "b", "d", true, true);

    intrc = md.getJDBCMajorVersion();
    LOG.debug("JDBC major version is " + intrc);

    intrc = md.getJDBCMinorVersion();
    LOG.debug("JDBC minor version is " + intrc);

    intrc = md.getMaxColumnNameLength();
    LOG.debug("Maximum column name length is " + intrc);

    strrc = md.getNumericFunctions();
    LOG.debug("Numeric functions are " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getPrimaryKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedureColumns("a", "b", "d", "e");

    strrc = md.getProcedureTerm();
    LOG.debug("Procedures are called " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedures("a", "b", "d");

    strrc = md.getSchemaTerm();
    LOG.debug("Schemas are called " + strrc);

    rs = md.getSchemas();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found schema " + strrc);
    }

    strrc = md.getSearchStringEscape();
    LOG.debug("Search string escape is " + strrc);

    strrc = md.getStringFunctions();
    LOG.debug("String functions are " + strrc);

    strrc = md.getSystemFunctions();
    LOG.debug("System functions are " + strrc);

    rs = md.getTableTypes();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found table type " + strrc);
    }

    strrc = md.getTimeDateFunctions();
    LOG.debug("Time/date functions are " + strrc);

    rs = md.getTypeInfo();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found type " + strrc);
    }

    // In Hive 1.2 this always returns an empty RS
    rs = md.getUDTs("a", "b", "d", null);

    boolrc = md.supportsAlterTableWithAddColumn();
    LOG.debug("Supports alter table with add column? " + boolrc);

    boolrc = md.supportsAlterTableWithDropColumn();
    LOG.debug("Supports alter table with drop column? " + boolrc);

    boolrc = md.supportsBatchUpdates();
    LOG.debug("Supports batch updates? " + boolrc);

    boolrc = md.supportsCatalogsInDataManipulation();
    LOG.debug("Supports catalogs in data manipulation? " + boolrc);

    boolrc = md.supportsCatalogsInIndexDefinitions();
    LOG.debug("Supports catalogs in index definition? " + boolrc);

    boolrc = md.supportsCatalogsInPrivilegeDefinitions();
    LOG.debug("Supports catalogs in privilege definition? " + boolrc);

    boolrc = md.supportsCatalogsInProcedureCalls();
    LOG.debug("Supports catalogs in procedure calls? " + boolrc);

    boolrc = md.supportsCatalogsInTableDefinitions();
    LOG.debug("Supports catalogs in table definition? " + boolrc);

    boolrc = md.supportsColumnAliasing();
    LOG.debug("Supports column aliasing? " + boolrc);

    boolrc = md.supportsFullOuterJoins();
    LOG.debug("Supports full outer joins? " + boolrc);

    boolrc = md.supportsGroupBy();
    LOG.debug("Supports group by? " + boolrc);

    boolrc = md.supportsLimitedOuterJoins();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsMultipleResultSets();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsNonNullableColumns();
    LOG.debug("Supports non-nullable columns? " + boolrc);

    boolrc = md.supportsOuterJoins();
    LOG.debug("Supports outer joins? " + boolrc);

    boolrc = md.supportsPositionedDelete();
    LOG.debug("Supports positioned delete? " + boolrc);

    boolrc = md.supportsPositionedUpdate();
    LOG.debug("Supports positioned update? " + boolrc);

    boolrc = md.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set holdability? " + boolrc);

    boolrc = md.supportsResultSetType(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set type? " + boolrc);

    boolrc = md.supportsSavepoints();
    LOG.debug("Supports savepoints? " + boolrc);

    boolrc = md.supportsSchemasInDataManipulation();
    LOG.debug("Supports schemas in data manipulation? " + boolrc);

    boolrc = md.supportsSchemasInIndexDefinitions();
    LOG.debug("Supports schemas in index definitions? " + boolrc);

    boolrc = md.supportsSchemasInPrivilegeDefinitions();
    LOG.debug("Supports schemas in privilege definitions? " + boolrc);

    boolrc = md.supportsSchemasInProcedureCalls();
    LOG.debug("Supports schemas in procedure calls? " + boolrc);

    boolrc = md.supportsSchemasInTableDefinitions();
    LOG.debug("Supports schemas in table definitions? " + boolrc);

    boolrc = md.supportsSelectForUpdate();
    LOG.debug("Supports select for update? " + boolrc);

    boolrc = md.supportsStoredProcedures();
    LOG.debug("Supports stored procedures? " + boolrc);

    boolrc = md.supportsTransactions();
    LOG.debug("Supports transactions? " + boolrc);

    boolrc = md.supportsUnion();
    LOG.debug("Supports union? " + boolrc);

    boolrc = md.supportsUnionAll();
    LOG.debug("Supports union all? " + boolrc);

}

From source file:org.apache.ddlutils.TestSummaryCreatorTask.java

/**
 * Adds the data from the test jdbc propertis file to the document.
 * /*from   ww w.j a va2s. c om*/
 * @param element            The element to add the relevant database properties to
 * @param jdbcPropertiesFile The path of the properties file
 */
protected void addTargetDatabaseInfo(Element element, String jdbcPropertiesFile)
        throws IOException, BuildException {
    if (jdbcPropertiesFile == null) {
        return;
    }

    Properties props = readProperties(jdbcPropertiesFile);
    Connection conn = null;
    DatabaseMetaData metaData = null;

    try {
        String dataSourceClass = props.getProperty(
                TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class",
                BasicDataSource.class.getName());
        DataSource dataSource = (DataSource) Class.forName(dataSourceClass).newInstance();

        for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String propName = (String) entry.getKey();

            if (propName.startsWith(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX)
                    && !propName.equals(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class")) {
                BeanUtils.setProperty(dataSource,
                        propName.substring(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX.length()),
                        entry.getValue());
            }
        }

        String platformName = props.getProperty(TestAgainstLiveDatabaseBase.DDLUTILS_PLATFORM_PROPERTY);

        if (platformName == null) {
            platformName = new PlatformUtils().determineDatabaseType(dataSource);
            if (platformName == null) {
                throw new BuildException(
                        "Could not determine platform from datasource, please specify it in the jdbc.properties via the ddlutils.platform property");
            }
        }

        element.addAttribute("platform", platformName);
        element.addAttribute("dataSourceClass", dataSourceClass);

        conn = dataSource.getConnection();
        metaData = conn.getMetaData();

        try {
            element.addAttribute("dbProductName", metaData.getDatabaseProductName());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("dbProductVersion", metaData.getDatabaseProductVersion());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            int databaseMajorVersion = metaData.getDatabaseMajorVersion();
            int databaseMinorVersion = metaData.getDatabaseMinorVersion();

            element.addAttribute("dbVersion", databaseMajorVersion + "." + databaseMinorVersion);
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("driverName", metaData.getDriverName());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("driverVersion", metaData.getDriverVersion());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            int jdbcMajorVersion = metaData.getJDBCMajorVersion();
            int jdbcMinorVersion = metaData.getJDBCMinorVersion();

            element.addAttribute("jdbcVersion", jdbcMajorVersion + "." + jdbcMinorVersion);
        } catch (Throwable ex) {
            // we ignore it
        }
    } catch (Exception ex) {
        throw new BuildException(ex);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                // we ignore it
            }
        }
    }
}

From source file:org.apache.drill.jdbc.ITTestShadedJar.java

@Test
public void testDatabaseVersion() throws Exception {

    // print class path for debugging
    System.out.println("java.class.path:");
    System.out.println(System.getProperty("java.class.path"));

    final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);/*from   www .  j a  v  a2  s . co m*/
    method.invoke(loader, getJdbcUrl());

    Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
    try {
        Driver driver = (Driver) clazz.newInstance();
        try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) {
            DatabaseMetaData metadata = c.getMetaData();
            assertEquals("Apache Drill JDBC Driver", metadata.getDriverName());
            assertEquals("Apache Drill Server", metadata.getDatabaseProductName());
            //assertEquals()
        }
    } catch (Exception ex) {
        throw ex;
    }

}

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}// ww  w  .  j  a  v  a  2  s. c o  m
 */
public void init(PMContext context) throws Exception {
    if (initialized) {
        throw new IllegalStateException("already initialized");
    }

    // setup jdbc connection
    initConnection();

    DatabaseMetaData meta = con.getMetaData();
    try {
        log.info("Database: " + meta.getDatabaseProductName() + " / " + meta.getDatabaseProductVersion());
        log.info("Driver: " + meta.getDriverName() + " / " + meta.getDriverVersion());
    } catch (SQLException e) {
        log.warn("Can not retrieve database and driver name / version", e);
    }

    // make sure schemaObjectPrefix consists of legal name characters only
    prepareSchemaObjectPrefix();

    // check if schema objects exist and create them if necessary
    if (isSchemaCheckEnabled()) {
        checkSchema();
    }

    // build sql statements
    buildSQLStatements();

    // prepare statements
    initPreparedStatements();

    if (externalBLOBs) {
        /**
         * store BLOBs in local file system in a sub directory
         * of the workspace home directory
         */
        LocalFileSystem blobFS = new LocalFileSystem();
        blobFS.setRoot(new File(context.getHomeDir(), "blobs"));
        blobFS.init();
        this.blobFS = blobFS;
        blobStore = new FileSystemBLOBStore(blobFS);
    } else {
        /**
         * store BLOBs in db
         */
        blobStore = new DbBLOBStore();
    }

    initialized = true;
}

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

/**
 * This method is called when the dictionary first sees any connection.
 * It is used to initialize dictionary metadata if needed. If you
 * override this method, be sure to call
 * <code>super.connectedConfiguration</code>.
 *///w w  w .  ja  v  a2s .com
public void connectedConfiguration(Connection conn) throws SQLException {
    if (!connected) {
        DatabaseMetaData metaData = null;
        try {
            metaData = conn.getMetaData();

            databaseProductName = nullSafe(metaData.getDatabaseProductName());
            databaseProductVersion = nullSafe(metaData.getDatabaseProductVersion());
            setMajorVersion(metaData.getDatabaseMajorVersion());
            setMinorVersion(metaData.getDatabaseMinorVersion());
            try {
                // JDBC3-only method, so it might throw an
                // AbstractMethodError
                int JDBCMajorVersion = metaData.getJDBCMajorVersion();
                isJDBC3 = JDBCMajorVersion >= 3;
                isJDBC4 = JDBCMajorVersion >= 4;
            } catch (Throwable t) {
                // ignore if not JDBC3
            }
        } catch (Exception e) {
            if (log.isTraceEnabled())
                log.trace(e.toString(), e);
        }

        if (log.isTraceEnabled()) {
            log.trace(DBDictionaryFactory.toString(metaData));

            if (isJDBC3) {
                try {
                    log.trace(_loc.get("connection-defaults", new Object[] { conn.getAutoCommit(),
                            conn.getHoldability(), conn.getTransactionIsolation() }));
                } catch (Throwable t) {
                    log.trace("Unable to trace connection settings", t);
                }
            }
        }

        // Configure the naming utility
        if (supportsDelimitedIdentifiers == null) // not explicitly set
            configureNamingUtil(metaData);

        // Auto-detect generated keys retrieval support unless user specified it.
        if (supportsGetGeneratedKeys == null) {
            supportsGetGeneratedKeys = (isJDBC3) ? metaData.supportsGetGeneratedKeys() : false;
        }
        if (log.isInfoEnabled()) {
            log.info(_loc.get("dict-info", new Object[] { metaData.getDatabaseProductName(), getMajorVersion(),
                    getMinorVersion(), metaData.getDriverName(), metaData.getDriverVersion() }));
        }
    }
    connected = true;
}