Package appl.Portal.Personalize.DB

Source Code of appl.Portal.Personalize.DB.P_Db

/*
*  This software and supporting documentation were developed by
*
*    Siemens Corporate Technology
*    Competence Center Knowledge Management and Business Transformation
*    D-81730 Munich, Germany
*
*    Authors (representing a really great team ;-) )
*            Stefan B. Augustin, Thorbj�rn Hansen, Manfred Langen
*
*  This software is Open Source under GNU General Public License (GPL).
*  Read the text of this license in LICENSE.TXT
*  or look at www.opensource.org/licenses/
*
*  Once more we emphasize, that:
*  THIS SOFTWARE IS MADE AVAILABLE,  AS IS,  WITHOUT ANY WARRANTY
*  REGARDING  THE  SOFTWARE,  ITS  PERFORMANCE OR
*  FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR
*  ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND
*  PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
*
*/


// P_Db

// ************ package ******************************************************
package appl.Portal.Personalize.DB;

// ************ imports ******************************************************

// Personalize packages
import appl.Portal.Personalize.GUI.*;
import appl.Portal.Personalize.Servlet.P_Props;

// KFM packages
import KFM.Exceptions.KFM_SQLException;
import KFM.DB.*;
import KFM.log.*;
import KFM.Converter;
import KFM.Smtp;
import KFM.DateTimeServices.*;
import KFM.GUI.*;

// Java packages
import java.sql.*;
import java.util.*;

/** DB class for `Personalize�.
*
* <P>Contains commands to update the DB, but not to query.
* We use the "view" classes to query the DB.</P>
*
*
* <H2>Related classes</H2>
*
* <P>Cut+paste-source was `EX3_Db�</P>
*
* @version 0.1 (2001-02-05)
*/
public class P_Db extends ApplicationDb2
{

    // ************************************************************
    // Constants
    // ************************************************************

    /** String constants for events (HTTP parameter `execute�). */
    private final static P_Events mEvents = new P_Events();

    // ************************************************************
    // Variables
    // ************************************************************

    /** Log, copy of `KFM_PropertyServlet2_Props.mLog� for easier access. */
    protected KFMLog mLog;

    /** Logging for ES access only */
    protected KFMLog mLog2;

    /** Servlet properties. */
    P_Props mServletProps = null;

    /** statistics */
    long mRequestNumber;
    TransientServletStatistic mStatistic;

    // sending mails when received tcgid or apd_persnr do not
    // match with values stored in DB
    String mMailSubject;

    // The name of the server on which our software is running
    protected static final String mHostname="("+getHostName()+")";




    // ************************************************************
    // Methods
    // ************************************************************

    /** Constructor.
     *
     * @param aAdapter  The KFM_JdbcAdapter of the DB to be used.
     */
    public P_Db (KFM_JdbcAdapter aAdapter, KFMLog aLog, P_Props aServletProps,
                 long aRequestNumber,
                 TransientServletStatistic aStatistic,
                 KFMLog aLog2)
    {
        super(aAdapter, "appl.Portal.Personalize.DB.P_Db");
        mLog  = aLog;
        mLog2 = aLog2;
        mServletProps = aServletProps;
        mRequestNumber= aRequestNumber;
        mStatistic=aStatistic;
        mMailSubject=mServletProps.LogFileOriginator2+mHostname;
    }

    /** Constructor.
     *
     * @param aAdapter  The KFM_JdbcAdapter of the DB to be used.
     */
    public P_Db (KFM_JdbcAdapter aAdapter, KFMLog aLog, P_Props aServletProps, KFMLog aLog2)
    {
        this(aAdapter, aLog, aServletProps, -1, null, aLog2);
    }

    /** Update the user settings
     *
     * <P>Note: This method does *not* commit. Do that in the ApplPage.</P>
     *
     * @param aValues    vector containing column name, new value and column type of
     *                   the columns which have to be updated in the database.
     * @param aNick      nick of the user
     * @param aWhere     column to use for the where clause
     */
    public void updateMember (Vector aValues, String aNick, String aWhere)
        throws KFM_SQLException
    {
        // update part
        String tSqlString = "UPDATE members SET ";
        Vector tDesktopNames = new Vector();

        // value part
        StringBuffer tValuesBuf=new StringBuffer();
        for (int i=0; i<aValues.size(); i++){
            int tType=((P_DBEntry)aValues.elementAt(i)).getDBType();
            // Text
            if (tType==PersonalizeDbConsts.cText){
                //do Nothing because Clobs mustn't be inserted in the UPDATE clause
                tDesktopNames.addElement(((P_DBEntry)aValues.elementAt(i)).getName());
            }
            else {
                String tName = ((P_DBEntry)aValues.elementAt(i)).getName();
                if (!tName.equals("id")){
                    tValuesBuf.append(((P_DBEntry)aValues.elementAt(i)).getName()+"=?");
                    tValuesBuf.append(", ");
                }
            }
        }
        String tValues = tValuesBuf.toString();
        if (tValues.endsWith(", "))
            tValues = tValues.substring(0, (tValues.length() - 2));

        /**
        * First get the current members_id to identify the current profile.
        * If we have more profile that fits to 'aNick' and 'aWhere', all of the
        * profiles would be updated then. That makes it difficult to identify old profiles.
        */
        String tMembers_Id = getMembersId(aNick, aWhere);
        // where part
        String tWhere =" WHERE "
                      + aWhere
                      + " ='"
                      + mDbA.convertString(aNick)
                      + "' "
                      + "and id"
                      + " ='"
                      + tMembers_Id
                      + "' ";


        // complete SQL update statement
        tSqlString=tSqlString+tValues+tWhere;
        int mUpdateCmd = mDbA.prepareStmt(tSqlString);
        Vector tDeskopValues = new Vector(); //holds the values for the desktops
        try {
            String tMembersID = getMembersId(aNick, aWhere);
            // replace the "?" with values
            // empty values will be written as SQL null
            int j = -1;
            for (int i=0; i<aValues.size(); i++){
                String tName = ((P_DBEntry)aValues.elementAt(i)).getName();
                if (!tName.equals("id")){
                    String tValue=((P_DBEntry)aValues.elementAt(i)).getValue();
                    int tType=((P_DBEntry)aValues.elementAt(i)).getDBType();
                    j ++;
                    // Text
                    if (tType==PersonalizeDbConsts.cText){
                        tDeskopValues.addElement(tValue);
                        j --;
                    // VarChar
                    } else if ((tType==PersonalizeDbConsts.cVarChar)
                        || (tType==PersonalizeDbConsts.cChar)){
                        mDbA.setStringOrNull(mUpdateCmd, j+1, tValue);
                    // Integer
                    } else if (tType==PersonalizeDbConsts.cInt){
                        if (tValue.equals("")){
                            mDbA.setNull(mUpdateCmd, j+1, java.sql.Types.INTEGER);
                        } else {
                            int tIntValue = Integer.parseInt(tValue);
                            mDbA.setValue(mUpdateCmd, j+1, tIntValue);
                        }
                    // Tiny Integer
                    } else {
                        if (tValue.equals("")){
                            mDbA.setNull(mUpdateCmd, j+1, java.sql.Types.TINYINT);
                        } else {
                            int tIntValue = Integer.parseInt(tValue);
                            mDbA.setValue(mUpdateCmd, j+1, tIntValue);
                        }
                    }
                }

            }

            mDbA.executeUpdate(mUpdateCmd);

            //now set the desktop values
            if (tDesktopNames.size() > 0) {
                try {
                    PersonalizeDbServices tServices = new PersonalizeDbServices(
                    mDbA, mLog);
                    StringBuffer tDesktopSQL = new StringBuffer("Update desktops set ");
                    tDesktopSQL.append("item0=?,");
                    tDesktopSQL.append("item1=?,");
                    tDesktopSQL.append("item2=?,");
                    tDesktopSQL.append("item3=?,");
                    tDesktopSQL.append("item4=?,");
                    tDesktopSQL.append("item5=?");
                    tDesktopSQL.append(" where members_id='"+tMembersID + "' and desktopName=?");
                    String[] tDesktopNamesStr = new String[tDesktopNames.size()];
                    tDesktopNames.copyInto(tDesktopNamesStr);
                    tServices.executeP_DesktopsUpdate(
                        tDesktopSQL.toString(),
                        tDesktopNamesStr,
                        tDeskopValues);
                    //closes the statement automatically
                } catch (KFM_SQLException ex){
                    //rollback
                    mDbA.rollback();
                    throw niceSqlException(ex); //inform the user about the error
                }
            }
            mDbA.commit(); //no error has occured so save the values
        } catch(SQLException e) {
            mLog.error("", e);
            throw niceSqlException(e);
        }
        finally{
            //close the statement to free db resources (open cursors)
            mDbA.closeStmt(mUpdateCmd);
        }
    }


    /** Checks whether the given password for the user is correct.
     *
     *@param aNick     nick you want to check
     *@param aPassword the plain password of user you want to check
     *@param aExecute  execute parameter
     *
     *@return true if password of user is correct, otherwise false
     */
    public boolean passwordIsCorrectPlain (
        String aNick,
        String aPassword,
        String aExecute)
        throws KFM_SQLException
    {
        try {

            // check if user is registered in portal db
            String sql = "SELECT password, authtype FROM members WHERE nick = ? order by APD_PERSNR, tcgid";

            long tTime=System.currentTimeMillis();

            int tSel = mDbA.prepareStmt(sql);
            try {
                mDbA.setValue(tSel, 1, aNick);
                ResultSet rs = mDbA.executeQuery(tSel);

                // statistics
                long tEnd=System.currentTimeMillis()-tTime;
                mLog.debug(mRequestNumber+": passwordIsCorrect took ms: "+tEnd);
                if (mStatistic != null){
                    mStatistic.addRemark(" PWIsCorrect: ms "+tEnd, mRequestNumber);
                }
                if(!rs.next()){
                    // not registered user is trying to login, display the registration form
                    if (aExecute.equals(mEvents.P_FW_Login)){
                        mLog.debug("User tries to login but account does not exist in the members DB");
                        return true;
                    }
                    return false;
                }

                // From now on user is registered in members DB
                String tPassword = rs.getString(1);
                String tAuthtype = rs.getString(2);

                // authtype stored in database has to be plain and
                // passwords have to be equal
                if(tAuthtype.equals("plain") && aPassword.equals(tPassword)){
                    return true;
                }

                return false;
            } finally {
                mDbA.closeStmt(tSel);
            }
        } catch(SQLException e) {
            throw niceSqlException(e);
        }
    }

    /** Changes a password for a user with authtype plain.
     *
     *@param aNick     nick you want to check
     *@param aPassword the plain password of user you want to check
     *@param aExecute  execute parameter
     *
     *@return true if password of user is correct, otherwise false
     */
    public boolean changePasswordPlain (
        String aNick,
        String aNewPassword)
        throws KFM_SQLException
    {
        boolean tRetValue = false;
        try {
            // check if user is registered in portal db
            String sql = "Update members set password=? WHERE nick = ? and authtype='plain'";

            long tTime=System.currentTimeMillis();

            int tSel = mDbA.prepareStmt(sql);
            try {
                mDbA.setValue(tSel, 1, aNewPassword);
                mDbA.setValue(tSel, 2, aNick);
                mDbA.executeUpdate(tSel);
                tRetValue = true;
            } finally {
                mDbA.closeStmt(tSel);
            }

        } catch(SQLException e) {
            throw niceSqlException(e);
        }
        return tRetValue;
    }



    /** Used for statistics
    */
    public void setRequestNumber(long aRequestNumber){
        mRequestNumber=aRequestNumber;
    }

    /** Checks whether a user profile for a given user exits.
     * The check depends on the authtype.
     * PKI or SCD: A profile based on tcgid has to exist
     * PLAIN: A Profile based on nick has to exist
     *
     *@param aUser      user to check.
     *@param aAuthtype  authtype of the user
     *@return           whether profile exists.
     *@exception KFM_SQLException
     */
    public boolean checkUserProfileExists (String aUser, String aAuthtype)
        throws KFM_SQLException
    {
        // Empty user id is not allowed
        if (aUser.equals("")) return false;
        //we use delegation to centralize the code on one place
        PersonalizeDbServices tServices = new PersonalizeDbServices(mDbA, mLog);
        return tServices.checkUserProfileExists(aUser, aAuthtype);

    }

    /** Returns the current login counter 'count_logins' of the given nick.
     *
     *@param aNick  nick of the user
     *@param aWhere column to use for the where clause
     *@exception KFM_SQLException
     */
    public int getCurrentLoginCounter (String aNick, String aWhere)
        throws KFM_SQLException
    {
        int tResult=0;
        try {
            int tSel = mDbA.prepareStmt("SELECT count_logins FROM members WHERE "+aWhere+" = ? order by APD_PERSNR, tcgid");
            mDbA.setValue(tSel, 1, aNick);
            ResultSet rs = mDbA.executeQuery(tSel);
            if (rs.next()){
                tResult = rs.getInt(1);
            }
            mDbA.closeStmt(tSel);
            return tResult;
        } catch(SQLException e) {
            throw niceSqlException(e);
        }
    }


     /** Returns the date when user has used the portal last time.
     *
     *@param aNick  nick of the user
     *@param aWhere column to use for the where clause
     *@exception KFM_SQLException
     */
    public String getLastLogin (String aNick, String aWhere)
        throws KFM_SQLException
    {
        String tResult="";
        try {
            int tSel = mDbA.prepareStmt("SELECT last_login FROM members WHERE "+aWhere+" = ? order by APD_PERSNR, tcgid");
            mDbA.setValue(tSel, 1, aNick);
            ResultSet rs = mDbA.executeQuery(tSel);
            if (rs.next()){
                tResult = rs.getString(1);
            }
            mDbA.closeStmt(tSel);
            return tResult;
        } catch(SQLException e) {
            throw niceSqlException(e);
        }
    }

    /** Returns the default dn (that means the dn of the SCD profile which should be
     * used in case of multiple SCD entries)
     *
     *@param aTcgid  tcgid of the user
     *@exception KFM_SQLException
     *
     * Note: This method is currently not used.
     * Maybe later we decide to store the default dn of an user in the database, currently we
     * prompt the user at every login time for the dn to use (MULTIPLE SCD ENTRIES).
     *
     * @deprecated first construct a proper finally block which closes the statement in all cases.
     */
    public String getDefaultDN (String aTcgid)
        throws KFM_SQLException
    {
        String tResult=null;
        try {
            mLog.info("VOR SELECT dn FROM members WHERE tcgid");
            int tSel = mDbA.prepareStmt("SELECT dn FROM members WHERE tcgid  = ? order by APD_PERSNR, tcgid");
            mDbA.setValue(tSel, 1, aTcgid);
            ResultSet rs = mDbA.executeQuery(tSel);
            if (rs.next()){
                // user is registered
                tResult = rs.getString(1);
                if (tResult.toLowerCase().equals("null")){
                    // default dn is not set
                    tResult="";
                }
            }
            mDbA.closeStmt(tSel);
            return tResult;
        } catch(SQLException e) {
            throw niceSqlException(e);
        }
    }

    /** Returns the ID of the given nick.
     *
     *@param String aNick  nick of the user
     *@param String aWhere column to use for the where clause
     *@exception KFM_SQLException
     */
    public String getMembersId (String aNick, String aWhere)
        throws KFM_SQLException
    {
        //we use delegation to centralize the code on one place
        PersonalizeDbServices tServices = new PersonalizeDbServices(mDbA, mLog);
        return tServices.getMembersId(aNick, aWhere);

    }


    /** Check if the given  SCD user is registered in the PortalDB.
     *
     * For a SCD user we check if already a TCGID based profile exists.
     * If there exists no TCGID profile but we got the apd_persnr from the ES,
     * we check if a MAD based profile exists.
     *
     * For a SCD user the TCGID profile is the first
     * try and the MAD based the second try.
     *
     ***** SCD USER *****
     * TCGID based profile found:
     * 1)if we got the APD_PersNr from the ES and the APD_PersNr is not set in the
     *   database we set it
     * 2)if APD_PersNr received from the ES does not equal the APD_PersNr stored in
     *   the database we update it
     * 3)we update email and ma-ident if necessary
     *
     * MAD based profile found:
     * 1)set tcgid in profile
     * 2)we update email and ma-ident if necessary
     *
     *@param String aFirst     2002-04-15 MAD not longer supported =>tcgid of the user
     *@param String aType      the authType: 'SCD' or 'MAD'
     *@param Hashtable aUserData  userdata received from the ES
     *@exception KFM_SQLException
     */
    public void checkAndUpdateDatabaseES(String aFirst, String aType, Hashtable aUserData)
        throws KFM_SQLException
    {
        boolean tFIRSTProfileExists   = false;
        boolean tSECONDProfileExists  = false;
        String  tCSecond;
        String  tWhereFirst;
        String  tWhereSecond;
        String  tSelectFirst;
        String  tSelectSecond;

        tCSecond=(String)aUserData.get("apd")+(String)aUserData.get("persno");
        tWhereFirst  ="tcgid";
        tWhereSecond ="apd_persnr";
        tSelectFirst ="apd_persnr";
        tSelectSecond="tcgid";

        try {
            boolean tUpdateAPD=false;
            String tNewAPD="";

            // check if profile based on FIRST exists
            int tSel = mDbA.prepareStmt("SELECT "+tSelectFirst+", MA_IDENT, email FROM members WHERE "+tWhereFirst+" = ? order by APD_PERSNR, tcgid");
            mDbA.setValue(tSel, 1, aFirst);
            ResultSet rs = mDbA.executeQuery(tSel);

            if (rs.next()){
                // FIRST profile exists
                tFIRSTProfileExists=true;
            } else {
                // FIRST profile does not exist, try if SECOND profile can be used
                if (!tCSecond.equals("")){

                    tSel = mDbA.prepareStmt("SELECT "+tSelectSecond+", MA_IDENT, email FROM members WHERE "+tWhereSecond+" = ? order by APD_PERSNR, tcgid");
                    mDbA.setValue(tSel, 1, tCSecond);
                    rs = mDbA.executeQuery(tSel);
                    if (rs.next()){
                        // SECOND profile exists

                       String tSecond=rs.getString(1);
                       if ((tSecond != null) && !tSecond.equals("")){
                            if (aType.equals("scd")){
                                // wrong tcgid received, this should not happen
                                sendMail(mMailSubject+": inconsitent data received from ES", "",
                                        "Inconsistent data received from the ES Authentication servlet\n"+
                                        "User: "+ tCSecond+ "\nvalue stored in DB: "+tSecond+"\nvalue received: "+aFirst);
                            } else {
                                tSECONDProfileExists=true;
                            }
                       } else {
                        tSECONDProfileExists=true;
                       }
                    }
                }
            }

            // if one of the profiles exists we update columns if necessary
            if (tFIRSTProfileExists || tSECONDProfileExists){
                Vector tUpdateData = new Vector();
                // values in DB
                String tSecond   = rs.getString(1);
                String tMAIDENT  = rs.getString(2);
                String tEMail    = rs.getString(3);
                if (tSecond==nulltSecond="";
                if (tMAIDENT==null) tMAIDENT="";
                if (tEMail==null)   tEMail="";


                // values received from ES
                String tCMAIDENT  = (String)aUserData.get("maident");
                String tCEMail    = (String)aUserData.get("email");

                if (tFIRSTProfileExists){
                    // if SECOND is not set in database AND we got SECOND from the ES
                    // then we store it in DB
                    if (tSecond.equals("") && !tCSecond.equals("")){
                        P_DBEntry tEntry=new P_DBEntry(tSelectFirst, tCSecond, PersonalizeDbConsts.cVarChar);
                        tUpdateData.addElement(tEntry);
                    }

                    // if SECOND is set in database AND SECOND received from the ES does not
                    // equal SECOND in DB then we send email
                    if (!tSecond.equals("") && !tCSecond.equals("") && !tSecond.equals(tCSecond)){
                        if (aType.equals("mad")){
                            sendMail(mMailSubject+": inconsitent data received from ES", "",
                                    "Inconsistent data received from the ES Authentication servlet\n"+
                                    "User: "+ aFirst+ " value stored in DB: "+tSecond+" value received: "+tCSecond);
                        } else {
                            // SCD
                            tUpdateAPD=true;
                            tNewAPD=tCSecond;
                        }
                    }
                }
                if (tSECONDProfileExists){
                    // set FIRST
                    P_DBEntry tEntry=new P_DBEntry(tWhereFirst, aFirst, PersonalizeDbConsts.cVarChar);
                    tUpdateData.addElement(tEntry);
                }

                // if MA-Ident stored in DB does not match received MA-Ident we update DB
                if (!tMAIDENT.equals(tCMAIDENT) && !tCMAIDENT.equals("")){
                    // we have to update the ma-ident
                    P_DBEntry tEntry=new P_DBEntry("MA_IDENT", tCMAIDENT, PersonalizeDbConsts.cVarChar);
                    tUpdateData.addElement(tEntry);
                }

                // add update data to the vector
                addUpdateData(tUpdateData, aUserData);

                // if APD_PERSNR stored in DB does not match received APD_PERSNR we update DB
                if (tUpdateAPD){
                    // we have to update the APD personal number
                    P_DBEntry tEntry=new P_DBEntry("APD_PERSNR", tNewAPD, PersonalizeDbConsts.cVarChar);
                    tUpdateData.addElement(tEntry);
                }

                // update database if necessary
                if (!tUpdateData.isEmpty()){
                    if (tFIRSTProfileExists){
                        updateMember(tUpdateData, aFirst,   tWhereFirst);
                    } else{
                        updateMember(tUpdateData, tCSecond, tWhereSecond);
                    }
                }
            }
            mDbA.closeStmt(tSel);
        } catch(SQLException e) {
            throw niceSqlException(e);
        }

    }



    /** Check if the given user is registered in the 'members' database.
     * If yes, we update some columns (@see P_DB.addUpdateData(...) )
     *
     *@param aTcgid tcgid of the user
     *@param aUserData a hashtable with all userdata received from PKI certificate server
     */
    public void checkAndUpdateDatabasePKI (String aTcgid, Hashtable aUserData)
        throws KFM_SQLException
    {
        try {
            int tSel = mDbA.prepareStmt("SELECT email FROM members WHERE tcgid = ? ORDER BY apd_persnr, tcgid");
            mDbA.setValue(tSel, 1, aTcgid);
            ResultSet rs = mDbA.executeQuery(tSel);
            if (rs.next()){
                Vector tUpdateData = new Vector();

                // add data (column names and related entries) from the
                // hastable to the vector
                addUpdateData(tUpdateData, aUserData);

                // update 'members' database
                updateMember(tUpdateData, aTcgid, "tcgid");
            } else {
                // USER is not registered, nothing to do
            }
            mDbA.closeStmt(tSel);
        } catch(SQLException e) {
            throw niceSqlException(e);
        }

    }

    /** Add data (key value pairs) from the given hastable to the given vector, in
     * order to update our 'members' database.
     *
     *  Note: The key names in the hashtable are not identical to the column names
     *  in our 'members' db. Therefore we do a mapping between key and column names.
     *
     * @param aUpdateData Vector that will be filled with user data
     * @param aUserData   Hashtable that contains the userdata
     */
    private void addUpdateData(Vector aUpdateData, Hashtable aUserData)
    {
        // Requirement from gusty: update the following columns of table members
        // on each login request. this entries can be used for statistic purposes.

        // column names of 'members' db
        String[] tDBColumns = {"email", "first_name", "last_name", "unit", "phone", "location", "country"};

        // key names of hashtable from auth service (happe servlet)
        String[] tHappeColumns = {"email", "firstname", "lastname", "siemensorganisation", "phone", "location", "country"};

        for (int i=0; i < tDBColumns.length; i++) {
            String tColumnValue = (String)aUserData.get(tHappeColumns[i]);
            if (tColumnValue != null) {
                P_DBEntry tEntry=new P_DBEntry(tDBColumns[i], tColumnValue, PersonalizeDbConsts.cVarChar);
                aUpdateData.addElement(tEntry);
            } else {
                // System.out.println("tColumns["+ i + "] is null");
            }
        }
        return;
    }
    /** Sends mail to receivers.
     */
    protected void sendMail (
        String aSubject,
        String aEvent,
        String aMessage)
    {
        aMessage = "Subject: "+aSubject + ": "+ aEvent+"\n\n"
            + KFM_DateTimeService.createTimeStamp() + ": " + aMessage;

        // *Send* mail via Smtp class. Yes, really, the constructor *sends* a mail.
        Smtp tMail = new Smtp(mServletProps.MailHost,
            mServletProps.SCDHotlineEmail,
            mServletProps.SCDHotlineEmail,
            aMessage,
            true /*several recipients*/);
    }

    /**
     * This method returns the name of the host on which the software is running.
     */
    private static String getHostName() {
        String tHostname="Unkown";
        try {
             tHostname= java.net.InetAddress.getLocalHost().getHostName();
        } catch (Exception e){}
        return tHostname;
    }

    /**
     * Delete a Portal User from the Database.
     *
     * @param String aNick the nick according to aWhere
     * @param String aWhere "nick"/plain, "apd_persno"/mad, "tcgid"/scd/pki
     */
    public boolean deleteUser(String aNick, String aWhere)
        throws KFM_SQLException
    {
        String tSQLSelectString = "SELECT COUNT(*) FROM members";
        String tSQLDeleteString = "DELETE FROM members";
        String tWhere = " WHERE " + aWhere + " ='" + aNick + "'";

        int tSel=-1;
        int tStmt=-1;
        try {
            tSel = mDbA.prepareStmt(tSQLSelectString + tWhere);
            ResultSet rs = mDbA.executeQuery(tSel);
            if (rs.next()){
                int tCount=Integer.parseInt(rs.getString(1));
                if (tCount == 1){
                    tStmt = mDbA.prepareStmt(tSQLDeleteString + tWhere);
                    int tResult = mDbA.executeUpdate(tStmt);

                    // i'm not sure what result to expect here
                    return (tResult > 0);
                }
            }
        } catch(SQLException e) {
            throw niceSqlException(e);
        } finally {
            // make sure the statement is closed in any case
            if(tStmt != -1) {
                try {
                    mDbA.closeStmt(tStmt);
                } catch(SQLException e) {
                }
            }
            if(tSel != -1) {
                try {
                    mDbA.closeStmt(tSel);
                } catch(SQLException e) {
                }
            }
        }
        return false;
    }

    /**
     * Update login counter and last login entries in the members database.
     */
    public boolean updateLoginInfo(String aUserId, String aWhere) throws KFM_SQLException
    {
        boolean tAlreadyLoggedInToday=false;

        // update last_login and count_logins entries in database
        Vector tUpdateData = new Vector();
        P_DBEntry tEntry;

        // check if last_login date has to be updated
        String tLastLoginDate=getLastLogin(aUserId, aWhere);
        java.util.Date tDate = new java.util.Date();
        String tCurrentDate= new KFM_Date(tDate).toIsoString();
        if (!tCurrentDate.equals(tLastLoginDate)){
            tEntry=new P_DBEntry("last_login", tCurrentDate, PersonalizeDbConsts.cChar);
            tUpdateData.addElement(tEntry);
        } else {
            tAlreadyLoggedInToday=true;
        }

        int tCurrentCounter;
        tCurrentCounter=getCurrentLoginCounter (aUserId, aWhere)+1;
        tEntry=new P_DBEntry("count_logins", ""+tCurrentCounter, PersonalizeDbConsts.cInt);
        tUpdateData.addElement(tEntry);

        updateMember(tUpdateData, aUserId,   aWhere);

        return tAlreadyLoggedInToday;
    }

    /**
     * Update one entry in table portal_properties.
     * @param aKey
     * @param aValue
     */
    public void updatePortalProperty(String aKey, String aValue)
        throws KFM_SQLException
    {
        try {
            String sql = "UPDATE portal_properties SET value = ? WHERE key = ?";

            int tSel = mDbA.prepareStmt(sql);
            try {
                mDbA.setValue(tSel, 1, aValue);
                mDbA.setValue(tSel, 2, aKey);
                mDbA.executeUpdate(tSel);
            } finally {
                mDbA.closeStmt(tSel);
            }
        } catch(SQLException e) {
            throw niceSqlException(e);
        }
    }

    /**
     * Update pki version in table portal_properties.
     * @param aPkiVersion 1 = openSSL, 2 = IAIK libs
     */
    public void updatePKIVersion(String aPkiVersion)
        throws KFM_SQLException
    {
        updatePortalProperty("PKIVersion", aPkiVersion);
    }
}
TOP

Related Classes of appl.Portal.Personalize.DB.P_Db

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.