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:FacultyAdvisement.StudentRepository.java

public static Student readById(DataSource ds, String key) throws SQLException {
    String studentSQL = "SElECT * FROM STUDENT WHERE STUID = ?";
    Student student = new Student();

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }/*ww w .  j  a  va  2  s  . c o  m*/

    Connection conn = ds.getConnection();

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

    try {

        PreparedStatement sqlStatement = conn.prepareStatement(studentSQL);

        sqlStatement.setString(1, key);

        ResultSet result = sqlStatement.executeQuery();
        while (result.next()) {
            student.setId(key);
            student.setFirstName(result.getString("firstname"));
            student.setLastName(result.getString("lastname"));
            student.setMajorCode(result.getString("majorcode"));
            student.setPhoneNumber(result.getString("phone"));
            student.setUsername(result.getString("email"));

        }

    } finally {
        conn.close();
    }

    return student;
}

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Gets the db connection./*from  w ww  .j  a  v  a  2 s  .com*/
 *
 * @return the db connection
 * @throws SQLException
 *             the SQL exception
 */
public static synchronized Connection getDbConnection(DataSourceNames dataSourceName) throws Exception {

    try {
        if (!dbDataSourceMap.containsKey(dataSourceName)) {

            Context ctx = new InitialContext();
            dbDataSourceMap.put(dataSourceName, (DataSource) ctx.lookup(dataSourceName.jndiName()));
        }

        DataSource dbDatasource = dbDataSourceMap.get(dataSourceName);

        if (dbDatasource != null) {

            log.info(dataSourceName.toString() + " DB Initialize successfully.");
            return dbDatasource.getConnection();
        } else {

            log.info(dataSourceName.toString() + " DB NOT Initialize successfully.");
            return null;
        }
    } catch (Exception e) {

        log.info("Error while looking up the data source: " + dataSourceName.toString(), e);
        throw e;
    }
}

From source file:org.apache.synapse.commons.transaction.TranscationManger.java

public static Connection addConnection(final DataSource ds) throws Exception {
    long key = Thread.currentThread().getId();
    Connection conn = getConnection();
    if (conn != null) {
        log.debug(" Connection can get from map : " + key);
        return conn;
    }/*from  w  w w . j ava  2  s  . co m*/

    int count = 0;
    do {
        conn = ds.getConnection();
        Connection actual = ((javax.sql.PooledConnection) conn).getConnection();
        if (conn == null || actual == null) {
            continue;
        }
        if (!TranscationManger.checkConnectionAlreadyUse(conn) && !actual.isClosed()) {
            if (!connections.containsKey(key)) {
                connections.putIfAbsent(key, new ConnectionMapper(conn));
                log.debug(" Connection added to map in attempt : " + count + " Thread : " + key);
            }
            break;
        } else {
            conn.close();
            conn = null;
            Thread.sleep(500l);
            continue;
        }
    } while (++count < 5);

    if (conn == null && count >= 5) {
        throw new Exception(" Not enough Connections in the pool, Cache size : " + connections.size());
    }
    return conn;

}

From source file:FacultyAdvisement.StudentRepository.java

public static void update(DataSource ds, Student student) throws SQLException {
    String studentSQL = "UPDATE STUDENT SET STUID = ?, FIRSTNAME = ?, LASTNAME = ?, MAJORCODE = ?, PHONE = ? WHERE EMAIL = ?";

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }/*from   w ww.  j  a v a2  s .c o m*/

    Connection conn = ds.getConnection();

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

    try {
        //Student Information
        PreparedStatement sqlStatement = conn.prepareStatement(studentSQL);
        sqlStatement.setString(1, student.getId());
        sqlStatement.setString(2, student.getFirstName());
        sqlStatement.setString(3, student.getLastName());
        sqlStatement.setString(4, student.getMajorCode());
        sqlStatement.setString(5, student.getPhoneNumber());
        sqlStatement.setString(6, student.getUsername());

        sqlStatement.executeUpdate();

    } finally {
        conn.close();
    }
}

From source file:FacultyAdvisement.StudentRepository.java

public static Student read(DataSource ds, String key) throws SQLException {
    String studentSQL = "SElECT * FROM STUDENT JOIN USERTABLE on EMAIL = USERNAME WHERE EMAIL = ?";
    Student student = new Student();

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }//  w w w.  jav  a 2 s.c om

    Connection conn = ds.getConnection();

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

    try {

        PreparedStatement sqlStatement = conn.prepareStatement(studentSQL);

        sqlStatement.setString(1, key);

        ResultSet result = sqlStatement.executeQuery();
        while (result.next()) {
            student.setId(result.getString("STUID"));
            student.setFirstName(result.getString("firstname"));
            student.setLastName(result.getString("lastname"));
            student.setMajorCode(result.getString("majorcode"));
            student.setPhoneNumber(result.getString("phone"));
            student.setUsername(key);
            student.setPassword(result.getString("password"));
        }

    } finally {
        conn.close();
    }

    return student;
}

From source file:com.tern.db.db.java

public static Database establish(DataSource ds, String name) throws SQLException {
    if (name == null || name.length() <= 0) {
        name = "default";
    }/*from w  w w . ja va2 s.co m*/
    if (Database.dbs.containsKey(name)) {
        throw new SQLException("Has duplicate database name:" + name);
    }

    Connection con = null;
    String driverName = null;
    try {
        con = ds.getConnection();
        java.sql.DatabaseMetaData meta = con.getMetaData();
        driverName = meta.getDriverName();
    } catch (SQLException e) {
        Trace.write(Trace.Error, e, "Create database from DataSource");
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (java.sql.SQLException ex1) {
            }
        }
    }

    if (driverName == null) {
        return null;
    }

    Database d = null;

    if (driverName.indexOf("Oracle") >= 0) {
        d = new OracleDB();
    } else if (driverName.indexOf("mysql") >= 0) {
        d = new MySqlDB();
    } else {
        throw new SQLException("Unknown database driver:" + driverName);
    }

    d.ds = ds;

    if (Database.db == null) {
        Database.db = d;
    }

    Database.dbs.put(name, d);
    Trace.write(Trace.Running, "database added,name = %s,driver=%s", name, driverName);

    return d;
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static String buildDataBaseVersion() {
    if (Parameters.isNoDatabase()) {
        return null;
    }//from   w  w w . j  av  a  2  s .c  om
    final StringBuilder result = new StringBuilder();
    try {
        // on commence par voir si le driver jdbc a t utilis
        // car s'il n'y a pas de datasource une exception est dclenche
        if (Parameters.getLastConnectUrl() != null) {
            final Connection connection = DriverManager.getConnection(Parameters.getLastConnectUrl(),
                    Parameters.getLastConnectInfo());
            connection.setAutoCommit(false);
            try {
                appendDataBaseVersion(result, connection);
            } finally {
                // rollback inutile ici car on ne fait que lire les meta-data (+ cf issue 38)
                connection.close();
            }
        }

        // on cherche une datasource avec InitialContext pour afficher nom et version bdd + nom et version driver jdbc
        // (le nom de la dataSource recherche dans JNDI est du genre jdbc/Xxx qui est le nom standard d'une DataSource)
        final Map<String, DataSource> dataSources = JdbcWrapper.getJndiAndSpringDataSources();
        for (final Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
            final String name = entry.getKey();
            final DataSource dataSource = entry.getValue();
            final Connection connection = dataSource.getConnection();
            // on ne doit pas changer autoCommit pour la connection d'une DataSource
            // (ou alors il faudrait remettre l'autoCommit aprs, issue 233)
            // connection.setAutoCommit(false);
            try {
                if (result.length() > 0) {
                    result.append("\n\n");
                }
                result.append(name).append(":\n");
                appendDataBaseVersion(result, connection);
            } finally {
                // rollback inutile ici car on ne fait que lire les meta-data (+ cf issue 38)
                connection.close();
            }
        }
    } catch (final Exception e) {
        result.append(e.toString());
    }
    if (result.length() > 0) {
        return result.toString();
    }
    return null;
}

From source file:com.dangdang.ddframe.rdb.sharding.example.transaction.Main.java

private static void updateFailure(final DataSource dataSource) throws SQLException {
    String sql1 = "UPDATE t_order SET status='UPDATE_1' WHERE user_id=10 AND order_id=1000";
    String sql2 = "UPDATE t_order SET not_existed_column=1 WHERE user_id=1 AND order_id=?";
    String sql3 = "UPDATE t_order SET status='UPDATE_2' WHERE user_id=10 AND order_id=1000";
    SoftTransactionManager transactionManager = new SoftTransactionManager(
            getSoftTransactionConfiguration(dataSource));
    transactionManager.init();/*from  w w w  .ja v a  2  s.c  om*/
    BEDSoftTransaction transaction = (BEDSoftTransaction) transactionManager
            .getTransaction(SoftTransactionType.BestEffortsDelivery);
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        transaction.begin(conn);
        PreparedStatement preparedStatement1 = conn.prepareStatement(sql1);
        PreparedStatement preparedStatement2 = conn.prepareStatement(sql2);
        preparedStatement2.setObject(1, 1000);
        PreparedStatement preparedStatement3 = conn.prepareStatement(sql3);
        preparedStatement1.executeUpdate();
        preparedStatement2.executeUpdate();
        preparedStatement3.executeUpdate();
    } finally {
        transaction.end();
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:org.hengdao.utils.SqlSessionUtils.java

/**
 * If a Spring transaction is active it uses {@code DataSourceUtils} to get
 * a Spring managed {@code Connection}, then creates a new
 * {@code SqlSession} with this connection and synchronizes it with the
 * transaction. If there is not an active transaction it gets a connection
 * directly from the {@code DataSource} and creates a {@code SqlSession}
 * with it.//from www.  ja  v a  2 s .  c  om
 *
 * @param sessionFactory
 *            a MyBatis {@code SqlSessionFactory} to create new sessions
 * @param executorType
 *            The executor type of the SqlSession to create
 * @param exceptionTranslator
 *            Optional. Translates SqlSession.commit() exceptions to Spring
 *            exceptions.
 * @throws TransientDataAccessResourceException
 *             if a transaction is active and the {@code SqlSessionFactory}
 *             is not using a {@code SpringManagedTransactionFactory}
 * @see SpringManagedTransactionFactory
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

    Assert.notNull(sessionFactory, "No SqlSessionFactory specified");
    Assert.notNull(executorType, "No ExecutorType specified");

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);

    if (holder != null && holder.isSynchronizedWithTransaction()) {
        if (holder.getExecutorType() != executorType) {
            throw new TransientDataAccessResourceException(
                    "Cannot change the ExecutorType when there is an existing transaction");
        }

        holder.requested();

        if (logger.isDebugEnabled()) {
            logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
        }

        return holder.getSqlSession();
    }

    DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource();

    // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but
    // we keep this check for the case that SqlSessionUtils is called from
    // custom code
    boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
    Connection conn;
    try {
        conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource);
    } catch (SQLException e) {
        throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]");
    }

    // Assume either DataSourceTransactionManager or the underlying
    // connection pool already dealt with enabling auto commit.
    // This may not be a good assumption, but the overhead of checking
    // connection.getAutoCommit() again may be expensive (?) in some drivers
    // (see DataSourceTransactionManager.doBegin()). One option would be to
    // only check for auto commit if this function is being called outside
    // of DSTxMgr, but to do that we would need to be able to call
    // ConnectionHolder.isTransactionActive(), which is protected and not
    // visible to this class.
    SqlSession session = sessionFactory.openSession(executorType, conn);

    // Register session holder and bind it to enable synchronization.
    //
    // Note: The DataSource should be synchronized with the transaction
    // either through DataSourceTxMgr or another tx synchronization.
    // Further assume that if an exception is thrown, whatever started the
    // transaction will
    // handle closing / rolling back the Connection associated with the
    // SqlSession.
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        if (!(sessionFactory.getConfiguration().getEnvironment()
                .getTransactionFactory() instanceof SpringManagedTransactionFactory)
                && DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
            throw new TransientDataAccessResourceException(
                    "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
        }
        holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
        TransactionSynchronizationManager.bindResource(sessionFactory, holder);
        TransactionSynchronizationManager
                .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
        holder.setSynchronizedWithTransaction(true);
        holder.requested();
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }

    return session;
}

From source file:com.flexive.core.security.FxDBAuthentication.java

/**
 * @param username the username/*from   w  w  w  . j  a v a 2s  . c  o  m*/
 * @param password the password
 * @param currentTicket the UserTicket requesting the password match
 * @param ds thedatasource
 * @return returns true if the login and password match
 * @throws FxDbException on db errors
 * @throws FxLoginFailedException on authentication errors
 */
public static boolean checkLogin(String username, String password, UserTicket currentTicket, DataSource ds)
        throws FxDbException, FxLoginFailedException {
    FxContext inf = FxContext.get();

    // Avoid null pointer exceptions
    if (password == null)
        password = "";
    if (username == null)
        username = "";

    String curSql;
    PreparedStatement ps = null;
    Connection con = null;
    try {
        // Obtain a database connection
        con = ds.getConnection();
        //               1      2           3
        curSql = "SELECT a.ID,a.USERNAME,a.PASSWORD " + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN "
                + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM "
                + TBL_ACCOUNT_DETAILS
                + " WHERE APPLICATION=?) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)";
        ps = con.prepareStatement(curSql);
        ps.setString(1, inf.getApplicationId());
        ps.setString(2, username);
        final ResultSet rs = ps.executeQuery();

        // Anything found
        if (rs == null || !rs.next())
            throw new FxLoginFailedException("Invalid user or password",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);

        // check if the hashed password matches the hash stored in the database
        final long id = rs.getLong(1);
        final String dbUserName = rs.getString(2);
        final String hashedPass = rs.getString(3);

        // current user authorised to perform the check (ticket user id matches db user id?)
        if (id != currentTicket.getUserId() && !currentTicket.isGlobalSupervisor())
            throw new FxLoginFailedException("User not authorized to perform login check",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);

        return FxSharedUtils.hashPassword(id, dbUserName, password).equals(hashedPass)
                // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name
                || ("SUPERVISOR".equals(username)
                        && FxSharedUtils.hashPassword(id, "supervisor", password).equals(hashedPass));

    } catch (SQLException exc) {
        throw new FxDbException("Database error: " + exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR);
    } finally {
        Database.closeObjects(FxDBAuthentication.class, con, ps);
    }
}