⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usermanagerbean.java

📁 老外的在线考试
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * UserEJB - CyberDemia's User management library implemented using EJBs. * Copyright (C) 2004 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;import javax.ejb.*;import javax.naming.*;import java.util.*;import java.security.*;import java.util.logging.*;import com.cyberdemia.util.HexString;import com.cyberdemia.ejb.BaseSessionBean;/** * UserManagerBean is a facade that provides * useful methods for managing User and related beans. * * @ejb.bean name="UserManagerBean" *           type="Stateless" *           view-type="remote" *           jndi-name="ejb/UserManager" * * @ejb.util generate="physical" * @ejb.interface remote-class="com.cyberdemia.user.UserManager" extends="javax.ejb.EJBObject" * @ejb.home remote-class="com.cyberdemia.user.UserManagerHome" extends="javax.ejb.EJBHome" * @ejb.ejb-ref ejb-name="UserBean" ref-name="ejb/LocalUser" view-type="local" * @ejb.ejb-ref ejb-name="UserRoleBean" ref-name="ejb/LocalUserRole" view-type="local" * @ejb.ejb-ref ejb-name="ResourceReferenceBean" ref-name="ejb/LocalResourceReference" view-type="local" * * @author Alexander Yap * @version $Revision: 1.10 $ at $Date: 2004/06/19 14:25:59 $ by $Author: alexycyap $ * */public class UserManagerBean extends BaseSessionBean{	/**	 * 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 login name does not match	 * any existing login names in the database.	 * Note that the lastName is always atored in all upper-case to simplify searching.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @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 login name already exists in the database, or due to some other error.	 */	public Integer addUser(UserData data) throws UserException	{		if (isLoginExists(data.getLogin()))		{			throw new UserException(UserException.DUPLICATE_LOGIN, "User with login "+data.getLogin()+" already exists.");		}		Integer uid = null;		// Last name is always saved in all upper case to simplify searching		try		{			LocalUser user = s_userHome.create(data.login, data.password, data.email,				data.title, data.firstName, data.lastName.toUpperCase() );			uid = user.getGeneratedPrimaryKey();		}		catch (CreateException ex)		{			getSessionContext().setRollbackOnly();			throw new UserException("Error adding user "+data.login, ex);		}		try		{			addRolesForUser(data.login, data.roles );        }		catch (CreateException cex)		{			getSessionContext().setRollbackOnly();			throw new UserException("Error adding roles for user "+data.login, cex);		}		return uid;	}	/**	 * Removed an existing user from the database.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param id Unique ID of user to remove.	 * @throws RemoteException	 * @throws UserException if there is an error.	 */	public void removeUser(Integer id) throws UserException	{		LocalUser user =  doFindUserById(id);		try		{			user.removeAllResources();			removeRolesForUser(user.getName());			user.remove();		}		catch (Exception ex)		{			getSessionContext().setRollbackOnly();			throw new UserException("Error removing user with ID "+id, ex);		}	}	/**	 * Gets the unique IDs of all users in the database.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @return Array of all user IDs.	 */	public Integer[] getUsers()	{		Integer[] ids = null;		try		{			Iterator userIter = s_userHome.findAll().iterator();			ArrayList idList = new ArrayList();			while (userIter.hasNext())			{				LocalUser user = (LocalUser)userIter.next();				idList.add( user.getPrimaryKey() );			}			ids = (Integer[])idList.toArray(new Integer[0]);		}		catch (Exception ex)		{			// If there is a problem finding users, just return empty array			ids = new Integer[0];		}		return ids;	}	/**	 * Gets the data of a user identified by its unique ID. 	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param id User ID.	 * @param includeRoles true to also retrieve roles, false to skip them.	 * @return UserData instance storing the user's data, or null if the user doesn't exist.	 * @throws UserException if there is an error.	 */	public UserData getUserData(Integer id, boolean includeRoles) throws UserException	{		LocalUser user =  doFindUserById(id);		UserData data = null;		try		{			data = createUserData(user, includeRoles);		}		catch (Exception ex)		{			throw new UserException( "Error getting data for User "+user.getName(), ex);		}		return data;	}	/**	 * Finds users by searching for a substring within the login name.	 * The search may or may not be case-sensitive depending on the	 * underlying database.	 * For example, search string "lex@yah" will match login names	 * like "alex@yahoo.com" and "lex@yahoo.com".	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param loginSearchStr Login substring to search for.	 * @param limit Number to limit the results to.	 * @param includeRoles true to also retrieve roles, false to skip them.	 * @return Array of UserData instances for found users, or empty array if no user found.	 */	public UserData[] searchUsersByLogin(String loginSearchStr, int limit, boolean includeRoles)	{			UserData[] userDataArr = null;		try		{			Collection userCollection = s_userHome.findByLoginSubString(loginSearchStr, limit);			userDataArr = convertUserCollectionToDataArray( userCollection, includeRoles);		}		catch (FinderException fex)		{			s_logger.log( Level.WARNING, "Cannot search User by login search string \""+loginSearchStr+"\"");			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".	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param lastNameSearchStr Last name substring to search for.	 * @param limit Number to limit the results to.	 * @param includeRoles true to also retrieve roles, false to skip them.	 * @return Array of UserData instances for found users, or empty array if no user found.	 */	public UserData[] searchUsersByLastName(String lastNameSearchStr, int limit, boolean includeRoles)	{		UserData[] userDataArr = null;		try		{			Collection userCollection = s_userHome.findByLastNameSubString(lastNameSearchStr.toUpperCase(), limit);			userDataArr = convertUserCollectionToDataArray( userCollection, includeRoles);		}		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 login name.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param login User login name	 * @param includeRoles true to also retrieve roles, false to skip them.	 * @return UserData instance storing the user's data, or null if the user doesn't exist.	 */	public UserData getUserDataByLogin(String login, boolean includeRoles)	{		UserData data = null;		LocalUser user = findUserByLogin(login);		if (user != null)		{			data = createUserData(user, includeRoles);		}		else		{	// return null if user not found.			s_logger.log( Level.WARNING, "Cannot find User with login "+login);		}		return data;	}	/**	* Checks if any user with the specified login name already exists in the database.	* Login name comparison is case-insensitive.	*	* @ejb.interface-method	* @ejb.transaction type="Required"	*	* @param loginName Login name to check for.	* @return true if a user with the login name exists, otherwise false.	*/	public boolean isLoginExists(String loginName)	{		boolean exists = false;		try		{			exists = !s_userHome.findByLogin(loginName.toLowerCase()).isEmpty();		}		catch (FinderException fex)		{            // Ignore, exists remains false.		}		return exists;	}	/**	 * Updates an existing user with new data passed in as a UserData instance.	 * The user to modify is identified by UserData's id field.	 *	 * @ejb.interface-method	 * @ejb.transaction type="Required"	 *	 * @param data UserData instance storing user data.	 * @throws RemoteException	 * @throws UserException if an error occurs such as the id is invalid.	 */	public void setUser(UserData data) throws UserException	{		String hashedPassword = null;		if ( (data.password!=null) && (data.password.length()>0))		{			try			{				byte[] hashed = MessageDigest.getInstance("MD5").digest( data.password.getBytes() );				hashedPassword =  HexString.toString(hashed) ;			}			catch (NoSuchAlgorithmException ex)			{				throw new UserException("Cannot create MD5 MessageDigest",ex);			}		}		LocalUser user =  doFindUserById(data.id);		try		{			user.setEmail( data.email );			if ( hashedPassword!=null )			{				user.setHashedPassword(hashedPassword);			}			user.setName( data.login );			user.setTitle( data.title );			user.setFirstName( data.firstName );			// Last name is always saved in all upper case to simplify searching			user.setLastName( data.lastName.toUpperCase() );			user.setLastModifiedMillis( System.currentTimeMillis() );		}		catch (Exception ex)		{			getSessionContext().setRollbackOnly();			throw new UserException("Error setting data for User "+data.login, ex);		}		// Refresh the roles for this user in case they have changed, if roles are available.		if (data.roles!=null)		{

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -