dao.PendingfriendDaoDb.java Source code

Java tutorial

Introduction

Here is the source code for dao.PendingfriendDaoDb.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.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import model.Friend;
import model.Hdlogin;
import model.Hdprofile;
import model.Pendingfriend;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
import util.*;

/**
  * This object implements PendingfriendDao
  *
  * @author Smitha Gudur (smitha@redbasin.com)
  * @version $Revision: 1.1 $
  */
public class PendingfriendDaoDb extends BaseDao implements PendingfriendDao {

    protected final Log logger = LogFactory.getLog(getClass());
    private volatile GlobalConst webconstants;
    private volatile SMTPTool hdmail;
    private volatile ExpiringObjectPool eop;

    private volatile PendingfriendExistsQuery listQuery;
    private volatile PendingfriendAddQuery addQuery;
    private volatile HdprofileQuery myprofileQuery;
    private volatile PendingfriendDeleteQuery deleteQuery;
    private volatile PendingfriendinQuery inQuery;
    private volatile PendingfriendoutQuery outQuery;
    private volatile FriendAddQuery friendAddQuery;
    private volatile IsFriendQuery friendQuery;

    /**
     * This method adds a pending friend as a friend.
     * @param guestLogin - the guest login that is added as a pending friend
     * @param memberId - the memberId to whom the pending friend is added.
     * @param memberLoginInfo - the members login information bean
     * @throws BaseDaoException
     **/
    public void addPendingFriend(String guestLogin, String memberId, Hdlogin memberLoginInfo)
            throws BaseDaoException {

        /**
          * (loginId = memberId) (sending person) 
          * (destloginId=guestLogin) (Receiving person, receives the request as a friend)
        */
        if (RegexStrUtil.isNull(guestLogin) || RegexStrUtil.isNull(memberId)) {
            throw new BaseDaoException("params are null");
        }

        /**
         * Get the guest's login information from guestLogin
              * the person sending the request, the order is important, do not remove this
         */
        Hdlogin hdlogin = getLoginid(guestLogin);
        if (hdlogin == null) {
            throw new BaseDaoException("hdlogin is null for guestLogin " + guestLogin);
        }
        String guestId = hdlogin.getValue(DbConstants.LOGIN_ID);
        if (RegexStrUtil.isNull(guestId)) {
            throw new BaseDaoException("guestId is null for guestLogin " + guestLogin);
        }
        String gfname = hdlogin.getValue("fname");
        String glname = hdlogin.getValue("lname");
        String to = hdlogin.getValue("email");

        /**
        * if already a friend, ignore it
        */
        List prefResult = null;
        Object[] myParams = { (Object) guestId, (Object) memberId };

        /**
         *  Get scalability datasource for pendingfriends - not partitioned
         */
        String sourceName = scalabilityManager.getWriteZeroScalability();
        ds = scalabilityManager.getSource(sourceName);
        if (ds == null) {
            throw new BaseDaoException("ds null, addPendingfriend() " + sourceName);
        }
        String from = webconstants.getMailfrom();

        /**
        * check if this entry exists for this user, do read_uncommitted also
        */
        HashSet pendingSet = null;
        Connection conn = null;
        try {
            conn = ds.getConnection();
            if (conn != null) {
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                pendingSet = listQuery.run(conn, memberId, guestId);
                conn.close();
            }
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e1) {
                throw new BaseDaoException("connection close exception ", e1);
            }

            throw new BaseDaoException("error occured in db query", e);
        }

        /**
        * this entry already exists in the pendinglist, return
        */
        if (!pendingSet.isEmpty()) {
            Iterator it1 = pendingSet.iterator();
            Integer count = new Integer(((Pendingfriend) it1.next()).getValue("count(*)"));
            if (count > 0) {
                return;
            }
        }

        /**
         *  add this friend
         */
        try {
            addQuery.run(guestId, memberId);
        } catch (Exception e) {
            throw new BaseDaoException("error occured while adding a PendingfriendAddQuery()" + addQuery.getSql()
                    + ", guestId = " + guestId + ", memberId = " + memberId, e);
        }

        /**
         * If the Email "to" field is missing, don't send email, just return
         */
        if (!RegexStrUtil.isNull(to)) {

            /**
             *  Get scalability datasource for hdprofile - partitioned on loginId
             */
            sourceName = scalabilityManager.getReadScalability(guestId);
            ds = scalabilityManager.getSource(sourceName);
            if (ds == null) {
                throw new BaseDaoException("ds null, addPendingfriend() " + sourceName);
            }

            /**
             * check if the guest needs to be notified
             */
            Object[] params = { (Object) guestId };
            //params[0] = guestId;
            prefResult = null;
            try {
                prefResult = myprofileQuery.execute(params);
            } catch (Exception e) {
                throw new BaseDaoException("error occured while executing HdprofileQuery()"
                        + myprofileQuery.getSql() + " guestId = " + params[0], e);
            }

            if (prefResult.size() == 1) {
                Hdprofile hdprofile = (Hdprofile) prefResult.get(0);
                if (hdprofile.getValue("informfd").equalsIgnoreCase("1")) {
                    //memberId = memberLoginInfo.getValue(DbConstants.LOGIN_ID);
                    String fname = memberLoginInfo.getValue(DbConstants.FIRST_NAME);
                    String lname = memberLoginInfo.getValue(DbConstants.LAST_NAME);
                    String subject = "Invitation for friendship with " + fname + " " + lname;
                    String msg = "Hi, " + gfname + "\n" + fname + " " + lname + " has sent you " + "\n\n"
                            + "Members webpage: " + webconstants.getHddomain() + "/userpage?member="
                            + memberLoginInfo.getValue(DbConstants.LOGIN) + webconstants.getMailfooter();
                    hdmail.sendEmail(to, subject, msg, from);
                }
            }
        }

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

        fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
        if (treeCache.exists(fqn, memberLoginInfo.getValue(DbConstants.LOGIN))) {
            treeCache.remove(fqn, memberLoginInfo.getValue(DbConstants.LOGIN));
        }
    }

    /**
     * delete a pendingfriend
     * @param guestLogin - guest login
     * @param loginId - the login id
     * @param login - the login 
     * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
    */
    public void deletePendingFriend(String guestLogin, String loginId, String login) throws BaseDaoException {

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

        /**
         *  Get scalability datasource for pendingfriends - not partitioned
         */
        String sourceName = scalabilityManager.getWriteZeroScalability();
        ds = scalabilityManager.getSource(sourceName);
        if (ds == null) {
            throw new BaseDaoException("ds null, deletePendingFriend() " + sourceName);
        }
        String guestId = getLoginid(guestLogin).getValue(DbConstants.LOGIN_ID);
        try {
            deleteQuery.run(guestId, loginId);
        } catch (Exception e) {
            throw new BaseDaoException("error occured while PendingfriendDeleteQuery()" + deleteQuery.getSql()
                    + ", guestId = " + guestId + ", loginId = " + loginId, e);
        }

        /**
         * delete the cache based on the loginId  
         */
        Fqn fqn = cacheUtil.fqn(DbConstants.OUT_PENDING);
        if (treeCache.exists(fqn, guestId)) {
            treeCache.remove(fqn, guestId);
        }

        /**
         * delete the cache based on the destination loginId
         */
        fqn = cacheUtil.fqn(DbConstants.IN_PENDING);
        if (treeCache.exists(fqn, loginId)) {
            treeCache.remove(fqn, loginId);
        }

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

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

    /**
     * check if there are pending in/out requests. it sets inreq and outreq params.
     * @param loginId
     * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
     */
    public Pendingfriend checkPendingfriends(String loginId) throws BaseDaoException {

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

        List result = getIncomingPendingList(loginId);
        List oResult = getOutgoingPendingList(loginId);

        Pendingfriend pending = null;
        if ((oResult == null) && (result == null)) {
            pending = (Pendingfriend) eop.newObject(DbConstants.PENDING_FRIEND);
        }

        if ((result != null) && (result.size() > 0)) {
            pending = (Pendingfriend) result.get(0);
            pending.setValue("inreq", "1");
        } else {
            if ((oResult != null) && (oResult.size() > 0)) {
                pending = (Pendingfriend) oResult.get(0);
                pending.setValue("outreq", "1");
            } else {
                // oResult.size() <= 0 and result.size <= 0
                if (oResult != null) {
                    pending = (Pendingfriend) eop.newObject(DbConstants.PENDING_FRIEND);
                }
                pending.setValue("outreq", "0");
            }
            pending.setValue("inreq", "0");
        }
        return pending;
    }

    /**
     * incoming requests are matched with (pendingfriends.destloginId = loginId)
     * get list of incoming pending friends.
     * @param loginId
     * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
     */
    public List getIncomingPendingList(String loginId) throws BaseDaoException {

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

        Fqn fqn = cacheUtil.fqn(DbConstants.IN_PENDING);
        Object obj = treeCache.get(fqn, loginId);
        if (obj != null) {
            return (List) obj;
        }

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

        List result = null;
        try {
            result = inQuery.execute(loginId);
        } catch (Exception e) {
            throw new BaseDaoException(
                    "error occured while PendingfriendinQuery() " + inQuery.getSql() + ", loginId = " + loginId, e);
        }
        if ((result != null) && (result.size() > 0)) {
            treeCache.put(fqn, loginId, result);
        }
        return result;
    }

    /**
     * get list of outgoing pending friends.
     * @param loginId
     * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
     */
    public List getOutgoingPendingList(String loginId) throws BaseDaoException {

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

        Fqn fqn = cacheUtil.fqn(DbConstants.OUT_PENDING);
        Object obj = treeCache.get(fqn, loginId);
        if (obj != null) {
            return (List) obj;
        }

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

        /**
              * outgoing request is matched with (pendingfriends.loginId = loginId) 
         */
        List result = null;
        try {
            result = outQuery.execute(loginId);
        } catch (Exception e) {
            throw new BaseDaoException("error occured while executing PendingfriendoutQuery()" + outQuery.getSql()
                    + ", loginId = " + loginId, e);
        }

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

    /**
     * adds the guestLogin as a friend
     * @param guestLogin  - the guestId
     * @param loginId  - the loginid
     * @param login  - the login
     * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
     */
    public void addFriend(String guestLogin, String loginId, String login) throws BaseDaoException {

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

        Hdlogin hdlogin = getLoginid(guestLogin);
        if (hdlogin == null) {
            throw new BaseDaoException("hdlogin is null for guestLogin " + guestLogin);
        }
        String guestId = hdlogin.getValue(DbConstants.LOGIN_ID);
        if (RegexStrUtil.isNull(guestId)) {
            throw new BaseDaoException("guestId is null for guestLogin " + guestId);
        }

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

        /**
        *  add friend
        */
        Connection conn = null;
        try {
            conn = ds.getConnection();
            conn.setAutoCommit(false);
            if (conn != null) {
                friendAddQuery.run(conn, guestId, loginId);
            }
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (Exception e1) { // (Exception e1)
                try {
                    if (conn != null) {
                        conn.setAutoCommit(true);
                        conn.close();
                    }
                } catch (Exception e2) { // (Exception e2)
                    throw new BaseDaoException("conn.setAutoCommit() error in friendAddQuery() guestId = " + guestId
                            + ", loginId = " + loginId, e2);
                }
                throw new BaseDaoException(
                        "conn.rollback error in friendAddQuery() guestId = " + guestId + ", loginId = " + loginId,
                        e1);
            }
            throw new BaseDaoException(
                    "error occured while executing friendAddQuery() guestId =" + guestId + ", loginId = " + loginId,
                    e);
        } // (Exception e)

        /**
         * commit the transaction
         */
        try {
            if (conn != null) {
                conn.commit();
                conn.setAutoCommit(true);
                conn.close();
            }
        } catch (Exception e) {
            throw new BaseDaoException("con.commit()/conn.setAutoCommit()/conn.close() exception", e);
        }

        /**
         * delete the cache based on the loginId 
         */
        Fqn fqn = cacheUtil.fqn(DbConstants.OUT_PENDING);
        if (treeCache.exists(fqn, guestId)) {
            treeCache.remove(fqn, guestId);
        }

        fqn = cacheUtil.fqn(DbConstants.IN_PENDING);
        if (treeCache.exists(fqn, loginId)) {
            treeCache.remove(fqn, loginId);
        }

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

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

    /**
     * returns true if this guest is a friend else false.
     * @param guestLogin
     * @param loginId
     * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
     * @return boolean
     */
    public boolean isAFriend(String guestLogin, String loginId) {

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

        Hdlogin hdlogin = getLoginid(guestLogin);
        if (hdlogin == null) {
            throw new BaseDaoException("hdlogin is null for guestLogin " + guestLogin);
        }

        String guestId = hdlogin.getValue(DbConstants.LOGIN_ID);
        if (RegexStrUtil.isNull(guestId)) {
            throw new BaseDaoException("guestId is null for guestLogin " + guestLogin);
        }
        /**
        * return true if guestLogin is a friend of login. 
        */
        return isMyFriend(loginId, guestId);
    }

    /**
     * checks if the guestId and loginId are friends
     * @param guestId
     * @param loginId
     * @param ds
     * @return boolean
     */
    private boolean isMyFriend(String guestId, String loginId) {

        StringBuffer sb = new StringBuffer(guestId);
        sb.append("-");
        sb.append(loginId);
        Fqn fqn = cacheUtil.fqn(DbConstants.FRIEND);
        Object obj = treeCache.get(fqn, sb.toString());
        if (obj != null) {
            return (((Friend) obj).getValue(DbConstants.IS_FRIEND).equals("1"));
        }

        StringBuffer loginBuf = new StringBuffer(loginId);
        loginBuf.append("-");
        loginBuf.append(guestId);
        obj = treeCache.get(fqn, loginBuf.toString());
        if (obj != null) {
            return (((Friend) obj).getValue(DbConstants.IS_FRIEND).equals("1"));
        }

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

        Object[] params = { (Object) loginId, (Object) guestId };
        List result1 = friendQuery.execute(params);
        if (result1 != null) {
            if (result1.size() > 0) {
                treeCache.put(fqn, loginBuf.toString(), ((Friend) result1.get(0)));
                return true;
            }
        } else {
            params[0] = guestId;
            params[1] = loginId;
            result1 = friendQuery.execute(params);
            if (result1 != null) {
                if (result1.size() > 0) {
                    ((Friend) result1.get(0)).setValue(DbConstants.IS_FRIEND, "1");
                    treeCache.put(fqn, sb.toString(), ((Friend) result1.get(0)));
                    return true;
                }
            }
        }
        return false;
    }

    /**
     *  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 setMailutils(SMTPTool mailutils) {
        this.hdmail = mailutils;
    }

    public void setWebconstants(GlobalConst webconstants) {
        this.webconstants = webconstants;
    }

    public void setpendingfriendexistsQuery(PendingfriendExistsQuery daq) {
        this.listQuery = daq;
    }

    public void setpendingfriendaddQuery(PendingfriendAddQuery daq) {
        this.addQuery = daq;
    }

    public void sethdprofileQuery(HdprofileQuery daq) {
        this.myprofileQuery = daq;
    }

    public void setpendingfrienddeleteQuery(PendingfriendDeleteQuery daq) {
        this.deleteQuery = daq;
    }

    public void setpendingfriendinQuery(PendingfriendinQuery daq) {
        this.inQuery = daq;
    }

    public void setpendingfriendoutQuery(PendingfriendoutQuery daq) {
        this.outQuery = daq;
    }

    public void setfriendaddQuery(FriendAddQuery daq) {
        this.friendAddQuery = daq;
    }

    public void setisfriendQuery(IsFriendQuery daq) {
        this.friendQuery = daq;
    }

    public void setEop(ExpiringObjectPool eop) {
        this.eop = eop;
    }
}