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:org.reusables.dbunit.handler.DataSourceOperationHandler.java

/**
 * @param task The task to handle./*from ww w . j  a  v  a  2  s  .c  o m*/
 * @return False if the {@link DataSource} bean was not present.
 */
@Override
public boolean handleOperation(final JdbcTask task) {
    final DataSource dataSource = getDataSource();

    if (dataSource != null) {
        Connection connection = null;

        try {
            connection = dataSource.getConnection();
            task.execute(connection);
            connection.close();
            return true;
        } catch (final SQLException e) {
            throw new RuntimeException("Error executing JDBC task.", e);
        } finally {
            JdbcUtils.closeConnection(connection);
        }
    }
    return false;
}

From source file:Controllers.myAppointmentController.java

public Appointment[] fetchAppointments(java.sql.Date date) {

    Appointment[] Appoint = null;/*w  w  w .j  ava2 s . c  o m*/

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        PreparedStatement pstmt = connection
                .prepareStatement("SELECT appointments.message," + "FROM appointments JOIN accounts\n"
                        + "WHERE appointments.date = ? and email=${sessionScope.user};");

        pstmt.setDate(1, date);

        ResultSet resultSet = pstmt.executeQuery();

        List<Appointment> appointmentsList = new ArrayList<Appointment>();
        while (resultSet.next()) {
            Appointment appoint = new Appointment();
            appoint.setAppointmentId(resultSet.getInt("appointmentId"));
            appoint.setMessage(resultSet.getString("message"));
            appoint.setDepartmentId(resultSet.getInt("depoartmentId"));

            appointmentsList.add(appoint);
        }

        Appoint = new Appointment[appointmentsList.size()];
        Appoint = appointmentsList.toArray(Appoint);

        pstmt.close();

    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Appoint;
}

From source file:org.biblionum.ouvrage.modele.OuvrageTypeModele.java

/**
 * Java method that updates a row in the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param designation_typeou/*from  www .j  a  va  2  s.  com*/
 * @return boolean (true on success)
 * @throws SQLException
 */
public boolean updateOuvragetype(DataSource ds, int keyId, String designation_typeou) throws SQLException {
    con = ds.getConnection();
    String sql = "SELECT * FROM ouvragetype WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (designation_typeou != null) {
        entry.updateString("designation_typeou", designation_typeou);
    }

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:com.thinkbiganalytics.server.KyloUpgradeDatabaseVersionChecker.java

/**
 * Query the Database for the Kylo Version
 *
 * @return the KyloVersion from the database, or null if not found or if an error occurs
 */// ww w. j  a v a2  s. c  o  m
public KyloVersion getDatabaseVersion() {
    KyloVersion version = null;
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String user = environmentProperties.getPropertyValueAsString("spring.datasource.username");
        String password = environmentProperties.getPropertyValueAsString("spring.datasource.password");
        password = encryptionService.isEncrypted(password) ? encryptionService.decrypt(password) : password;
        String uri = environmentProperties.getPropertyValueAsString("spring.datasource.url");
        String driverClassName = environmentProperties
                .getPropertyValueAsString("spring.datasource.driverClassName");
        boolean testOnBorrow = BooleanUtils
                .toBoolean(environmentProperties.getPropertyValueAsString("spring.datasource.testOnBorrow"));
        String validationQuery = environmentProperties.getPropertyValueAsString("spring.data.validationQuery");

        PoolingDataSourceService.DataSourceProperties dataSourceProperties = new PoolingDataSourceService.DataSourceProperties(
                user, password, uri, driverClassName, testOnBorrow, validationQuery);

        DataSource dataSource = PoolingDataSourceService.getDataSource(dataSourceProperties);

        connection = dataSource.getConnection();
        String query = "SELECT MAJOR_VERSION,MINOR_VERSION FROM kylo.KYLO_VERSION ";
        statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        if (rs.next()) {
            String majorVersion = rs.getString("MAJOR_VERSION");
            String minorVersion = rs.getString("MINOR_VERSION");
            version = new KyloVersionUtil.Version(majorVersion, minorVersion);
        }

    } catch (SQLException e) {
        // this is ok.. If an error happens assume the upgrade is needed.  The method will return a null value if errors occur and the upgrade app will start.
    } finally {
        JdbcUtils.closeStatement(statement);
        JdbcUtils.closeResultSet(resultSet);
        JdbcUtils.closeConnection(connection);
    }
    return version;

}

From source file:org.seedstack.spring.SeedFactoryBeanIT.java

@Test
public void datasource_injection_is_working() throws Exception {
    DataSource ds = ((DummyService) context.getBean("service4")).getDataSource();
    Assertions.assertThat(ds).isNotNull();
    Assertions.assertThat(ds.getConnection()).isNotNull();
}

From source file:net.bull.javamelody.SpringTestFacadeImpl.java

/**
 * {@inheritDoc}/*w ww .  j  a  v  a  2s. c o  m*/
 */
@Override
public Date nowWithSql() throws SQLException {
    //      final javax.sql.DataSource dataSource = (javax.sql.DataSource) new javax.naming.InitialContext()
    //            .lookup("java:comp/env/jdbc/TestDB");
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "net/bull/javamelody/monitoring-spring.xml", "spring-context.xml", });
    final javax.sql.DataSource dataSource = (javax.sql.DataSource) context.getBean("dataSource");
    final java.sql.Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);
    try {
        // test pour explain plan en oracle
        //         final PreparedStatement statement = connection
        //               .prepareStatement("select * from v$session where user# = ?");
        final Statement statement = connection.createStatement();
        try {
            //            statement.setInt(1, 36);
            //            statement.executeQuery();

            statement.execute(
                    "DROP ALIAS if exists SLEEP; CREATE ALIAS SLEEP FOR \"java.lang.Thread.sleep(long)\"");
            statement.execute("call sleep(.01)");
            for (int i = 0; i < 5; i++) {
                statement.execute("call sleep(.02)");
            }
        } finally {
            statement.close();
        }
    } finally {
        connection.rollback();
        connection.close();
    }

    return new Date();
}

From source file:com.gs.obevo.db.impl.platforms.mssql.MsSqlDeployerMainIT.java

private void validateStep1(DataSource ds, PhysicalSchema physicalSchema, JdbcHelper jdbc) throws Exception {
    List<Map<String, Object>> results;
    Connection conn = ds.getConnection();
    try {//  w  ww . j  a v a 2 s .  co m
        results = jdbc.queryForList(conn,
                "select * from " + physicalSchema.getPhysicalName() + "..TestTable order by idField");
    } finally {
        DbUtils.closeQuietly(conn);
    }

    assertEquals(4, results.size());
    this.validateResultRow(results.get(0), 1, "str1", 0);
    this.validateResultRow(results.get(1), 2, "str2", 0);
    this.validateResultRow(results.get(2), 3, "str3", 0);
    this.validateResultRow(results.get(3), 4, "str4", 0);
}

From source file:com.jaspersoft.jasperserver.remote.dbservices.impl.JndiConnectionServiceImpl.java

/**
 *
 * @param resource//from   ww w .j a  va  2 s  .  com
 * @return Connection object, guaranteed to be non-null (not found or not supported resource indicated by exception)
 * @throws ResourceNotFoundException if no resource found 
 * @throws RemoteException in case of unclassified error
 */
@SuppressWarnings("unused")
public Connection getConnection(Resource resource) {
    Connection result = null;
    String DATASOURCE_CONTEXT = null;
    long startTime = System.currentTimeMillis();
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Enter getConnection .. Start Time" + System.currentTimeMillis());
        }
        if (resource instanceof JndiJdbcReportDataSource) {
            JndiJdbcReportDataSource jndiDataSource = (JndiJdbcReportDataSource) resource;
            DATASOURCE_CONTEXT = "java:comp/env/" + jndiDataSource.getJndiName();
            Context initialContext = new InitialContext();
            if (initialContext != null) {
                DataSource datasource = (DataSource) initialContext.lookup(DATASOURCE_CONTEXT);
                if (datasource != null) {
                    result = datasource.getConnection();
                } else {
                    throw new RemoteException("Cannot get database connection: Please check datasource url");
                }
            } else {
                throw new RemoteException("Cannot get jndi context: Please check datasource url");
            }

        } else {
            throw new RemoteException("Invalid Resource: Please check datasource url");
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new RemoteException("Cannot get jndi connection:" + ex.getMessage());
    } finally {
        if (logger.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Exit getConnection .. Total Time Spent: " + elapsedTime);
        }
    }
    return result;

}

From source file:com.gs.obevo.db.impl.platforms.mssql.MsSqlDeployerMainIT.java

private void validateStep2(DataSource ds, PhysicalSchema physicalSchema, JdbcHelper jdbc) throws Exception {
    List<Map<String, Object>> results;
    Connection conn = ds.getConnection();
    try {//ww  w .  j a v  a  2 s  .c  o m
        results = jdbc.queryForList(conn,
                "select * from " + physicalSchema.getPhysicalName() + "..TestTable order by idField");
    } finally {
        DbUtils.closeQuietly(conn);
    }

    assertEquals(5, results.size());
    this.validateResultRow(results.get(0), 1, "str1", 0);
    this.validateResultRow(results.get(1), 3, "str3Changed", 0);
    this.validateResultRow(results.get(2), 4, "str4", 0);
    this.validateResultRow(results.get(3), 5, "str5", 0);
    this.validateResultRow(results.get(4), 6, "str6", 0);
}

From source file:opa.DatabaseResourceBundle.java

/**
 * Return a database connection. null if one cannot be achieved.
 * // w  w  w. j  ava  2  s  .  com
 * @return
 */
private Connection createConnection() {
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jndiJdbc);
        return ds.getConnection();
    } catch (NamingException e) {
        log.error("java:comp/env/" + jndiJdbc + " not found!", e);
    } catch (SQLException e) {
        log.error(e, e);
    }

    return null;
}