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:DatabaseInfo.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;/* w w w.j a v a2s. c o m*/ Connection connection = null; Statement statement; ResultSet rs; outResponse.setContentType("text/html"); out = outResponse.getWriter(); try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); DatabaseMetaData md = connection.getMetaData(); statement = connection.createStatement(); out.println("<HTML><HEAD><TITLE>Database Server Information</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>General Source Information</H1>"); out.println("getURL() - " + md.getURL() + "<BR>"); out.println("getUserName() - " + md.getUserName() + "<BR>"); out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion() + "<BR>"); out.println("getDriverMajorVersion - " + md.getDriverMajorVersion() + "<BR>"); out.println("getDriverMinorVersion - " + md.getDriverMinorVersion() + "<BR>"); out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh() + "<BR>"); out.println("<H1>Feature Support</H1>"); out.println("supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>"); out.println("supportsBatchUpdates - " + md.supportsBatchUpdates() + "<BR>"); out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames() + "<BR>"); out.println("supportsPositionedDelete - " + md.supportsPositionedDelete() + "<BR>"); out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins() + "<BR>"); out.println("supportsStoredProcedures - " + md.supportsStoredProcedures() + "<BR>"); out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers() + "<BR>"); out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL() + "<BR>"); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>"); out.println("<H1>Data Source Limits</H1>"); out.println("getMaxRowSize - " + md.getMaxRowSize() + "<BR>"); out.println("getMaxStatementLength - " + md.getMaxStatementLength() + "<BR>"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>"); out.println("getMaxConnections - " + md.getMaxConnections() + "<BR>"); out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength() + "<BR>"); out.println("<H1>SQL Object Available</H1>"); out.println("getTableTypes()<BR><UL>"); rs = md.getTableTypes(); while (rs.next()) { out.println("<LI>" + rs.getString(1)); } out.println("</UL>"); out.println("getTables()<BR><UL>"); rs = md.getTables("accounts", "", "%", new String[0]); while (rs.next()) { out.println("<LI>" + rs.getString("TABLE_NAME")); } out.println("</UL>"); out.println("<H1>Transaction Support</H1>"); out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation() + "<BR>"); out.println( "dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions() + "<BR>"); out.println("<H1>General Source Information</H1>"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>"); out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable() + "<BR>"); out.println("getTimeDateFunctions - " + md.getTimeDateFunctions() + "<BR>"); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>"); out.println("getTypeInfo()<BR><UL>"); rs = md.getTypeInfo(); while (rs.next()) { out.println("<LI>" + rs.getString(1)); } out.println("</UL>"); out.println("</BODY></HTML>"); } catch (Exception e) { e.printStackTrace(); } }
From source file:Controllers.ReportController.java
public int fetchDepartmentId(int accountId) { int departmentId = 0; try {//from w w w .j a v a 2s . co m Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource"); connection = ds.getConnection(); PreparedStatement pstmt = connection .prepareStatement("SELECT * FROM doctors" + " WHERE accountId = ?;"); pstmt.setInt(1, accountId); ResultSet resultSet = pstmt.executeQuery(); List<Doctor> appointmentsList = new ArrayList<Doctor>(); while (resultSet.next()) { departmentId = resultSet.getInt("departmentId"); } pstmt.close(); } catch (NamingException ex) { Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex); } return departmentId; }
From source file:org.apache.jackrabbit.core.util.db.ConnectionFactoryTest.java
public void testUnwrap() throws Exception { DataSource ds = connectionFactory.getDataSource(DRIVER, DERBY_URL, "user", "password"); Connection wrappedCon = ds.getConnection(); assertNotNull(wrappedCon);/*from www . ja v a2 s. c om*/ Connection con = ConnectionFactory.unwrap(wrappedCon); assertTrue(con instanceof EngineConnection); }
From source file:org.apache.tiles.test.init.InitContextListener.java
/** * Execute SQL commands.//from w ww . j a v a 2 s . com * * @param dataSource The data source to use. * @param commands The commands to execute. */ private void executeCommands(DataSource dataSource, String[] commands) { Connection conn = null; Statement stmt = null; try { conn = dataSource.getConnection(); for (int i = 0; i < commands.length; i++) { stmt = conn.createStatement(); stmt.executeUpdate(commands[i]); } conn.commit(); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e1) { log.error("Error during rollback", e); } throw new TilesTestRuntimeException("Error during execution of SQL commands", e); } finally { try { if (conn != null) { conn.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { log.error("Error during closing resources", e); } } }
From source file:fll.web.admin.ChangePassword.java
@Override protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try {/*from w w w.jav a 2s . c o m*/ connection = datasource.getConnection(); final Collection<String> loginKeys = CookieUtils.findLoginKey(request); final String user = Queries.checkValidLogin(connection, loginKeys); final String passwordHash = Queries.getHashedPassword(connection, user); final String oldPassword = request.getParameter("old_password"); final String hashedOldPass = DigestUtils.md5Hex(oldPassword); if (!ComparisonUtils.safeEquals(passwordHash, hashedOldPass)) { session.setAttribute(SessionAttributes.MESSAGE, "<p class='error'>Old password is incorrect</p>"); response.sendRedirect(response.encodeRedirectURL("changePassword.jsp")); return; } final String newPassword = request.getParameter("pass"); final String newPasswordCheck = request.getParameter("pass_check"); if (!ComparisonUtils.safeEquals(newPassword, newPasswordCheck)) { session.setAttribute(SessionAttributes.MESSAGE, "<p class='error'>New passwords don't match</p>"); response.sendRedirect(response.encodeRedirectURL("changePassword.jsp")); return; } final String newPasswordHash = DigestUtils.md5Hex(newPassword); // invalidate all login keys now that the password has changed Queries.changePassword(connection, user, newPasswordHash); Queries.removeValidLoginByUser(connection, user); session.setAttribute(SessionAttributes.MESSAGE, "<p id='success'>Password changed for '" + user + "', you will now need to login again.</p>"); response.sendRedirect(response.encodeRedirectURL("changePassword.jsp")); } catch (final SQLException e) { throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
/** * Initialize implementation with configuration. * /*from w w w.j ava 2 s . c o m*/ * @param configuration * configuration properties * @param initializeStore * truncate and initialize persistent store */ public static void initialize(Configuration configuration, boolean initializeStore) { try { // configuration cacheSize = configuration.getString(PERSISTENCE_MANAGER_CACHE_SIZE_PROPERTY_NAME); dbType = configuration.getString(PERSISTENCE_MANAGER_DB_TYPE_PROPERTY_NAME); dictionaryType = ((dbType != null) ? DB_TYPE_TO_JPA_DICTIONARY_MAP.get(dbType) : null); if ((dbType != null) && (dictionaryType == null)) { throw new IllegalArgumentException("Unsupported database type: " + dbType); } // initialize persistent store if (initializeStore && (dbType != null)) { // get datasource connection Context initialContext = new InitialContext(); DataSource dataSource = (DataSource) initialContext .lookup(WIDGET_DATABASE_JNDI_DATASOURCE_FULL_NAME); Connection connection = dataSource.getConnection(); connection.setAutoCommit(true); // execute initialization scripts String sqlScriptResource = dbType + "-wookie-schema.sql"; InputStream sqlStream = JPAPersistenceManager.class.getResourceAsStream(sqlScriptResource); if (sqlStream == null) { throw new IllegalArgumentException( "Unsupported persistent store initialization script: " + sqlScriptResource); } SQLScriptReader reader = new SQLScriptReader(sqlStream); int statementCount = 0; int statementErrorCount = 0; for (;;) { String scriptStatement = reader.readSQLStatement(); if (scriptStatement != null) { Statement statement = connection.createStatement(); statementCount++; try { statement.execute(scriptStatement); } catch (SQLException sqle) { statementErrorCount++; } } else { break; } } logger.info("Persistent store initialized from " + sqlScriptResource + ", (" + statementCount + " statements, " + statementErrorCount + " errors)"); // close datasource connection connection.close(); } // initialize entity manager factory Properties persistenceProperties = new Properties(); InputStream propertiesStream = JPAPersistenceManager.class .getResourceAsStream("persistence.properties"); if (propertiesStream == null) { throw new IllegalArgumentException("Unable to load configuration: persistence.properties"); } persistenceProperties.load(propertiesStream); if (cacheSize != null) { int dataCacheSize = Integer.parseInt(cacheSize); persistenceProperties.setProperty("openjpa.DataCache", "true(CacheSize=" + dataCacheSize + ",SoftReferenceSize=0)"); int queryCacheSize = Integer.parseInt(cacheSize) / 10; persistenceProperties.setProperty("openjpa.QueryCache", "CacheSize=" + queryCacheSize + ",SoftReferenceSize=0"); } if (dictionaryType != null) { persistenceProperties.setProperty("openjpa.jdbc.DBDictionary", dictionaryType); } EntityManagerFactory factory = Persistence.createEntityManagerFactory("wookie", persistenceProperties); entityManagerFactory = OpenJPAPersistence.cast(factory); logger.info("Initialized"); } catch (Exception e) { throw new RuntimeException("Unable to initialize 1: " + e, e); } }
From source file:fll.web.report.finalist.StoreFinalistSchedule.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 . ja v a2 s.c om final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final int tournament = Queries.getCurrentTournament(connection); // get parameters final String schedDataStr = request.getParameter("sched_data"); if (null == schedDataStr || "".equals(schedDataStr)) { throw new FLLRuntimeException("Parameter 'sched_data' cannot be null"); } final String categoryDataStr = request.getParameter("category_data"); if (null == categoryDataStr || "".equals(categoryDataStr)) { throw new FLLRuntimeException("Parameter 'category_data' cannot be null"); } final String division = request.getParameter("division_data"); if (null == division || "".equals(division)) { throw new FLLRuntimeException("Parameter 'division_data' cannot be null"); } 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<FinalistDBRow> rows = jsonMapper.readValue(schedDataStr, FinalistScheduleTypeInformation.INSTANCE); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Sched Data has " + rows.size() + " rows"); for (final FinalistDBRow row : rows) { LOGGER.trace("row category: " + row.getCategoryName() + " time: " + row.getTime() + " team: " + row.getTeamNumber()); } } final Collection<FinalistCategory> categories = jsonMapper.readValue(categoryDataStr, FinalistCategoriesTypeInformation.INSTANCE); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Category Data has " + rows.size() + " rows"); } final FinalistSchedule schedule = new FinalistSchedule(tournament, division, categories, rows); schedule.store(connection); final Collection<NonNumericNominees> nominees = jsonMapper.readValue(nomineesStr, NonNumericNomineesTypeInformation.INSTANCE); for (final NonNumericNominees nominee : nominees) { nominee.store(connection, tournament); } message.append("<p id='success'>Finalist schedule saved to the database</p>"); } catch (final SQLException e) { message.append("<p class='error'>Error saving finalist schedule 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("schedule-saved.jsp")); }
From source file:com.gs.obevo.db.scenariotests.MetadataGroupTest.java
@Before public void setup() throws Exception { DataSource ds = JdbcDataSourceFactory.createFromJdbcUrl(org.h2.Driver.class, H2JdbcDataSourceFactory.getUrl("MetadataGroup", false), new Credential("sa", "")); JdbcHelper jdbc = new JdbcHelper(); this.conn = ds.getConnection(); // clean up from previous tests if not shut down cleanly jdbc.update(conn, "DROP ALL objects DELETE files"); }
From source file:org.biblionum.authentification.modele.UtilisateurModele.java
/** * verifier si l'utilisateur existe// ww w.j ava2 s . com * * @param pseudo */ public boolean userExist(String pseudo, DataSource ds) { boolean exist = false; try { con = ds.getConnection(); PreparedStatement sql = con.prepareStatement("SELECT id FROM utilisateur WHERE pseudo=?"); sql.setString(1, pseudo); ResultSet rs = sql.executeQuery(); while (rs.next()) { exist = true; } rs.close(); con.close(); } catch (SQLException ex) { Logger.getLogger(UtilisateurModele.class.getName()).log(Level.SEVERE, null, ex); } return exist; }
From source file:com.netspective.axiom.connection.BasicConnectionProviderEntry.java
public void init(String dataSourceId, DataSource dataSource) { try {//from w w w .j a v a 2 s. c om this.dataSource = dataSource; init(dataSourceId, dataSource.getConnection()); } catch (SQLException e) { this.dataSourceId = dataSourceId; exception = e; log.error("SQL Exception while obtaining connection", e); } }