List of usage examples for java.sql ResultSet getLong
long getLong(String columnLabel) throws SQLException;
ResultSet
object as a long
in the Java programming language. From source file:com.keybox.manage.db.PublicKeyDB.java
/** * returns public keys based on sort order defined * * @param sortedSet object that defines sort order * @param userId user id/*from ww w .j a va2 s. c o m*/ * @return sorted script list */ public static SortedSet getPublicKeySet(SortedSet sortedSet, Long userId) { ArrayList<PublicKey> publicKeysList = new ArrayList<>(); String orderBy = ""; if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) { orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection(); } String sql = "select * from public_keys where user_id = ? and enabled=true " + orderBy; Connection con = null; try { con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement(sql); stmt.setLong(1, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { PublicKey publicKey = new PublicKey(); publicKey.setId(rs.getLong("id")); publicKey.setKeyNm(rs.getString(KEY_NM)); publicKey.setPublicKey(rs.getString(PUBLIC_KEY)); publicKey.setProfile(ProfileDB.getProfile(con, rs.getLong(PROFILE_ID))); publicKey.setType(SSHUtil.getKeyType(publicKey.getPublicKey())); publicKey.setFingerprint(SSHUtil.getFingerprint(publicKey.getPublicKey())); publicKey.setCreateDt(rs.getTimestamp(CREATE_DT)); publicKeysList.add(publicKey); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); } catch (Exception e) { log.error(e.toString(), e); } DBUtils.closeConn(con); sortedSet.setItemList(publicKeysList); return sortedSet; }
From source file:com.flexive.core.security.FxDBAuthentication.java
/** * @param username the username// www. j a va 2 s. c o m * @param password the password * @param currentTicket the UserTicket requesting the password match * @param ds thedatasource * @return returns true if the login and password match * @throws FxDbException on db errors * @throws FxLoginFailedException on authentication errors */ public static boolean checkLogin(String username, String password, UserTicket currentTicket, DataSource ds) throws FxDbException, FxLoginFailedException { FxContext inf = FxContext.get(); // Avoid null pointer exceptions if (password == null) password = ""; if (username == null) username = ""; String curSql; PreparedStatement ps = null; Connection con = null; try { // Obtain a database connection con = ds.getConnection(); // 1 2 3 curSql = "SELECT a.ID,a.USERNAME,a.PASSWORD " + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN " + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM " + TBL_ACCOUNT_DETAILS + " WHERE APPLICATION=?) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)"; ps = con.prepareStatement(curSql); ps.setString(1, inf.getApplicationId()); ps.setString(2, username); final ResultSet rs = ps.executeQuery(); // Anything found if (rs == null || !rs.next()) throw new FxLoginFailedException("Invalid user or password", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); // check if the hashed password matches the hash stored in the database final long id = rs.getLong(1); final String dbUserName = rs.getString(2); final String hashedPass = rs.getString(3); // current user authorised to perform the check (ticket user id matches db user id?) if (id != currentTicket.getUserId() && !currentTicket.isGlobalSupervisor()) throw new FxLoginFailedException("User not authorized to perform login check", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); return FxSharedUtils.hashPassword(id, dbUserName, password).equals(hashedPass) // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name || ("SUPERVISOR".equals(username) && FxSharedUtils.hashPassword(id, "supervisor", password).equals(hashedPass)); } catch (SQLException exc) { throw new FxDbException("Database error: " + exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR); } finally { Database.closeObjects(FxDBAuthentication.class, con, ps); } }
From source file:com.tethrnet.manage.db.PublicKeyDB.java
/** * returns public keys based on sort order defined * * @param sortedSet object that defines sort order * @return sorted script list//from w ww .j av a 2s .c om */ public static SortedSet getPublicKeySet(SortedSet sortedSet) { ArrayList<PublicKey> publicKeysList = new ArrayList<PublicKey>(); String orderBy = ""; if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) { orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection(); } String sql = "select p.*, u.username from public_keys p, users u where u.id=p.user_id "; sql += StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER_ID)) ? " and p.user_id=? " : ""; sql += StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_PROFILE_ID)) ? " and p.profile_id=? " : ""; sql += StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_ENABLED)) ? " and p.enabled=? " : " and p.enabled=true"; sql = sql + orderBy; Connection con = null; try { con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement(sql); int i = 1; //set filters in prepared statement if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER_ID))) { stmt.setLong(i++, Long.valueOf(sortedSet.getFilterMap().get(FILTER_BY_USER_ID))); } if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_PROFILE_ID))) { stmt.setLong(i++, Long.valueOf(sortedSet.getFilterMap().get(FILTER_BY_PROFILE_ID))); } if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_ENABLED))) { stmt.setBoolean(i++, Boolean.valueOf(sortedSet.getFilterMap().get(FILTER_BY_ENABLED))); } ResultSet rs = stmt.executeQuery(); while (rs.next()) { PublicKey publicKey = new PublicKey(); publicKey.setId(rs.getLong("id")); publicKey.setKeyNm(rs.getString("key_nm")); publicKey.setPublicKey(rs.getString("public_key")); publicKey.setProfile(ProfileDB.getProfile(con, rs.getLong("profile_id"))); publicKey.setType(SSHUtil.getKeyType(publicKey.getPublicKey())); publicKey.setFingerprint(SSHUtil.getFingerprint(publicKey.getPublicKey())); publicKey.setCreateDt(rs.getTimestamp("create_dt")); publicKey.setUsername(rs.getString("username")); publicKey.setUserId(rs.getLong("user_id")); publicKey.setEnabled(rs.getBoolean("enabled")); publicKeysList.add(publicKey); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); } catch (Exception e) { log.error(e.toString(), e); } DBUtils.closeConn(con); sortedSet.setItemList(publicKeysList); return sortedSet; }
From source file:com.keybox.manage.db.PublicKeyDB.java
/** * returns public keys based on sort order defined * * @param sortedSet object that defines sort order * @return sorted script list/*w w w.j a v a 2 s . c o m*/ */ public static SortedSet getPublicKeySet(SortedSet sortedSet) { ArrayList<PublicKey> publicKeysList = new ArrayList<>(); String orderBy = ""; if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) { orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection(); } String sql = "select p.*, u.username from public_keys p, users u where u.id=p.user_id "; sql += StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER_ID)) ? " and p.user_id=? " : ""; sql += StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_PROFILE_ID)) ? " and p.profile_id=? " : ""; sql += StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_ENABLED)) ? " and p.enabled=? " : " and p.enabled=true"; sql = sql + orderBy; Connection con = null; try { con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement(sql); int i = 1; //set filters in prepared statement if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER_ID))) { stmt.setLong(i++, Long.valueOf(sortedSet.getFilterMap().get(FILTER_BY_USER_ID))); } if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_PROFILE_ID))) { stmt.setLong(i++, Long.valueOf(sortedSet.getFilterMap().get(FILTER_BY_PROFILE_ID))); } if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_ENABLED))) { stmt.setBoolean(i, Boolean.valueOf(sortedSet.getFilterMap().get(FILTER_BY_ENABLED))); } ResultSet rs = stmt.executeQuery(); while (rs.next()) { PublicKey publicKey = new PublicKey(); publicKey.setId(rs.getLong("id")); publicKey.setKeyNm(rs.getString(KEY_NM)); publicKey.setPublicKey(rs.getString(PUBLIC_KEY)); publicKey.setProfile(ProfileDB.getProfile(con, rs.getLong(PROFILE_ID))); publicKey.setType(SSHUtil.getKeyType(publicKey.getPublicKey())); publicKey.setFingerprint(SSHUtil.getFingerprint(publicKey.getPublicKey())); publicKey.setCreateDt(rs.getTimestamp(CREATE_DT)); publicKey.setUsername(rs.getString("username")); publicKey.setUserId(rs.getLong("user_id")); publicKey.setEnabled(rs.getBoolean("enabled")); publicKeysList.add(publicKey); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); } catch (Exception e) { log.error(e.toString(), e); } DBUtils.closeConn(con); sortedSet.setItemList(publicKeysList); return sortedSet; }
From source file:com.flexive.core.LifeCycleInfoImpl.java
/** * Helper function for a less error prone and faster loading from the database * * @param rs ResultSet containing all the required info * @param creatorColumn column index of the create user reference * @param creationTimeColumn column index of the create timestamp * @param modificatorColumns column index of the modified by user reference * @param modificationTimeColumn column index of the modified by timestamp * @return LifeCycleInfo with the relevant data gathered from the ResultSet * @throws java.sql.SQLException if a column could not be read *//*from www . j a va 2 s. c o m*/ public static LifeCycleInfo load(ResultSet rs, int creatorColumn, int creationTimeColumn, int modificatorColumns, int modificationTimeColumn) throws SQLException { if (rs == null) { throw new IllegalArgumentException("Can not read from a null ResultSet!"); } int cid; long ct; int mid; long mt; long dTmp; cid = rs.getInt(creatorColumn); if (rs.wasNull()) { cid = NOT_DEFINED; } dTmp = rs.getLong(creationTimeColumn); ct = (rs.wasNull() ? NOT_DEFINED : dTmp); if (modificatorColumns < 0) { mid = NOT_DEFINED; } else { mid = rs.getInt(modificatorColumns); if (rs.wasNull()) mid = NOT_DEFINED; } if (modificationTimeColumn < 0) { mt = NOT_DEFINED; } else { dTmp = rs.getLong(modificationTimeColumn); mt = (rs.wasNull() ? NOT_DEFINED : dTmp); } return new LifeCycleInfoImpl(cid, ct, mid, mt); }
From source file:com.stratelia.webactiv.util.DBUtil.java
/** * Gets a long value from a current result set. * @param resultSet//from ww w. j av a 2s . c om * @param index * @return the long value if it exists, null otherwise. * @throws SQLException */ public static Long getLong(ResultSet resultSet, int index) throws SQLException { if (resultSet.getObject(index) != null) { return resultSet.getLong(index); } return null; }
From source file:com.concursive.connect.web.modules.profile.utils.ProjectUtils.java
private static String generateUniqueId(String title, int projectId, Connection db) throws SQLException { // Title can look like... // Some Project Name // some-project-name // some-project-name-2 // Format to allowed characters to get extension (some will be treated later) String allowed = "abcdefghijklmnopqrstuvwxyz1234567890-/& "; String nameToSearch = StringUtils.toAllowedOnly(allowed, title.trim().toLowerCase()); if (!StringUtils.hasText(nameToSearch)) { nameToSearch = "listing"; }/*w w w .j a va 2 s . c o m*/ // Break out any numbered extension: ex. name-5 String originalExtension = null; int dotIndex = nameToSearch.lastIndexOf("-"); if (dotIndex > -1 && dotIndex + 1 < nameToSearch.length()) { if (StringUtils.isNumber(nameToSearch.substring(dotIndex + 1))) { originalExtension = nameToSearch.substring(dotIndex); nameToSearch = nameToSearch.substring(0, dotIndex); } } // Convert spaces to - for url compliance and search engine readability nameToSearch = StringUtils.replace(nameToSearch, " ", "-"); nameToSearch = StringUtils.replace(nameToSearch, "&", "and"); nameToSearch = StringUtils.replace(nameToSearch, "/", "-"); // See if there is a dupe in the database, and retrieve the latest value boolean originalExtensionExists = false; PreparedStatement pst = db.prepareStatement( "SELECT project_id, projecttextid " + "FROM projects " + "WHERE projecttextid LIKE ? "); pst.setString(1, nameToSearch + "%"); ResultSet rs = pst.executeQuery(); long value = 0; while (rs.next()) { long thisProjectId = rs.getLong("project_id"); String thisTextId = rs.getString("projecttextid"); // If it already owns this id, then keep it if (projectId > -1 && projectId == thisProjectId && nameToSearch.equals(thisTextId)) { return nameToSearch; } if (originalExtension != null) { if (thisTextId.equals(nameToSearch + originalExtension)) { originalExtensionExists = true; } } // Only compare to this name exactly, or this named iteration if (thisTextId.equals(nameToSearch)) { if (1 > value) { value = 1; } } if (thisTextId.startsWith(nameToSearch + "-")) { String foundExtensionValue = thisTextId.substring(thisTextId.lastIndexOf("-") + 1); if (StringUtils.isNumber(foundExtensionValue)) { try { long thisValue = Long.parseLong(foundExtensionValue); if (thisValue > value) { value = thisValue; } } catch (Exception e) { // The extension is big... so add another extension rs.close(); pst.close(); return generateUniqueId(nameToSearch + "-2", projectId, db); } } } } if (originalExtension != null && !originalExtensionExists) { return (nameToSearch + originalExtension); } // Set this one accordingly if (value == 0) { return nameToSearch; } else { ++value; return (nameToSearch + "-" + value); } }
From source file:com.flexive.core.security.FxDBAuthentication.java
/** * Login a user using flexive's database * * @param loginname name of the user/* www. java 2s .co m*/ * @param password plaintext password * @param callback callback providing datasource, ejb context and "take over" * @return Authenticated UserTicket * @throws FxAccountInUseException on errors * @throws FxLoginFailedException on errors * @throws FxAccountExpiredException on errors */ public static UserTicket login(String loginname, String password, FxCallback callback) throws FxAccountInUseException, FxLoginFailedException, FxAccountExpiredException { final long SYS_UP = CacheAdmin.getInstance().getSystemStartTime(); FxContext inf = FxContext.get(); // Avoid null pointer exceptions if (password == null) password = ""; if (loginname == null) loginname = ""; final String applicationId = StringUtils.defaultString(inf.getApplicationId()); if (StringUtils.isBlank(applicationId)) { LOG.warn("Login: application ID is not set"); } String curSql; PreparedStatement ps = null; Connection con = null; try { // Obtain a database connection con = callback.getDataSource().getConnection(); // 1-6 7 8 9 10 11 12 13 14 15 16 curSql = "SELECT d.*,a.ID,a.IS_ACTIVE,a.IS_VALIDATED,a.ALLOW_MULTILOGIN,a.VALID_FROM,a.VALID_TO,NOW(),a.PASSWORD,a.MANDATOR,a.LOGIN_NAME " + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN " + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM " + TBL_ACCOUNT_DETAILS + " WHERE APPLICATION=? ORDER BY LAST_LOGIN DESC) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)"; ps = con.prepareStatement(curSql); ps.setString(1, applicationId); ps.setString(2, loginname); final ResultSet rs = ps.executeQuery(); // Anything found? if (rs == null || !rs.next()) throw new FxLoginFailedException("Login failed (invalid user or password)", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); // check if the hashed password matches the hash stored in the database final long id = rs.getLong(7); final String dbLoginName = rs.getString(16); // use DB login name for non-lowercase login names final String dbPassword = rs.getString(14); boolean passwordMatches = FxSharedUtils.hashPassword(id, dbLoginName, password).equals(dbPassword); if (!passwordMatches && "supervisor".equalsIgnoreCase(loginname)) { // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name passwordMatches = FxSharedUtils.hashPassword(id, "supervisor", password).equals(dbPassword); } if (!passwordMatches && !callback.isCalledAsGlobalSupervisor()) { increaseFailedLoginAttempts(con, id); throw new FxLoginFailedException("Login failed (invalid user or password)", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); } // Read data final boolean loggedIn = rs.getBoolean(2); final Date lastLogin = new Date(rs.getLong(3)); final String lastLoginFrom = rs.getString(4); final long failedAttempts = rs.getLong(5); final boolean active = rs.getBoolean(8); final boolean validated = rs.getBoolean(9); final boolean allowMultiLogin = rs.getBoolean(10); final Date validFrom = new Date(rs.getLong(11)); final Date validTo = new Date(rs.getLong(12)); final Date dbNow = rs.getTimestamp(13); final long mandator = rs.getLong(15); // Account active? if (!active || !validated || (CacheAdmin.isEnvironmentLoaded() && !CacheAdmin.getEnvironment().getMandator(mandator).isActive())) { if (LOG.isDebugEnabled()) LOG.debug("Login for user [" + loginname + "] failed, account is inactive. Active=" + active + ", Validated=" + validated + ", Mandator active: " + CacheAdmin.getEnvironment().getMandator(mandator).isActive()); increaseFailedLoginAttempts(con, id); throw new FxLoginFailedException("Login failed, account is inactive.", FxLoginFailedException.TYPE_INACTIVE_ACCOUNT); } // Account date from-to valid? //Compute the day AFTER the dValidTo Calendar endDate = Calendar.getInstance(); endDate.setTime(validTo); endDate.add(Calendar.DAY_OF_MONTH, 1); if (validFrom.getTime() > dbNow.getTime() || endDate.getTimeInMillis() < dbNow.getTime()) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); if (LOG.isDebugEnabled()) LOG.debug("Login for user [" + loginname + "] failed, from/to date not valid. from='" + sdf.format(validFrom) + "' to='" + validTo + "'"); increaseFailedLoginAttempts(con, id); throw new FxAccountExpiredException(loginname, dbNow); } // Check 'Account in use and takeOver false' if (!allowMultiLogin && !callback.getTakeOverSession() && loggedIn && lastLogin != null) { // Only if the last login time was AFTER the system started if (lastLogin.getTime() >= SYS_UP) { FxAccountInUseException aiu = new FxAccountInUseException(loginname, lastLoginFrom, lastLogin); if (LOG.isInfoEnabled()) LOG.info(aiu); // don't log this as an invalid login attempt - this happens routinely when a session times // out and the cached session data has not been evicted by the maintenance task yet //increaseFailedLoginAttempts(con, id); throw aiu; } } // Clear any old data curSql = "DELETE FROM " + TBL_ACCOUNT_DETAILS + " WHERE ID=? AND APPLICATION=?"; ps.close(); ps = con.prepareStatement(curSql); ps.setLong(1, id); ps.setString(2, applicationId); ps.executeUpdate(); // Mark user as active in the database // This can lead to duplicate rows for a user/application for concurrent logins (e.g. WebDAV clients), // but we prefer this to actually locking the complete table before updates. (FX-868) curSql = "INSERT INTO " + TBL_ACCOUNT_DETAILS + " (ID,APPLICATION,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC) " + "VALUES (?,?,?,?,?,?,?)"; ps.close(); ps = con.prepareStatement(curSql); ps.setLong(1, id); ps.setString(2, applicationId); ps.setBoolean(3, true); ps.setLong(4, System.currentTimeMillis()); ps.setString(5, inf.getRemoteHost()); ps.setLong(6, 0); //reset failed attempts ps.setString(7, AuthenticationSource.Database.name()); ps.executeUpdate(); // Load the user and construct a user ticket try { final UserTicketImpl ticket = (UserTicketImpl) UserTicketStore.getUserTicket(loginname); ticket.setFailedLoginAttempts(failedAttempts); ticket.setAuthenticationSource(AuthenticationSource.Database); return ticket; } catch (FxApplicationException e) { if (callback.getSessionContext() != null) callback.getSessionContext().setRollbackOnly(); throw new FxLoginFailedException( e.getExceptionMessage().getLocalizedMessage( CacheAdmin.getEnvironment().getLanguage(FxLanguage.DEFAULT_ID)), FxLoginFailedException.TYPE_UNKNOWN_ERROR); } } catch (SQLException exc) { if (callback.getSessionContext() != null) callback.getSessionContext().setRollbackOnly(); throw new FxLoginFailedException("Database error: " + exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR); } finally { Database.closeObjects(FxDBAuthentication.class, con, ps); } }
From source file:com.silverpeas.gallery.dao.MediaDAO.java
/** * Centralization of internal media decoration. * @param rs// w ww.j ava 2 s . co m * @param iMedia */ private static void decorateInternalMedia(ResultSet rs, InternalMedia iMedia) throws SQLException { iMedia.setFileName(rs.getString(2)); iMedia.setFileSize(rs.getLong(3)); iMedia.setFileMimeType(MediaMimeType.fromMimeType(rs.getString(4))); iMedia.setDownloadAuthorized(rs.getInt(5) == 1); iMedia.setDownloadPeriod(getPeriod(rs, 6, 7)); }
From source file:com.stratelia.webactiv.util.DBUtil.java
/** * Select count SQL query executor.//from w w w .j av a 2s . com * @param con * @param selectCountQuery * @param params * @throws SQLException */ public static <O> long selectCount(Connection con, String selectCountQuery, Collection<O> params) throws SQLException { PreparedStatement prepStmt = null; ResultSet rs = null; try { prepStmt = con.prepareStatement(selectCountQuery); DBUtil.setParameters(prepStmt, params); rs = prepStmt.executeQuery(); rs.next(); long count = rs.getLong(1); if (rs.next()) { throw new IllegalArgumentException("select count execution error"); } return count; } finally { DBUtil.close(rs, prepStmt); } }