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:de.iritgo.aktario.jdbc.StoreObject.java
/** * Insert a new data object into the database. * * @param object The data object to create. * @param owner The data object owning this one. * @param listAttribute The name of the list attribute to which the new * object belongs.//from w w w . j a v a 2 s . c o m */ private void insert(DataObject object, DataObject owner, String listAttribute) { Connection connection = null; PreparedStatement stmt = null; try { JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager"); DataSource dataSource = jdbcManager.getDefaultDataSource(); connection = dataSource.getConnection(); StringBuffer sqlFields = new StringBuffer("id"); StringBuffer sqlValues = new StringBuffer("?"); for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) { Map.Entry attribute = (Map.Entry) i.next(); if (attribute.getValue() instanceof IObjectList) { continue; } sqlFields.append(", " + (String) attribute.getKey()); sqlValues.append(", ?"); } String sql = "insert into " + object.getTypeId() + " (" + sqlFields.toString() + ") values (" + sqlValues.toString() + ")"; stmt = connection.prepareStatement(sql); putAttributesToStatement(object, stmt); stmt.execute(); Log.logVerbose("persist", "JDBCManager", "CREATED " + object.getTypeId() + ":" + object.getUniqueId() + " |" + sql + "|"); stmt.close(); if (owner != null) { sql = "insert into IritgoObjectList (type, id, attribute, elemType, elemId) values (?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql); stmt.setString(1, owner.getTypeId()); stmt.setLong(2, owner.getUniqueId()); stmt.setString(3, listAttribute); stmt.setString(4, object.getTypeId()); stmt.setLong(5, object.getUniqueId()); stmt.execute(); Log.logVerbose("persist", "StoreObject", "CREATED REFRENCE " + owner.getTypeId() + ":" + owner.getUniqueId() + " => " + object.getTypeId() + ":" + object.getUniqueId() + " |" + sql + "|"); } } catch (Exception x) { Log.logDebug("persist", "StoreObject", "Error while creating new database record: " + x); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(connection); } }
From source file:org.camunda.bpm.spring.boot.starter.configuration.impl.custom.EnterLicenseKeyConfigurationTest.java
private void readLicenseKeyFromDataSource(DataSource dataSource, EnterLicenseKeyConfiguration enterLicenseKeyConfiguration) throws SQLException { try (Connection connection = dataSource.getConnection()) { Optional<String> keyFromDatasource = enterLicenseKeyConfiguration .readLicenseKeyFromDatasource(connection); assertThat(keyFromDatasource.get()).isNotNull().startsWith("1234567890").endsWith("Github;unlimited") .doesNotContain("\n"); }/* ww w.j a v a2 s . com*/ }
From source file:org.biblionum.ouvrage.modele.OuvrageModele.java
/** * Java method that deletes a row from the generated sql table * * @param con (open java.sql.Connection) * @param keyId (the primary key to the row) * @throws SQLException// w w w . j a va2s.c o m */ public void deleteFromUtilisateur(DataSource ds, int keyId) throws SQLException { con = ds.getConnection(); String sql = "DELETE FROM ouvrage WHERE id = ?"; PreparedStatement statement = con.prepareStatement(sql); statement.setInt(1, keyId); statement.executeUpdate(); statement.close(); con.close(); }
From source file:net.sf.jdbcwrappers.spring.SpringTest.java
@Test public void test() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "net/sf/jdbcwrappers/spring/beans.xml"); try {/*w ww . j a v a 2 s . c o m*/ DataSource ds = (DataSource) context.getBean("dataSource"); assertTrue(Proxy.getInvocationHandler(ds) instanceof TrimmingDelegateInvocationHandler); // Attempt to get a connection ds.getConnection().close(); } finally { context.close(); } }
From source file:com.tacitknowledge.util.migration.jdbc.DataSourceMigrationContext.java
/** * Returns the database connection to use * * @return the database connection to use * @throws SQLException if an unexpected error occurs *///from w w w . j a v a2s . c o m public Connection getConnection() throws SQLException { if ((connection == null) || connection.isClosed()) { DataSource ds = getDataSource(); if (ds != null) { connection = ds.getConnection(); } else { throw new SQLException("Datasource is null"); } } return connection; }
From source file:sample.config.DataConfiguration.java
@Bean @DependsOn("entityManagerFactory") public ResourceDatabasePopulator initDatabase(DataSource dataSource) throws Exception { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(new ClassPathResource("data.sql")); populator.populate(dataSource.getConnection()); return populator; }
From source file:fll.web.api.TournamentsServlet.java
@Override protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext application = getServletContext(); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try {//from w ww. java2 s.c o m connection = datasource.getConnection(); final ObjectMapper jsonMapper = new ObjectMapper(); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); final String pathInfo = request.getPathInfo(); if (null != pathInfo && pathInfo.length() > 1) { final String tournamentStr = pathInfo.substring(1); int id; if ("current".equals(tournamentStr)) { id = Queries.getCurrentTournament(connection); } else { try { id = Integer.parseInt(tournamentStr); } catch (final NumberFormatException e) { throw new RuntimeException("Error parsing tournament id " + tournamentStr, e); } } final Tournament tournament = Tournament.findTournamentByID(connection, id); if (null != tournament) { jsonMapper.writeValue(writer, tournament); return; } else { throw new RuntimeException("No tournament found with id " + id); } } final Collection<Tournament> tournaments = Tournament.getTournaments(connection); jsonMapper.writeValue(writer, tournaments); } catch (final SQLException e) { throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:com.qagen.osfe.programData.ConfigFileLoader.java
@SuppressWarnings("unchecked") private void loadData(Element root) { try {/*from w w w .j a va 2 s . c o m*/ final List<Element> elements = root.element(ELEMENT.table.name()).element(ELEMENT.rows.name()) .elements(ELEMENT.row.name()); final ApplicationContext context = new ClassPathXmlApplicationContext(APP_CONTEXT); final DataSource dataSource = (DataSource) context.getBean("dataSource"); final Connection con = dataSource.getConnection(); for (Element element : elements) { final String statement = getStatement(element); final PreparedStatement preparedStatement = con.prepareStatement(statement); preparedStatement.execute(); } } catch (SQLException e) { throw new ProgramDataException(e); } }
From source file:azkaban.db.DatabaseOperatorImplTest.java
@Before public void setUp() throws Exception { queryRunner = mock(QueryRunner.class); conn = datasource.getConnection();/*from w ww. j a v a 2s . c om*/ DataSource mockDataSource = mock(datasource.getClass()); when(queryRunner.getDataSource()).thenReturn(mockDataSource); when(mockDataSource.getConnection()).thenReturn(conn); this.dbOperator = new DatabaseOperatorImpl(queryRunner); list.add(index_1); list.add(index_2); // valid query returns correct value when(queryRunner.query("select * from blah where ? = ?", handler, "id", 2)).thenReturn(index_2); // If select an non-existing entry, handler returns 0. when(queryRunner.query("select * from blah where ? = ?", handler, "id", 3)).thenReturn(0); //If typos, throw Exceptions. doThrow(SQLException.class).when(queryRunner).query("sele * from blah where ? = ?", handler, "id", 2); doAnswer(invocation -> { index_1 = 26; return 1; }).when(queryRunner).update("update blah set ? = ?", "1", 26); }
From source file:name.marcelomorales.siqisiqi.bonecp.DataSourceProviderTest.java
@Test public void testOneDatabase() throws Exception { Config config = ConfigFactory.load(); DataSourceProvider dsp = new DataSourceProvider(config); dsp.getBoneCPConfig().setAcquireRetryDelayInMs(2000); DataSource dataSource = dsp.get(); Connection connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); assertEquals("Apache Derby", metaData.getDatabaseProductName()); connection.close();//from www. j a va 2 s . c o m dsp.close(); }