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:io.seldon.db.jdbc.JDBCConnectionFactory.java
public Connection getConnection(String client, boolean readonly) throws SQLException { DataSource ds = dataSources.get(client); Connection c = null;/*from ww w. ja v a2 s. c o m*/ if (ds != null) { c = ds.getConnection(); if (readonly) c.setReadOnly(true); else c.setReadOnly(false); c.setCatalog(clientToCatalog.get(client)); } else { // logger.error("Can't get connection for client "+client); final String message = "Can't get connection for client " + client; logger.error(message, new Exception(message)); } return c; }
From source file:fll.web.report.StoreNonNumericNominees.java
@Override protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final StringBuilder message = new StringBuilder(); Connection connection = null; try {/*from w ww. j ava 2 s . co m*/ final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final int tournament = Queries.getCurrentTournament(connection); // get parameters final String nomineesStr = request.getParameter("non-numeric-nominees_data"); if (null == nomineesStr || "".equals(nomineesStr)) { throw new FLLRuntimeException("Parameter 'non-numeric-nominees_data' cannot be null"); } // decode JSON final ObjectMapper jsonMapper = new ObjectMapper(); final Collection<NonNumericNominees> nominees = jsonMapper.readValue(nomineesStr, NonNumericNomineesTypeInformation.INSTANCE); for (final NonNumericNominees nominee : nominees) { nominee.store(connection, tournament); } message.append("<p id='success'>Non-numeric nominees saved to the database</p>"); } catch (final SQLException e) { message.append("<p class='error'>Error saving non-numeric nominees into the database: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error saving subjective data into the database", e); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL("non-numeric-nominees.jsp")); }
From source file:com.emc.ecs.sync.service.RowIterator.java
public RowIterator(DataSource ds, RowMapper<T> rowMapper, String query, Object... params) { try {//w w w. j a v a 2 s .co m this.rowMapper = rowMapper; this.con = ds.getConnection(); this.st = con.prepareStatement(query); if (params != null && params.length > 0) new ArgumentPreparedStatementSetter(params).setValues(st); this.rs = st.executeQuery(); } catch (SQLException e) { close(); throw new RuntimeException(e); } }
From source file:org.jasig.portlet.calendar.hibernate.ApplicationContextConnectionProvider.java
@Override public Connection getConnection() throws SQLException { if (context == null) { init();//from ww w.jav a2s.c om } final DataSource dataSource = context.getBean(DATA_SOURCE_BEAN_NAME, DataSource.class); final Connection rslt = dataSource.getConnection(); logger.info("Providing the following connection to hbm2ddl: " + rslt); return rslt; }
From source file:org.apache.nifi.registry.db.CustomFlywayMigrationStrategy.java
/** * Determines if the database represented by this data source is being initialized for the first time based on * whether or not the table named 'BUCKET' or 'bucket' already exists. * * @param dataSource the data source/*ww w.j a v a 2 s.c o m*/ * @return true if the database has never been initialized before, false otherwise */ private boolean isNewDatabase(final DataSource dataSource) { try (final Connection connection = dataSource.getConnection(); final ResultSet rsUpper = connection.getMetaData().getTables(null, null, "BUCKET", null); final ResultSet rsLower = connection.getMetaData().getTables(null, null, "bucket", null)) { return !rsUpper.next() && !rsLower.next(); } catch (SQLException e) { LOGGER.error(e.getMessage(), e); throw new FlywayException("Unable to obtain connection from Flyway DataSource", e); } }
From source file:org.dashbuilder.dataprovider.sql.SQLDataSetTestBase.java
@Before public void setUp() throws Exception { // Prepare the datasource to test SQLDataSourceLocator dataSourceLocator = testSettings.getDataSourceLocator(); sqlDataSetProvider.setDataSourceLocator(dataSourceLocator); // Add SQL data sets support DataSetProviderRegistry dataSetProviderRegistry = DataSetCore.get().getDataSetProviderRegistry(); dataSetProviderRegistry.registerDataProvider(sqlDataSetProvider); // Register the SQL data set URL fileURL = Thread.currentThread().getContextClassLoader().getResource(getExpenseReportsDsetFile()); 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(); printDatabaseInfo();// ww w .ja v a2 s. c o m // Create the expense reports table createTable(conn).table(EXPENSES).columns(ID, CITY, DEPT, EMPLOYEE, DATE, AMOUNT).primaryKey(ID).execute(); // Populate the table populateDbTable(); }
From source file:id.go.kemdikbud.tandajasa.dao.PegawaiDaoTest.java
@Before public void resetDatabase() { try {//from www . j av a2 s . c o m DataSource ds = ctx.getBean(DataSource.class); Connection koneksiDatabase = ds.getConnection(); DatabaseOperation.CLEAN_INSERT.execute(new DatabaseConnection(koneksiDatabase), new FlatXmlDataSetBuilder().build(new File("src/test/resources/pegawai.xml"))); koneksiDatabase.close(); } catch (Exception ex) { Logger.getLogger(PegawaiDaoTest.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.fornax.cartridges.sculptor.framework.util.db.DbUnitConnection.java
public IDatabaseConnection getConnection() throws SQLException, DatabaseUnitException { ApplicationContext context = ApplicationContextSingleton.getApplicationContext(); DataSource ds = (DataSource) context.getBean(dataSourceSpringBeanName); IDatabaseConnection connection = new DatabaseConnection(ds.getConnection()); DatabaseConfig config = connection.getConfig(); config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqlDataTypeFactory()); return connection; }
From source file:org.biblionum.ouvrage.modele.OuvrageTypeModele.java
/** * Java method that inserts a row in the generated sql table and returns the * new generated id/*from ww w . j a va 2s. c o m*/ * * @param con (open java.sql.Connection) * @param designation_typeou * @return id (database row id [id]) * @throws SQLException */ public int insertIntoOuvragetype(DataSource ds, String designation_typeou) throws SQLException { con = ds.getConnection(); int generatedId = -1; String sql = "INSERT INTO ouvragetype (designation_typeou)" + "VALUES (?)"; PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, designation_typeou); 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:schemacrawler.tools.integration.spring.SchemaCrawlerSpringCommandLine.java
@Override public void execute() throws Exception { final Path contextFile = Paths.get(springOptions.getContextFileName()).normalize().toAbsolutePath(); final ApplicationContext appContext; if (exists(contextFile)) { final String contextFilePath = contextFile.toUri().toString(); LOGGER.log(Level.INFO, "Loading context from file, " + contextFilePath); appContext = new FileSystemXmlApplicationContext(contextFilePath); } else {//from w ww. ja v a 2 s . c o m LOGGER.log(Level.INFO, "Loading context from classpath, " + springOptions.getContextFileName()); appContext = new ClassPathXmlApplicationContext(springOptions.getContextFileName()); } try { final DataSource dataSource = (DataSource) appContext.getBean(springOptions.getDataSourceName()); try (Connection connection = dataSource.getConnection();) { final Executable executable = (Executable) appContext.getBean(springOptions.getExecutableName()); executable.execute(connection); } } finally { ((AbstractXmlApplicationContext) appContext).close(); } }