Package org.any_openeai_enterprise.gateways.sakai

Source Code of org.any_openeai_enterprise.gateways.sakai.PasswordSyncCommand

/*******************************************************************************
$Source: /cvs/repositories/openii3/project/java/examples/org/any_openeai_enterprise/gateways/sakai/PasswordSyncCommand.java,v $
$Revision: 1.6 $
*******************************************************************************/

/**********************************************************************
This file is part of the OpenEAI sample, reference implementation,
and deployment management suite created by Tod Jackson
(tod@openeai.org) and Steve Wheat (steve@openeai.org) at
the University of Illinois Urbana-Champaign.

Copyright (C) 2004-2006 The OpenEAI Software Foundation

This program 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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

For specific licensing details and examples of how this software
can be used to implement integrations for your enterprise, visit
http://www.OpenEai.org/licensing.
*/

package org.any_openeai_enterprise.gateways.sakai;

// Core Java
import javax.jms.*;
import javax.mail.MessagingException;

import java.util.*;
import java.io.*;
import java.security.*;
import java.sql.*;

// JDOM
import org.jdom.Document;
import org.jdom.Element;

// OpenEAI Foundation
import org.openeai.jms.consumer.commands.*;
import org.openeai.jms.producer.PointToPointProducer;
import org.openeai.layouts.EnterpriseLayoutException;
import org.openeai.config.*;
import org.openeai.dbpool.*;

// OpenEAI message objects.
import org.openeai.moa.EnterpriseObjectQueryException;
import org.openeai.moa.objects.resources.Error;

// Any OpenEAI Enterprise message objects.
import org.any_openeai_enterprise.moa.jmsobjects.coreapplication.v1_0.NetId;
import org.any_openeai_enterprise.moa.jmsobjects.coreapplication.v1_0.EnterpriseUser;
import org.any_openeai_enterprise.moa.jmsobjects.coreapplication.v1_0.EnterpriseUserPassword;

import com.any_erp_vendor.moa.jmsobjects.person.v1_0.BasicPerson;
import com.any_erp_vendor.moa.objects.resources.v1_0.LightweightPerson;
import com.any_erp_vendor.moa.objects.resources.v1_0.Email;

/**
* This command handles EnterpriseUserPassword.Create-Sync messages and
* EnterpriseUserPassword.Update-Sync message to apply password changes to
* uPortal.
* <P>
*
*/
public class PasswordSyncCommand  extends AbstractPortalSyncCommand
  implements SyncCommand {

  private EnterpriseConnectionPool m_connPool = null;
  private String m_enterpriseIdDomain = null;
  private PointToPointProducer p2p4BpQuery;


  /**
   * Constructor
   */
  public PasswordSyncCommand(CommandConfig cConfig) throws
    InstantiationException {

    super(cConfig);

    // Get the enterpriseIdDomain property.
    String enterpriseIdDomain = getProperties()
      .getProperty("enterpriseIdDomain", null);
    setEnterpriseIdDomain(enterpriseIdDomain.trim());
    if (enterpriseIdDomain == null) {
      // The enterpriseIdDomain is null, log it an throw an exception.
      String errMsg = "Missing 'enterpriseIdDomain' property in the " +
        "deployment descriptor. Can't continue.";
      logger.fatal("[PasswordSyncCommand] " + errMsg);
      throw new InstantiationException(errMsg);
    }
    logger.info("[PasswordSyncCommand] " + "enterpriseIdDomain is: " +
      getEnterpriseIdDomain() + ".");

    // Verify that all message objects required are in AppConfig.
    // Get a configured NetId object out of AppConfig.
    try {
      NetId netId = (NetId)getAppConfig().getObject("NetId");

      EnterpriseUser entUser = (EnterpriseUser)getAppConfig()
        .getObject("EnterpriseUser");
      EnterpriseUserPassword entUserPassword =
        (EnterpriseUserPassword)getAppConfig()
        .getObject("EnterpriseUserPassword");
    }
    catch (EnterpriseConfigurationObjectException eoce) {
      // An error occurred retrieving a required object from AppConfig. Log it
      // and throw an exception.
      String errMsg = "An error occurred retrieving a required object from " +
        "AppConfig. The exception is: " + eoce.getMessage();
      logger.fatal("[PasswordSyncCommand] " + errMsg);
      throw new InstantiationException(errMsg);
    }
   
    // Get the producer from AppConfig.
  try {
    p2p4BpQuery = (PointToPointProducer) getAppConfig().getObject("BasicPersonQuery");
    logger.info("p2p4BpQuery is "+p2p4BpQuery.getClass());
  } catch (EnterpriseConfigurationObjectException e) {
        String errMsg = "[PasswordSyncCommand] Error configuring producer for BasicPersonQuery. The exception is: " + e.getMessage();
        logger.error(errMsg);
        throw new InstantiationException(errMsg);       
  }
 
    // Make sure all objects needed are configured and available for use.
  // LightweightPerson, BasicPersion, EnterpriseUserPassword
     try {
      LightweightPerson lPerson =
            (LightweightPerson)getAppConfig().getObject("LightweightPerson");
        BasicPerson aeo = (BasicPerson)getAppConfig().getObject("BasicPerson");
        EnterpriseUserPassword newEntUserPassword = (EnterpriseUserPassword)getAppConfig()
          .getObject("EnterpriseUserPassword");
    }
    catch (EnterpriseConfigurationObjectException ecoe) {
      String errMsg = "[PasswordSyncCommand] An error occurred getting an  object from " +
          "AppConfig. the exception is: " + ecoe.getMessage();
      logger.error(errMsg);
      throw new InstantiationException(errMsg);       
    }

     
    logger.info("[PasswordSyncCommand] instantiated successfully.");
  }

  public void execute(int messageNumber, Message aMessage) {
    // Initialize some working variables.
    Properties props = getProperties();

     // Create the input document from the JMS message passed in.
    Document inDoc = null;
    try { inDoc = initializeInput(messageNumber, aMessage); }
    catch (JMSException jmse) {
      // An error occurred creating the input document from the JMS message
      // passed in. Log it and publish a sync error.
      Error error = new Error();
      error.setErrorNumber("OpenEAI-2101");
      error.setErrorDescription("An error occurred creating the input " +
        "document from the JMS message passed in. The exception is: " +
        jmse.getMessage());
      logger.fatal("[PasswordSyncCommand.execute]" +
        error.getErrorDescription());
      return;
    }

    // Get the message metadata.
    Element eControlArea = getControlArea(inDoc.getRootElement());
    String messageCategory = eControlArea.getAttribute("messageCategory")
      .getValue();
    String messageObject = eControlArea.getAttribute("messageObject")
      .getValue();
    String messageRelease = eControlArea.getAttribute("messageRelease")
      .getValue();
    String messageAction = eControlArea.getAttribute("messageAction")
      .getValue();
    String messageType = eControlArea.getAttribute("messageType").getValue();

    logger.info("[PasswordSyncCommand.execute] Received a(n) " + messageCategory
      + "." + messageObject + "." + messageAction + "-" + messageType +
      " (release " + messageRelease + ") message.");

    // Verify that this is a message we support.
    ArrayList errors = new ArrayList();
    if (messageObject.equalsIgnoreCase("EnterpriseUserPassword") == false) {
      Error error = new Error();
      error.setType("application");
      error.setErrorNumber("OpenEAI-1002");
      error.setErrorDescription("Message object '" + messageObject +
        "' is not supported.");
      errors.add(error);
    }
    if (messageType.equalsIgnoreCase("Sync") == false) {
      Error error = new Error();
      error.setType("application");
      error.setErrorNumber("OpenEAI-1002");
      error.setErrorDescription("Message type '" + messageType + "' is not " +
        "supported.");
      errors.add(errors);
    }
    if (errors.size() > 0) {
      ListIterator iterator = errors.listIterator();
      while (iterator.hasNext()) {
        Error error = (Error)iterator.next();
        logger.fatal("[PasswordSyncCommand.execute] " +
          error.getErrorDescription());
      }
      publishSyncError(eControlArea, errors);
      return;
    }

    // Get two configured EnterpriseUserPassword from AppConfig.
    EnterpriseUserPassword currentEntUserPassword = null;
    EnterpriseUserPassword newEntUserPassword = null;
    try {
      currentEntUserPassword = (EnterpriseUserPassword)getAppConfig()
        .getObject("EnterpriseUserPassword");
      newEntUserPassword = (EnterpriseUserPassword)getAppConfig()
        .getObject("EnterpriseUserPassword");
    }
    catch (EnterpriseConfigurationObjectException ecoe) {
      // An error occurred getting an object from AppConfig. Log it and
      // publish a sync error message.
      Error error = new Error();
      error.setType("application");
      error.setErrorNumber("OpenEAI-3001");
      error.setErrorDescription("An error occurred getting an object from " +
        "AppConfig. the exception is: " + ecoe.getMessage());
      errors = new ArrayList();
      errors.add(error);
      publishSyncError(eControlArea, errors, ecoe);
      return;
    }

    // Handle an EnterpriseUserPassword.CreateSync
    if (messageAction.equalsIgnoreCase("Create")) {
     
      // Get the new state of the EnterpriseUserPassword and build an
      // EnterpriseUserPassword object.
      Element eNewPassword = inDoc.getRootElement().getChild("DataArea")
        .getChild("NewData").getChild("EnterpriseUserPassword");
      try
        newEntUserPassword.buildObjectFromInput(eNewPassword);
      }
      catch (EnterpriseLayoutException ele) {
        // An error occurred building the EnterpriseUserPassword object from the
        // EnterpriseUserPassword element contained in the NewData element of
        // the message. Log it and publish a sync error message.
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-1002");
        error.setErrorDescription("An error occurred building the " +
          "EnterpriseUserPassword object from the EnterpriseUserPassword " +
          "element contained in the NewData element of the message. The " +
          "exception is: " + ele.getMessage());
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors, ele);
        return;
      }

      // Determine whether the user exists in the database.
      String userId = getUserId(newEntUserPassword);
      String instId = newEntUserPassword.getEnterpriseUser()
        .getLightweightPerson().getInstitutionalId();
      BasicPerson bp=null;
      try {
        logger.info("[PasswordSyncCommand.execute] Querying for BasicPerson.");
        bp = getBasicPerson(instId);
        logger.info("[PasswordSyncCommand.execute] Queried for BasicPerson.");
    } catch (EnterpriseConfigurationObjectException e) {
        // Log it, publish a error message, and return.
        String errMsg = "EnterpriseConfigurationObjectException: " + e.getMessage();
        logger.error("[PasswordSyncCommand.execute] " + errMsg);
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-1014");
        error.setErrorDescription(errMsg);
        errors = new ArrayList();
        errors.add(error);
        logger.info("[PasswordSyncCommand.execute] Publishing Sync.Error-Sync.");
        publishSyncError(eControlArea, errors);
        return
     } catch (EnterpriseFieldException e) {
        // Log it, publish a error message, and return.
        String errMsg = "EnterpriseFieldException: " + e.getMessage();
        logger.error("[PasswordSyncCommand.execute] " + errMsg);
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-1014");
        error.setErrorDescription(errMsg);
        errors = new ArrayList();
        errors.add(error);
       logger.info("[PasswordSyncCommand.execute] Publishing Sync.Error-Sync.");
        publishSyncError(eControlArea, errors);
        return
     } catch (EnterpriseObjectQueryException e) {
        // Log it, publish a error message, and return.
        String errMsg = "EnterpriseObjectQueryException: " + e.getMessage();
        logger.error("[PasswordSyncCommand.execute] " + errMsg);
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-1014");
        error.setErrorDescription(errMsg);
        errors = new ArrayList();
        errors.add(error);
        logger.info("[PasswordSyncCommand.execute] Publishing Sync.Error-Sync.");
        publishSyncError(eControlArea, errors);
        return
     }
  if (bp==null) {
        // No BasicPerson exists for this instId.
        // Log it, publish a error message, and return.
        String errMsg = "No BasicPerson exists for " + instId;
        logger.debug("[PasswordSyncCommand.execute] " + errMsg);
        Error error = new Error();
        error.setType("application");
        error.setErrorNumber("SakaiGateway-1012");
        error.setErrorDescription(errMsg);
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors);
        return
      }
      PortalPerson portalPerson = null
      try { portalPerson = retrievePortalPersonByUserId(userId); }
      catch (CommandException ce) {
        // An error occurred querying the portal database to determine whether
        // the user exists. Log it, publish a error message, and return.
        String errMsg = "An error occurred querying the portal database to " +
          "determine whether the user exists.";
        logger.debug("[PasswordSyncCommand.execute] " + errMsg);
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-2001");
        error.setErrorDescription(errMsg);
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors, ce);
        return;
      }

      // If the user does exist, publish a error message indicating
      // that the user already exists.
      if (portalPerson != null) {
        Error error = new Error();
        error.setType("application");
        error.setErrorNumber("SakaiGateway-1011");
        error.setErrorDescription("User with user ID " + userId +
          ") exists in the portal. Cannot reset the password for this user.");
        logger.fatal("[PasswordSyncCommand.execute] " +
          error.getErrorDescription());
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors);
        return;
      }

      // Create the portal user with info from BasicPerson and the
      // user's password to be the new value indicated in the message.
      else {
        logger.info("[PasswordSyncCommand.execute] BasicPerson="+bp);
        portalPerson = new PortalPerson();
        portalPerson.setEmailAddress(getEmailAddress(bp.getEmail()));
        portalPerson.setUserId(userId);
        portalPerson.setInstId(instId);
        portalPerson.setFirstName(bp.getName().getFirstName());
        portalPerson.setLastName(bp.getName().getLastName());
       
        // Encypt the password.
        String encryptedPassword=null;
        String cleartextPassword = newEntUserPassword.getPassword().getValue();
        try {
          encryptedPassword = hashPassword(cleartextPassword);
          logger.info("[PasswordSyncCommand.execute] cleartext password is: " +
                  cleartextPassword);
          logger.info("[PasswordSyncCommand.execute] excrypted password is: " +
                  encryptedPassword);
        } catch (NoSuchAlgorithmException nsae) {
          Error error = new Error();
          error.setType("application");
          error.setErrorNumber("SakaiGateway-1002");
          error.setErrorDescription("A NoSuchAlgorithmException occurred encrypting the user " +
            "password. The exception is: " + nsae.getMessage());
          logger.fatal("[PasswordSyncCommand.execute] " +
            error.getErrorDescription());
          errors = new ArrayList();
          errors.add(error);
          publishSyncError(eControlArea, errors, nsae);
          return;
        } catch (MessagingException nsae) {
            Error error = new Error();
            error.setType("application");
            error.setErrorNumber("SakaiGateway-1002");
            error.setErrorDescription("A MessagingException occurred encrypting the user " +
              "password. The exception is: " + nsae.getMessage());
            logger.fatal("[PasswordSyncCommand.execute] " +
              error.getErrorDescription());
            errors = new ArrayList();
            errors.add(error);
            publishSyncError(eControlArea, errors, nsae);
            return;
    } catch (IOException nsae) {
            Error error = new Error();
            error.setType("application");
            error.setErrorNumber("SakaiGateway-2022");
            error.setErrorDescription("An IOException occurred encrypting the user " +
              "password. The exception is: " + nsae.getMessage());
            logger.fatal("[PasswordSyncCommand.execute] " +
              error.getErrorDescription());
            errors = new ArrayList();
            errors.add(error);
            publishSyncError(eControlArea, errors, nsae);
            return;
    }       
       
        portalPerson.setPassword(encryptedPassword);
        try {
      createPortalPerson(portalPerson);
    } catch (CommandException e) {
          Error error = new Error();
          error.setType("system");
          error.setErrorNumber("SakaiGateway-1020");
          String errmsg = "An error occurred building the portal person. The exception is: " +
              e.getMessage();
          error.setErrorDescription(errmsg);
          errors = new ArrayList();
          errors.add(error);
          publishSyncError(eControlArea, errors, e);
          logger.error("[PasswordSyncCommand.execute] Can't create portal person. \n"+errmsg);
          return;
    }
      }
    }

   
    // Handle an EnterpriseUserPassword.Update-Sync.
    if (messageAction.equalsIgnoreCase("Update")) {
     
      // Get the new state of the EnterpriseUserPassword and build an
      // EnterpriseUserPassword object.
      Element eNewPassword = inDoc.getRootElement().getChild("DataArea")
        .getChild("NewData").getChild("EnterpriseUserPassword");
      try
        newEntUserPassword.buildObjectFromInput(eNewPassword);
      }
      catch (EnterpriseLayoutException ele) {
        // An error occurred building the EnterpriseUserPassword object from the
        // EnterpriseUserPassword element contained in the NewData element of
        // the message. Log it and publish a sync error message.
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-1002");
        error.setErrorDescription("An error occurred building the " +
          "EnterpriseUserPassword object from the EnterpriseUserPassword " +
          "element contained in the NewData element of the message. The " +
          "exception is: " + ele.getMessage());
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors, ele);
        return;
      }

      // Determine whether the user exists in the database.
      String userId = getUserId(newEntUserPassword);
      PortalPerson portalPerson = null
      try {
        portalPerson = retrievePortalPersonByUserId(userId);
      }
      catch (CommandException ce) {
        // An error occurred querying the portal database to determine whether
        // the user exists. Log it, publish a error message, and return.
        String errMsg = "An error occurred querying the portal database to " +
          "determine whether the user exists.";
        logger.debug("[PasswordSyncCommand.execute] " + errMsg);
        Error error = new Error();
        error.setType("system");
        error.setErrorNumber("SakaiGateway-2001");
        error.setErrorDescription(errMsg);
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors, ce);
        return;
      }

      // If the user does not exist, publish a error message indicating
      // that the user does not exist.
      if (portalPerson == null) {
        Error error = new Error();
        error.setType("application");
        error.setErrorNumber("SakaiGateway-1001");
        error.setErrorDescription("No user with user ID " + userId +
          ") exists in the portal. Cannot reset the password for this user.");
        logger.fatal("[PasswordSyncCommand.execute] " +
          error.getErrorDescription());
        errors = new ArrayList();
        errors.add(error);
        publishSyncError(eControlArea, errors);
        return;
      }

      // Otherwise, the user already exists in the portal, so reset the
      // user's password to be the new value indicated in the message.
      else {
        // Encypt the password.
        String encryptedPassword=null;
        String cleartextPassword = newEntUserPassword.getPassword().getValue();
        try {
          encryptedPassword = hashPassword(cleartextPassword);
          logger.info("[PasswordSyncCommand.execute] cleartext password is: " +
                  cleartextPassword);
          logger.info("[PasswordSyncCommand.execute] excrypted password is: " +
                  encryptedPassword);
        } catch (NoSuchAlgorithmException nsae) {
          Error error = new Error();
          error.setType("application");
          error.setErrorNumber("SakaiGateway-1002");
          error.setErrorDescription("A NoSuchAlgorithmException occurred encrypting the user " +
            "password. The exception is: " + nsae.getMessage());
          logger.fatal("[PasswordSyncCommand.execute] " +
            error.getErrorDescription());
          errors = new ArrayList();
          errors.add(error);
          publishSyncError(eControlArea, errors, nsae);
          return;
        } catch (MessagingException nsae) {
            Error error = new Error();
            error.setType("application");
            error.setErrorNumber("SakaiGateway-1002");
            error.setErrorDescription("A MessagingException occurred encrypting the user " +
              "password. The exception is: " + nsae.getMessage());
            logger.fatal("[PasswordSyncCommand.execute] " +
              error.getErrorDescription());
            errors = new ArrayList();
            errors.add(error);
            publishSyncError(eControlArea, errors, nsae);
            return;
    } catch (IOException nsae) {
            Error error = new Error();
            error.setType("application");
            error.setErrorNumber("SakaiGateway-1002");
            error.setErrorDescription("An IOException occurred encrypting the user " +
              "password. The exception is: " + nsae.getMessage());
            logger.fatal("[PasswordSyncCommand.execute] " +
              error.getErrorDescription());
            errors = new ArrayList();
            errors.add(error);
            publishSyncError(eControlArea, errors, nsae);
            return;
    }

        // Update the password in the database.
        try { updatePassword(userId, encryptedPassword); }
        catch (CommandException ce) {
          // An error occurred accessing the database to update the user
          // password. Log it, publish a error message, and return.
          String errMsg = "An error occurred accessing the database to " +
            "update the user password.";
          logger.debug("[PasswordSyncCommand.execute] " + errMsg);
          Error error = new Error();
          error.setType("system");
          error.setErrorNumber("SakaiGateway-2001");
          error.setErrorDescription(errMsg);
          errors = new ArrayList();
          errors.add(error);
          publishSyncError(eControlArea, errors, ce);
          return;
        }
       
        return
      }
    }

    // Otherwise, the message is unsupported. Log it and publish a sync error.
    else {
      Error error = new Error();
      error.setType("application");
      error.setErrorNumber("OpenEAI-1002");
      error.setErrorDescription("Unsupported message action. This command only "
        + "supports an action of 'update'");
      errors = new ArrayList();
      errors.add(error);
      publishSyncError(eControlArea, errors);
      return;
    }
   
  }

  /**
* @param newEntUserPassword
* @return
*/
private String getUserId(EnterpriseUserPassword newEntUserPassword) {
  List netIds=newEntUserPassword.getEnterpriseUser().getNetId();
  if (netIds==null || netIds.size()==0) {
      logger.info("[PasswordSyncCommand.getUserId] No NetId found in EnterpriseUserPassword: "
          + newEntUserPassword);
    return null;
  } else {
    NetId ni = (NetId)netIds.get(0);
    String userId = ni.getPrincipal();
      logger.info("[PasswordSyncCommand.getUserId] UserId "+userId+"  found in EnterpriseUserPassword: "
          + newEntUserPassword);   
    return userId;
  }
}

/**
   *
   *<P>
   * @param EnterpriseUser, an EnterpriseUser. 
   *<P>
   */
  public final NetId getEnterpriseId (EnterpriseUser entUser) {
    // If EnterpriseUser is null, return null.
    if (entUser == null) return null;
    logger.debug("[PasswordSyncCommand.getEnterpriseId] Getting the " +
      "EnterpriseId for the EnterpriseUser.");
    logger.debug("[PasswordSyncCommand.getEnterpriseId] The " +
      "enterpriseIdDomain is: " + m_enterpriseIdDomain);

    // Get a list of NetIds.
    List netIds = entUser.getNetId();
   
    // Iterate through the NetIds for the EnterpriseUser and find the
    // EnterpriseId and return it.
    NetId netId = new NetId();
    for (int i=0; i < netIds.size(); i++) {
      netId = (NetId)netIds.get(i);
      logger.debug("[PasswordSyncCommand.getEnterpriseId] Found NetId: "
        + toString(netId));
      if (netId.getDomain().equals(m_enterpriseIdDomain)) {
        logger.debug("[PasswordSyncCommand.getEnterpriseId] Found " +
          "EnterpriseId: " + toString(netId));
        return netId;
      }
    }
    logger.debug("[PasswordSyncCommand.getEnterpriseId] Did not find an " +
      "EnterpriseId.");
    return null;
  }

  private String getEnterpriseIdDomain() {
    return m_enterpriseIdDomain;
  }

  private void setEnterpriseIdDomain(String domain) {
    m_enterpriseIdDomain = domain;
  }

  private String toString(NetId netId) {
    String sNetId = netId.getPrincipal() + "@" + netId.getDomain();
    return sNetId;
  }
 
  private final void updatePassword(String instId, String password) throws
    CommandException {
    logger.debug("[PasswordSyncCommand.updatePassword] Updating password for " +
      "portal with user ID: " + instId + ".");

    try {
      String userName = null;
   
      // Retrieve the user name for the portal user. This is done in a separate
      // query because some database management systems do not support nested
      // queries.
      // -- Specify a query string.
      String getString1 = "SELECT USER_ID FROM SAKAI_USER WHERE USER_ID = ?";
      EnterpriseConnectionPool ecp = getEnterpriseConnectionPool();
      EnterprisePooledConnection epc = ecp.getExclusiveConnection();
      java.sql.Connection conn = epc.getConnection();
      PreparedStatement getStmt1 = conn.prepareStatement(getString1);
     
      // Perform the query.
      getStmt1.clearParameters();
      getStmt1.setString(1, instId);
      ResultSet rs1 = getStmt1.executeQuery();

      // If there is a result, this is the user name. Otherwise, the user does
      // not exist, so throw an exception.
      if (rs1.next())
        userName = rs1.getString(1);
      else throw new CommandException("No portal user exists with user ID: " +
        instId);
      getStmt1.close();
       
      // Update the portal user's password.
      // -- Specify an update string for the statement to update the password.
      String updString1 = "UPDATE SAKAI_USER SET PW = ?, " +
        "MODIFIEDON = ? WHERE USER_ID = ?";
      PreparedStatement updStmt1 = conn.prepareStatement(updString1);
      
      // -- Clear the statement parameters, set the parameter value of the
      //    statement and execute it.
      updStmt1.clearParameters();
      updStmt1.setString(1, password);
      updStmt1.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
      updStmt1.setString(3, userName);
      int rc = updStmt1.executeUpdate();
      updStmt1.close();
      ecp.releaseExclusiveConnection(epc);
      logger.info("[PasswordSyncCommand.updatePassword] Updated password " +
        "for user '" + userName + "'. Return code: " + rc + ".");
      return;
    }
    catch (SQLException se) {
      // An error occurred accessing the database to determine whether the
      // portal user exists. Log it, and throw
      // an exception.
      String errMsg = "An error occurred accessing the database to determine " +
        "whether the protal user exists. The " +
        "exception is: " + se.getMessage();
      logger.fatal("[PasswordSyncCommand.userExists] " + errMsg);
      se.printStackTrace();
      throw new CommandException(errMsg, se);
    }
  }

  private BasicPerson getBasicPerson(String instId) throws EnterpriseConfigurationObjectException, EnterpriseFieldException, EnterpriseObjectQueryException {
       
    LightweightPerson lPerson =
          (LightweightPerson)getAppConfig().getObject("LightweightPerson");
        logger.info("[PasswordSyncCommand.getBasicPerson] Got LightweightPerson...");
 
        lPerson.setInstitutionalId(instId);
        logger.info("[PasswordSyncCommand.getBasicPerson] Set instid on lightweight person...");
       
        BasicPerson aeo = (BasicPerson)getAppConfig().getObject("BasicPerson");
        logger.info("[PasswordSyncCommand.getBasicPerson] Got BasicPerson from AppConfig, performing Query...");
 
        java.util.List a = aeo.query(lPerson, p2p4BpQuery);
        logger.info("[PasswordSyncCommand.getBasicPerson] Executed Query...");
 
        StringBuffer results = new StringBuffer();
        if (a.size() == 0) {
          logger.info("[PasswordSyncCommand.getBasicPerson] No rows found matching the query.");
          return null;
        }
        else {
          BasicPerson bp = (BasicPerson)a.get(0);
          return bp;
        }
  }
    /**
   * @param emailList
   * @return
   */
  private String getEmailAddress(List emailList) {
      List emailAddresses = emailList;
      ListIterator li = emailAddresses.listIterator();
     
      switch (emailAddresses.size()) {
        // If there are no e-mail addresses in the list, set the value of the
        // e-mail address to null.
        case 0:
          return null;

        // If there is one e-mail address in the list, that will become the
        // value of the e-mail address.
        case 1:
          Email emailAddress = (Email)li.next();
          return emailAddress.getEmailAddress();

        // If there are multiple e-mail addresses in the list, uPortal can
        // store only one of them, so get any one that has the preferred
        // indicator set or take the first e-mail address in the list if
        // none are preferred.
        default:
          emailAddress = (Email)li.next();
          String email = emailAddress.getEmailAddress();
          while (li.hasNext()) {
            emailAddress = (Email)li.next();
            if (emailAddress.getPreferred() != null &&
                emailAddress.getPreferred().equalsIgnoreCase("Yes")) {

                email = emailAddress.getEmailAddress();
            }
          }
          return email;
      }
  } 
}
TOP

Related Classes of org.any_openeai_enterprise.gateways.sakai.PasswordSyncCommand

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.