/*
* Created on Oct 3, 2006
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.any_service_provider.gateways.avs.commands;
import java.util.ArrayList;
import javax.jms.Message;
import javax.jms.TextMessage;
import org.jdom.Document;
import org.jdom.Element;
import org.openeai.config.CommandConfig;
import org.openeai.config.EnterpriseConfigurationObjectException;
import org.openeai.config.PropertyConfig;
import org.openeai.jms.consumer.commands.CommandException;
import org.openeai.jms.consumer.commands.RequestCommand;
import org.openeai.jms.consumer.commands.RequestCommandImpl;
import org.openeai.xml.XmlDocumentReader;
import org.openeai.xml.XmlDocumentReaderException;
import org.openeai.layouts.EnterpriseLayoutException;
import org.openeai.config.EnterpriseFieldException;
import com.openii.moa.objects.resources.v1_0.*;
/**
* @author tcerven
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class MockAddressValidationRequestCommand extends RequestCommandImpl implements RequestCommand {
private Document m_responseDoc = null; // the primed XML response document
/**
* @param CommandConfig
* @throws InstantiationException
* <P>
* This constructor initializes the command using a CommandConfig object. It
* invokes the constructor of the ancestor, RequestCommandImpl, and then
* retrieves one PropertyConfig object from AppConfig by name and gets and
* sets the command properties using that PropertyConfig object. This means
* that this command must have one PropertyConfig object in its configuration
* named 'GreetingRequestCommandProperties'. This constructor also initializes
* the response document and provide document used in replies. It also gets a
* pool of PubSubProducers from AppConfig for the command to use in publishing
* sync messages. The command excpects a producer pool named
* 'EgsSubSubProducerPool'. Then the constuctor gets the value of the
* defaultGreetingText property and sets the value of the defaultGreetingText
* to use if no Greetee information is received in a request.
*/
public MockAddressValidationRequestCommand(CommandConfig cConfig) throws InstantiationException {
super(cConfig);
// Get and set the general properties for this command.
PropertyConfig pConfig = new PropertyConfig();
try {
pConfig = (PropertyConfig)getAppConfig()
.getObject("AddressValidationRequestCommandProperties");
}
catch (EnterpriseConfigurationObjectException eoce) {
String errMsg = "Error retrieving a PropertyConfig object from " +
"AppConfig: The exception is: " + eoce.getMessage();
logger.fatal("[MockAddressValidationRequestCommand] " + errMsg);
throw new InstantiationException(errMsg);
}
setProperties(pConfig.getProperties());
// Initialize response document.
XmlDocumentReader xmlReader = new XmlDocumentReader();
try {
logger.debug("[MockAddressValidationRequestCommand] " +
"responseDocumentUri: " + getProperties()
.getProperty("responseDocumentUri"));
m_responseDoc = xmlReader.initializeDocument(getProperties()
.getProperty("responseDocumentUri"), getOutboundXmlValidation());
if (m_responseDoc == null) {
String errMsg = "Missing 'responseDocumentUri' " +
"property in the deployment descriptor. Can't continue.";
logger.fatal("[MockAddressValidationRequestCommand] " + errMsg);
throw new InstantiationException(errMsg);
}
}
catch (XmlDocumentReaderException e) {
logger.fatal("[MockAddressValidationRequestCommand] Error initializing" +
" the primed documents.");
e.printStackTrace();
throw new InstantiationException(e.getMessage());
}
}
/**
* @param int, the number of the message processed by the consumer.
* @param Message, the message for the command to process.
* @throws CommandException, with details of the error processing the message.
* <P>
* This method makes a local copy of the response and provide documents to
* use in the reply to the request. Then it converts the JMS message to an XML
* document, retrieves the text portion of the message, clears the message
* body in preparation for the reply, gets the ControlArea from the XML
* document, and verifies that message object of the message is a
* ValidAddress. If the message object is not a ValidAddress, the command replies with
* an error to the client. If the message object is a ValidAddress, it processes
* the message. The comments above contain a detailed description of the
* processing logic for supported message actions for a Greeting. That logic
* is implemented in this method.
*/
public final Message execute(int messageNumber, Message aMessage)
throws CommandException {
// Make a local copy of the response document to use in the replies.
Document localResponseDoc = (Document)m_responseDoc.clone();
// Convert the JMS Message to an XML Document
Document inDoc = null;
try {
inDoc = initializeInput(messageNumber, aMessage);
}
catch (Exception e) {
String errMsg = "Exception occurred processing input message in " +
"org.openeai.jms.consumer.commands.Command. Exception: " +
e.getMessage();
throw new CommandException(errMsg);
}
// Retrieve text portion of message.
TextMessage msg = (TextMessage)aMessage;
try {
// Clear the message body for the reply, so we do not
// have to do it later.
msg.clearBody();
}
catch (Exception e) {
String errMsg = "Error clearing the message body.";
throw new CommandException(errMsg + ". The exception is: " +
e.getMessage());
}
// Get the ControlArea from XML document.
Element eControlArea = getControlArea(inDoc.getRootElement());
// Get messageAction and messageObject attributes from the
// ControlArea element.
String msgAction = eControlArea.getAttribute("messageAction").getValue();
String msgObject = eControlArea.getAttribute("messageObject").getValue();
// Verify that the message object we are dealing with is a ValidAddress; if not,
// reply with an error.
if (msgObject.equalsIgnoreCase("ValidAddress") == false) {
String errType = "application";
String errCode = "OpenEAI-1001";
String errDesc = "Unsupported message object: " + msgObject +
". This command expects 'ValidAddress'.";
logger.fatal("[MockAddressValidationRequestCommand] " + errDesc);
logger.fatal("[MockAddressValidationRequestCommand] Message sent in is: \n" +
getMessageBody(inDoc));
ArrayList errors = new ArrayList();
errors.add(buildError(errType, errCode, errDesc));
String replyContents =
buildReplyDocumentWithErrors(eControlArea, localResponseDoc, errors);
return getMessage(msg, replyContents);
}
// Handle a Query-Request.
if (msgAction.equalsIgnoreCase("Query")) {
logger.info("[MockAddressValidationRequestCommand] Handling an " +
"com.openii.Services.ValidAddress.Query-Request" +
" message.");
Element eAddress = inDoc.getRootElement().getChild("DataArea").getChild("AddressValidationQuerySpecification").getChild("Address");
// Verify that Address element is not null; if it is, reply with an error.
if (eAddress == null) {
String errType = "application";
String errCode = "OpenEAI-1015";
String errDesc = "Invalid element found in the Query-Request message. This command expects an Address.";
logger.fatal("[MockAddressValidationRequestCommand] " + errDesc);
logger.fatal("Message sent in is: \n" + getMessageBody(inDoc));
ArrayList errors = new ArrayList();
errors.add(buildError(errType, errCode, errDesc));
String replyContents =
buildReplyDocumentWithErrors(eControlArea, localResponseDoc, errors);
return getMessage(msg, replyContents);
}
// Copy the address into the reply
Address address = new Address();
ArrayList matchStatuses = new ArrayList();
try {
address.buildObjectFromInput(eAddress);
logger.info("[MockAddressValidationRequestCommand] Address to validate is: "+address);
// Simulate validation behaviour for special cases
boolean streetValid=true;
boolean cityValid=true;
boolean zipValid=true;
if (address.getStreet1()!=null
&& "728 W. Roostervelt Rd.".equals(address.getStreet1().trim())) {
streetValid=false;
address.setStreet1("728 W. Roosevelt Rd.");
}
if (address.getCityOrLocality()!=null
&& "Chicaga".equals(address.getCityOrLocality().trim())) {
cityValid=false;
address.setCityOrLocality("Chicago");
}
if (address.getZipOrPostalCode()!=null
&& "60606".equals(address.getZipOrPostalCode().trim())) {
zipValid=false;
address.setZipOrPostalCode("60607");
}
if(streetValid && cityValid && zipValid) {
MatchStatus matchStatus=new MatchStatus();
matchStatus.setStatusCode("OK");
matchStatus.setDescription("This address is valid");
matchStatuses.add(matchStatus);
} else {
if (!streetValid) {
MatchStatus matchStatus=new MatchStatus();
matchStatus.setStatusCode("S");
matchStatus.setDescription("The street has been changed");
matchStatuses.add(matchStatus);
}
if (!cityValid) {
MatchStatus matchStatus=new MatchStatus();
matchStatus.setStatusCode("C");
matchStatus.setDescription("The city has been changed");
matchStatuses.add(matchStatus);
}
if (!zipValid) {
MatchStatus matchStatus=new MatchStatus();
matchStatus.setStatusCode("Z");
matchStatus.setDescription("The zipcode has been changed");
matchStatuses.add(matchStatus);
}
}
} catch (EnterpriseLayoutException ele) {
logger.fatal("[MockAddressValidationRequestCommand] Error building Address " +
"object from Query object: The exception is: " + ele.getMessage());
String errType = "application";
String errCode = "OpenEAI-1016";
String errDesc = "EnterpriseLayoutException thrown during address build.";
logger.fatal("[MockAddressValidationRequestCommand] " + errDesc);
logger.fatal("Message sent in is: \n" + getMessageBody(inDoc));
ArrayList errors = new ArrayList();
errors.add(buildError(errType, errCode, errDesc));
String replyContents =
buildReplyDocumentWithErrors(eControlArea, localResponseDoc, errors);
return getMessage(msg, replyContents);
} catch (EnterpriseFieldException efe) {
logger.fatal("[MockAddressValidationRequestCommand] Address validation processing error. The exception is: "
+ efe.getMessage());
String errType = "application";
String errCode = "OpenEAI-1017";
String errDesc = "EnterpriseFieldException thrown during address build.";
logger.fatal("[MockAddressValidationRequestCommand] " + errDesc);
logger.fatal("Message sent in is: \n" + getMessageBody(inDoc));
ArrayList errors = new ArrayList();
errors.add(buildError(errType, errCode, errDesc));
String replyContents =
buildReplyDocumentWithErrors(eControlArea, localResponseDoc, errors);
return getMessage(msg, replyContents);
}
// Serialize the Address and place it into the reply.
String replyContents = null;
try {
localResponseDoc.getRootElement().getChild("DataArea").removeContent();
localResponseDoc.getRootElement().getChild("DataArea").addContent(new Element("AddressValidation"));
localResponseDoc.getRootElement().getChild("DataArea").getChild("AddressValidation")
.addContent((Element)address.buildOutputFromObject());
for (int i=0;i<matchStatuses.size();i++) {
MatchStatus ms = (MatchStatus)matchStatuses.get(i);
localResponseDoc.getRootElement().getChild("DataArea").getChild("AddressValidation")
.addContent((Element)ms.buildOutputFromObject());
}
replyContents = buildReplyDocument(eControlArea, localResponseDoc);
}
catch (EnterpriseLayoutException ele) {
// There was an error building the ValidAddress element from the query
// object.
String errType = "application";
String errCode = "MockAddressValidationService-1004";
String errDesc = "Error building Address element from the Address " +
"object. The exception is: " + ele.getMessage();
logger.fatal("[MockAddressValidationRequestCommand " + errDesc);
ArrayList errors = new ArrayList();
errors.add(buildError(errType, errCode, errDesc));
replyContents = buildReplyDocumentWithErrors(eControlArea,
localResponseDoc, errors);
return getMessage(msg, replyContents);
}
// Return the response with status success.
return getMessage(msg, replyContents);
} else {
// The messageAction is invalid; it is not a query.
String errType = "application";
String errCode = "OpenEAI-1002";
String errDesc = "Unsupported message action: " + msgAction + ". " +
"This command only supports 'query'.";
logger.fatal("[MockAddressValidationRequestCommand] " + errDesc);
logger.fatal("Message sent in is: \n" + getMessageBody(inDoc));
ArrayList errors = new ArrayList();
errors.add(buildError(errType, errCode, errDesc));
String replyContents =
buildReplyDocumentWithErrors(eControlArea, localResponseDoc, errors);
return getMessage(msg, replyContents);
}
}
}