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.dashbuilder.dataprovider.backend.sql.SQLDataSetTestBase.java

@Before
public void setUp() throws Exception {

    // Register the SQL data set
    URL fileURL = Thread.currentThread().getContextClassLoader().getResource("expenseReports.dset");
    String json = IOUtils.toString(fileURL);
    SQLDataSetDef def = (SQLDataSetDef) jsonMarshaller.fromJson(json);
    dataSetDefRegistry.registerDataSetDef(def);

    // Get a data source connection
    DataSource dataSource = dataSourceLocator.lookup(def);
    conn = dataSource.getConnection();

    // Create the expense reports table
    using(conn).execute(CREATE_TABLE);//w ww  . j ava  2 s.c o m

    // Populate the table
    populateDbTable();
}

From source file:net.fender.sql.LoadBalancingDataSource.java

@Override
protected ManagedConnection getManagedConnection() throws SQLException {
    ManagedConnection managedConnection = null;
    SQLException exceptionToThrow = new SQLException();
    int tries = 0;
    while (managedConnection == null && tries <= timesToRetry) {
        DataSource dataSource = getNextDataSource();
        try {//from  ww w  .ja  v  a2s.com
            Connection connection = dataSource.getConnection();
            managedConnection = new ManagedConnection(connection, this);
            if (validateConnectionOnAquire) {
                validateConnection(managedConnection);
            }
        } catch (SQLException e) {
            log.warn("connection failure " + e.getMessage());
            exceptionToThrow.setNextException(e);
            tries++;
        }
    }
    if (managedConnection == null) {
        throw exceptionToThrow;
    }
    return managedConnection;
}

From source file:SeeAccount.java

public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse)
        throws ServletException, IOException {

    PrintWriter out = null;/*from  ww w .jav a2 s.c om*/
    Connection connection = null;
    Statement statement = null;

    ResultSet rs;

    try {
        outResponse.setContentType("text/html");
        out = outResponse.getWriter();

        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        statement = connection.createStatement();
        rs = statement.executeQuery("SELECT * FROM acc_acc");
        ResultSetMetaData md = rs.getMetaData();

        out.println("<HTML><HEAD><TITLE>        Thumbnail Identification Record</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("Account Information:<BR>");
        out.println("<table>");
        out.println("<tr><td>");
        for (int i = 1; i <= md.getColumnCount(); i++) {
            out.println("Column #" + i + "<BR>");
            out.println("getColumnName : " + md.getColumnName(i) + "<BR>");
            out.println("getColumnClassName : " + md.getColumnClassName(i) + "<BR>");
            out.println("getColumnDisplaySize : " + md.getColumnDisplaySize(i) + "<BR>");
            out.println("getColumnType : " + md.getColumnType(i) + "<BR>");
            out.println("getTableName : " + md.getTableName(i) + "<BR>");
            out.println("<HR>");
        }
        out.println("</BODY></HTML>");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:mvc.dao.TarefaDAO.java

@Autowired
public TarefaDAO(DataSource dataSource) {
    try {/*from w ww  . j  a v  a2  s  . c o m*/
        this.connection = dataSource.getConnection();
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

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

/**
 * Java method that deletes a row from the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param keyId (the primary key to the row)
 * @throws SQLException//w  ww .j a v a2 s  . c  o m
 */
public void deleteFromOuvragetype(DataSource ds, int keyId) throws SQLException {
    con = ds.getConnection();
    String sql = "DELETE FROM ouvragetype WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql);
    statement.setInt(1, keyId);
    statement.executeUpdate();
    statement.close();
    con.close();
}

From source file:net.certifi.audittablegen.HsqldbDMRTest.java

@Test
public void testGetRunTimeDataSource_0args() throws SQLException {
    logger.error("****************************************************");
    DataSource ds = HsqldbDMR.getRunTimeDataSource();
    assertThat(ds.getConnection().getSchema()).isEqualTo("PUBLIC");
    logger.trace("Got connection to schema: {}", ds.getConnection().getSchema());
}

From source file:azkaban.executor.JdbcExecutorLoaderTest.java

@BeforeClass
public static void setupDB() {
    DataSource dataSource = DataSourceUtils.getMySQLDataSource(host, port, database, user, password,
            numConnections);/*from   w  w  w  .  j a  v a  2  s . c o 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 active_executing_flows", countHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

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

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

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

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

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

    DbUtils.closeQuietly(connection);
}

From source file:org.jasig.portlet.announcements.SchemaCreator.java

private int create() {

    /*/*  ww  w  . j ava2  s  .c  o  m*/
     * We will need to provide a Configuration and a Connection;  both should be properly
     * managed by the Spring ApplicationContext.
     */

    final LocalSessionFactoryBean sessionFactoryBean = applicationContext.getBean(SESSION_FACTORY_BEAN_NAME,
            LocalSessionFactoryBean.class);
    final DataSource dataSource = applicationContext.getBean(DATA_SOURCE_BEAN_NAME, DataSource.class);

    try (final Connection conn = dataSource.getConnection()) {
        final Configuration cfg = sessionFactoryBean.getConfiguration();
        final SchemaExport schemaExport = new SchemaExport(cfg, conn);
        schemaExport.execute(true, true, false, false);

        final List<Exception> exceptions = schemaExport.getExceptions();
        if (exceptions.size() != 0) {
            logger.error("Schema Create Failed;  see below for details");
            for (Exception e : exceptions) {
                logger.error("Exception from Hibernate Tools SchemaExport", e);
            }
            return 1;
        }
    } catch (SQLException sqle) {
        logger.error("Failed to initialize & invoke the SchemaExport tool", sqle);
        return 1;
    }

    return 0;

}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JndiJdbcDataSourceService.java

protected Connection createConnection() {

    try {/*from   w w  w  .jav  a2  s  . c o m*/
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jndiName);
        Connection c = ds.getConnection();
        if (log.isDebugEnabled()) {
            log.debug(
                    "CreateConnection successful at com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JndiJdbcDataSourceService.createConnection");
        }
        return c;
    } catch (NamingException e) {
        try {
            //Added as short time solution due of http://bugzilla.jaspersoft.com/show_bug.cgi?id=26570.
            //The main problem - this code executes in separate tread (non http).
            //Jboss 7 support team recommend that you use the non-component environment namespace for such situations.
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            Connection c = ds.getConnection();
            if (log.isDebugEnabled()) {
                log.debug(
                        "CreateConnection successful at com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JndiJdbcDataSourceService.createConnection");
            }
            return c;

        } catch (NamingException ex) {
            if (log.isDebugEnabled())
                log.debug(e, e);
            throw new JSExceptionWrapper(e);
        } catch (SQLException ex) {
            if (log.isDebugEnabled())
                log.debug(e, e);
            throw new JSExceptionWrapper(e);
        }

    } catch (SQLException e) {
        if (log.isDebugEnabled())
            log.debug(e, e);
        throw new JSExceptionWrapper(e);
    }
}

From source file:org.apache.sling.datasource.DataSourceIT.java

@SuppressWarnings("unchecked")
@Test//from w w w. j  a  v a2  s  .c o m
public void testDataSourceAsService() throws Exception {
    Configuration config = ca.createFactoryConfiguration(PID, null);
    Dictionary<String, Object> p = new Hashtable<String, Object>();
    p.put("url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
    p.put("datasource.name", "test");
    p.put("initialSize", "5");
    p.put("defaultAutoCommit", "default");
    p.put("defaultReadOnly", "false");
    p.put("datasource.svc.properties", new String[] { "initSQL=SELECT 1", });
    p.put("maxActive", 70);
    config.update(p);

    Filter filter = context.createFilter("(&(objectclass=javax.sql.DataSource)(datasource.name=test))");
    ServiceTracker<DataSource, DataSource> st = new ServiceTracker<DataSource, DataSource>(context, filter,
            null);
    st.open();

    DataSource ds = st.waitForService(10000);
    assertNotNull(ds);

    Connection conn = ds.getConnection();
    assertNotNull(conn);

    //Cannot access directly so access via reflection
    assertEquals("70", getProperty(ds, "poolProperties.maxActive"));
    assertEquals("5", getProperty(ds, "poolProperties.initialSize"));
    assertEquals("SELECT 1", getProperty(ds, "poolProperties.initSQL"));
    assertEquals("false", getProperty(ds, "poolProperties.defaultReadOnly"));
    assertNull(getProperty(ds, "poolProperties.defaultAutoCommit"));

    config = ca.listConfigurations("(datasource.name=test)")[0];
    Dictionary dic = config.getProperties();
    dic.put("defaultReadOnly", Boolean.TRUE);
    config.update(dic);

    TimeUnit.MILLISECONDS.sleep(100);
    assertEquals("true", getProperty(ds, "poolProperties.defaultReadOnly"));
}