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:fll.web.DoLogin.java
/** * Does the work of login. Exists as a separate method so that it can be * called from {@link fll.web.admin.CreateUser} *///from w w w . j a va 2 s . c om public static void doLogin(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 { connection = datasource.getConnection(); // check for authentication table if (Queries.isAuthenticationEmpty(connection)) { LOGGER.warn("No authentication information in the database"); session.setAttribute(SessionAttributes.MESSAGE, "<p class='error'>No authentication information in the database - see administrator</p>"); response.sendRedirect(response.encodeRedirectURL("login.jsp")); return; } // compute hash final String user = request.getParameter("user"); final String pass = request.getParameter("pass"); if (null == user || user.isEmpty() || null == pass || pass.isEmpty()) { LOGGER.warn("Form fields missing"); session.setAttribute(SessionAttributes.MESSAGE, "<p class='error'>You must fill out all fields in the form.</p>"); response.sendRedirect(response.encodeRedirectURL("login.jsp")); return; } final String hashedPass = DigestUtils.md5Hex(pass); // compare login information if (LOGGER.isTraceEnabled()) { LOGGER.trace("Checking user: " + user + " hashedPass: " + hashedPass); } final Map<String, String> authInfo = Queries.getAuthInfo(connection); for (final Map.Entry<String, String> entry : authInfo.entrySet()) { if (user.equals(entry.getKey()) && hashedPass.equals(entry.getValue())) { // clear out old login cookies first CookieUtils.clearLoginCookies(application, request, response); final String magicKey = String.valueOf(System.currentTimeMillis()); Queries.addValidLogin(connection, user, magicKey); CookieUtils.setLoginCookie(response, magicKey); String redirect = SessionAttributes.getRedirectURL(session); if (null == redirect) { redirect = "index.jsp"; } response.sendRedirect(response.encodeRedirectURL(redirect)); return; } else { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Didn't match user: " + entry.getKey() + " pass: " + entry.getValue()); } } } LOGGER.warn("Incorrect login credentials user: " + user); session.setAttribute(SessionAttributes.MESSAGE, "<p class='error'>Incorrect login information provided</p>"); response.sendRedirect(response.encodeRedirectURL("login.jsp")); return; } catch (final SQLException e) { throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:com.github.dactiv.common.unit.Fixtures.java
/** * ,excludeTables.disable.// w w w . j a v a2s . c om * @throws SQLException */ public static void deleteAllTable(DataSource h2DataSource, String... excludeTables) throws SQLException { List<String> tableNames = new ArrayList<String>(); try { ResultSet rs = h2DataSource.getConnection().getMetaData().getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); if (Arrays.binarySearch(excludeTables, tableName) < 0) { tableNames.add(tableName); } } deleteTable(h2DataSource, tableNames.toArray(new String[tableNames.size()])); } catch (SQLException e) { throw e; } }
From source file:com.pactera.edg.am.metamanager.extractor.util.GenSqlUtil.java
/** * ????Oracle?Teradata?SQL/*from w ww. jav a 2 s. c om*/ * * @return * @throws IOException * ????Bean * @throws SQLException * ????? */ private static Map<String, String> findDatabaseSQL() { Connection conn = null; String databaseName = instance.databaseName; try { if (databaseName == null) { DataSource dataSource = ExtractorContextLoader.getDataSource(); conn = dataSource.getConnection(); DatabaseMetaData meta = conn.getMetaData(); instance.databaseName = meta.getDatabaseProductName(); databaseName = instance.databaseName; } String location = instance.getLocation(databaseName); if (location == null) { throw new SQLFileNotLoadException("???" + databaseName + "SQLspring/context-service.xmlGenSqlUtil"); } if (instance.sqlHolder.get(databaseName) == null) { Map<String, String> sqls = readSQL(location); instance.sqlHolder.put(databaseName, sqls); } return instance.sqlHolder.get(databaseName); } catch (SQLException e) { databaseName = (databaseName == null) ? "Unkown" : databaseName; String s = "??[" + databaseName + "]SQL"; log.error(s, e); throw new SQLFileNotLoadException(s, e); } catch (IOException e) { databaseName = (databaseName == null) ? "Unkown" : databaseName; String s = "??[" + databaseName + "]SQL"; log.error(s, e); throw new SQLFileNotLoadException(s, e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
From source file:com.dangdang.ddframe.rdb.sharding.example.jdbc.Main.java
private static void printHintSimpleSelect(final DataSource dataSource) throws SQLException { String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id"; try (HintManager hintManager = HintManager.getInstance(); Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { hintManager.addDatabaseShardingValue("t_order", "user_id", 10); hintManager.addTableShardingValue("t_order", "order_id", 1001); try (ResultSet rs = preparedStatement.executeQuery()) { while (rs.next()) { System.out.println(rs.getInt(1)); System.out.println(rs.getInt(2)); System.out.println(rs.getInt(3)); }/* w w w .j a v a2s . c o m*/ } } }
From source file:org.springside.modules.test.data.H2Fixtures.java
/** * ,excludeTables.disable./*from w w w . j a v a 2s .c o m*/ */ public static void deleteAllTable(DataSource dataSource, String... excludeTables) { List<String> tableNames = new ArrayList<String>(); ResultSet rs = null; try { rs = dataSource.getConnection().getMetaData().getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); if (Arrays.binarySearch(excludeTables, tableName) < 0) { tableNames.add(tableName); } } deleteTable(dataSource, tableNames.toArray(new String[tableNames.size()])); } catch (SQLException e) { Exceptions.unchecked(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
From source file:edu.mayo.cts2.uriresolver.dao.DAOUtiltities.java
public static boolean checkTablesExist(DataSource ds) { Connection con = null;//from w w w.j a v a 2s .c o m boolean tablesExist = true; try { con = ds.getConnection(); DatabaseMetaData metaData = con.getMetaData(); for (int i = 0; i < TABLENAMES.length; i++) { if (!tableExists(metaData, TABLENAMES[i])) { tablesExist = false; logger.error("Database is missing table: " + TABLENAMES[i]); } } con.close(); } catch (SQLException e) { logger.error("Unknown error while checking tables exist, check all connection values"); return false; } finally { try { if (con != null) { con.close(); } } catch (SQLException e) { logger.error("Error while closing data source connection object: " + e.getMessage()); return false; } } return tablesExist; }
From source file:org.biblionum.commentaire.modele.CommentaireOuvragesModele.java
public static int insertIntoOuvragetype(DataSource ds, String contenu_commentaire, int utilisateurid, int ouvrageid) throws SQLException { Connection con = ds.getConnection(); int generatedId = -1; String sql = "INSERT INTO ouvragetype (contenu_commentaire, utilisateurid, ouvrageid)" + "VALUES (?, ?, ?)"; PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, contenu_commentaire); statement.setInt(2, utilisateurid);/*from w w w.ja v a2s.com*/ statement.setInt(3, ouvrageid); 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:org.biblionum.ouvrage.modele.OuvrageTypeModele.java
public static ArrayList<OuvrageType> getTypeOuvrage(DataSource ds) { ArrayList<OuvrageType> list = new ArrayList<OuvrageType>(); PreparedStatement stm;/* www. ja v a 2 s.c om*/ String requete; ResultSet rs; try { con = ds.getConnection(); stm = con.prepareStatement("SELECT * FROM ouvragetype"); rs = stm.executeQuery(); BeanProcessor bp = new BeanProcessor(); list = (ArrayList) bp.toBeanList(rs, OuvrageType.class); con.close(); rs.close(); } catch (SQLException ex) { Logger.getLogger(UtilisateurModele.class.getName()).log(Level.SEVERE, null, ex); } return list; }
From source file:com.github.dactiv.common.unit.Fixtures.java
/** * XML?H2?Operation./*from w ww .ja va2s . co m*/ * * @param xmlFilePaths ?Spring Resource?. */ private static void execute(DatabaseOperation operation, DataSource dataSource, String... xmlFilePaths) throws DatabaseUnitException, SQLException { //?HardCodeH2Connetion IDatabaseConnection connection = new H2Connection(dataSource.getConnection(), null); for (String xmlPath : xmlFilePaths) { try { InputStream input = resourceLoader.getResource(xmlPath).getInputStream(); IDataSet dataSet = new FlatXmlDataSetBuilder().setColumnSensing(true).build(input); operation.execute(connection, dataSet); } catch (IOException e) { logger.warn(xmlPath + " file not found", e); } finally { connection.close(); } } }
From source file:edu.psu.citeseerx.disambiguation.CsxDisambiguation.java
public static void createBlocks(ListableBeanFactory factory) throws Exception { String dirpath = "data/csauthors/blocks"; DataSource dataSource = (DataSource) factory.getBean("csxDataSource"); PreparedStatement st = dataSource.getConnection().prepareStatement("SELECT * FROM authors", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); st.setFetchSize(Integer.MIN_VALUE); ResultSet rs = st.executeQuery(); initDirectories(dirpath);// ww w . j a va 2 s . com CsxAuthorFilter filter = (CsxAuthorFilter) factory.getBean("csxAuthorFilter"); //new CsxAuthorFilter("data/csauthors/name_stopwords.txt"); BufferedWriter skip = new BufferedWriter(new FileWriter("skip.txt")); int count = 0; Map<String, List<String>> blocks = new HashMap<String, List<String>>(); while (rs.next()) { count++; if ((count % 10000) == 0) System.out.println("#Auth:" + count); String rsname = rs.getString("name"); if (!filter.isStopword(rsname) && !filter.isInstitute(rsname) && !filter.isPosition(rsname)) { CsxAuthor auth = new CsxAuthor(rs); String lname = auth.getLastName(); String fname = auth.getFirstName(); if ((lname != null) && (fname != null)) { if ((lname.charAt(0) >= 'A') && (lname.charAt(0) <= 'Z') && (fname.charAt(0) >= 'A') && (fname.charAt(0) <= 'Z') && !((fname.length() == 1) && (lname.length() == 1)) && !(lname.matches(".*/.*"))) { String l_init = lname.substring(0, 1).toUpperCase(); String f_init = fname.substring(0, 1).toUpperCase(); String key = l_init + f_init + "/" + lname.toLowerCase() + "_" + f_init.toLowerCase() + ".txt"; List<String> list; if (!blocks.containsKey(key)) { list = new ArrayList<String>(); blocks.put(key, list); } else { list = blocks.get(key); } list.add(auth.getId()); } else { skip.write("SKIP: [" + rsname + "]\n"); } } } } skip.close(); for (String key : blocks.keySet()) { List<String> aids = blocks.get(key); // only care about cluster with more than one document if (aids.size() > 1) { BufferedWriter out = new BufferedWriter(new FileWriter(dirpath + "/" + key)); for (String aid : aids) { out.write(aid + "\n"); } out.close(); } } }