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

📄 usermanagerbean.java

📁 展示使用J2EE容器实现安全机制
💻 JAVA
字号:
package com.jdon.security.auth.ejb;

import javax.ejb.*;
import java.util.*;

import org.apache.log4j.Logger;

import com.jdon.servicelocator.ejb.*;
import com.jdon.security.auth.PrincipalException;
import com.jdon.security.auth.util.JNDINames;
import com.jdon.security.Constants;

import com.jdon.sequence.SequenceGeneratorLocalHome;
import com.jdon.sequence.SequenceGeneratorLocal;

import com.jdon.security.auth.PrincipalException;
import java.security.Principal;

import com.jdon.security.events.UserEvent;
import com.jdon.security.User;
import com.jdon.security.model.UserModel;

import com.jdon.security.Role;
import com.jdon.security.model.RoleModel;

import com.jdon.security.Group;

public class UserManagerBean implements SessionBean {

  private final static Logger logger = Logger.getLogger(UserManagerBean.class);

  SessionContext sessionContext;
  UserHome userHome;
  UsersRolesHome usersRolesHome;
  UsersGroupsHome usersGroupsHome;
  RoleManagerLocalHome roleManagerLocalHome;
  SequenceGeneratorLocalHome sequenceHome;

  public void ejbCreate() throws CreateException {
    try {

      ServiceLocator serviceLocator = new ServiceLocator();
      userHome = (UserHome) serviceLocator.getLocalHome(
          JNDINames.USER_HOME);

      sequenceHome = (SequenceGeneratorLocalHome) serviceLocator.getLocalHome(
          JNDINames.SEQUENCEGENERATOR_HOME);

      usersRolesHome = (UsersRolesHome) serviceLocator.getLocalHome(
            JNDINames.USERSROLES_HOME);

      usersGroupsHome = (UsersGroupsHome) serviceLocator.getLocalHome(
          JNDINames.USERSGROUPS_HOME);

      roleManagerLocalHome = (RoleManagerLocalHome) serviceLocator.getLocalHome(
              JNDINames.ROLEMANAGER_HOME);


    } catch (Exception ex) {
      logger.error("Service Locate error:" + ex);
      throw new CreateException();

    }
  }

  public int getNewId(String name) {
    try {
      SequenceGeneratorLocal seq = sequenceHome.create();
      return seq.nextSequenceNumber(name);
    } catch (Exception ex) {
      throw new EJBException("Error generating id for : " + name + ex);
    }
  }

  public void createUser(UserEvent userEvent) {
    User userDTO = userEvent.getUser();

    if (nameIsExisted(userDTO)){
      logger.debug("name :" + userDTO.getName() + " has been exsited");
      userEvent.setErrors(Constants.NAME_EXISTED);
      return;
    }
    if (emailIsExisted(userDTO)){
      logger.debug("eamil :" + userDTO.getEmail() + " has been exsited");
      userEvent.setErrors(Constants.EMAIL_EXISTED);
      return;
    }

    UserLocal userLocal = null;
    try {
      String id = Integer.toString(getNewId(Constants.SEQUENCE_USER_NAME));
      userLocal = userHome.create(id);
      userDTO.setUserId(id);
      updateUser(userEvent);

      createUsersRoles(userDTO);
    } catch (Exception ex) {
      logger.error(ex);
      throw new EJBException("create user error : " + ex);
    }

  }

  private boolean nameIsExisted(User userDTO) {
    boolean found = false;
    User user = getUserByName(userDTO.getName());
    if (user != null)
      found = true;
    return found;
  }

  private boolean emailIsExisted(User userDTO) {
    boolean found = false;
    User user = getUserByEmail(userDTO.getEmail());
    if (user != null)
      found = true;
    return found;
  }


  /**
   * create the relation with role and user
   * @param userDTO
   */
  public void createUsersRoles(User userDTO) throws Exception {
    UsersRoles usersRoles = null;
    try {
      RoleManagerLocal roleManagerLocal = roleManagerLocalHome.create();
      String roleId = roleManagerLocal.getRoleId(Role.USER);
      usersRoles = usersRolesHome.create(userDTO.getUserId(), roleId);
    } catch (Exception ex) {
      logger.error(ex);
      throw new EJBException("createUsersRoles error : " + ex);
    }
  }


  public void updateUser(UserEvent userEvent) {
    User userDTO = userEvent.getUser();
    UserLocal userLocal = null;
    try {
      userLocal = userHome.findByPrimaryKey(userDTO.getUserId());
      userLocal.setName(userDTO.getName());
      userLocal.setEmail(userDTO.getEmail());
      userLocal.setPassword(userDTO.getPassword());

    } catch (Exception ex) {
      logger.error(ex);
    }

  }

  public User getUserByEmail(String emailAddress) {
    emailAddress = emailAddress.trim().toLowerCase();
    UserLocal userLocal = null;
    try {
      userLocal = userHome.findByEmail(emailAddress);
    } catch (Exception ex) {
      logger.warn(ex);
    }
    return getUser(userLocal);

  }

  public User getUserById(String userId) {
    userId = userId.trim().toLowerCase();
    logger.debug(" userId =" + userId);
    UserLocal userLocal = null;
    try {
      userLocal = userHome.findByPrimaryKey(userId);
    } catch (Exception ex) {
      logger.warn(ex);
    }
    return getUser(userLocal);

  }

  public User getUserByName(String name) {
    logger.debug(" name =" + name);
    UserLocal userLocal = null;
    try {
      userLocal = userHome.findByName(name);
    } catch (Exception ex) {
      logger.warn(ex);
    }
    return getUser(userLocal);

  }

  public Collection getUsersByRole(Role roleDTO) {
    Collection list = new ArrayList();
    try {
      Collection c = usersRolesHome.findByRoleId(roleDTO.getRoleId());
      Iterator iter = c.iterator();
      while(iter.hasNext()){
        String userId = (String)iter.next();
        list.add(getUserById(userId));
      }
      return list;
    } catch (Exception ex) {
      logger.warn(ex);
    }
    return null;
  }

  public Role getRoleByUser(User userDTO) {
    String roleId = null;
    try {
      Collection c = usersRolesHome.findByUserId(userDTO.getUserId());
      Iterator iter = c.iterator();
      while (iter.hasNext()) {
        roleId = (String) iter.next();
      }
      RoleManagerLocal roleManagerLocal = roleManagerLocalHome.create();
      return roleManagerLocal.getRoleById(roleId);
    } catch (Exception ex) {
      logger.warn(ex);
    }
    return null;
  }


  private User getUser(UserLocal userLocal) {
    if (userLocal == null)
      return null;

    logger.debug(" userId =" + userLocal.getUserId());
    User user = new UserModel(userLocal.getUserId());
    user.setEmail(userLocal.getEmail());
    user.setName(userLocal.getName());
    user.setPassword(userLocal.getPassword());
    user.setUserId(userLocal.getUserId());

    return user;

  }


  public User getUserByPrincipal() throws Exception, PrincipalException {
    Principal principal = null;

    try {
      principal = sessionContext.getCallerPrincipal();
      logger.debug(" EJB  principal: " + principal.getName());
    } catch (Exception e) {
      logger.error(e);
      throw new PrincipalException();
    }

    if (principal == null) {
      throw new PrincipalException();
    }
    String name = principal.getName();
    return getUserByName(name);
   }


  public void ejbRemove() {
    /**@todo Complete this method*/
  }

  public void ejbActivate() {
    /**@todo Complete this method*/
  }

  public void ejbPassivate() {
    /**@todo Complete this method*/
  }

  public void setSessionContext(SessionContext sessionContext) {
    this.sessionContext = sessionContext;
  }
}

⌨️ 快捷键说明

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