// // Integrity Manager Scheduled Based Trigger //
// This script is used to process incoming e-mail messages from specific addresses. //
// @param String Sweep Name
// A Name used to turn the sweep on and off in the env.properties.
// @param String Production Mail Host
// The Production Mail Server Name
// @param String Production Mail Login
// The Production Mail Server Login domain/user id if blank will be pulled from env.properties
// @param String Production Mail Password
// The Production Mail Server Password if blank will be pulled from env.properties
// @param String Production Mail Mailbox
// The Production Mail Server Mailbox - Example: INBOX
// @param String Production Mail Error Mailbox Example: INBOX
// The Production Mail Server Error Mailbox (imap ONLY)
// @param String Production Mail Store Type
// The Production Mail Server Store Type imap or pop3 or pop3s
// @param String Staging Mail Host
// The Staging Mail Server Name
// @param String Staging Mail Login
// The Staging Mail Server Login domain/user id if blank will be pulled from env.properties
// @param String Staging Mail Password
// The Staging Mail Server Password if blank will be pulled from env.properties
// @param String Staging Mail Mailbox
// The Staging Mail Server Mailbox - Example: INBOX
// @param String Staging Mail Error Mailbox
// The Staging Mail Server Error Mailbox (imap only)
// @param String Staging Mail Store Type
// The Staging Mail Server Store Type imap or pop3 or pop3s
// @param String Empty Subject Override
// Used to substitute empty subject lines default text
// @param TypeList Mapping Item Type
// What Type of item request is to be created
// @param Field Mapping Subject
// Email subject line to map to what field example summary
// @param String Mapping User Defined
// Used to provide name value pairs to supply static data on item creation. Example: FieldName=Value,FieldName2=Value
// @param String User Defined Outer Delimiter
// Used to control the delimiter for User Defined Mapping between each field. Example: , to
// @param String User Defined Inner Delimiter
// Used to control the delimiter for User Defined Mapping to assign the value to field. Example: =
// @param String Email Filter
// Comma delimited list of email addresses to process. All addresses will be used if left blank to limit what emails would be processed better to use the mail rules.
// @param Field Mapping From Email
// From email address
// @param Field Mapping From Name
// From sender email split away at the domain marker symbol
// @param Field Mapping From Name Failover
// If sender name is blank then use this default name for the from email name value
// @param Field Mapping Body
// This field will be loaded with as much of the email body as possible the overflow will go in to attachment
// @param Field Mapping To Email
// This is the field to hold the full email address that the email was sent to
// @param Field Mapping To Name
// This is field to hold the name parsed from the email address that the email was sent to
// @param Field Mapping To Name Failover
// This is the field to hold the to email address when the to email address is missing.
// @param Field Mapping CC
// This the cc email address that came in on the email
// @param Field Mapping All
// All Fields of the email combined i.e. the entire email is embedded in this field most likely the for for Detail Description
// @param Field:attachment Mapping Attachments
// The field to be used for this types attachment field i.e. attachments contained in the email are attached to this field
// @param Field:relationship Mapping Related Field
// The field to be used for this types relationship to indicated which field is used for relationships
// @param Field Update Item Logging Field
// The field to be used for this types field update/replacement based upon the type of field can not be multiple values or rich text type. best use is logging field
// @param String Error Re Send Pause Minutes
// Prevents multiple mail messages within the specified minutes (pop3 or pop3s only)
// @param String Error From Email
// email address to be used to send email from when there is an error in the process
// @param String Error To Email
// email address to be used to send email to when there is an error in the process
// @param String Error Subject
// email subject line to indicate that an error was in countered during the process
// to support debug of mail.jar process
// import javax.mail.Address;
// Global bean initialization
var eb = bsf.lookupBean("siEnvironmentBean");
var sb = bsf.lookupBean("imServerBean");
var params = bsf.lookupBean("parametersBean");
var delta = bsf.lookupBean("imIssueDeltaBean");
// the regular expression used to match related item id's in the function getRelationshipStringFromEmail
// the first slash means the beginning of the test expression
// the : means matches the character : literally (case sensitive) the \d means matches a digit(equal to [0-9] {1,} quantifier matches between 1 and unlimited time, as many times as possible, giving back as needed
// this process is looking for number's perfixed with a DT to relate back to program change requests
var testForRelatedIdInSubject = new RegExp(/DT\d{1,}|:\d{1,}/);
//
var testForValidIncidentTicketToUpdate = RegExp(/Incident\d{6,6}/);
//
var host;
var username;
var password;
var activeserver;
var sweepConfig;
var mailbox;
var errormailbox;
var tempdirectory;
var emptySubjectOverride;
var newItemSubject;
var newItemUserDefined;
var newItemFromEmail;
var newItemFromName;
var newItemFromNameFailover;
var newItemBody;
var newItemToEmail;
var newItemCC;
var newItemToName;
var newItemToNameFailover;
var newItemAll;
var newItemAttachments;
var messageContent;
var errorEmailDelayMinutes;
var errorEmailFromAddress;
var errorEmailToAddress;
var errorEmailSubject;
var newItemItemType;
var relatedItemLinkField;
var delimiterOuter;
var delimiterInner;
var storetype;
var apiBean;
var issuesCommand;
var listofAttachments;
var listofContent;
var emailFilter;
var sweepName;
var FirstName
var UpdateItemField
var emailbody
try {
main();
}
catch (ex) {
print("catch");
abort("emailCheckThenSubmit failed main try catch - " + ex.toString());
}
function main() {
initParams();
printParams();
if (activeserver == "production" || activeserver == "staging") {
cleanTempDirectory();
processMail();
} else {
print("No server set as activeserver. sweep will not process email.");
}
}
function processMail() {
print("Begin function ProcessMail");
var Flags = Packages.javax.mail.Flags;
var folder = Packages.javax.mail.Folder;
var messages = Packages.javax.mail.Message;
var jmail_props = new java.util.Properties(); // empty props
var session = Packages.javax.mail.Session.getDefaultInstance(jmail_props, null); // get session
var jmail_store = Packages.javax.mail.Store; // Get the store
jmail_store = session.getStore(storetype);
jmail_store.connect(host, username, password);
folder = jmail_store.getDefaultFolder();
folder = folder.getFolder(mailbox);
print("folder " + folder);
folder.open(Packages.javax.mail.Folder.READ_WRITE);
print("Mail box opened ");
messages = folder.getMessages();
print("This is the number of messages to be processed: " + messages.length);
apiBean = eb.createAPISessionBean();
var popErrorMessage = "";
for (var i = 0; i < messages.length; i++) {
var fromAddress = messages[i].getFrom()[0].getAddress();
print("email fromAddress " + fromAddress);
var fromSubject = messages[i].getSubject();
print("email fromSubject " + fromSubject);
if (null == messages[i].getAllRecipients()) {
print("Null email");
var recipientemail = "Help@summitholdings.com";
} else {
var recipientemail = messages[i].getAllRecipients()[0].getAddress().toLowerCase(); //first email address in the To: section
}
print("this is the recipientemail " + recipientemail);
try {
var isValid = true;
print("email filter variable i.e. list of email address to be processed " + emailFilter);
if (null != emailFilter && emailFilter.trim() != "") {
isValid = false;
var validEmailList = emailFilter.split(",");
for (var z = 0; z < validEmailList.length; z++) {
for (var x = 0; x < messages[i].getAllRecipients().length; x++) {
var testToMail = messages[i].getAllRecipients()[x].getAddress().toLowerCase();
print("testing email from : " + testToMail + " against filter of : " + validEmailList[z]);
if (validEmailList[z].equalsIgnoreCase(testToMail)) {
recipientemail = testToMail;
isValid = true;
break;
}
}
}
}
print("isValid " + isValid);
if (isValid) {
processMessageAPI(messages[i]);
messages[i].setFlag(Flags.Flag.DELETED, true);
// added this function call to print details of email
printMessageDetails(messages[i], i, messages.length);
} else {
print("NOT a valid email for this sweep ");
}
} catch (ex) {
print("ERROR PROCESSING EMAIL SWEEP : " + ex);
try {
popErrorMessage = popErrorMessage.concat("Unable to Process Message From: " + fromAddress + "
");
popErrorMessage = popErrorMessage.concat("Subject: " + fromSubject + "
");
popErrorMessage = popErrorMessage.concat("Error Message: " + ex.message + "
");
if (storetype == "imap") {
moveErrorMessage(jmail_store, messages[i], fromSubject);
handleErrorMessageIMAP(errorEmailSubject, popErrorMessage);
popErrorMessage = "";
}
} catch (ie) {
print("ERROR PROCESSING EMAIL ALERT : " + ie);
}
}
}
if ((storetype == "pop3" || storetype == "pop3s") && popErrorMessage != "") {
try {
handleErrorMessagePOP(errorEmailSubject, popErrorMessage);
} catch (hemex) {
}
}
folder.close(true);
jmail_store.close();
}
function processMessageAPI(message) {
print("Begin function processMessageAPI 254");
listofAttachments = new java.util.ArrayList();
listofContent = new java.util.ArrayList();
var senderemail = message.getFrom()[0].getAddress(); //Get email components
var sentdate = message.getSentDate(); //sent date
var recipientemail = message.getAllRecipients()[0].getAddress().toLowerCase(); //first email address in the To: section
var cc = message.getRecipients(Packages.javax.mail.Message.RecipientType.CC);
var emailsubject = message.getSubject(); //email subject
var allrecipients = message.getAllRecipients(); //all recipients email address
var contenttype = Packages.javax.mail.internet.ContentType;
var ct = contenttype(message.getContentType());
messageContent = "";
print("ct.getPrimaryType 260: " + ct.getPrimaryType());
if (ct.getPrimaryType().equals("multipart")) {processMultPartMessage(message);} else {processBasicMessage(message, ct);}
// check to see if this is an update for Incident ticket by checking for an embeded number in the subject line
var UpdateItemId = getUpdateIncidentNumberFromEmail(emailsubject);
// valid item id for update found then update the item field on the Incident ticket
if (isValidItemId(UpdateItemId)) {UpdateIncidentTicket(UpdateItemId); return; }
// create new item
createItemAPI(senderemail, sentdate, recipientemail, emailsubject, allrecipients, cc);
}
function createItemAPI(senderemail, sentdate, recipientemail, emailsubject, allrecipients, cc) {
print("Start function createItemAPI 273: ");
issuesCommand = new Packages.com.mks.api.Command("im", "createissue");
issuesCommand.addOption(new Packages.com.mks.api.Option("type", newItemItemType));
if ((emailsubject == null) || (emailsubject == "")) emailsubject = emptySubjectOverride;
setEmailFields(senderemail, sentdate, recipientemail, emailsubject, allrecipients, cc);
setUserDefinedFields();
for (var k = 0; k < listofAttachments.size(); k++) addAttachment(listofAttachments.get(k));
var response = apiBean.executeCmd(issuesCommand);
var result = response.getResult();
var relatedItemId = getRelationshipStringFromEmail(emailsubject);
var newItemId = result.getMessage().replaceAll("Created " + newItemItemType + " ", "");
print('newItemId 299: ' + newItemId);
if (isValidItemId(relatedItemId)) addRelatedItem(newItemId, relatedItemId);
return
}
function setItemFieldValue(field, value) {
if (null != field && field.trim() != "" && null != value && value != "") {
issuesCommand.addOption(new Packages.com.mks.api.Option("field", field + "=" + value));
}
}
function addAttachment(attachname) {
print("Add the email attachments addAttachment : " + attachname);
try {
var filename = tempdirectory + "/".concat(attachname);
var filelookup = new java.io.File(filename);
print("the attachment filename 305: " + filename);
// check if file exists
var chkforfile = filelookup.exists();
var attachsize = filelookup.length();
if (attachsize != null && attachsize > 0 && attachsize < 64000000 && chkforfile != false) {
print("attaching 312: " + filename + "----to----" + newItemAttachments);
issuesCommand.addOption(new Packages.com.mks.api.Option("addAttachment", "field=" + newItemAttachments + ",path=\"" + filename + "\""));
} else {
print("addAttachment() attachment is either 0 bytes or > 64Meg");
}
}
catch (ex) {print('addAttachment Failed 320: ' + ex.message);}
}
function UpdateIncidentTicket(UpdateItemId) {
print('UpdateIncidentTicket 917: ' + UpdateItemId);
try {
// convert email to an attachement and attach to referenced ticket issue number
var attachname = saveBodyAsFile("computerinformationreport.txt", messageContent);
listofAttachments.add(attachname);
issuesCommand = new Packages.com.mks.api.Command("im", "editissue");
issuesCommand.addSelection(UpdateItemId);
for (var k = 0; k < listofAttachments.size(); k++) addAttachment(listofAttachments.get(k));
var response = apiBean.executeCmd(issuesCommand);
var result = response.getResult();
print('Results of the command to update the request with the additional informatoin 333: ' + result);
// var command = new Packages.com.mks.api.Command("im", "editissue");
// command.addOption(new Packages.com.mks.api.Option("UpdateIssue", updateField + "=" + messageContent));
// command.addSelection(UpdateItemId);
// var response = apiBean.executeCmd(command);
// var result = response.getResult();
// print('show results value 342 : '+ result)
} catch (ex) {print('UpdateIncidentTicket Failed 340: ' + ex.message);}
}
function processBasicMessage(message, contentType) {
print("Begin function processBasicMessage");
var disposition = message.getDisposition();
var attachname = checkForAttachment(message);
listofContent.add(message.getContent());
messageContent = message.getContent();
if (null != disposition && disposition.equals("attachment")) {
if (attachname != null) {listofAttachments.add(attachname);}
}
}
function processMultPartMessage(message) {
print("begin function processMultPartMessage 341");
var multipart = Packages.javax.mail.Multipart;
multipart = message.getContentType();
getMultipartContent(message.getContent());
}
function getMultipartContent(multipart) {
print("begin function getMultipartContent");
for (var j = 0; j < multipart.getCount(); j++) {
var part = Packages.javax.mail.Part;
part = multipart.getBodyPart(j);
var contentTypeforPart = part.getContentType();
var attachname = checkForAttachment(part);
if (attachname != null) {
listofAttachments.add(attachname);
} else {
var content = getEmailContentforPart(part);
var emailbody = content
if (null != content && content.toString().indexOf("javax.mail.internet.MimeMultipart@") != 0) { messageContent = content;}
print("Content 353: " + listofContent.add(content));
listofContent.add(content);
}
if (contentTypeforPart.match("multipart")) {
var innerMultipart = Packages.javax.mail.Multipart;
innerMultipart = part.getContent();
print("innerMultipart : " + innerMultipart);
getMultipartContent(innerMultipart);
}
}
}
function getEmailContentforPart(part) {
print("Begin function getemailContentforPart");
var email = part.getContent();
if (email != null) {
print("email : " + email);
return email;
} else {
return "--";
}
}
function getRelationshipStringFromEmail(emailsubject) {
// This funcition is for the purpose of relating Incident tickets to program change requests
print("Beginning of function getRelationshipStringFromEmail " + emailsubject);
var estring = emailsubject;
var tempStr = "";
if (estring != "" && relatedItemLinkField != "") {
if (testForRelatedIdInSubject.test(estring)) {
print("estring after testing for :, - ######, DT###### " + estring);
tempStr = testForRelatedIdInSubject.exec(estring).toString();
}
if (tempStr.length > 0) {
print("tempstr greater than zero");
tempStr = tempStr.replace(":", "");
tempStr = tempStr.replace(" -", "");
tempStr = tempStr.replace("DT", "");
print("tempStr " + tempStr);
}
}
return tempStr;
}
function getUpdateIncidentNumberFromEmail(emailsubject) {
var estring = emailsubject;
var tempStr = 0;
if (estring != "") {
if (testForValidIncidentTicketToUpdate.test(estring)) {tempStr = testForValidIncidentTicketToUpdate.exec(estring).toString();}
return tempStr;
}
}
function setEmailFields(senderemail, sentdate, recipientemail, emailsubject, allrecipients, cc) {
print("Begin function setEmailFields senderemail - 421 : " + senderemail);
setUpNewItemToName(senderemail);
// Email Subject
var subjectFieldLength = getFieldLength(newItemSubject);
if (subjectFieldLength >= emailsubject.length()) {
setItemFieldValue(newItemSubject, emailsubject);
} else {
if (null != newItemSubject && newItemSubject.trim() != "") {
setItemFieldValue(newItemSubject, "Subject Too Long For Field Length");
messageContent = "Subject: " + emailsubject + "
" + messageContent;
}
}
// Email body
messageContent = "\n" + messageContent;
var bodyFieldLength = getFieldLength(newItemBody);
if (bodyFieldLength >= messageContent.length) {
setItemFieldValue(newItemBody, messageContent);
} else {
if (null != newItemBody && newItemBody.trim() != "") {
setItemFieldValue(newItemBody, "Message content was to long for the item field, please see the attached file messageContent.txt.");
var attachname = saveBodyAsFile("messageContent.txt", messageContent);
listofAttachments.add(attachname);
}
}
var allemail = "\n" + getEmailAsString(senderemail, sentdate, recipientemail, emailsubject, allrecipients);
var allFieldLength = getFieldLength(newItemAll);
if (allFieldLength >= allemail.length) {
print("newItemAll 472 : " + newItemAll);
setItemFieldValue(newItemAll, allemail);
print("newItemAll 482 :" + newItemAll);
} else {
if (null != newItemAll && newItemAll.trim() != "") {
setItemFieldValue(newItemAll, "Message content was to long for the item field, please see the attached file allMessageContent.txt.");
var attachname = saveBodyAsFile("allMessageContent.txt", allemail);
listofAttachments.add(attachname);
}
}
setItemFieldValue(newItemFromEmail, senderemail);
setItemFieldValue(newItemToEmail, recipientemail);
setItemFieldValue(newItemCC, getCCAsString(cc));
}
function setUserDefinedFields() {
if (null != newItemUserDefined && newItemUserDefined != "") {
var customProperties = newItemUserDefined.split(delimiterOuter);
for (var x = 0; x < customProperties.length; x++) {
var customProperty = customProperties[x].split(delimiterInner);
setItemFieldValue(customProperty[0], customProperty[1]);
print("setItemFieldValue " + setItemFieldValue);
}
}
}
function getCCAsString(cc) {
print("Begin function getCCAsString");
var ccString = "";
if (null != cc) {
for (var i = 0; i < cc.length; i++) {
ccString = ccString.concat(cc[i].getAddress());
if (i == (cc.length - 1)) {
ccString = ccString.concat("\n");
} else {
ccString = ccString.concat("; ");
}
}
}
return ccString;
}
function getEmailAsString(senderemail, sentdate, recipientemail, emailsubject, allrecipients) {
var allemail = "\nFrom: ";
allemail = allemail.concat(senderemail + "\n");
allemail = allemail.concat("Sent: " + sentdate + "\n");
allemail = allemail.concat("To: ")
for (var i = 0; i < allrecipients.length; i++) {
allemail = allemail.concat(allrecipients[i].getAddress());
if (i == (allrecipients.length - 1)) {
allemail = allemail.concat("\n");
} else {
allemail = allemail.concat("; ");
}
}
allemail = allemail.concat("\nSubject: " + emailsubject + "\n");
if (messageContent == null) {
var tmpcontent = "\n";
for (var j = 0; j < listofContent.size(); j++) {
var tmpcontent = tmpcontent.concat(listofContent.get(j));
}
allemail = allemail.concat(tmpcontent + "\n");
print("allemail from getEmailAsString function : " + getEmailAsString);
} else {
allemail = allemail.concat(messageContent + "\n");
}
return allemail;
}
function cleanTempDirectory() {
print("Begin function cleanTempDirectory");
var dir = new java.io.File(tempdirectory);
dir.mkdir();
var listoffiles = dir.listFiles();
for (var i = 0; i < listoffiles.length; i++) {
if (listoffiles[i].isFile() == true) {
print(listoffiles[i] + " " + (listoffiles[i])["delete"]());
}
}
}
function checkForAttachment(part) {
print("Begin function checkForAttachment");
var disposition = part.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase(part.ATTACHMENT) || disposition.equalsIgnoreCase(part.INLINE))) {
return saveFile(part.getFileName(), part.getInputStream());
} else if (null == disposition && part.getFileName() != null) {
try {
return saveFile(part.getFileName(), part.getInputStream());
} catch (ex) {
print("exception trying to save null disposition attachment " + ex);
return null;
}
} else {
return null;
}
}
function saveFile(filename, input) {
print("Begin function saveFile : " + filename);
if (filename == null) {
filename = "attachment";
}
tmpname = tempdirectory + "/";
tmpname = tempdirectory + "/";
print("tmpname -- " + tmpname)
print("filename name is 1: " + filename);
var tempfilename = " " + filename
tempfilename = tempfilename.replace(/ /g, "_");
print("tempfilename name is 2: " + tempfilename);
var filename = tempfilename
var newFileName = tmpname.concat(filename);
print("newFileName -- " + newFileName)
var file = new java.io.File(newFileName);
print("file name is : " + file);
for (var i = 0; file.exists(); i++) {
file = new java.io.File(tmpname + i + "_" + filename);
print("file name is : " + file);
}
var fos = new java.io.FileOutputStream(file);
var bos = new java.io.BufferedOutputStream(fos);
var bis = new java.io.BufferedInputStream(input);
var aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
return file.getName();
}
function saveBodyAsFile(filename, input) {
print("Begin function saveBodyAsFile : " + filename);
tmpname = tempdirectory + "/";
var newFileName = tmpname.concat(filename);
var file = new java.io.File(newFileName);
for (var i = 0; file.exists(); i++) {
file = new java.io.File(tmpname + i + "_" + filename);
}
var outWriter = new java.io.PrintWriter(file);
outWriter.print(input);
outWriter.flush();
outWriter.close();
return file.getName();
}
function sendMail(emailsubject, emailbody) {
try {
var envprops = eb.getEnvironmentVariables();
var disableEmail = envprops.getProperty("disableEmail", "false");
if (disableEmail != null && "true".equalsIgnoreCase(disableEmail)) {
// email notifications are disabled
print("E-MAIL DISABLED: disableEmail property set in data/triggers/env.properties");
} else {
var jmail_props = new java.util.Properties();
jmail_props.put("mail.smtp.host", getSMTPServer());
jmail_props.put("mail.smtp.port", getSMTPPort());
// socket connection and I/O timeouts in milliseconds,
// set to five minutes
jmail_props.put("mail.smtp.connectiontimeout", 5 * 60 * 1000);
jmail_props.put("mail.smtp.timeout", 5 * 60 * 1000);
var session = Packages.javax.mail.Session.getInstance(jmail_props);
var html_msg = new Packages.javax.mail.internet.MimeMessage(session);
html_msg.setFrom(new Packages.javax.mail.internet.InternetAddress(errorEmailFromAddress));
html_msg.addHeader("X-Priority", "1");
var addresses = java.lang.reflect.Array.newInstance(Packages.javax.mail.internet.InternetAddress, 1);
addresses[0] = new Packages.javax.mail.internet.InternetAddress(errorEmailToAddress);
html_msg.setRecipients(Packages.javax.mail.Message.RecipientType.TO, addresses);
html_msg.setSubject(emailsubject);
html_msg.setSentDate(new java.util.Date());
var htmlBody = new Packages.javax.mail.internet.MimeBodyPart();
htmlBody.setDataHandler(new Packages.javax.activation.DataHandler(emailbody, "text/html"));
print("htmlBody : " + htmlBody);
var multiPart = new Packages.javax.mail.internet.MimeMultipart("alternative");
multiPart.addBodyPart(htmlBody);
html_msg.setContent(multiPart);
Packages.javax.mail.Transport.send(html_msg);
}
} catch (ex) {print('sendMail Failed 673: ' + ex.message);}
}
function getSMTPServer() {
var smtpHostPort = eb.getMailHostnameAndPort();
var SMTPserver = smtpHostPort[0];
// Logging
//
// Abort if none found, or return found value
if (SMTPserver == null || SMTPserver.length() == 0) {
print("'mksis.mailserver' property is not set in server configuration properties");
} else {return SMTPserver;}
}
function getSMTPPort() {
var smtpHostPort = eb.getMailHostnameAndPort();
var SMTPport = smtpHostPort[1];
// Logging
//
// Abort if none found, or return found value
if (SMTPport == null || SMTPport.length() == 0) {
print("'mksis.mailserver' property is not set in server configuration properties");
} else {
return SMTPport;
}
}
function print(s) {
Packages.mks.util.Logger.message(eb.getScriptName() + ": DEBUG PRINT GENERAL SETTING 10 " + s + "--**DEBUG PRINT");
}
function abort(s) {
eb.abortScript(s, true);
}
function initParams() {
var sweepserver = null;
print("Begin function initParams ");
var serverprops = eb.getEnvironmentVariables();
print("serverprops " + serverprops);
sweepName = params.getParameter("Sweep Name");
print("sweepName " + sweepName);
if (null == sweepName || "".equals(sweepName)) {
activeserver = serverprops.getProperty("sweepserver");
print("Actual activeserver " + sweepserver);
} else {
activeserver = serverprops.getProperty("sweepserver");
print("server activeserver " + activeserver);
}
if ("production".equalsIgnoreCase(activeserver)) {
username = params.getParameter("Production Mail Login");
password = params.getParameter("Production Mail Password");
} else {
username = params.getParameter("Staging Mail Login");
password = params.getParameter("Staging Mail Password");
}
if (null == username || "".equals(username)) {
username = serverprops.getProperty("sweeplogin");
}
if (null == password || "".equals(password)) {
var encodedPassword = serverprops.getProperty("sweeppassword");
password = new java.lang.String(java.util.Base64.getDecoder().decode(encodedPassword));
}
if ("production".equalsIgnoreCase(activeserver)) {
host = params.getParameter("Production Mail Host");
mailbox = params.getParameter("Production Mail Mailbox");
errormailbox = params.getParameter("Production Mail Error Mailbox");
storetype = params.getParameter("Production Mail Store Type");
} else if ("staging".equalsIgnoreCase(activeserver)) {
host = params.getParameter("Staging Mail Host");
mailbox = params.getParameter("Staging Mail Mailbox");
errormailbox = params.getParameter("Staging Mail Error Mailbox");
storetype = params.getParameter("Staging Mail Store Type");
}
tempdirectory = eb.getInstallDirectory() + "/data/tmp/mailsweep";
emptySubjectOverride = params.getParameter("Empty Subject Override");
newItemItemType = params.getParameter("Mapping Item Type");
newItemSubject = params.getParameter("Mapping Subject");
newItemUserDefined = params.getParameter("Mapping User Defined");
delimiterOuter = params.getParameter("User Defined Outer Delimiter");
delimiterInner = params.getParameter("User Defined Inner Delimiter");
newItemFromEmail = params.getParameter("Mapping From Email");
newItemFromName = params.getParameter("Mapping From Name");
newItemFromNameFailover = params.getParameter("Mapping From Name Failover");
newItemBody = params.getParameter("Mapping Body");
newItemToEmail = params.getParameter("Mapping To Email");
newItemToName = params.getParameter("Mapping To Name");
newItemToNameFailover = params.getParameter("Mapping To Name Failover");
newItemCC = params.getParameter("Mapping CC");
newItemAll = params.getParameter("Mapping All");
newItemAttachments = params.getParameter("Mapping Attachments");
relatedItemLinkField = params.getParameter("Mapping Related Field");
UpdateItemField = params.getParameter("Update Item Logging Field");
errorEmailDelayMinutes = params.getParameter("Error Re Send Pause Minutes");
errorEmailFromAddress = params.getParameter("Error From Email");
errorEmailToAddress = params.getParameter("Error To Email");
errorEmailSubject = params.getParameter("Error Subject");
emailFilter = params.getParameter("Email Filter");
}
function printParams() {
print("begin function printParams 852");
print("Mail Sweep : sweepConfig : " + sweepConfig);
print("Mail Sweep : activeserver : " + activeserver);
print("Mail Sweep : host : " + host);
print("Mail Sweep : username : " + username);
print("Mail Sweep : storetype : " + storetype);
print("Mail Sweep : mailbox : " + mailbox);
print("Mail Sweep : tempdirectory : " + tempdirectory);
print("Mail Sweep : emptySubjectOverride : " + emptySubjectOverride);
}
function printMessageDetails(message, messageNumber, messageCount) {
print("printMessageDetails");
print("Message number '" + messageNumber + "' of '" + messageCount + "'");
print("From Address is '" + message.getFrom()[0].getAddress() + "'");
print("Recipients are '" + message.getAllRecipients()[0].getAddress() + "'");
print("Message Subject is '" + message.getSubject() + "'");
print("Sent Date is '" + message.getSentDate() + "'");
}
function moveErrorMessage(jmail_store, message, inbox) {
print("Begin function moveErrorMessage");
try {
if (storetype == "imap") {
var Flags = Packages.javax.mail.Flags;
var errorfolder = jmail_store.getFolder(errormailbox);
if (!errorfolder.exists()) {
errorfolder.create(Folder.HOLDS_MESSAGES);
}
var errormsgs = new Array(1)
errormsgs[0] = message;
inbox.copyMessages(errormsgs, errorfolder);
message.setFlag(Flags.Flag.DELETED, true);
inbox.expunge();
}
} catch (ex) {print('moveErrorMessage Failed 817: ' + ex.message);}
}
function handleErrorMessageIMAP(emailsubject, emailbody) {
print("Begin function handleErrorMessageIMAP");
sendMail(emailsubject, emailbody);
}
function handleErrorMessagePOP(emailsubject, emailbody) {
print("Start function handleErrorMessagePOP: " + emailsubject + " --- " + emailbody);
var dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
var props = eb.getEnvironmentVariables();
print("getEnvironmentVariables : props : " + props);
var lastDateStored = props.getProperty("sweepserver.errormessage.lastsent", "2000/01/01 00:00:01");
var lastErrorSent = dateFormat.parse(lastDateStored);
var lastCal = java.util.Calendar.getInstance();
var nowCal = java.util.Calendar.getInstance();
print("nowCal " + nowCal);
lastCal.setTime(lastErrorSent);
lastCal.add(java.util.Calendar.MINUTE, errorEmailDelayMinutes)
if (lastCal.before(nowCal)) {
sendMail(emailsubject, emailbody);
props.setProperty("sweepserver.errormessage.lastsent", dateFormat.format(new java.util.Date));
} else {print("error found, waiting on next email alert time");}
}
function initErrorConfig() {
print("Begin function initErrorConfig");
var dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
var errorconfig = "../data/" + sweepConfig;
var props = new java.util.Properties();
errorconfig = errorconfig.replace(".config", ".error.config");
props.setProperty("error.message.lastsent", dateFormat.format(new java.util.Date));
var fos = new java.io.FileOutputStream(errorconfig);
props.store(fos, "");
fos.close();
}
function isUser(userName) {
print("Begin function isUser " + userName);
try {
var testUser = sb.getUserBean(userName);
if (null != testUser && testUser.isActive()) {
return true;
} else {
print("no user found");
return false;
}
} catch (ex) {print('isUser Failed 866: ' + ex.message);}
return false;
}
function getFieldLength(fieldName) {
print("Begin function getFieldLength " + fieldName);
try {
var fieldCommand = new Packages.com.mks.api.Command("im", "viewfield");
fieldCommand.addSelection(fieldName);
var response = apiBean.executeCmd(fieldCommand);
if (response.getWorkItemListSize() > 0) {
var workItems = response.getWorkItems();
while (workItems.hasNext()) {
var workItem = workItems.next();
field = workItem.getField("maxLength");
print(field.getValueAsString());
return parseInt(field.getValueAsString());
}
}
} catch (ex) {print('getFieldLength Failed 885: ' + ex.message);}
return 0;
}
function isValidReltedItemId(newItemId, relatedItemId) {
print("Begin function isValidReltedItemId : " + newItemId + " -- " + relatedItemId);
try {
var id = parseInt(relatedItemId);
var command = new Packages.com.mks.api.Command("im", "issue");
print('id 894: ' + id);
command.addSelection(id);
var response = apiBean.executeCmd(command);
var result = response.getResult();
print('results from running the command im viewissue 898: ' + result);
// error message "MKS1093164: Item (id or UpdateItemid) does not exist."
// >im issues 131279
return true;
} catch (ex) {print('isValidReltedItemId 901: ' + ex.message);}
return false;
}
function isValidItemId(UpdateItemId) {
print("Begin function isValidItemId : " + UpdateItemId);
try {
var id = parseInt(UpdateItemId);
var command = new Packages.com.mks.api.Command("im", "issues --fields='Detailed Description' ");
print('UpdateItemID 905: ' + UpdateItemId);
command.addSelection(UpdateItemId);
var response = apiBean.executeCmd(command);
var result = response.getResult();
print('results from running the command im viewissue 913: ' + result);
// >im issues --fields='Detailed Description' 131279
// error message "MKS1093164: Item (id or UpdateItemid) does not exist."
return true;
} catch (ex) {print('isValidItemId(UpdateItemId) 912: ' + ex.message);}
return (false);
}
function addRelatedItem(newItemId, relatedItemId) {
try {
var command = new Packages.com.mks.api.Command("im", "editissue");
command.addOption(new Packages.com.mks.api.Option("addRelationships", relatedItemLinkField + "=" + relatedItemId));
command.addSelection(newItemId);
var response = apiBean.executeCmd(command);
var result = response.getResult();
} catch (ex) {print('addRelatedItem Failed 924: ' + ex.message);}
}
function buildCommandExcute(commandPassed, parameterspassed) {
try {
command = new Command(commandPassed);
command.addOption(new Option (parameterspassed));
print("comand to execute 1028 : " + Command);
var response = apiBean.executeCmd(Command);
var result = response.getResult();
print("result.getmessage from buildCommandExcute 1032 : " + result.getMessage());
} catch (ex) {print('buildCommandExcute Failed 935: ' + ex.message);}
}
function setUpNewItemToName(senderemail) {
// Break ou the sender's email address split function turns the string variable into an array
var senderName = senderemail.split("@");
// move array element 0 which is the email portion before the @ symbol
var FirstPeriodLastName = senderName[0];
// split the email address name based upon the period between the first and last name
var firstNameandLastName = FirstPeriodLastName.split(".");
var firstName = FirstPeriodLastName.substr(0, FirstPeriodLastName.indexOf('.'));
var firstNameInitial = firstName.slice(0, 1);
var lastName = FirstPeriodLastName.substr(FirstPeriodLastName.indexOf('.') + 1);
var FirstNamePlusLastName = firstNameInitial + lastName;
// if the email address was not seperatated by a period then it would classified as undefined
if (firstName == "undefined") {
var FirstNamePlusLastName = senderName[0];
} else {
var FirstNamePlusLastName = firstNameInitial + lastName;
}
if (isUser(FirstNamePlusLastName)) {
setItemFieldValue(newItemToName, FirstNamePlusLastName);
} else {
// hard coded the helpdeskem due to issue with not able to extract the exact contact name from email address information only.
// otherwise it would have to be setup to use non-employee option to set the email address.
setItemFieldValue(newItemToName, "helpdeskem");
}
return (newItemToName);
}