dao.DirectoryUserDaoDb.java Source code

Java tutorial

Introduction

Here is the source code for dao.DirectoryUserDaoDb.java

Source

/**
* Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org]
*
* This file is part of Redbasin OpenDocShare community project.
*
* Redbasin OpenDocShare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package dao;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import model.Directory;
import model.Hdlogin;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
import util.DbConstants;
import util.RegexStrUtil;

/**
  * <B>DirectoryUserDaoDb</B> <BR>
  * This object implements DirectoryUserDao interface
  * Busines folksonomy access control and user management
  *
  * @author Smitha Gudur (smitha@redbasin.com)
  * @version $Revision: 1.1 $
  */
public class DirectoryUserDaoDb extends DirectoryAbstractDao implements DirectoryUserDao {

    protected final Log logger = LogFactory.getLog(getClass());
    /**
     * these objects are set by spring
     */
    private volatile DirUserAddQuery addUserQuery;
    private volatile DirUserDeleteQuery deleteUserQuery;
    // private volatile ListDirectoriesQuery listDirectoriesQuery; 
    // private volatile ListUsersQuery listUsersQuery; 
    private volatile BasicQuery listDirectoriesQuery;
    private volatile BasicQuery listUsersQuery;

    DirectoryListUsersQuery listDirUsersQuery;

    /**
     *  This methods lists all the directories of this userLogin, reads from a slave
     *  @param userId the user Id
     *  @param userLogin the user Login
     *  @return List - list of all directories that this user belongs to
     *  @throws BaseDaoException
     */
    public List listDirectories(String userId, String userLogin) throws BaseDaoException {
        return listDirectories(userId, userLogin, DbConstants.READ_FROM_SLAVE);
    }

    /**
     *  This methods lists all the directories of this userLogin as Author
     *  @param userId the user Id
     *  @param userLogin the user Login
     *  @param accessFlag the acess flag to read from either slave(0) or master (1)
     *  @return List - list of all directories that this user belongs to
     *  @throws BaseDaoException
     */
    public List listDirectories(String userId, String userLogin, int accessFlag) throws BaseDaoException {

        if (RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(userLogin)) {
            throw new BaseDaoException("params are null");
        }

        /** Jboss methods
         * fqn - full qualified name
         * check if the userpage already set in the cache
         * If it exists, return the userpage from the cache.
         */
        Fqn fqn = cacheUtil.fqn(DbConstants.USER_DIRS);
        Object obj = treeCache.get(fqn, userLogin);
        if (obj != null) {
            return (List) obj;
        }

        /**
         *  Get scalability datasource for directory, diradmin, not partitioned 
         */
        String queryName = null;
        if (accessFlag == 1) {
            queryName = scalabilityManager.getWriteZeroScalability("listdirectoriesQuery");
        } else {
            queryName = scalabilityManager.getReadZeroScalability("listdirectoriesQuery");
        }
        listDirectoriesQuery = getQueryMapper().getQuery(queryName);

        /**
         * Get the list of directories for this user
         */
        List result = null;
        try {
            Object params[] = { (Object) userId };
            result = listDirectoriesQuery.execute(params);
        } catch (Exception e) {
            throw new BaseDaoException("exception in getting directories for this user "
                    + listDirectoriesQuery.getSql() + " userId = " + userId + " userlogin = " + userLogin, e);
        }

        if ((result != null) && (result.size() > 0)) {
            treeCache.put(fqn, userLogin, result);
        }
        return result;
    }

    /**
     *  Adds the users in directory for access list
     *  @param memberList memberList
     *  @param directoryId  directoryId 
     *  @param userId  the user Login is used to check if this user has the permission to add user
     *  @param userLogin  the user Login is used to check if this user has the permission to add user
     *  @return List - list of users who are not members
     *  @throws BaseDaoException
     */
    public String addUsers(List memberList, String directoryId, String userId, String userLogin)
            throws BaseDaoException {

        if ((memberList == null) || RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(userId)
                || RegexStrUtil.isNull(userLogin)) {
            throw new BaseDaoException("params are null");
        }

        /* get existing users */
        List userList = listUsers(directoryId, DbConstants.READ_FROM_SLAVE);
        List existingUserList = null;
        if (userList != null) {
            existingUserList = new ArrayList();
            for (int i = 0; i < userList.size(); i++) {
                if ((Directory) userList.get(i) != null) {
                    existingUserList.add(((Directory) userList.get(i)).getValue(DbConstants.LOGIN));
                }
            }
        }

        logger.info("memberList = " + memberList.toString());
        logger.info("existingUserList = " + existingUserList.toString());

        /* remove existing users from the memberList */
        List idList = null;
        if ((existingUserList != null) && (existingUserList.size() > 0)) {
            HashSet hs1 = new HashSet(memberList);
            HashSet hs2 = new HashSet(existingUserList);
            if (hs1.removeAll(hs2)) {
                if (hs1 != null) {
                    logger.info("hs1 = " + hs1.toString());
                }
                idList = new ArrayList(hs1);
            } else {
                idList = memberList;
            }
        } else {
            idList = memberList;
        }

        /* add only new valid users in the directory */
        StringBuffer notMembers = new StringBuffer();
        try {
            if (idList != null && idList.size() > 0) {
                logger.info("idList = " + idList.toString());
                for (int i = 0; i < idList.size(); i++) {
                    if (idList.get(i) != null) {
                        logger.info("idList.get(i)=" + idList.get(i) + " i = " + i);
                        String mLogin = (String) idList.get(i);
                        Hdlogin hdlogin = getLoginid(mLogin);
                        if (hdlogin == null) {
                            notMembers.append(mLogin);
                            notMembers.append(" ");
                        } else {
                            addUser(directoryId, mLogin, userId, userLogin);
                        }
                    }
                }
            }
        } catch (BaseDaoException e) {
            throw new BaseDaoException(
                    "Exception occured in addUser(), DirectoryAddUser for userLogin " + userLogin, e);
        }

        logger.info("notMembers = " + notMembers);
        if (notMembers != null) {
            return notMembers.toString();
        } else {
            return null;
        }
    }

    /**
      *  Adds the user for this directory access list
      *  @param directoryId the directory id
      *  @param member  the member who is added as user to this directory
      *  @param userId  the user Login is used to check if this user has the permission to add user
      *  @param userLogin  the user Login is used to check if this user has the permission to add user
      */
    public void addUser(String directoryId, String member, String userId, String userLogin)
            throws BaseDaoException {

        if (RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(userLogin) || RegexStrUtil.isNull(member)
                || RegexStrUtil.isNull(userId)) {
            throw new BaseDaoException("params are null");
        }

        /**
              *  check if this user has permission to add user
              */
        if (!diaryAdmin.isDiaryAdmin(userLogin) && !isAuthor(directoryId, userId)) {
            throw new BaseDaoException("User does not have permission to add user to directory, " + directoryId
                    + " userId = " + userId);
        }

        /**
         *  Get scalability datasource for diradmin, not partitioned
         */
        String sourceName = scalabilityManager.getWriteZeroScalability();
        ds = scalabilityManager.getSource(sourceName);
        if (ds == null) {
            throw new BaseDaoException("ds null, addUser() " + sourceName + " userId = " + userId);
        }

        /**
         *  Add user to this directory
         */
        String memberId = null;
        try {

            Hdlogin hdlogin = getLoginid(member);
            memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
            addUserQuery.run(directoryId, memberId);
        } catch (Exception e) {
            throw new BaseDaoException("error executing add user to dirallow table " + addUserQuery.getSql(), e);
        }

        /**
         *  member's list needs to be updated with the new query, remove the old entries for this member
         */

        Fqn fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
        if (treeCache.exists(fqn, member)) {
            treeCache.remove(fqn, member);
        }

        fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

        fqn = cacheUtil.fqn(DbConstants.USER_DIRS);
        if (treeCache.exists(fqn, member)) {
            treeCache.remove(fqn, member);
        }

        fqn = cacheUtil.fqn(DbConstants.DIR_OF_USERS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }
        removeUsersFromDirAuthorsCache(directoryId);
    }

    /**
      *  Removes the user from this directory access list
      *  @param directoryId the directory id
      *  @param member  the member who is added as user to this directory
      *  @param authorId  the user who has permission to add
      *  @param authorLogin  the Login who has the permission to add
      */
    public void removeUser(String directoryId, String member, String authorId, String authorLogin)
            throws BaseDaoException {

        if (RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(authorLogin) || RegexStrUtil.isNull(member)
                || RegexStrUtil.isNull(authorId)) {
            throw new BaseDaoException("params are null");
        }

        /**
              *  check if this user has permission to delete user
              */
        if (!diaryAdmin.isDiaryAdmin(authorLogin) && !isAuthor(directoryId, authorId)) {
            throw new BaseDaoException("User does not have permission to delete user to directory, " + directoryId
                    + " authorId = " + authorId);
        }

        /**
         *  Get scalability datasource for diradmin, not partitioned
         */
        String sourceName = scalabilityManager.getWriteZeroScalability();
        ds = scalabilityManager.getSource(sourceName);
        if (ds == null) {
            throw new BaseDaoException("ds null, deleteUser() " + sourceName + " authorId = " + authorId);
        }

        /**
         *  Delete user from this directory
         */
        String memberId = null;
        try {

            Hdlogin hdlogin = getLoginid(member);
            memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
            deleteUserQuery.run(directoryId, memberId);
        } catch (Exception e) {
            throw new BaseDaoException(
                    "error executing delete user from dirallow table " + deleteUserQuery.getSql(), e);
        }

        /**
         *  member's list needs to be updated with the new query, remove the old entries for this member
         */

        Fqn fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
        if (treeCache.exists(fqn, member)) {
            treeCache.remove(fqn, member);
        }

        fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

        fqn = cacheUtil.fqn(DbConstants.USER_DIRS);
        if (treeCache.exists(fqn, member)) {
            treeCache.remove(fqn, member);
        }

        fqn = cacheUtil.fqn(DbConstants.DIR_OF_USERS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }
        removeUsersFromDirAuthorsCache(directoryId);

    }

    /**
     *  This methods lists all the users that can access this directory
     *  @param directoryId  - directoryId
     *  @param accessFlag - slave(0) or master (1)
     *  @return List - list all users for this directory
     *  @throws BaseDaoException
     */
    public List listUsers(String directoryId, int accessFlag) throws BaseDaoException {
        if (RegexStrUtil.isNull(directoryId)) {
            throw new BaseDaoException("params are null");
        }

        /** Jboss methods
         * fqn - full qualified name
         * check if the userpage already set in the cache
         * If it exists, return the userpage from the cache.
         */
        Fqn fqn = cacheUtil.fqn(DbConstants.DIR_OF_USERS);
        Object obj = treeCache.get(fqn, directoryId);
        if (obj != null) {
            return (List) obj;
        }

        /**
         *  Get scalability datasource, not partitioned
         */
        String sourceName = scalabilityManager.getReadZeroScalability();
        ds = scalabilityManager.getSource(sourceName);
        if (ds == null) {
            throw new BaseDaoException("ds null, listUsers() " + sourceName + " directoryId = " + directoryId);
        }

        /**
         * Get the list of users for this directory
         */
        HashSet hs1 = null;
        Connection conn = null;
        try {
            conn = ds.getConnection();
            if (conn != null) {
                hs1 = listDirUsersQuery.run(conn, directoryId);
            }
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e1) {
                throw new BaseDaoException("error listUsers()", e1);
            }
            throw new BaseDaoException("error in listing users  directoryId  " + directoryId, e);
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            throw new BaseDaoException("error, listUsers() conn.close(),directoryId = " + directoryId, e);
        }
        List result = new ArrayList(hs1);
        if ((result != null) && (result.size() > 0)) {
            treeCache.put(fqn, directoryId, result);
        }
        return result;
    }

    /**
    * getLoginsOfUsers - returns the list of users with their logins
    * @param userSet - HashSet of users with logins and member info
    * @return List -list of users with logins
    * @throws BaseDaoException -when error occurs
    */
    public List getLoginsOfUsers(List dirUsers) throws BaseDaoException {

        if (dirUsers == null) {
            return null;
        }

        List userList = new ArrayList();
        if (userList != null) {
            Iterator iterator = dirUsers.iterator();
            while (iterator.hasNext()) {
                Directory dir = (Directory) iterator.next();
                if (dir != null) {
                    userList.add(dir.getValue(DbConstants.LOGIN));
                }
            }
            return userList;
        }
        return null;
    }

    /**
     *  This property is setby spring automatically at web.xml startup
     * @param ds - this is JDBC datasource bean that is connection from the pool
     */
    public void setJdbcSource(DataSource ds) {
        this.ds = ds;
    }

    public void setdirectorydeleteuserQuery(DirUserDeleteQuery daq) {
        this.deleteUserQuery = daq;
    }

    public void setdirectoryadduserQuery(DirUserAddQuery daq) {
        this.addUserQuery = daq;
    }

    public void setdirlistusersQuery(DirectoryListUsersQuery daq) {
        this.listDirUsersQuery = daq;
    }

}