📄 usermanagerbean.java
字号:
/* * UserEJB - CyberDemia's User management library implemented using EJBs. * Copyright (C) 2003 CyberDemia Research and Services * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * See the COPYING file located in the top-level-directory of * the archive of this library for complete text of license. */package com.cyberdemia.user.impl;import javax.ejb.*;import javax.naming.*;import java.util.*;import java.security.*;import java.util.logging.*;import com.cyberdemia.user.*;import com.cyberdemia.util.HexString;/*** UserManagerBean is a session bean implementation* of UserManager.** @author Alexander Yap*/public class UserManagerBean implements SessionBean{ /** * * Creates an instance of UserManagerBean. * */ public UserManagerBean() { try { Context ctx = new InitialContext(); m_userHome = (LocalUserHome)ctx.lookup("java:comp/env/ejb/localUser"); m_userRoleHome = (LocalUserRoleHome)ctx.lookup("java:comp/env/ejb/localUserRole"); m_resourceRefHome = (LocalResourceReferenceHome)ctx.lookup("java:comp/env/ejb/localResourceReference"); } catch (Exception ex) { throw new EJBException(ex); } } /** * Adds a new user to the database using the data passed in * by a UserData instance. Some fields in UserData are ignored, such * as id and createdMillis. * This method first checks that the user's email address does not match * any existing email addresses in the database. * Note that the lastName is always atored in all upper-case to simplify searching. * * @param data UserData instance storing data for the new user. * @return Unique ID (primary key) of the new user. * @throws RemoteException * @throws UserException if the email address already exists in the database, or due to some other error. */ public String addUser(UserData data) throws UserException { if (isEmailExists(data.getEmail())) { throw new UserException(UserException.DUPLICATE_EMAIL, "User with email "+data.getEmail()+" already exists."); } String uid = null; // Last name is always saved in all upper case to simplify searching try { LocalUser user = m_userHome.create(data.password, data.email, data.title, data.firstName, data.lastName.toUpperCase(), data.groups ); uid = user.getId(); } catch (Exception ex) { throw new UserException("Error adding user with email "+data.getEmail(), ex); } addRolesForUserId(uid, data.groups ); return uid; } /** * Removed an existing user from the database. * @param id Unique ID of user to remove. * @throws RemoteException * @throws UserException if there is an error. */ public void removeUser(String id) throws UserException { try { LocalUser user = m_userHome.findByPrimaryKey(id); user.removeAllResources(); removeRolesForUserId(id); user.remove(); } catch (FinderException fex) { s_logger.log( Level.WARNING, "Cannot find User with ID "+id); throw new UserException(UserException.USER_NOT_FOUND, "Cannot find User with ID "+id); } catch (Exception ex) { throw new UserException("Error removing user with ID "+id, ex); } } /** * Gets the unique IDs of all users in the database. * @return Array of all user IDs. * @throws RemoteException */ public String[] getUsers() { String[] ids = null; try { Iterator userIter = m_userHome.findAll().iterator(); ArrayList idList = new ArrayList(); while (userIter.hasNext()) { LocalUser user = (LocalUser)userIter.next(); idList.add( user.getPrimaryKey() ); } ids = (String[])idList.toArray(new String[0]); } catch (Exception ex) { throw new EJBException(ex); } return ids; } /** * Gets the data of a user identified by its unique ID. * @param id User ID. * @return UserData instance storing the user's data, or null if the user doesn't exist. * @throws RemoteException */ public UserData getUserData(String id) { UserData data = null; try { LocalUser user = m_userHome.findByPrimaryKey(id); data = user.getUserData(); } catch (FinderException ex) { // return null if user not found. s_logger.log( Level.WARNING, "Cannot find User with id "+id); } return data; } /** * Finds users by searching for a substring within the email address. * The search may or may not be case-sensitive depending on the * underlying database. * For example, search string "lex@yah" will match email addresses * like "alex@yahoo.com" and "lex@yahoo.com". * * @param emailSearchStr Email address substring to search for. * @return Array of UserData instances for found users, or empty array if no user found. * @throws RemoteException */ public UserData[] searchUsersByEmail(String emailSearchStr) { UserData[] userDataArr = null; try { Collection userCollection = m_userHome.findByEmailSubString(emailSearchStr); userDataArr = new UserData[userCollection.size()]; Iterator userIter = userCollection.iterator(); for (int uidx=0; userIter.hasNext(); uidx++) { LocalUser user = (LocalUser)userIter.next(); userDataArr[uidx] = user.getUserData(); } } catch (FinderException fex) { s_logger.log( Level.WARNING, "Cannot search User by email search string "+emailSearchStr); userDataArr = new UserData[0]; } return userDataArr; } /** * Finds users by searching for a substring within the last name. * The substring is converted to upper-case before being compared * with values from database what are also all in upper-case. * Hence, the search is effectively case-insensitive regardless * of the underlying database. * For example, search string "le" will match last names * like "alex", "leonardo" and "napolean". * * @param lastNameSearchStr Last name substring to search for. * @return Array of UserData instances for found users, or empty array if no user found. * @throws RemoteException */ public UserData[] searchUsersByLastName(String lastNameSearchStr) { UserData[] userDataArr = null; try { Collection userCollection = m_userHome.findByLastNameSubString(lastNameSearchStr.toUpperCase()); userDataArr = new UserData[userCollection.size()]; Iterator userIter = userCollection.iterator(); for (int uidx=0; userIter.hasNext(); uidx++) { LocalUser user = (LocalUser)userIter.next(); userDataArr[uidx] = user.getUserData(); } } catch (FinderException fex) { s_logger.log( Level.WARNING, "Cannot search User by lastName search string "+lastNameSearchStr); userDataArr = new UserData[0]; } return userDataArr; } /** * Gets the data of a user identified by its unique ID. * @param email User email address * @return UserData instance storing the user's data, or null if the user doesn't exist. * @throws RemoteException */ public UserData getUserDataByEmail(String email) { UserData data = null; LocalUser user = findUserByEmail(email); if (user != null) { data = user.getUserData(); } else { // return null if user not found. s_logger.log( Level.WARNING, "Cannot find User with email "+email); } return data; } /** * Checks if any user with the specified email address already exists in the database. * @param email Email address to check for. * @return true if a user with the email address exist, otherwise false. * @throws RemoteException */ public boolean isEmailExists(String email) { return (findUserByEmail(email)!=null); } /** * Updates an existing user with new data passed in as a UserData instance. * The user to modify is identified by UserData's id field. * @param data UserData instance storing user data. * @throws RemoteException * @throws UserException if an error occurs such as the id is invalid. */ public void setUserData(UserData data) throws UserException { try { LocalUser user = m_userHome.findByPrimaryKey(data.id); user.setUserData(data); } catch (FinderException ex) { throw new UserException(UserException.USER_NOT_FOUND, "Cannot find User with ID "+data.id); } // refresh the roles for this user in case the groups have changed. removeRolesForUserId(data.id); addRolesForUserId(data.id, data.groups ); } /** * Validates a User ID against a specified password. * This method is provided in case the client code needs to perform some * programmatic authentication. If authentication is managed by the container, * there is no need for this method. * @param id User ID to validate. * @param password Password of user. * @return true if user is valid and the password matches, otherwise false */ public boolean validateUser(String id, String password) { LocalUser user = null; try { user = m_userHome.findByPrimaryKey(id); } catch (FinderException ex) { return false; } assert user!=null : "User is null for id "+id; String hashedHex = null; try { byte[] hashed = MessageDigest.getInstance("MD5").digest( password.getBytes() ); hashedHex = HexString.toString(hashed); } catch (NoSuchAlgorithmException ex) { s_logger.log(Level.SEVERE, "Cannot create MD5 MessageDigest",ex); return false; } return user.getHashedPassword().equalsIgnoreCase(hashedHex); } /** * Gets resources within the specified category that are * associated with the specified user. * @param id User ID * @param catKey Key to identify the category of resource to extract, or null to extract all resources. * @return Array of resource IDs. */ public String[] getResourcesInUser( String id, String catKey ) { String[] resourceIds = null; try { LocalUser user = m_userHome.findByPrimaryKey(id); LocalResourceReference[] resourceRefs = user.getResources( catKey ); resourceIds = new String[ resourceRefs.length ]; for (int ridx=0; ridx<resourceIds.length; ridx++) { resourceIds[ridx] = resourceRefs[ridx].getResourceId(); } } catch (FinderException fex) { s_logger.log( Level.WARNING, "Cannot find User with id "+id); } catch (Exception ex) { throw new EJBException(ex); } return resourceIds; } /** * Associates a resource with the specified user. * @param id User ID * @param catKey Key to identify the category of resource to add. * @param resId The ID of the resource to add. * @return true if resource is added successfully, otherwise false (it already exists). */ public boolean addResourceToUser( String id, String catKey, String resId ) { boolean success = false; try { LocalUser user = m_userHome.findByPrimaryKey(id); // Try to find if the reference already exists, if not create a new one. LocalResourceReference resRef = null; try { Iterator resRefIter = m_resourceRefHome.findByCategoryAndResource(catKey, resId).iterator(); if (resRefIter.hasNext()) { resRef = (LocalResourceReference)resRefIter.next(); } else { resRef = m_resourceRefHome.create( catKey, resId ); } } catch (FinderException fex) { resRef = m_resourceRefHome.create( catKey, resId ); } success = user.addResource( resRef ); } catch (Exception ex) { throw new EJBException(ex); } return success; } /** * Removes a resource from the specified user. * @param id User ID * @param catKey Key to identify the category of resource to remove. * @param resId The ID of the resource to remove. * @return true if resource is removed successfully, otherwise false (not found). */ public boolean removeResourceFromUser( String id, String catKey, String resId ) { // If the reference doesn't exist, skip everything because there is nothing to remove LocalResourceReference resRef = null; try { Iterator resRefIter = m_resourceRefHome.findByCategoryAndResource(catKey, resId).iterator(); if (resRefIter.hasNext()) { resRef = (LocalResourceReference)resRefIter.next(); } } catch (FinderException fex) { } if (resRef==null) { return false; } boolean success = false; try { LocalUser user = m_userHome.findByPrimaryKey(id); success = user.removeResource( resRef ); } catch (Exception ex) { throw new EJBException(ex); } return success; } /** * Gets roles that are associated with the specified user. * @param id User ID * @return Array of role names, or empty array if none. */ public String[] getRolesInUser( String id ) { ArrayList roleList = new ArrayList(); try { Collection uRoles = m_userRoleHome.findByUserId(id.toString()); Iterator uRoleIter = uRoles.iterator(); while (uRoleIter.hasNext()) { roleList.add( ((LocalUserRole)uRoleIter).getRoleName() ); } } catch (FinderException fex2) { // Its alright for a user not to have any role } return (String[])roleList.toArray(new String[0]); } /** * Associates roles with specified user. */ private void addRolesForUserId( String id, String groups) { String[] roles = UserUtils.getRolesForGroups(groups); try { for (int r=0; r<roles.length; r++) { m_userRoleHome.create( id.toString(), roles[r]); } } catch (Exception ex) { throw new EJBException(ex); } } /** * Removes any roles associated with specified user id. */ private void removeRolesForUserId( String id ) { try { Collection uRoles = m_userRoleHome.findByUserId(id.toString()); Iterator uRoleIter = uRoles.iterator(); while (uRoleIter.hasNext()) { ((LocalUserRole)uRoleIter.next()).remove(); } } catch (FinderException fex2) { // Its alright for a user not to have any role } catch (Exception ex) { throw new EJBException(ex); } } private LocalUser findUserByEmail(String email) { LocalUser user = null; try { Iterator userIter = m_userHome.findByEmail(email).iterator(); if (userIter.hasNext()) { user = (LocalUser)userIter.next(); } } catch (FinderException fex) { } return user; } public void ejbCreate() {} public void ejbPostCreate() { } public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) { m_context = sc; } private SessionContext m_context = null; private LocalUserHome m_userHome = null; private LocalUserRoleHome m_userRoleHome = null; private LocalResourceReferenceHome m_resourceRefHome = null; private static Logger s_logger = Logger.getLogger(UserManagerBean.class.getName());}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -