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:net.certifi.audittablegen.AuditTableGenTest.java
/** * This is an example use case scenario// w w w . j a v a 2s . c o m */ @Test public void testUseCase() { //get a dataSource for setting up the test dataBase //the same dataSource will be used to run the application DataSource myDataSource = HsqldbDMR.getRunTimeDataSource(); //set up the database using liquibase try { Database database = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(myDataSource.getConnection())); Liquibase liquibase = new Liquibase("src/test/resources/changesets/changeset-init-config.xml", new FileSystemResourceAccessor(), database); liquibase.update(null); liquibase = new Liquibase("src/test/resources/changesets/changeset-sample-tables.xml", new FileSystemResourceAccessor(), database); liquibase.update(null); } catch (SQLException e) { logger.error("error setting up unit tests", e); } catch (LiquibaseException le) { logger.error("liquibase error", le); } //run the application AuditTableGen atg = new AuditTableGen(myDataSource, "PUBLIC"); atg.updateAuditTables(); //that's it. }
From source file:net.certifi.audittablegen.AuditTableGenTest.java
/** * This is an example use case scenario//from w ww. j a v a 2s .com */ @Test public void testUseCaseAgp() { //get a dataSource for setting up the test dataBase //the same dataSource will be used to run the application DataSource myDataSource = HsqldbDMR.getRunTimeDataSource(); //set up the database using liquibase try { Database database = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(myDataSource.getConnection())); Liquibase liquibase = new Liquibase("src/test/resources/changesets/changeset-init-config.xml", new FileSystemResourceAccessor(), database); liquibase.update(null); liquibase = new Liquibase("src/test/resources/changesets/changeset-sample-tables.xml", new FileSystemResourceAccessor(), database); liquibase.update(null); } catch (SQLException e) { logger.error("error setting up unit tests", e); } catch (LiquibaseException le) { logger.error("liquibase error", le); } //run the application AuditTableGen atg = new AuditTableGen(myDataSource, "PUBLIC"); atg.updateAuditTables(); //that's it. }
From source file:org.accada.epcis.repository.capture.CaptureOperationsBackendSQL.java
/** * {@inheritDoc}//from w w w. jav a2 s . c o m */ public CaptureOperationsSession openSession(final DataSource dataSource) throws SQLException { return new CaptureOperationsSession(dataSource.getConnection()); }
From source file:org.apereo.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDaoTest.java
@Override protected void setUpSchema(final DataSource dataSource) throws SQLException { final Connection con = dataSource.getConnection(); con.prepareStatement(/* w w w . j a v a 2 s.co m*/ "CREATE TABLE user_table " + "(netid VARCHAR, " + "attr_name VARCHAR, " + "attr_val VARCHAR)") .execute(); con.prepareStatement( "INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('awp9', 'name', 'Andrew')") .execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('awp9', 'email', 'andrew.petro@yale.edu')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('awp9', 'shirt_color', 'blue')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('edalquist', 'name', 'Eric')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('edalquist', 'email', 'edalquist@unicon.net')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('edalquist', 'shirt_color', 'blue')").execute(); con.prepareStatement( "INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('atest', 'name', 'Andrew')") .execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('atest', 'email', 'andrew.test@test.net')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('atest', 'shirt_color', 'red')").execute(); con.prepareStatement( "INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('susan', 'name', 'Susan')") .execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('susan', 'email', 'susan.test@test.net')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, attr_name, attr_val) " + "VALUES ('susan', 'shirt_color', null)").execute(); con.close(); }
From source file:org.apache.cayenne.modeler.dialog.db.MergerOptions.java
/** * check database and create the {@link List} of {@link MergerToken}s *//* w w w . j a v a2 s. c o m*/ protected void prepareMigrator() { try { adapter = connectionInfo.makeAdapter(getApplication().getClassLoadingService()); MergerTokenFactory mergerTokenFactory = mergerTokenFactoryProvider.get(adapter); tokens.setMergerTokenFactory(mergerTokenFactory); FiltersConfig filters = FiltersConfig.create(null, defaultSchema, TableFilter.everything(), PatternFilter.INCLUDE_NOTHING); DbMerger merger = DbMerger.builder(mergerTokenFactory).filters(filters).build(); DbLoaderConfiguration config = new DbLoaderConfiguration(); config.setFiltersConfig(filters); DataSource dataSource = connectionInfo.makeDataSource(getApplication().getClassLoadingService()); DataMap dbImport = new DataMap(); try (Connection conn = dataSource.getConnection();) { new DbLoader(conn, adapter, new LoggingDbLoaderDelegate(LogFactory.getLog(DbLoader.class)), new DefaultObjectNameGenerator(NoStemStemmer.getInstance())).load(dbImport, config); } catch (SQLException e) { throw new CayenneRuntimeException("Can't doLoad dataMap from db.", e); } tokens.setTokens(merger.createMergeTokens(dataMap, dbImport)); } catch (Exception ex) { reportError("Error loading adapter", ex); } }
From source file:kenh.xscript.database.elements.Execute.java
@Processing public int process_Source_Var_SqlBean(@Attribute(ATTRIBUTE_SQL) SQLBean sqlBean, @Attribute(ATTRIBUTE_VARIABLE) String var, @Attribute(ATTRIBUTE_REF) DataSource source) throws UnsupportedScriptException { java.sql.Connection conn = null; try {/*from ww w.jav a 2 s. co m*/ conn = source.getConnection(); conn.setAutoCommit(true); return executeSQL(sqlBean, var, conn); } catch (java.sql.SQLException sqle) { throw new UnsupportedScriptException(this, sqle); } finally { if (conn != null) { try { conn.close(); } catch (Exception e_) { } conn = null; } } }
From source file:org.apache.openaz.xacml.std.pip.engines.jdbc.JDBCEngine.java
protected Connection getJNDIConnection() throws PIPException { try {/*from ww w . j av a2 s . co m*/ Context initialContext = new InitialContext(); DataSource datasource = (DataSource) initialContext.lookup(this.jndiDataSource); if (datasource == null) { throw new PIPException(""); } return datasource.getConnection(); } catch (NamingException | SQLException e) { this.logger.error("JNDIException creating Connection", e); throw new PIPException("JNDIException creating Connection", e); } }
From source file:com.alfaariss.oa.engine.authentication.jdbc.JDBCProfile.java
private Vector<IAuthenticationMethod> readMethods(DataSource oDataSource, String sMethodTable) throws AuthenticationException { Vector<IAuthenticationMethod> vMethods = new Vector<IAuthenticationMethod>(); Connection oConnection = null; PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null;/* w w w .ja va 2 s .c o m*/ try { oConnection = oDataSource.getConnection(); StringBuffer sbSelect = new StringBuffer("SELECT * FROM "); sbSelect.append(sMethodTable); 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 AuthenticationException(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:fll.web.admin.UploadSubjectiveData.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final StringBuilder message = new StringBuilder(); final File file = File.createTempFile("fll", null); Connection connection = null; try {/*from ww w. j a v a 2s . c om*/ // must be first to ensure the form parameters are set UploadProcessor.processUpload(request); final FileItem subjectiveFileItem = (FileItem) request.getAttribute("subjectiveFile"); subjectiveFileItem.write(file); final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); saveSubjectiveData(file, Queries.getCurrentTournament(connection), ApplicationAttributes.getChallengeDescription(application), connection, application); message.append("<p id='success'><i>Subjective data uploaded successfully</i></p>"); } catch (final SAXParseException spe) { final String errorMessage = String.format( "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.", spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage()); message.append("<p class='error'>" + errorMessage + "</p>"); LOGGER.error(errorMessage, spe); } catch (final SAXException se) { final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else"; message.append("<p class='error'>" + errorMessage + "</p>"); LOGGER.error(errorMessage, se); } catch (final SQLException sqle) { message.append("<p class='error'>Error saving subjective data into the database: " + sqle.getMessage() + "</p>"); LOGGER.error(sqle, sqle); throw new RuntimeException("Error saving subjective data into the database", sqle); } catch (final ParseException e) { message.append( "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error saving subjective data into the database", e); } catch (final FileUploadException e) { message.append("<p class='error'>Error processing subjective data upload: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error processing subjective data upload", e); } catch (final Exception e) { message.append( "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error saving subjective data into the database", e); } finally { if (!file.delete()) { LOGGER.warn("Unable to delete file " + file.getAbsolutePath() + ", setting to delete on exit"); file.deleteOnExit(); } SQLFunctions.close(connection); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL("index.jsp")); }
From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java
public Connection checkOutJdbcConnection(JdbcConnectionDescriptor jcd) throws LookupException { final DataSource ds = getDataSource(jcd); // Returned DS is never null, exception are logged by getDataSource and gets // re-thrown here since we don't catch them Connection conn;/*from w w w .ja v a 2 s . c om*/ try { conn = ds.getConnection(); } catch (SQLException e) { throw new LookupException("Could not get connection from DBCP DataSource", e); } return conn; }