List of usage examples for javax.sql DataSource getConnection
Connection getConnection() throws SQLException;
Attempts to establish a connection with the data source that this DataSource object represents.
From source file:org.apache.cayenne.merge.DbMerger.java
private DataMap loadDataMapFromDb(DataSource dataSource, DbAdapter adapter, DbLoaderConfiguration config) { try (Connection conn = dataSource.getConnection();) { return new DbLoader(conn, adapter, new LoggingDbLoaderDelegate(LOGGER)).load(config); } catch (SQLException e) { throw new CayenneRuntimeException("Can't doLoad dataMap from db.", e); }// www .jav a 2 s .co m }
From source file:org.apache.torque.JndiConfigurationTest.java
/** * checks whether we can retrieve a connection from a DataSource. * @throws Exception if no connection can be established. */// ww w . j ava 2 s. co m protected void dataSourceConnect(DataSource dataSource) throws Exception { Connection connection = null; try { connection = dataSource.getConnection(); connection.close(); connection = null; } finally { if (connection != null) { connection.close(); } } }
From source file:com.alfaariss.oa.engine.authorization.jdbc.JDBCProfile.java
private Vector<AuthorizationMethod> readMethods(DataSource oDataSource, String sMethodsTable) throws AuthorizationException { Vector<AuthorizationMethod> vMethods = new Vector<AuthorizationMethod>(); Connection oConnection = null; PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null;/*from ww w . ja v a 2 s .co m*/ try { oConnection = oDataSource.getConnection(); StringBuffer sbSelect = new StringBuffer("SELECT * FROM "); sbSelect.append(sMethodsTable); sbSelect.append(" WHERE "); sbSelect.append(JDBCMethod.COLUMN_PROFILE); sbSelect.append("=? ORDER BY "); sbSelect.append(COLUMN_ORDER_ID); sbSelect.append(" ASC"); oPreparedStatement = oConnection.prepareStatement(sbSelect.toString()); oPreparedStatement.setString(1, _sID); oResultSet = oPreparedStatement.executeQuery(); while (oResultSet.next()) { JDBCMethod oMethod = new JDBCMethod(oResultSet); vMethods.add(oMethod); } } catch (Exception e) { _logger.fatal("Internal error during initialization", e); throw new AuthorizationException(SystemErrors.ERROR_INTERNAL); } finally { try { if (oResultSet != null) oResultSet.close(); } catch (Exception e) { _logger.error("Could not close resultset", e); } try { if (oPreparedStatement != null) oPreparedStatement.close(); } catch (Exception e) { _logger.error("Could not close statement", e); } try { if (oConnection != null) oConnection.close(); } catch (Exception e) { _logger.error("Could not close connection", e); } } return vMethods; }
From source file:org.biblionum.ouvrage.modele.OuvrageModele.java
/** * Java method that inserts a row in the generated sql table and returns the * new generated id/*from www . j a v a 2 s. c o m*/ * * @param con (open java.sql.Connection) * @param auteur * @param editeur * @param annee_edition * @param resume * @param nb_page * @param emplacement * @param couverture * @param ouvrageTipeid * @param categorieOuvrageid * @param niveauid_niveau * @param filiereid * @param titre * @return id (database row id [id]) * @throws SQLException */ public int insertIntoUtilisateur(DataSource ds, String auteur, String editeur, int annee_edition, String resume, int nb_page, String emplacement, String couverture, int ouvrageTipeid, int categorieOuvrageid, int niveauid_niveau, int filiereid, String titre) throws SQLException { con = ds.getConnection(); int generatedId = -1; String sql = "INSERT INTO ouvrage (auteur, editeur, annee_edition, resume, nb_page, emplacement, " + "couverture, ouvrageTipeid, categorieOuvrageid, niveauid_niveau, filiereid, titre" + ")" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, auteur); statement.setString(2, editeur); statement.setInt(3, annee_edition); statement.setString(4, resume); statement.setInt(5, nb_page); statement.setString(6, emplacement); statement.setString(7, couverture); statement.setInt(8, ouvrageTipeid); statement.setInt(9, categorieOuvrageid); statement.setInt(10, niveauid_niveau); statement.setInt(11, filiereid); statement.setString(12, titre); statement.execute(); ResultSet auto = statement.getGeneratedKeys(); if (auto.next()) { generatedId = auto.getInt(1); } else { generatedId = -1; } statement.close(); con.close(); return generatedId; }
From source file:com.gs.obevo.db.impl.platforms.oracle.OracleReveng.java
@Override protected File printInstructions(PrintStream out, AquaRevengArgs args) { DbEnvironment env = getDbEnvironment(args); JdbcDataSourceFactory jdbcFactory = new OracleJdbcDataSourceFactory(); DataSource ds = jdbcFactory.createDataSource(env, new Credential(args.getUsername(), args.getPassword()), 1);//from ww w. j a v a 2 s . co m JdbcHelper jdbc = new JdbcHelper(null, false); Path interim = new File(args.getOutputPath(), "interim").toPath(); interim.toFile().mkdirs(); try (Connection conn = ds.getConnection(); BufferedWriter fileWriter = Files.newBufferedWriter(interim.resolve("output.sql"), Charset.defaultCharset())) { // https://docs.oracle.com/database/121/ARPLS/d_metada.htm#BGBJBFGE // Note - can't remap schema name, object name, tablespace name within JDBC calls; we will leave that to the existing code in AbstractDdlReveng jdbc.update(conn, "{ CALL DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',false) }"); MutableList<Map<String, Object>> maps = jdbc.queryForList(conn, "SELECT CASE WHEN OBJECT_TYPE = 'TABLE' THEN 1 WHEN OBJECT_TYPE = 'INDEX' THEN 2 ELSE 3 END SORT_ORDER,\n" + " OBJECT_TYPE,\n" + " dbms_metadata.get_ddl(REPLACE(object_type,' ','_'), object_name, owner) || ';' AS object_ddl\n" + "FROM DBA_OBJECTS WHERE OWNER = '" + args.getDbSchema() + "' AND OBJECT_TYPE NOT IN ('PACKAGE BODY', 'LOB','MATERIALIZED VIEW', 'TABLE PARTITION')\n" + "ORDER BY 1"); for (Map<String, Object> map : maps) { Clob clobObject = (Clob) map.get("OBJECT_DDL"); InputStream in = clobObject.getAsciiStream(); StringWriter w = new StringWriter(); try { IOUtils.copy(in, w); } catch (IOException e) { throw new RuntimeException(e); } String clobAsString = w.toString(); clobAsString = clobAsString.replaceAll(";.*$", ""); LOG.debug("Content for {}: ", map.get("OBJECT_TYPE"), clobAsString); fileWriter.write(clobAsString); fileWriter.newLine(); fileWriter.write("~"); fileWriter.newLine(); } } catch (SQLException | IOException e) { throw new RuntimeException(e); } return interim.toFile(); }
From source file:org.jasig.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDaoTest.java
@Override protected void tearDownSchema(DataSource dataSource) throws SQLException { Connection con = dataSource.getConnection(); con.prepareStatement("DROP TABLE user_table").execute(); con.close();/* ww w .jav a 2s .c o m*/ }
From source file:com.alfaariss.oa.engine.authentication.jdbc.JDBCProfile.java
private void addProperties(DataSource oDataSource, String sProfilePropertiesTable) throws AuthenticationException { Connection oConnection = null; PreparedStatement oPreparedStatement = null; ResultSet rsProperties = null; try {//from ww w .java 2 s . co m oConnection = oDataSource.getConnection(); StringBuffer sbSelectProperties = new StringBuffer("SELECT "); sbSelectProperties.append(sProfilePropertiesTable).append(".*"); sbSelectProperties.append(" FROM "); sbSelectProperties.append(sProfilePropertiesTable); sbSelectProperties.append(" WHERE "); sbSelectProperties.append(sProfilePropertiesTable); sbSelectProperties.append("."); sbSelectProperties.append(COLUMN_PROPERTY_PROFILE_ID); sbSelectProperties.append("=?"); oPreparedStatement = oConnection.prepareStatement(sbSelectProperties.toString()); oPreparedStatement.setString(1, _sID); rsProperties = oPreparedStatement.executeQuery(); _properties = new Properties(); while (rsProperties.next()) { String sName = rsProperties.getString(COLUMN_PROPERTY_NAME); Object value = rsProperties.getString(COLUMN_PROPERTY_VALUE); _properties.put(sName, value); } _logger.debug("Retrieved properties: " + _properties); } catch (SQLException e) { _logger.error("Can not read from database", e); throw new AuthenticationException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (Exception e) { _logger.fatal("Internal error during create of an authentication profile", e); throw new AuthenticationException(SystemErrors.ERROR_INTERNAL); } finally { try { if (rsProperties != null) rsProperties.close(); } catch (Exception e) { _logger.error("Could not close resultset", e); } try { if (oPreparedStatement != null) oPreparedStatement.close(); } catch (Exception e) { _logger.error("Could not close statement", e); } try { if (oConnection != null) oConnection.close(); } catch (Exception e) { _logger.error("Could not close connection", e); } } }
From source file:org.apache.cayenne.tools.dbimport.DbImportActionDefault.java
public void execute(DbImportConfiguration config) throws Exception { if (logger.isDebugEnabled()) { logger.debug("DB connection: " + config.getDataSourceInfo()); }//from w w w.j a v a2s . c o m if (logger.isDebugEnabled()) { logger.debug(config); } DataNodeDescriptor dataNodeDescriptor = config.createDataNodeDescriptor(); DataSource dataSource = dataSourceFactory.getDataSource(dataNodeDescriptor); DbAdapter adapter = adapterFactory.createAdapter(dataNodeDescriptor, dataSource); DataMap loadedFomDb = load(config, adapter, dataSource.getConnection()); if (loadedFomDb == null) { logger.info("Nothing was loaded from db."); return; } DataMap existing = loadExistingDataMap(config.getDataMapFile()); if (existing == null) { logger.info(""); File file = config.getDataMapFile(); logger.info("Map file does not exist. Loaded db model will be saved into '" + (file == null ? "null" : file.getAbsolutePath() + "'")); saveLoaded(config.initializeDataMap(loadedFomDb)); } else { MergerFactory mergerFactory = adapter.mergerFactory(); List<MergerToken> mergeTokens = new DbMerger(mergerFactory).createMergeTokens(existing, loadedFomDb, config.getDbLoaderConfig()); if (mergeTokens.isEmpty()) { logger.info(""); logger.info("Detected changes: No changes to import."); return; } if (!isBlank(config.getDefaultPackage())) { existing.setDefaultPackage(config.getDefaultPackage()); } final Collection<ObjEntity> loadedObjEntities = new LinkedList<>(); DataMap executed = execute(new ProxyModelMergeDelegate(config.createMergeDelegate()) { @Override public void objEntityAdded(ObjEntity ent) { loadedObjEntities.add(ent); super.objEntityAdded(ent); } }, existing, log(sort(reverse(mergerFactory, mergeTokens)))); DbLoader.flattenManyToManyRelationships(executed, loadedObjEntities, config.getNameGenerator()); relationshipsSanity(executed); saveLoaded(executed); } }
From source file:fi.okm.mpass.shibboleth.profile.impl.StoreMonitoringResultTest.java
@Test public void testFailedConnection() throws Exception { final MonitoringResultContext monitoringCtx = new MonitoringResultContext(); long startTime = System.currentTimeMillis() - 1000; long endTime = System.currentTimeMillis(); DataSource dataSource = Mockito.mock(DataSource.class); Connection connection = Mockito.mock(Connection.class); SQLException exception = new SQLException("mock", retryableError); Mockito.when(connection.prepareStatement((String) Mockito.any(), Mockito.anyInt())).thenThrow(exception); Mockito.when(dataSource.getConnection()).thenReturn(connection); action = initAction(dataSource);//from w w w . jav a2s. co m monitoringCtx.addResult(initMonitoringResult(startTime, endTime)); prc.addSubcontext(monitoringCtx); ActionTestingSupport.assertEvent(action.execute(src), EventIds.IO_ERROR); }
From source file:org.apache.cayenne.tools.dbimport.DbImportAction.java
public void execute(DbImportConfiguration config) throws Exception { if (logger.isDebugEnabled()) { logger.debug("DB connection: " + config.getDataSourceInfo()); }//from w w w. j ava2 s. c o m if (logger.isDebugEnabled()) { logger.debug(config); } DataNodeDescriptor dataNodeDescriptor = config.createDataNodeDescriptor(); DataSource dataSource = dataSourceFactory.getDataSource(dataNodeDescriptor); DbAdapter adapter = adapterFactory.createAdapter(dataNodeDescriptor, dataSource); DataMap loadedFomDb; try (Connection c = dataSource.getConnection()) { loadedFomDb = load(config, adapter, c); } if (loadedFomDb == null) { logger.info("Nothing was loaded from db."); return; } DataMap existing = loadExistingDataMap(config.getDataMapFile()); if (existing == null) { logger.info(""); File file = config.getDataMapFile(); logger.info("Map file does not exist. Loaded db model will be saved into '" + (file == null ? "null" : file.getAbsolutePath() + "'")); saveLoaded(config.initializeDataMap(loadedFomDb)); } else { MergerFactory mergerFactory = adapter.mergerFactory(); List<MergerToken> mergeTokens = new DbMerger(mergerFactory).createMergeTokens(existing, loadedFomDb, config.getDbLoaderConfig()); if (mergeTokens.isEmpty()) { logger.info(""); logger.info("Detected changes: No changes to import."); return; } if (!isBlank(config.getDefaultPackage())) { existing.setDefaultPackage(config.getDefaultPackage()); } final Collection<ObjEntity> loadedObjEntities = new LinkedList<ObjEntity>(); DataMap executed = execute(new ProxyModelMergeDelegate(config.createMergeDelegate()) { @Override public void objEntityAdded(ObjEntity ent) { loadedObjEntities.add(ent); super.objEntityAdded(ent); } }, existing, log(sort(reverse(mergerFactory, mergeTokens)))); DbLoader.flattenManyToManyRelationships(executed, loadedObjEntities, config.getNameGenerator()); relationshipsSanity(executed); saveLoaded(executed); } }