/*******************************************************************************
$Source: /cvs/repositories/openii3/project/java/examples/org/any_openeai_enterprise/gateways/uportal/PasswordSyncCommand.java,v $
$Revision: 1.5 $
*******************************************************************************/
/**********************************************************************
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 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.uportal;
// Core Java
import javax.jms.*;
import javax.naming.directory.*;
import javax.naming.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.security.*;
import java.sql.*;
// JDOM
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
// OpenEAI Foundation
import org.openeai.jms.consumer.commands.*;
import org.openeai.layouts.EnterpriseLayoutException;
import org.openeai.config.*;
import org.openeai.xml.*;
import org.openeai.loggingutils.*;
import org.openeai.dbpool.*;
// OpenEAI message objects.
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 org.any_openeai_enterprise.moa.objects.resources.v1_0.LightweightPerson;
/**
* 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;
/**
* 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);
}
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 or an
// EnterpriseUserPassword.Update-Sync.
if (messageAction.equalsIgnoreCase("Create") ||
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("UportalGateway-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 instId = newEntUserPassword.getEnterpriseUser()
.getLightweightPerson().getInstitutionalId();
PortalPerson portalPerson = null;
try { portalPerson = retrievePortalPerson(instId); }
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("UportalGateway-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("UportalGateway-1001");
error.setErrorDescription("No user with user ID " + instId +
") 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 cleartextPassword = newEntUserPassword.getPassword().getValue();
byte[] hash, rnd = new byte[8], fin = new byte[24];
Long date = new Long((new java.util.Date()).getTime());
SecureRandom r = new SecureRandom((date.toString()).getBytes());
MessageDigest md = null;
try { md = MessageDigest.getInstance("MD5"); }
catch (NoSuchAlgorithmException nsae) {
Error error = new Error();
error.setType("application");
error.setErrorNumber("UportalGateway-1002");
error.setErrorDescription("An error 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;
}
r.nextBytes(rnd);
md.update(rnd);
hash = md.digest(cleartextPassword.getBytes());
System.arraycopy(rnd, 0, fin, 0, 8);
System.arraycopy(hash, 0, fin, 8, 16);
String encryptedPassword = "(MD5)"+encode(fin);
logger.debug("[PasswordSyncCommand.execute] cleartext password is: " +
cleartextPassword);
logger.debug("[PasswordSyncCommand.execute] excrypted password is: " +
encryptedPassword);
// Update the password in the database.
try { updatePassword(instId, 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("UportalGateway-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;
}
}
/**
*
*<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_NAME FROM UP_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 UP_PERSON_DIR SET ENCRPTD_PSWD = ?, " +
"LST_PSWD_CGH_DT = ? WHERE USER_NAME = ?";
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 static String encode(byte[] raw) {
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < raw.length; i += 3) {
encoded.append(encodeBlock(raw, i));
}
return encoded.toString();
}
private static char[] encodeBlock(byte[] raw, int offset) {
int block = 0;
int slack = raw.length - offset - 1;
int end = (slack >= 2) ? 2 : slack;
for (int i = 0; i <= end; i++) {
byte b = raw[offset + i];
int neuter = (b < 0) ? b + 256 : b;
block += neuter << (8 * (2 - i));
}
char[] base64 = new char[4];
for (int i = 0; i < 4; i++) {
int sixbit = (block >>> (6 * (3 - i))) & 0x3f;
base64[i] = getChar(sixbit);
}
if (slack < 1) base64[2] = '=';
if (slack < 2) base64[3] = '=';
return base64;
}
private static char getChar(int sixBit) {
if (sixBit >= 0 && sixBit <= 25)
return (char)('A' + sixBit);
if (sixBit >= 26 && sixBit <= 51)
return (char)('a' + (sixBit - 26));
if (sixBit >= 52 && sixBit <= 61)
return (char)('0' + (sixBit - 52));
if (sixBit == 62) return '+';
if (sixBit == 63) return '/';
return '?';
}
}