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.apache.openjpa.jdbc.sql.DBDictionaryFactory.java

/**
 * Create the dictionary using connection metadata to determine its type.
 *///from  w w w  .ja  v a 2  s. c om
public static DBDictionary newDBDictionary(JDBCConfiguration conf, DataSource ds, String props) {
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData meta = conn.getMetaData();
        String dclass = dictionaryClassForString(meta.getDatabaseProductName(), conf);
        if (dclass == null)
            dclass = dictionaryClassForString(getProtocol(meta.getURL()), conf);
        if (dclass == null)
            dclass = DBDictionary.class.getName();
        return newDBDictionary(conf, dclass, props, conn);
    } catch (SQLException se) {
        throw new StoreException(se).setFatal(true);
    } finally {
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException se) {
            }
    }
}

From source file:no.kantega.publishing.common.util.database.dbConnectionFactory.java

private static void ensureDatabaseExists(DataSource dataSource) {
    try (Connection c = dataSource.getConnection()) {
        boolean hasTables = true;

        try (Statement s = c.createStatement()) {
            s.execute("SELECT max(ContentId) from content");
        } catch (SQLException e) {
            hasTables = false;//from ww w .  j a v a  2  s.co  m
        }

        if (!hasTables) {
            createTables(dataSource);
        }
    } catch (SQLException e) {
        throw new SystemException("Can't connect to database, please check configuration", e);
    }
}

From source file:net.sf.jabb.util.db.ConnectionUtility.java

/**
 * ????//  w w  w.ja  v a 2s.c  om
 * @param source
 * @return the database connection
 * @throws SQLException
 */
public static Connection getConnection(String source) throws SQLException {
    DataSource ds = getDataSource(source);
    if (ds == null) {
        throw new SQLException("ConnectionUtility cannot get data source: " + source);
    }
    return ds.getConnection();
}

From source file:org.apereo.portal.jdbc.RDBMServices.java

/**
 * Returns a connection produced by a DataSource found in the
 * JNDI context.  The DataSource should be configured and
 * loaded into JNDI by the J2EE container or may be the portal
 * default database./*from  w  ww.jav a2 s .c om*/
 *
 * @param dbName the database name which will be retrieved from
 *   the JNDI context relative to "jdbc/"
 * @return a database Connection object or <code>null</code> if no Connection
 * @deprecated Where possible code should be injected with a {@link DataSource} object via the Spring application context
 */
@Deprecated
public static Connection getConnection(String dbName) {
    final DataSource dataSource = getDataSource(dbName);

    try {
        final long start = System.currentTimeMillis();
        final Connection c = dataSource.getConnection();
        lastDatabase = databaseTimes.add(System.currentTimeMillis() - start); // metric
        final int current = activeConnections.incrementAndGet();
        if (current > maxConnections) {
            maxConnections = current;
        }
        return c;
    } catch (SQLException e) {
        throw new DataAccessResourceFailureException(
                "RDBMServices sql error trying to get connection to " + dbName, e);
    }
}

From source file:FacultyAdvisement.StudentRepository.java

public static Map readAll(DataSource ds) throws SQLException {
    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }/*ww  w  .j  a v a 2s  . c o m*/

    Connection conn = ds.getConnection();

    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }

    HashMap<String, Student> list = new HashMap<>();

    try {
        PreparedStatement ps = conn.prepareStatement("select * from STUDENT");

        // retrieve customer data from database
        ResultSet result = ps.executeQuery();

        while (result.next()) {
            Student s = new Student();
            s.setId(result.getString("STUID"));
            s.setUsername(result.getString("EMAIL"));
            s.setFirstName(result.getString("FIRSTNAME"));
            s.setLastName(result.getString("LASTNAME"));
            s.setMajorCode(result.getString("MAJORCODE"));
            s.setPhoneNumber(result.getString("PHONE"));
            if (result.getString("ADVISED").equals("true")) {
                s.setAdvised(true);
            } else {
                s.setAdvised(false);
            }
            list.put(s.getId(), s);
        }

    } finally {
        conn.close();
    }

    return list;
}

From source file:org.wso2.carbon.metrics.impl.ReporterTest.java

public static Test suite() {
    return new TestSetup(new TestSuite(ReporterTest.class)) {

        protected void setUp() throws Exception {
            DataSource dataSource = JdbcConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");
            template = new JdbcTemplate(dataSource);
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.addScript(new ClassPathResource("dbscripts/h2.sql"));
            populator.populate(dataSource.getConnection());

            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            InitialContext ic = new InitialContext();
            ic.createSubcontext("jdbc");
            ic.bind("jdbc/WSO2MetricsDB", dataSource);

            // Set setup system property to cover database creator logic
            System.setProperty("setup", "");
        }//  w w  w .j ava  2 s .c  o m

        protected void tearDown() throws Exception {
            InitialContext ic = new InitialContext();
            ic.unbind("jdbc/WSO2MetricsDB");
            ic.unbind("jdbc");
        }
    };
}

From source file:com.glaf.core.jdbc.DBConnectionFactory.java

public static boolean checkConnection() {
    Connection connection = null;
    DataSource ds = null;
    try {//from   ww  w  .ja  va  2s.c o  m
        Properties props = DBConfiguration.getDefaultDataSourceProperties();
        if (props != null) {
            connection = getConnection(props);
        } else {
            ds = ContextFactory.getBean("dataSource");
            connection = ds.getConnection();
        }
        if (connection != null) {
            return true;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex);
    } finally {
        JdbcUtils.close(connection);
    }
    return false;
}

From source file:FacultyAdvisement.StudentRepository.java

public static void updatePassword(DataSource ds, String username, String password) throws SQLException {

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }/* ww  w.j  a va 2s .co m*/

    Connection conn = ds.getConnection();

    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }

    String newPassword = SHA256Encrypt.encrypt(password);
    try {
        PreparedStatement ps = conn.prepareStatement("Update USERTABLE set PASSWORD=? where USERNAME=?");
        ps.setString(1, newPassword);
        ps.setString(2, username);

        ps.executeUpdate();

    } finally {
        conn.close();
    }
}

From source file:com.jaspersoft.jasperserver.war.common.JasperServerUtil.java

public static Connection getJSDatabaseConnection()
        throws ClassNotFoundException, SQLException, NamingException {
    boolean sqlExcpn = false;
    Connection con = null;/*w  w  w .  j  a va  2s  . c  o m*/
    try {
        InitialContext cxt = new InitialContext();
        DataSource ds = (DataSource) cxt.lookup(JasperServerConstImpl.getJSDataSrc());
        con = ds.getConnection();
        if (log.isDebugEnabled()) {
            log.debug(
                    "getConnection successful at com.jaspersoft.jasperserver.war.common.JasperServerUtil.getJSDatabaseConnection");
        }
        return con;
    } catch (Exception _ex) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "getConnection FAILED at com.jaspersoft.jasperserver.war.common.JasperServerUtil.getJSDatabaseConnection: "
                            + _ex.getMessage());
        }
        if (log.isErrorEnabled())
            log.error(_ex, _ex);
        sqlExcpn = true;
    } finally {
        if (sqlExcpn) {
            Class.forName(JasperServerConstImpl.getJSConnector());
            con = DriverManager.getConnection(JasperServerConstImpl.getJSUrl(),
                    JasperServerConstImpl.getJSDbUser(), JasperServerConstImpl.getJSDbPasswd());
            return con;
        }
    }
    return con;
}

From source file:no.kantega.publishing.common.util.database.dbConnectionFactory.java

private static void createTables(DataSource dataSource) {
    String productName = null;/*from  w  ww  . j  a  va  2  s.  c  om*/

    try (Connection c = dataSource.getConnection()) {
        productName = c.getMetaData().getDatabaseProductName();

    } catch (SQLException e) {
        throw new SystemException("Error creating tables for Flyt CMS", e);
    }

    String dbType = getDBVendor(productName);

    final URL resource = dbConnectionFactory.class.getClassLoader()
            .getResource("dbschema/aksess-database-" + dbType + ".sql");

    if (resource != null) {
        log.info("Creating tables from schema definition " + resource);
        final InputStream schema;
        try {
            schema = resource.openStream();
        } catch (IOException e) {
            throw new SystemException("Can't load schema resource " + resource, e);
        }
        try {

            final String[] statements = IOUtils.toString(schema).split(";");

            JdbcTemplate template = new JdbcTemplate(dataSource);
            for (String statement : statements) {
                String[] lines = statement.split("\n");
                StringBuilder stripped = new StringBuilder();
                for (String line : lines) {
                    if (line.trim().length() != 0 && !line.trim().startsWith("#")
                            && !line.trim().startsWith("--")) {
                        stripped.append(line).append('\n');
                    }
                }
                String query = stripped.toString();
                if (query.length() > 0) {
                    template.execute(query);
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}