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.thinkbiganalytics.server.upgrade.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  . ja v a2s .  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.datasource.validationQuery");

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

        DataSource dataSource = PoolingDataSourceService.getDataSource(dataSourceProperties);

        connection = dataSource.getConnection();
        String query = "SELECT * FROM KYLO_VERSION ORDER BY MAJOR_VERSION DESC, MINOR_VERSION DESC, POINT_VERSION DESC, TAG DESC";
        statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        if (rs.next()) {
            String majorVersion = rs.getString("MAJOR_VERSION");
            String minorVersion = rs.getString("MINOR_VERSION");
            String pointVersion = rs.getString("POINT_VERSION");
            String tag = rs.getString("TAG");

            version = new KyloVersionUtil.Version(majorVersion, minorVersion, pointVersion, tag);
        }

    } 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.
        e.printStackTrace();
    } finally {
        JdbcUtils.closeStatement(statement);
        JdbcUtils.closeResultSet(resultSet);
        JdbcUtils.closeConnection(connection);
    }
    return version;

}

From source file:net.sf.jasperreports.data.jndi.JndiDataAdapterService.java

@Override
public void contributeParameters(Map<String, Object> parameters) throws JRException {
    JndiDataAdapter jndiDataAdapter = getJndiDataAdapter();
    if (jndiDataAdapter != null) {

        try {/*from  www. j  a  v a2 s  .  c om*/
            Context ctx = new InitialContext();
            DataSource dataSource = (DataSource) ctx
                    .lookup("java:comp/env/" + jndiDataAdapter.getDataSourceName());
            connection = dataSource.getConnection();
        } catch (Exception ex) {
            throw new JRException(ex);
        }

        parameters.put(JRParameter.REPORT_CONNECTION, connection);
    }
}

From source file:org.apache.kylin.query.QueryDataSourceTest.java

@Test(timeout = 10000)
public void testMaxConnLimit() throws SQLException {
    KylinConfig config = KylinConfig.getInstanceFromEnv();

    // Test with connection limit 
    Properties props = new Properties();
    props.setProperty("maxActive", "3");
    props.setProperty("maxWait", "1000");
    DataSource ds1 = QueryDataSource.create("default", config, props);
    Connection ds1Conn1 = ds1.getConnection();
    Connection ds1Conn2 = ds1.getConnection();
    Connection ds1Conn3 = ds1.getConnection();
    try {// w  w  w.  j  a  va2s . co m
        Connection ds1Conn4 = ds1.getConnection();
        DBUtils.closeQuietly(ds1Conn4);
        Assert.fail("This should fail with SQLException");
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SQLException);
    }
    DBUtils.closeQuietly(ds1Conn1);
    DBUtils.closeQuietly(ds1Conn2);
    DBUtils.closeQuietly(ds1Conn3);

    // Test with not connection limit
    DataSource ds2 = QueryDataSource.create("default", config);
    Connection ds2Conn1 = ds2.getConnection();
    Connection ds2Conn2 = ds2.getConnection();
    Connection ds2Conn3 = ds2.getConnection();
    Connection ds2Conn4 = ds2.getConnection();
    Connection ds2Conn5 = ds2.getConnection();
    Connection ds2Conn6 = ds2.getConnection();
    Connection ds2Conn7 = ds2.getConnection();
    Connection ds2Conn8 = ds2.getConnection(); // DBCP default is 8, should be bypassed with no limit
    Connection ds2Conn9 = ds2.getConnection();
    DBUtils.closeQuietly(ds2Conn1);
    DBUtils.closeQuietly(ds2Conn2);
    DBUtils.closeQuietly(ds2Conn3);
    DBUtils.closeQuietly(ds2Conn4);
    DBUtils.closeQuietly(ds2Conn5);
    DBUtils.closeQuietly(ds2Conn6);
    DBUtils.closeQuietly(ds2Conn7);
    DBUtils.closeQuietly(ds2Conn8);
    DBUtils.closeQuietly(ds2Conn9);
}

From source file:dk.nsi.haiba.minipasconverter.config.MinipasConverterConfiguration.java

@Bean
public DataSource haibaDataSource() throws Exception {
    JndiObjectFactoryBean factory = new JndiObjectFactoryBean();
    factory.setJndiName(haibaJNDIName);//w  w  w  . jav a  2s .  co m
    factory.setExpectedType(DataSource.class);
    factory.afterPropertiesSet();
    DataSource dataSource = (DataSource) factory.getObject();
    // requires manual transaction handling
    dataSource.getConnection().setAutoCommit(false);
    return dataSource;
}

From source file:org.beangle.ems.dev.hibernate.web.action.EvolutionAction.java

public void setDataSource(DataSource datasource) throws SQLException {
    this.jdbcTemplate = new JdbcTemplate(datasource);
    Connection connection = datasource.getConnection();
    databaseName = connection.getMetaData().getDatabaseProductName().toLowerCase();
    connection.close();//w ww  .j av a 2  s .  c  o  m
}

From source file:opa.filter.LoadInitiativeSetup.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
        throws IOException, ServletException {

    Connection conn = null;//from w  ww  . j  a va2s  . c o m

    try {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        /*
         * select the fields from initiative_setup and translate them to the
         * InitiativeSetup model.
         * 
         * TODO: use a real object-relational-mapper like hibernate.
         */
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jdbcJndi);
        conn = ds.getConnection();

        ResultSet rs = conn.createStatement()
                .executeQuery("select I.*, L.language from initiative_setup I, languages L "
                        + "where I.default_lang = L.lang_id");

        if (rs.next() == false) {
            log.fatal("Could not get info from initiative_setup table.");
            response.sendError(500);
        }

        InitiativeSetup setup = new InitiativeSetup();
        Map<String, Object> map = Utils.resultSetToMap(rs);

        try {
            BeanUtils.populate(setup, map);
        } catch (Exception e) {
            log.fatal("could not build InitiativeSetup from table initiative_setup");
            log.fatal(e, e);
            response.sendError(500);
        }

        request.getSession().setAttribute("initiativeSetup", setup);

    } catch (NamingException e) {
        log.fatal(e, e);
    } catch (SQLException e) {
        log.fatal(e, e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // bleh
            }
        }
    }

    fc.doFilter(req, res);
}

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

/**
 * Perform the command./*from ww  w.j av a2s .  c  om*/
 *
 * @return The database name and version.
 */
public Object performWithResult() {
    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;

    try {
        if (version == null) {
            connection = dataSource.getConnection();

            DatabaseMetaData meta = connection.getMetaData();

            version = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
        }

        return version;
    } catch (SQLException x) {
        Log.logError("persist", "Insert", "Unable to get database meta data: " + x);
    } finally {
        DbUtils.closeQuietly(connection);
    }

    return null;
}

From source file:com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBeanTest.java

@Test
public void shouldSupportNewConnection() throws Exception {
    DataSource dataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);
    given(dataSource.getConnection()).willReturn(connection);
    IDatabaseConnection databaseConnection = DatabaseDataSourceConnectionFactoryBean.newConnection(dataSource);
    assertNotNull(databaseConnection);/*from  w  ww  .j av a2  s . c o  m*/
    databaseConnection.getConnection().createStatement();
    verify(dataSource).getConnection();
}

From source file:fll.web.scoreEntry.ScoreEntry.java

/**
 * Generate the initial assignment of the global variables for editing a
 * team's score.//from   w w  w  .  j  a v  a 2 s.  c om
 */
public static void generateInitForScoreEdit(final JspWriter writer, final ServletContext application,
        final HttpSession session) throws SQLException, IOException {
    final ChallengeDescription description = ApplicationAttributes.getChallengeDescription(application);
    final int teamNumber = SessionAttributes.getNonNullAttribute(session, "team", Team.class).getTeamNumber();
    final int runNumber = SessionAttributes.getNonNullAttribute(session, "lRunNumber", Number.class).intValue();

    final DataSource datasource = ApplicationAttributes.getDataSource(application);

    PreparedStatement prep = null;
    ResultSet rs = null;
    Connection connection = null;
    try {
        connection = datasource.getConnection();
        final int tournament = Queries.getCurrentTournament(connection);

        prep = connection.prepareStatement("SELECT * from Performance" + " WHERE TeamNumber = ?" //
                + " AND RunNumber = ?"//
                + " AND Tournament = ?");
        prep.setInt(1, teamNumber);
        prep.setInt(2, runNumber);
        prep.setInt(3, tournament);

        rs = prep.executeQuery();
        if (rs.next()) {
            final PerformanceScoreCategory performanceElement = description.getPerformance();
            for (final AbstractGoal element : performanceElement.getGoals()) {
                if (!element.isComputed()) {
                    final Goal goal = (Goal) element;
                    final String name = goal.getName();
                    final String rawVarName = getVarNameForRawScore(name);

                    if (goal.isEnumerated()) {
                        // enumerated
                        final String storedValue = rs.getString(name);
                        boolean found = false;
                        for (final EnumeratedValue valueElement : goal.getSortedValues()) {
                            final String value = valueElement.getValue();
                            if (value.equals(storedValue)) {
                                writer.println("  " + rawVarName + " = \"" + value + "\";");
                                found = true;
                            }
                        }
                        if (!found) {
                            throw new RuntimeException(
                                    "Found enumerated value in the database that's not in the XML document, goal: "
                                            + name + " value: " + storedValue);
                        }
                    } else {
                        // just use the value that is stored in the database
                        writer.println("  " + rawVarName + " = " + rs.getString(name) + ";");
                    }
                } // !computed
            } // foreach goal
              // Always init the special double-check column
            writer.println("  Verified = " + rs.getBoolean("Verified") + ";");
        } else {
            throw new RuntimeException("Cannot find TeamNumber and RunNumber in Performance table"
                    + " TeamNumber: " + teamNumber + " RunNumber: " + runNumber);
        }
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(prep);
        SQLFunctions.close(connection);
    }
}

From source file:com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBeanTest.java

@Test
public void shouldCreateDatabaseDataSourceConnection() throws Exception {
    DataSource dataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);
    given(dataSource.getConnection()).willReturn(connection);
    this.factoryBean.setDataSource(dataSource);
    DatabaseDataSourceConnection bean = this.factoryBean.getObject();
    assertNotNull(bean);/* ww  w . ja  v  a2  s  . c o m*/
    bean.getConnection().createStatement();
    verify(dataSource).getConnection();
}