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.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java

/***
private static void printAvailableMethods(Object object) {
Method[] methods = object.getClass().getMethods();
for (Method method : methods) {// w w w .  jav  a  2 s .  c  o m
//    System.out.println("METHOD - " + method.getName());
    if (method.getName().equals("getNativeConnection")) {
        System.out.println("METHOD - " + method.getName());
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (Class parameterType : parameterTypes) {
            System.out.println("TYPE =  " + parameterType);
        }
    }
}
}
***/

private Connection getOriginalConnection(DataSource dataSource) throws SQLException {
    return dataSource.getConnection();
}

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

/**
 * Initialize.//from   w w  w .j  av a2  s.  c om
 *
 * @param context
 *            the context
 * @throws DatabaseUnitException
 *             the database unit exception
 * @throws SQLException
 *             the SQL exception
 * @throws MalformedURLException
 *             the malformed url exception
 */
public void initialize(ApplicationContext context)
        throws DatabaseUnitException, SQLException, MalformedURLException {
    if (!getInitXmlFiles().isEmpty()) {
        DataSource datas = GlobalUtils.findDataSourceBean(context);
        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

        //
        //
        // if (!getInitXmlFiles().isEmpty()) {
        // 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)); // Import your data
        // }
        // TODO handle the empty data file case.
        con.close();
    }

}

From source file:org.beangle.webapp.database.action.DatasourceAction.java

public String test() {
    Long datasourceId = getEntityId("datasource");
    DataSource dataSource = datasourceService.getDatasource(datasourceId);
    Map<String, String> driverinfo = CollectUtils.newHashMap();
    Map<String, Object> dbinfo = CollectUtils.newHashMap();
    Map<String, Object> jdbcinfo = CollectUtils.newHashMap();
    Connection con = null;/*from  w  w w. j  a  va2 s . c  o m*/
    try {
        con = dataSource.getConnection();
        if (con != null) {
            java.sql.DatabaseMetaData dm = con.getMetaData();
            driverinfo.put("Driver Name", dm.getDriverName());
            driverinfo.put("Driver Version", dm.getDriverVersion());
            dbinfo.put("Database Name", dm.getDatabaseProductName());
            dbinfo.put("Database Version", dm.getDatabaseProductVersion());
            jdbcinfo.put("JDBC Version", dm.getJDBCMajorVersion() + "." + dm.getJDBCMinorVersion());
            StringBuilder catelogs = new StringBuilder();
            dbinfo.put("Avalilable Catalogs", catelogs);
            java.sql.ResultSet rs = dm.getCatalogs();
            while (rs.next()) {
                catelogs.append(rs.getString(1));
                if (rs.next())
                    catelogs.append(',');
            }
            rs.close();
        }
    } catch (Exception e) {
        put("exceptionStack", ExceptionUtils.getFullStackTrace(e));
    } finally {
        try {
            if (con != null)
                con.close();
            con = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    put("driverinfo", driverinfo);
    put("dbinfo", dbinfo);
    put("jdbcinfo", jdbcinfo);
    return forward();
}

From source file:biz.taoconsulting.dominodav.resource.DAVResourceJDBC.java

private void getInitDBFileValues() {
    Statement stmt = null;/*from  w  w  w .  j ava2 s . c o m*/
    Statement stmt1 = null;
    Connection conn = null;
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource)

        envCtx.lookup(this.repositoryMeta.getInternalAddress());
        conn = ds.getConnection();
        stmt1 = conn.createStatement();
        // TODO fix this
        stmt1.executeQuery("select uis_mid_onetimeinitweb('DATENADMIN','umsys','DE') as a from dual");

        stmt = conn.createStatement();
        // TODO: Fix that SQL
        ResultSet rs = stmt.executeQuery(
                "select t.dtyp_mimetype,d.*," + "f.fil_length,f.fil_id from  umsys.ibkuis_co_filetype t,"
                        + "uis_pp_documents_v d, ibkuis_pp_files f where d.D_ID =" + this.getDBDocID()
                        + "and f.fil_id = d.D_FIL_ID and t.dtyp_kz = upper(d.D_TYP)");
        if (rs.next()) {
            this.setName(rs.getString("D_FILE"));
            this.setExtension(rs.getString("D_TYP"));
            this.setContentLength(rs.getString("FIL_LENGTH"));
            this.setDBFileID(rs.getString("FIL_ID"));
            this.setMimeType(rs.getString("dtyp_mimetype"));
            System.out.println("BREAK");
        }
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
            if (stmt1 != null)
                stmt1.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            /** Exception handling **/
        }
    }
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

@Override
public String execute() throws Exception {
    if (!checkAccess()) {
        return ERROR;
    }//from   w  ww .j  a v a 2  s  .c  o m
    timestamp = new Date(System.currentTimeMillis());
    Runtime rt = Runtime.getRuntime();
    jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0);
    jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0);
    jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0);
    HttpServletRequest req = ServletActionContext.getRequest();
    tomcatVersion = ServletActionContext.getServletContext().getServerInfo();
    sessionCount = SessionCounter.getSessionCount();
    host = req.getLocalName();
    hostIp = req.getLocalAddr();
    buildInfo = generateBuildInfo();

    // The easiest way I found to get the URL and username for the DB.
    // It's not that easy and involves opening a connection...
    Context initialContext = new InitialContext();
    Context context = (Context) initialContext.lookup("java:comp/env");
    DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();
        dbUrl = metadata.getURL();
        dbUser = metadata.getUserName();
    } finally {
        conn.close();
    }

    Configuration config = ConfigurationStore.getInstance().getConfiguration();
    FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore");
    filestore = filestoreService.toString();
    solrUrl = (String) config.getProperty("ambra.services.search.server.url");
    configuration = dumpConfig(config);
    cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline"));

    return SUCCESS;
}

From source file:com.manpowergroup.cn.icloud.util.Case0.java

private void p0(DataSource dataSource, String name) throws SQLException {
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();

    for (int i = 0; i < COUNT; ++i) {
        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT 1");
        rs.close();//from   w ww .j  ava 2s .  c om
        stmt.close();
        conn.close();
    }
    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println(name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc
            + " FGC " + fullGC);
}

From source file:com.uber.hoodie.utilities.HiveIncrementalPuller.java

private Connection getConnection() throws SQLException {
    if (connection == null) {
        DataSource ds = getDatasource();
        log.info("Getting Hive Connection from Datasource " + ds);
        this.connection = ds.getConnection();
    }/*from  w w w. ja v  a 2  s. com*/
    return connection;
}

From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java

private List<RequestDepository> fetchConnectionsAndDepositForLaterUse(List<ConcurrentRequest> requests) {
    List<RequestDepository> depos = new ArrayList<RequestDepository>();
    for (ConcurrentRequest request : requests) {
        DataSource dataSource = request.getDataSource();

        Connection springCon = null;
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
        try {/*from  w w w  .  java 2s .c o  m*/
            springCon = (transactionAware ? dataSource.getConnection()
                    : DataSourceUtils.doGetConnection(dataSource));
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        RequestDepository depo = new RequestDepository();
        depo.setOriginalRequest(request);
        depo.setConnectionToUse(springCon);
        depo.setTransactionAware(transactionAware);
        depos.add(depo);
    }

    return depos;
}

From source file:hnu.helper.DataBaseConnection.java

/** Fetches new DataBaseConnection from Pool */
public Connection getDBConnection() {
    Connection conn = null;/*from www. ja  v  a 2 s. c om*/

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/hnuDB");

        conn = ds.getConnection();
    } catch (Exception sqle) {
        log.error("Couln't get connection from DataSource", sqle);
        //sqle.printStackTrace();
    }

    return conn;
}

From source file:com.googlecode.flyway.core.dbsupport.mysql.MySQLMigrationTestCase.java

/**
 * Tests whether locking problems occur when Flyway's DB connection gets reused.
 *//* w w  w.  j a  v  a  2 s  .co  m*/
@Test
public void lockOnConnectionReUse() throws SQLException {
    DataSource twoConnectionsDataSource = new TwoConnectionsDataSource(flyway.getDataSource());
    flyway.setDataSource(twoConnectionsDataSource);
    flyway.setLocations(BASEDIR);
    flyway.migrate();

    Connection connection1 = twoConnectionsDataSource.getConnection();
    Connection connection2 = twoConnectionsDataSource.getConnection();
    assertEquals(2, new JdbcTemplate(connection1, 0).queryForInt("SELECT COUNT(*) FROM test_user"));
    assertEquals(2, new JdbcTemplate(connection2, 0).queryForInt("SELECT COUNT(*) FROM test_user"));
}