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.apereo.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDaoTest.java
@Override protected void setUpSchema(final DataSource dataSource) throws SQLException { final Connection con = dataSource.getConnection(); con.prepareStatement("CREATE TABLE user_table " + "(netid VARCHAR, " + "name VARCHAR, " + "email VARCHAR, " + "shirt_color VARCHAR)").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, name, email, shirt_color) " + "VALUES ('awp9', 'Andrew', 'andrew.petro@yale.edu', 'blue')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, name, email, shirt_color) " + "VALUES ('edalquist', 'Eric', 'edalquist@unicon.net', 'blue')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, name, email, shirt_color) " + "VALUES ('atest', 'Andrew', 'andrew.test@test.net', 'red')").execute(); con.prepareStatement("INSERT INTO user_table " + "(netid, name, email, shirt_color) " + "VALUES ('susan', 'Susan', 'susan.test@test.net', null)").execute(); con.close();/*from w w w. j a v a 2s. c o m*/ }
From source file:com.cyclopsgroup.tornado.hibernate.impl.DefaultHibernateService.java
/** * Override method getConnection in class DefaultHibernateHome * * @see com.cyclopsgroup.tornado.hibernate.HibernateService#getConnection(java.lang.String) *//*w w w . j av a2s . co m*/ public synchronized Connection getConnection(String dataSourceName) throws Exception { SessionWrapper wrapper = (SessionWrapper) localSession.get(); if (wrapper == null) { wrapper = new SessionWrapper(); localSession.set(wrapper); } Connection dbcon = wrapper.getConnection(dataSourceName); if (dbcon == null) { DataSource dataSource = dataSourceManager.getDataSource(dataSourceName); dbcon = dataSource.getConnection(); wrapper.setConnection(dataSourceName, dbcon); } return dbcon; }
From source file:nl.b3p.viewer.config.stripersist.DynamicStripersistInitializer.java
@Override public List<String> getPersistenceUnitsToCreate() throws Exception { log.info("Trying to determine persistence unit from JNDI DataSource database"); String persistenceUnit = null; DataSource ds = null; try {// w w w. ja v a 2 s . c om InitialContext ctx = new InitialContext(); ds = (DataSource) ctx.lookup(DATA_SOURCE_NAME); } catch (Exception e) { log.info("No JNDI DataSource found under " + DATA_SOURCE_NAME + ""); } if (ds != null) { try { Connection conn = ds.getConnection(); try { databaseProductName = conn.getMetaData().getDatabaseProductName(); } finally { conn.close(); } if (databaseProductName == null) { throw new Exception("No database product name found!"); } else { persistenceUnit = PU_PREFIX + databaseProductName.toLowerCase(); if (!persistenceUnits.containsKey(persistenceUnit)) { throw new Exception( String.format("No persistence unit \"%s\" found for database product name \"%s\"", persistenceUnit, databaseProductName)); } } } catch (Exception e) { log.error("Error looking up database product name", e); throw e; } } log.info("Found persistence unit: " + persistenceUnit); // If null, use HSQLDB with data directory in java.io.tmpdir or from // environment variable? return Arrays.asList(persistenceUnit); }
From source file:com.p6spy.engine.spy.XADataSourceTest.java
private void cleanData(DataSource dataSource) { Connection connection = null; try {/*from www. j av a 2 s . c o m*/ connection = dataSource.getConnection(); P6TestUtil.execute(connection, "delete from customers where id=50"); } catch (SQLException e) { e.printStackTrace(); Assert.fail(); } finally { try { if (null != connection) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
From source file:jp.co.acroquest.endosnipe.data.db.ConnectionManager.java
/** * ?????<br />/*from w ww. jav a2 s. c o m*/ * * @param dataSource * @param dbName {@link ConnectionWrapper} ???? * @return {@link Connection} * @throws SQLException ??????????? */ protected Connection getConnection(final DataSource dataSource, final String dbName) throws SQLException { Connection conn = dataSource.getConnection(); ConnectionWrapper wrapper = new ConnectionWrapper(conn, dbName); LOGGER.log(DB_CONNECTED, dbName); return wrapper; }
From source file:com.alibaba.druid.benckmark.pool.Case0.java
private void p0(DataSource dataSource, String name) throws SQLException { long startMillis = System.currentTimeMillis(); long startYGC = TestUtil.getYoungGC(); long startFullGC = TestUtil.getFullGC(); for (int i = 0; i < COUNT; ++i) { Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("SELECT 1"); // rs.close(); // stmt.close(); conn.close();//from w w w . jav a 2 s . co m } long millis = System.currentTimeMillis() - startMillis; long ygc = TestUtil.getYoungGC() - startYGC; long fullGC = TestUtil.getFullGC() - startFullGC; System.out.println(name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC); }
From source file:org.craftercms.cstudio.alfresco.activityfeed.CStudioActivityFeedDaoServiceImpl.java
@Override public void initIndexes() { DataSource dataSource = sqlMapper.getDataSource(); Connection connection = null; int oldval = -1; try {/*from w w w . jav a 2s. c o m*/ connection = dataSource.getConnection(); oldval = connection.getTransactionIsolation(); if (oldval != Connection.TRANSACTION_READ_COMMITTED) { connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } List<HashMap> checkTable = sqlMapper.queryForList(STATEMENT_CHECK_TABLE_EXISTS); if (checkTable == null || checkTable.size() < 1) { ScriptRunner scriptRunner = new ScriptRunner(connection, false, true); scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath)); } connection.commit(); List<TableIndexCheckTO> indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_USER_IDX); if (indexCheckResult == null || indexCheckResult.size() < 1) { sqlMapper.insert(STATEMENT_ADD_USER_IDX); } indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_SITE_IDX); if (indexCheckResult == null || indexCheckResult.size() < 1) { sqlMapper.insert(STATEMENT_ADD_SITE_IDX); } indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_CONTENT_IDX); if (indexCheckResult == null || indexCheckResult.size() < 1) { sqlMapper.insert(STATEMENT_ADD_CONTENT_IDX); } connection.commit(); if (oldval != -1) { connection.setTransactionIsolation(oldval); } } catch (SQLException e) { LOGGER.error("Error while initializing CStudio Activity DB indexes.", e); } catch (IOException e) { LOGGER.error("Error while initializing CStudio Activity DB indexes.", e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { } connection = null; } } }
From source file:net.webpasswordsafe.server.report.JasperReportServlet.java
private void processRequest(HttpServletRequest req, HttpServletResponse res) { OutputStream outputStream = null; Connection jdbcConnection = null; try {//w w w . ja va2 s . c om String reportName = req.getParameter(Constants.NAME); String type = req.getParameter(Constants.TYPE).trim().toLowerCase(); String locale = req.getParameter("locale"); setNoCache(res); if (isAuthorizedReport(req, reportName)) { JasperDesign jasperDesign = JRXmlLoader.load(getServletConfig().getServletContext() .getResourceAsStream("/WEB-INF/reports/" + reportName + ".jrxml")); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); jasperReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL); Map<String, Object> parameters = new HashMap<String, Object>(); if (null != locale) parameters.put(JRParameter.REPORT_LOCALE, new Locale(locale)); parameters.put(Constants.SESSION_KEY_USERNAME, (String) req.getSession().getAttribute(Constants.SESSION_KEY_USERNAME)); parameters.put(Constants.Function.BYPASS_PASSWORD_PERMISSIONS.name(), isAuthorized(req, Constants.Function.BYPASS_PASSWORD_PERMISSIONS.name()) ? "1" : "0"); ReportConfig reportConfig = (ReportConfig) WebApplicationContextUtils .getWebApplicationContext(getServletContext()).getBean("reportConfig"); @SuppressWarnings("unchecked") Enumeration<String> e = req.getParameterNames(); while (e.hasMoreElements()) { String param = e.nextElement(); if (param.startsWith(Constants.REPORT_PARAM_PREFIX)) { String pKey = param.substring(Constants.REPORT_PARAM_PREFIX.length()); String pValue = Utils.safeString(req.getParameter(param)); if (reportConfig.isDateParam(reportName, pKey)) { parameters.put(pKey, convertToDateTime(pValue)); } else { parameters.put(pKey, pValue); } } } encryptorRef.set((Encryptor) WebApplicationContextUtils .getWebApplicationContext(getServletContext()).getBean("encryptor")); DataSource dataSource = (DataSource) WebApplicationContextUtils .getWebApplicationContext(getServletContext()).getBean("dataSource"); jdbcConnection = dataSource.getConnection(); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jdbcConnection); JRExporter exporter = null; if (type.equals(Constants.REPORT_TYPE_PDF)) { res.setContentType("application/pdf"); exporter = new JRPdfExporter(); } else if (type.equals("rtf")) { res.setContentType("application/rtf"); exporter = new JRRtfExporter(); } else if (type.equals(Constants.REPORT_TYPE_CSV)) { res.setContentType("text/csv"); exporter = new JRCsvExporter(); } else if (type.equals("xml")) { res.setContentType("text/xml"); exporter = new JRXmlExporter(); } if (exporter != null) { DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); res.setHeader("Content-Disposition", "attachment; filename=" + reportName + dateFormat.format(System.currentTimeMillis()) + "." + type); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); outputStream = res.getOutputStream(); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); exporter.exportReport(); } else { throw new RuntimeException("Invalid report type: " + type); } } } catch (Exception e) { LOG.error("JasperReportServlet Error " + e.getMessage(), e); } finally { // close the output stream if (outputStream != null) { try { outputStream.close(); } catch (IOException io) { LOG.error("JasperReportServlet Error " + io.getMessage(), io); } } // close the db connection if (jdbcConnection != null) { try { jdbcConnection.close(); } catch (SQLException sql) { LOG.error("JasperReportServlet Error " + sql.getMessage(), sql); } finally { jdbcConnection = null; } } } }
From source file:biz.taoconsulting.dominodav.resource.DAVResourceJDBC.java
/** * /**/* www . j a va 2 s . c om*/ * * @see biz.taoconsulting.dominodav.resource.DAVAbstractResource#getStream() */ public InputStream getStream() { Connection conn = null; Statement stmt = null; InputStream blobStream = null; try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) // THe internal address of a JDBC source is the data source envCtx.lookup(this.repositoryMeta.getInternalAddress()); conn = ds.getConnection(); stmt = conn.createStatement(); // XXX: THat is plain wrong -- need to rework the JDBC data source // query ResultSet rs = stmt.executeQuery( "select f.fil_blocksize,f.fil_contents_blob from ibkuis_pp_files f where f.fil_id=" + this.getDBFileID()); if (rs.next()) { Blob blob = rs.getBlob(2); blobStream = blob.getBinaryStream(); } } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { /** Exception handling **/ } } return blobStream; }