Example usage for javax.sql DataSource getConnection

List of usage examples for javax.sql DataSource getConnection

Introduction

In this page you can find the example usage for javax.sql DataSource getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Attempts to establish a connection with the data source that this DataSource object represents.

Usage

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static Connection getSQLConnection(String name) {
    InitialContext initContext;//from   w w w. j  a  v a2  s.co m
    try {
        initContext = new InitialContext();
        DataSource dataSource = (DataSource) initContext.lookup(name);
        return dataSource.getConnection();
    } catch (NamingException e) {
        LOGGER.error("", e);
    } catch (SQLException e) {
        LOGGER.error("", e);
    }
    return null;
}

From source file:azkaban.project.JdbcProjectLoaderTest.java

private static void clearDB() {
    if (!testDBExists) {
        return;/*from w  w  w.  j  av a 2s  .c  o  m*/
    }

    DataSource dataSource = DataSourceUtils.getMySQLDataSource(host, port, database, user, password,
            numConnections);
    Connection connection = null;
    try {
        connection = dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    QueryRunner runner = new QueryRunner();
    try {
        runner.update(connection, "DELETE FROM projects");

    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM project_events");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM project_permissions");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM project_files");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM project_flows");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM project_properties");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    DbUtils.closeQuietly(connection);
}

From source file:azkaban.project.JdbcProjectLoaderTest.java

@BeforeClass
public static void setupDB() {
    DataSource dataSource = DataSourceUtils.getMySQLDataSource(host, port, database, user, password,
            numConnections);//from   w w  w .j  av a2  s . co  m
    testDBExists = true;

    Connection connection = null;
    try {
        connection = dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    CountHandler countHandler = new CountHandler();
    QueryRunner runner = new QueryRunner();
    try {
        runner.query(connection, "SELECT COUNT(1) FROM projects", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.query(connection, "SELECT COUNT(1) FROM project_events", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.query(connection, "SELECT COUNT(1) FROM project_permissions", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.query(connection, "SELECT COUNT(1) FROM project_files", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.query(connection, "SELECT COUNT(1) FROM project_flows", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.query(connection, "SELECT COUNT(1) FROM project_properties", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    DbUtils.closeQuietly(connection);

    clearDB();
}

From source file:org.apache.ode.store.ProcessStoreImpl.java

public static void shutdownInternalDB(DataSource ds) {
    try {//w  w w. j a v a 2s  .c o m
        ds.getConnection().createStatement().execute("SHUTDOWN;");
    } catch (SQLException e) {
        __log.error("Error shutting down.", e);
    }
}

From source file:org.jamwiki.db.DatabaseConnection.java

/**
 * Return a connection to the database with the specified parameters.
 * The caller <b>must</b> close this connection when finished!
 *
 * @param driver A String indicating the full path for the database driver class.
 * @param url The JDBC driver URL.//ww  w .j  a  v a 2s.  co  m
 * @param user The database user.
 * @param password The database user password.
 * @throws SQLException Thrown if any failure occurs while getting the test connection.
 */
protected static Connection getTestConnection(String driver, String url, String user, String password)
        throws SQLException {
    if (url.startsWith("jdbc:")) {
        if (!StringUtils.isBlank(driver)) {
            try {
                // ensure that the Driver class has been loaded
                ResourceUtil.forName(driver);
            } catch (ClassNotFoundException e) {
                throw new SQLException("Unable to instantiate class with name: " + driver);
            }
        }
        return DriverManager.getConnection(url, user, password);
    } else {
        DataSource testDataSource = null;
        try {
            Context ctx = new InitialContext();
            // TODO: Try appending "java:comp/env/" to the JNDI Name if it is missing?
            testDataSource = (DataSource) ctx.lookup(url);
        } catch (NamingException e) {
            logger.error("Failure while configuring JNDI data source with URL: " + url, e);
            throw new SQLException(
                    "Unable to configure JNDI data source with URL " + url + ": " + e.toString());
        }
        return testDataSource.getConnection();
    }
}

From source file:FacultyAdvisement.StudentRepository.java

public static void create(DataSource ds, Student student) throws SQLException {
    String studentSQL = "INSERT INTO STUDENT(STUID, EMAIL, FIRSTNAME, LASTNAME, MAJORCODE, PHONE, ADVISED) "
            + "VALUES (?, ?, ?, ?, ?, ?, \'false\')";
    String userSQL = "INSERT INTO USERTABLE(PASSWORD, USERNAME, VERIFIED) VALUES (?, ?, ?)"; //haseeb was here

    String groupSQL = "INSERT INTO GROUPTABLE(GROUPNAME, USERNAME) VALUES (\'customergroup\', ?)";

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }/*from  w w  w. ja v  a2  s  .com*/

    Connection conn = ds.getConnection();

    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }

    try {

        //Here we execute three SQL statements
        //Student Information
        PreparedStatement sqlStatement = conn.prepareStatement(studentSQL);

        sqlStatement.setString(1, student.getId());
        sqlStatement.setString(2, student.getUsername());
        sqlStatement.setString(3, student.getFirstName());
        sqlStatement.setString(4, student.getLastName());
        sqlStatement.setString(5, student.getMajorCode());
        sqlStatement.setString(6, student.getPhoneNumber());

        sqlStatement.executeUpdate();

        //user credentials
        sqlStatement = conn.prepareStatement(userSQL);

        //Encrypt the pssword into SHA-256
        sqlStatement.setString(1, SHA256Encrypt.encrypt(student.getPassword()));

        sqlStatement.setString(2, student.getUsername());
        sqlStatement.setString(3, "false");
        sqlStatement.execute();

        //Group Table
        sqlStatement = conn.prepareStatement(groupSQL);
        sqlStatement.setString(1, student.getUsername());
        sqlStatement.execute();
    } finally {
        conn.close();
    }

}

From source file:com.flexive.core.Database.java

/**
 * Checks if the given data source is initialized by opening a connection.
 *
 * @param ds    the data source to be checked
 * @return      true if the query succeeded
 *///  w w  w  . j  a v a 2s . c o  m
private static boolean isDefaultDataSourceInitialized(DataSource ds) {
    Connection con = null;
    try {
        con = ds.getConnection();
        return true;
    } catch (SQLException e) {
        // probable cause: schema not initialized, since we're using an embedded database
        // there should be no connection problems
        return false;
    } finally {
        closeObjects(Database.class, con, null);
    }
}

From source file:com.flexive.core.Database.java

/**
 * Return a connection for initializing the embedded default database.
 *
 * @param c             the initial context for looking up the data source
 * @return              an open connection, or null if the data source was not found
 * @throws SQLException if the connection could not be created
 *//* ww w . ja  v  a 2  s .  co m*/
private static Connection getDefaultInitConnection(final Context c) throws SQLException {
    try {
        final DataSource initDs = (DataSource) c.lookup(GlobalConfigurationEngineBean.DEFAULT_DS_INIT);
        return initDs.getConnection();
    } catch (NamingException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Default configuration schema not initialized, but could not find "
                    + GlobalConfigurationEngineBean.DEFAULT_DS_INIT);
            // continue, the caller will get a related exception when creating a connection anyway
        }
        return null;
    }
}

From source file:org.cfr.capsicum.datasource.DataSourceUtils.java

/**
 * Actually obtain a JDBC Connection from the given DataSource.
 * Same as {@link #getConnection}, but throwing the original SQLException.
 * <p>Is aware of a corresponding Connection bound to the current thread, for example
 * when using {@link DataSourceTransactionManager}. Will bind a Connection to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param dataSource the DataSource to obtain Connections from
 * @return a JDBC Connection from the given DataSource
 * @throws SQLException if thrown by JDBC methods
 * @see #doReleaseConnection/*from   ww w .j  a va  2  s  .c  o m*/
 */
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
    Assert.notNull(dataSource, "No DataSource specified");

    CayenneConnectionHolder conHolder = (CayenneConnectionHolder) TransactionSynchronizationManager
            .getResource(dataSource);
    if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
        conHolder.requested();
        if (!conHolder.hasConnection()) {
            logger.debug("Fetching resumed JDBC Connection from DataSource");
            conHolder.setConnection(dataSource.getConnection());
        }
        return conHolder.getConnection();
    }
    // Else we either got no holder or an empty thread-bound holder here.

    logger.debug("Fetching JDBC Connection from DataSource");
    Connection con = dataSource.getConnection();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering transaction synchronization for JDBC Connection");
        // Use same Connection for further JDBC actions within the transaction.
        // Thread-bound object will get removed by synchronization at transaction completion.
        CayenneConnectionHolder holderToUse = conHolder;
        if (holderToUse == null) {
            ObjectContext context = BaseContext.getThreadObjectContext();
            holderToUse = new CayenneConnectionHolder(con, context);
        } else {
            holderToUse.setConnection(con);
        }
        holderToUse.requested();
        TransactionSynchronizationManager
                .registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != conHolder) {
            TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
        }
    }

    return con;
}

From source file:ece356.UserDBAO.java

public static Connection getConnection() throws ClassNotFoundException, SQLException, NamingException {
    InitialContext cxt = new InitialContext();
    if (cxt == null) {
        throw new RuntimeException("Unable to create naming context!");
    }//from w ww. j a v  a  2 s . c  om
    Context dbContext = (Context) cxt.lookup("java:comp/env");
    DataSource ds = (DataSource) dbContext.lookup("jdbc/myDatasource");
    if (ds == null) {
        throw new RuntimeException("Data source not found!");
    }
    Connection con = ds.getConnection();

    /*Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, user, pwd);*/
    Statement stmt = null;
    try {
        con.createStatement();
        stmt = con.createStatement();
        stmt.execute("USE ece356db_" + nid);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
    return con;
}