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:edu.mayo.cts2.uriresolver.dao.UriDAOJdbc.java

@Override
public int checkDataSource(DataSource ds) {
    Connection con = null;/*  w  ww.  j a va  2  s . c om*/
    int code = 0;
    try {
        con = ds.getConnection();
    } catch (SQLException e) {
        String msg = e.getMessage();
        logger.error("Error connecting to data source: " + msg + "\n");
        return code;
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                logger.error("Error while closing connection to data source: " + e.getMessage());
            }
        }
    }
    return code;
}

From source file:de.iritgo.aktario.jdbc.JDBCIDGenerator.java

/**
 * Allocate new ids./*from  w w w. ja  v a  2  s  . c om*/
 */
protected void allocateIds() {
    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("update IritgoProperties set value=? where name=?");
        stmt.setLong(1, id + chunk * step);
        stmt.setString(2, "persist.ids.nextvalue");
        stmt.execute();

        free = chunk;

        Log.logVerbose("persist", "JDBCIDGenerator", "Successfully allocated new ids (id=" + id + ")");
    } catch (Exception x) {
        Log.logFatal("persist", "JDBCIDGenerator", "Error while allocating new ids: " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:nl.b3p.catalog.kaartenbalie.KbJDBCHelper.java

protected Connection getConnection() throws NamingException, SQLException {
    Context initCtx = new InitialContext();
    DataSource ds = (DataSource) initCtx.lookup(root.getJndiDataSource());

    return ds.getConnection();
}

From source file:org.biblionum.authentification.modele.UtilisateurModele.java

/**
 * get utilisateur par le login//from  w  w  w. jav  a2s.  com
 */
public Utilisateur getUtilisateurConnecter(DataSource ds, String pseudo, String pwd) {
    Utilisateur u = null;
    ArrayList<Utilisateur> list = new ArrayList<Utilisateur>();

    try {
        con = ds.getConnection();
        stm = con.prepareStatement("SELECT * FROM utilisateur WHERE pseudo=? AND password=?");
        stm.setString(1, pseudo);//type user prof 1
        stm.setString(2, pwd);
        rs = stm.executeQuery();

        BeanProcessor bp = new BeanProcessor();
        list = (ArrayList) bp.toBeanList(rs, Utilisateur.class);
        System.out.println("taille list utilisateur modele " + list.size());
        if (list.size() > 0) {
            u = list.get(0);
        }
        con.close();
        rs.close();

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

    return u;
}

From source file:com.p6spy.engine.spy.DataSourceTest.java

@Test
public void testGenericDataSourceWithOutDriverManager() throws Exception {
    // Create and bind the real data source
    // Note: This will get the driver from the DriverManager
    realDs = new TestBasicDataSource();
    realDs.setDriverClassName(driverClass);
    realDs.setUrl(url);/* ww  w. j av  a 2s  . c o  m*/
    realDs.setUsername(user);
    realDs.setPassword(password);
    realDs.setUseDriverManager(false);
    realDsResource = new Resource("jdbc/realDs", realDs);

    P6TestUtil.setupTestData(realDs);

    // get the data source from JNDI
    DataSource ds = new JndiDataSourceLookup().getDataSource("jdbc/spyDs");
    assertNotNull("JNDI data source not found", ds);

    // get the connection
    con = ds.getConnection();

    // verify that the connection class is a proxy
    assertTrue("Connection is not a proxy", ProxyFactory.isProxy(con));

}

From source file:com.p6spy.engine.spy.DataSourceTest.java

@Test
public void testGenericDataSourceWithDriverManager() throws Exception {
    // Create and bind the real data source
    // Note: This will get the driver from the DriverManager
    realDs = new TestBasicDataSource();
    realDs.setDriverClassName(driverClass);
    realDs.setUrl(url);/* w  ww . j a  v  a 2s .c o  m*/
    realDs.setUsername(user);
    realDs.setPassword(password);
    realDs.setUseDriverManager(true);
    realDsResource = new Resource("jdbc/realDs", realDs);

    P6TestUtil.setupTestData(realDs);

    // get the data source from JNDI
    DataSource ds = new JndiDataSourceLookup().getDataSource("jdbc/spyDs");
    assertNotNull("JNDI data source not found", ds);

    // get the connection
    con = ds.getConnection();

    // verify that the connection class is a proxy
    assertTrue("Connection is not a proxy", ProxyFactory.isProxy(con));

    Statement stmt = con.createStatement();
    stmt.execute("select 1 from customers");
    stmt.close();
    assertTrue(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry().indexOf("select 1") != -1);
    assertEquals("Incorrect number of spy log messages", 1,
            ((P6TestLogger) P6LogQuery.getLogger()).getLogs().size());
}

From source file:com.p6spy.engine.spy.MultipleDataSourceTest.java

@Test
public void testSpyEnabledDataSource() throws SQLException {
    DataSource spyDs1 = new JndiDataSourceLookup().getDataSource("jdbc/spyDs1");

    // The spy data sources should be spy enabled
    validateSpyEnabled(spyDs1);//from   w  w  w . j ava  2 s .  c  om
    // verify that the correct database driver was used
    assertTrue(spyDs1.getConnection().getMetaData().getDatabaseProductName().contains("H2"));

    DataSource spyDs3 = new JndiDataSourceLookup().getDataSource("jdbc/spyDs3");
    // The spy data sources should be spy enabled
    validateSpyEnabled(spyDs3);
    // verify that the correct database driver was used
    assertTrue(spyDs3.getConnection().getMetaData().getDatabaseProductName().contains("HSQL"));
}

From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java

/**
 * Initialize./*w  ww  .  j  ava2s .c  om*/
 *
 * @param context
 *            the context
 * @param dataSource
 *            the data source
 * @throws DatabaseUnitException
 *             the database unit exception
 * @throws SQLException
 *             the SQL exception
 * @throws MalformedURLException
 *             the malformed url exception
 */
public void initializeGlobalDataFile(ApplicationContext context)
        throws DatabaseUnitException, SQLException, MalformedURLException {
    DataSource datas = GlobalUtils.findDataSourceBean(context);
    IDatabaseConnection con = new DatabaseConnection(datas.getConnection()); // Create
    // DBUnit
    // Database
    // connection
    FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
    builder.setColumnSensing(true);

    datasets = new IDataSet[] { builder.build(singleInitXmlFile) };
    DatabaseOperation.REFRESH.execute(con, new CompositeDataSet(datasets)); // Import
    // your
    // data

    // TODO handle the empty data file case.
    con.close();

}

From source file:com.zionex.t3sinc.util.db.SincDatabaseUtility.java

public Connection getConnection(String datasource) throws SQLException {
    Connection connection = null;
    DataSource datasourceObject = (new DatabaseSetterImpl()).setupDataSource(datasource).getDatasource();
    if (datasourceObject != null) {
        connection = datasourceObject.getConnection();
    }/*from ww w.  ja  v a2s.  com*/
    return connection;
}

From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java

/**
 * Initialize./*from   ww w  .  j ava 2 s  .  c o m*/
 *
 * @param beanFac
 *            the bean factory
 * @throws DatabaseUnitException
 *             the database unit exception
 * @throws SQLException
 *             the SQL exception
 * @throws MalformedURLException
 *             the malformed url exception
 */
public void initialize(BeanFactory beanFac) throws DatabaseUnitException, SQLException, MalformedURLException {
    if (!getInitXmlFiles().isEmpty()) {
        DataSource datas = GlobalUtils.findDataSourceBean(beanFac);
        IDatabaseConnection con = new DatabaseConnection(datas.getConnection()); // Create
        // DBUnit
        // Database
        // connection
        FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
        builder.setColumnSensing(true);

        DatabaseOperation.CLEAN_INSERT.execute(con, builder.build(combineInitXmlFiles())); // Import your data
        // datasets = new IDataSet[getInitXmlFiles().size()];
        // for (int i = 0; i < getInitXmlFiles().size(); i++) {
        // datasets[i] = builder.build(getInitXmlFiles().get(i));
        // }
        // DatabaseOperation.CLEAN_INSERT.execute(con, new CompositeDataSet(
        // datasets, false)); // Import your data

        // TODO handle the empty data file case.
        con.close();
    }

}