* INITIAL POPULATIONS OF THIS REPO

This commit is contained in:
2021-12-23 13:04:01 +08:00
parent 3165defa2e
commit ed70cad6ea
182 changed files with 22964 additions and 0 deletions
@@ -0,0 +1,68 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
/**
* Get the value of a property defined in config file
* @param propertyName - the name or key of the property you want to retrieve
* @return the string value
* @throws IOException
*/
public static String getConfigValueImonitor(String propertyName) throws IOException
{
Properties prop = new Properties();
String propFileName = "config_imonitor.properties";
InputStream inputStream = Config.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String value = prop.getProperty(propertyName);
return value;
}
public static String getConfigValueEmail(String propertyName) throws IOException
{
Properties prop = new Properties();
String propFileName = "config_email.properties";
InputStream inputStream = Config.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String value = prop.getProperty(propertyName);
return value;
}
}
@@ -0,0 +1,397 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.collections4.map.MultiValueMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fourelementscapital.imonitor.email.Email;
import com.fourelementscapital.imonitor.email.EmailVO;
import com.fourelementscapital.imonitor.stackalarm.StackAlarm;
import com.fourelementscapital.imonitor.stackalarm.StackAlarmVO;
import com.fourelementscapital.tts.TTS;
/**
* A com.fourelementscapital Class
*/
public class IMonitor {
private static final Logger log = LogManager.getLogger(IMonitor.class.getName());
public static IMonitorVO processMessage(String message) throws Exception
{
IMonitorVO iMonitorVO = new IMonitorVO();
iMonitorVO.setId("" + (new Date().getTime()) + (int)(Math.random() * 10000)); // to display id on log
log.debug(iMonitorVO.getId() + " - new");
if (message == null) return null; // return null if message = null
message = message.replace("<EOF>",""); // remove '<EOF>' if exist
String[] strArr = message.split("~");
MultiValueMap multiMap = new MultiValueMap();
if (strArr.length > 0) {
for (int i=0; i<strArr.length; i++) {
String[] strArrSub = strArr[i].split("\\$\\#\\=");
multiMap.put(strArrSub[0], strArrSub[1]);
}
}
Iterator<String> mapIterator = multiMap.keySet().iterator();
while (mapIterator.hasNext()) {
String key = mapIterator.next();
Collection<String> values = multiMap.getCollection(key);
for(Iterator<String> entryIterator = values.iterator(); entryIterator.hasNext();) {
String value = entryIterator.next();
switch (key.toLowerCase()) {
case "theme":
iMonitorVO.setTheme(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "alertlevel":
iMonitorVO.setAlertLevel(value);
break;
case "subject":
iMonitorVO.setSubject(value);
break;
case "body":
iMonitorVO.setBody(value);
break;
case "recipients":
iMonitorVO.setRecipients(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "emailcc":
iMonitorVO.setEmailCC(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "emailbcc":
iMonitorVO.setEmailBCC(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "emailattachments":
iMonitorVO.setAttachments(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "emailimages":
iMonitorVO.setImages(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "emailreplyto":
iMonitorVO.setEmailReplyTo(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "sayit":
iMonitorVO.setSayIt(Boolean.parseBoolean(value));
break;
case "emailit":
iMonitorVO.setEmailIt(Boolean.parseBoolean(value));
break;
case "phonecall":
iMonitorVO.setPhoneIt(Boolean.parseBoolean(value));
break;
case "ym":
iMonitorVO.setYahooMessenger(Arrays.asList(value.split("\\s*,\\s*")));
break;
case "sms":
iMonitorVO.setSmsIt(Boolean.parseBoolean(value));
break;
case "escalation":
iMonitorVO.setEscalation(value);
break;
case "numbers":
iMonitorVO.setPhoneNumbers(Arrays.asList(value.split("\\s*,\\s*")));
break;
}
}
}
// use lib-stackalarm if recipients or numbers is not provided :
String theme = iMonitorVO.getTheme().get(0); // TODO: get only first theme.
// TODO: alarm level escalation minutes by minutes
//String alarmLevel = iMonitorVO.getAlertLevel();
String alarmLevel = (iMonitorVO.getAlertLevel() == null || "".equals(iMonitorVO.getAlertLevel())) ? "HIGH" : iMonitorVO.getAlertLevel();
boolean isGetRecipientsFromDb = false;
if (iMonitorVO.isEmailIt()) {
if (iMonitorVO.getRecipients() == null || iMonitorVO.getRecipients().size() == 0) {
isGetRecipientsFromDb = true;
}
}
if (iMonitorVO.isPhoneIt() || iMonitorVO.isSmsIt()) {
if (iMonitorVO.getPhoneNumbers() == null || iMonitorVO.getPhoneNumbers().size() == 0) {
isGetRecipientsFromDb = true;
}
}
// TODO : temporary, bypass stack alarm :
isGetRecipientsFromDb = false;
if (isGetRecipientsFromDb) {
StackAlarmVO stackAlarmVO = StackAlarm.collectRecipients(theme, alarmLevel);
if (iMonitorVO.isEmailIt()) {
if (iMonitorVO.getRecipients() == null || iMonitorVO.getRecipients().size() == 0) {
List<String> iMonitorVORecipients = new ArrayList<String>();
List<String> stackAlarmVORecipients = stackAlarmVO.getRecipients();
for (int i=0; i<stackAlarmVORecipients.size(); i++) {
iMonitorVORecipients.add(stackAlarmVORecipients.get(i));
}
iMonitorVO.setRecipients(iMonitorVORecipients);
}
}
if (iMonitorVO.isPhoneIt() || iMonitorVO.isSmsIt()) {
if (iMonitorVO.getPhoneNumbers() == null || iMonitorVO.getPhoneNumbers().size() == 0) {
List<String> iMonitorVOPhoneNumbers = new ArrayList<String>();
List<String> stackAlarmVOPhoneNumbers = stackAlarmVO.getPhoneNumbers();
for (int i=0; i<stackAlarmVOPhoneNumbers.size(); i++) {
iMonitorVOPhoneNumbers.add(stackAlarmVOPhoneNumbers.get(i));
}
iMonitorVO.setPhoneNumbers(stackAlarmVOPhoneNumbers);
}
}
}
return iMonitorVO;
}
/**
* Process the alarm message to do email, phone, etc.
* @param stackAlarmVO Stack alarm value object
* @throws Exception
*/
public static void process(IMonitorVO iMonitorVO) throws Exception {
List<String> tmpRecipientsList = iMonitorVO.getRecipients();
if (tmpRecipientsList != null && tmpRecipientsList.size() > 0) {
for (int i=0; i<tmpRecipientsList.size(); i++) {
log.debug("=== " + iMonitorVO.getId() + " Recipient[" + i + "] : " + tmpRecipientsList.get(i));
}
}
List<String> tmpPhoneNumberList = iMonitorVO.getPhoneNumbers();
if (tmpPhoneNumberList != null && tmpPhoneNumberList.size() > 0) {
for (int i=0; i<tmpPhoneNumberList.size(); i++) {
log.debug("=== " + iMonitorVO.getId() + " PhoneNumber[" + i + "] : " + tmpPhoneNumberList.get(i));
}
}
Exception exp = null;
if (iMonitorVO.isSayIt()) {
try {
processVOToSay(iMonitorVO);
log.debug(iMonitorVO.getId() + " - text to speech done");
}
catch (Exception e) {
exp = e;
}
}
if (iMonitorVO.isPhoneIt()) {
try {
processVOToPhone(iMonitorVO);
log.debug(iMonitorVO.getId() + " - phone called");
}
catch (Exception e) {
exp = e;
}
}
if (iMonitorVO.isSmsIt()) {
try {
processVOToSms(iMonitorVO);
log.debug(iMonitorVO.getId() + " - sms sent");
}
catch (Exception e) {
exp = e;
}
}
if (iMonitorVO.isEmailIt()) {
try {
processVOToEmail(iMonitorVO);
log.debug(iMonitorVO.getId() + " - email sent");
}
catch (Exception e) {
exp = e;
}
}
if (exp != null) {
//exp.printStackTrace();
//log.error(exp.getMessage());
throw exp;
}
log.debug(iMonitorVO.getId() + " - all done");
}
/**
* Process the alarm to send email
* @param iMonitorVO IMonitor value object
* @throws Exception
*/
private static void processVOToEmail(IMonitorVO iMonitorVO) throws Exception {
EmailVO emailVO = new EmailVO();
List<String> themeList = iMonitorVO.getTheme();
String theme = "ialarm";
if (themeList != null && themeList.size() > 0) {
theme = themeList.get(0);
}
List<ThemeEmailVO> themeEmailList = ThemeEmail.readFromExcelFile(theme); // TODO : get first theme only ?
String emailFrom = null;
String emailName = null;
String emailPassword = null;
if (themeEmailList.size() > 0) {
ThemeEmailVO themeEmailVO = (ThemeEmailVO) themeEmailList.get(0); // get first email only. should be 1 email per theme.
emailFrom = themeEmailVO.getEmail();
emailName = themeEmailVO.getName();
emailPassword = themeEmailVO.getPassword();
}
//log.debug("==== emailFrom : " + emailFrom);
//log.debug("==== emailName : " + emailName);
//log.debug("==== emailPassword : " + emailPassword);
iMonitorVO.setEmailFrom(emailFrom);
iMonitorVO.setEmailFromName(emailName);
iMonitorVO.setEmailPassword(emailPassword);
// to read recipients list from excel file
//iMonitorVO.setRecipients(Arrays.asList(emailFrom));
emailVO.setFrom(iMonitorVO.getEmailFrom());
emailVO.setFromName(iMonitorVO.getEmailFromName());
emailVO.setPassword(iMonitorVO.getEmailPassword());
String subject = iMonitorVO.isPhoneIt() ? "☎Phone: " + iMonitorVO.getSubject() : iMonitorVO.getSubject(); // add phone icon if send a phone call as well.
emailVO.setSubject(subject);
emailVO.setBody(iMonitorVO.getBody());
emailVO.setRecipient(iMonitorVO.getRecipients());
emailVO.setRecipientCC(iMonitorVO.getEmailCC());
emailVO.setRecipientBCC(iMonitorVO.getEmailBCC());
emailVO.setReplyTo(iMonitorVO.getEmailReplyTo());
emailVO.setAttachmentPath(iMonitorVO.getAttachments());
emailVO.setImages(iMonitorVO.getImages());
Email.send(emailVO);
}
/**
* Process the alarm to do phone
* @param iMonitorVO IMonitor value object
* @throws Exception
*/
private static void processVOToPhone(IMonitorVO iMonitorVO) throws Exception {
//String message = "ThisIsJustATest)";
String message = URLEncoder.encode(iMonitorVO.getSubject() == null ? "" : iMonitorVO.getSubject(), "UTF-8");
int maxDuration = 55; // in seconds
List<String> phoneNumbersList = iMonitorVO.getPhoneNumbers();
if (phoneNumbersList != null && phoneNumbersList.size() > 0) {
for (int i=0; i<phoneNumbersList.size(); i++) {
String phoneNumber = phoneNumbersList.get(i).replaceAll(Pattern.quote("+"), ""); // replace '+' char
phoneNumber = phoneNumber.replaceAll("\\s+",""); // remove all white spaces
String hoiioUrl = "https://secure.hoiio.com/open/ivr/start/dial?dest=%2B" + phoneNumber + "&access_token=ATJEKFoYHAbGYNxm&app_id=26hsfU4rkHvypTFe&msg=" + message + "&caller_id=private&max_duration=" + maxDuration;
URL phoneCallUrl = new URL(hoiioUrl);
URLConnection yc = phoneCallUrl.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
boolean isSuccess = false;
while ((inputLine = in.readLine()) != null) {
//System.out.println(inputLine);
if (inputLine.contains("\"status\":\"success_ok\"")) {
isSuccess = true;
break;
}
}
in.close();
}
}
}
/**
* Process the alarm to do sms
* @param iMonitorVO IMonitor value object
* @throws Exception
*/
private static void processVOToSms(IMonitorVO iMonitorVO) throws Exception {
//String message = "ThisIsJustATest%20My%20Message";
String message = URLEncoder.encode(iMonitorVO.getSubject() == null ? "" : iMonitorVO.getSubject(), "UTF-8");
List<String> phoneNumbersList = iMonitorVO.getPhoneNumbers();
if (phoneNumbersList != null && phoneNumbersList.size() > 0) {
for (int i=0; i<phoneNumbersList.size(); i++) {
String phoneNumber = "65" + phoneNumbersList.get(i).replaceAll("\\s+",""); // remove all white spaces
String hoiioUrl = "https://secure.hoiio.com/open/sms/send?access_token=ATJEKFoYHAbGYNxm&app_id=26hsfU4rkHvypTFe&dest=%2B" + phoneNumber + "&msg=" + message;
URL phoneCallUrl = new URL(hoiioUrl);
URLConnection yc = phoneCallUrl.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
boolean isSuccess = false;
while ((inputLine = in.readLine()) != null) {
//System.out.println(inputLine);
if (inputLine.contains("\"status\":\"success_ok\"")) {
isSuccess = true;
break;
}
}
in.close();
}
}
}
/**
* Process the alarm to do say
* @param iMonitorVO IMonitor value object
* @throws Exception
*/
private static void processVOToSay(IMonitorVO iMonitorVO) throws Exception {
TTS tts = new TTS();
tts.init(TTS.VOICE_MBROLA_US1);
tts.doSpeak(iMonitorVO.getSubject());
//tts.terminate(); // don't terminate, to prevent java.lang.IllegalThreadStateException
}
}
@@ -0,0 +1,42 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fourelementscapital.socket.SocketProcess;
/**
* A class implement SocketProcess to be used as dependency injection in SocketServer, so SocketServer serve as StackAlarm listener.
*/
public class IMonitorSocketProcess implements SocketProcess {
private static final Logger log = LogManager.getLogger(IMonitorSocketProcess.class.getName());
/**
* Run stack alarm process
* @param strReadLine Message received by SocketServer to be processed by StackAlarm.
*/
public void run(String strReadLine) {
try {
IMonitorVO iMonitorVO = IMonitor.processMessage(strReadLine); // RECEIVE socket message and process it (compose data & store to iMonitorVO)
IMonitor.process(iMonitorVO); // vo is ready to be processed (SEND to email / phone / say)
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
}
@@ -0,0 +1,188 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
import java.util.ArrayList;
import java.util.List;
public class IMonitorVO {
private String id;
private List<String> theme;
//private String sendingEmailStatus;
private String subject;
private List<String> emailReplyTo;
private List<String> emailBCC;
private List<String> emailCC;
private List<String> images;
private List<String> attachments;
private boolean sayIt;
private boolean emailIt;
private boolean phoneIt;
private boolean smsIt;
private String alertLevel;
private List<String> phoneNumbers;
private List<String> recipients;
private List<String> yahooMessenger;
private String escalation;
private String message;
private String body;
private String emailFrom;
private String emailFromName;
private String emailPassword;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<String> getTheme() {
return theme;
}
public void setTheme(List<String> theme) {
this.theme = theme;
}
/*
public String getSendingEmailStatus() {
return sendingEmailStatus;
}
public void setSendingEmailStatus(String sendingEmailStatus) {
this.sendingEmailStatus = sendingEmailStatus;
}
*/
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getEmailReplyTo() {
return emailReplyTo;
}
public void setEmailReplyTo(List<String> emailReplyTo) {
this.emailReplyTo = emailReplyTo;
}
public List<String> getEmailBCC() {
return emailBCC;
}
public void setEmailBCC(List<String> emailBCC) {
this.emailBCC = emailBCC;
}
public List<String> getEmailCC() {
return emailCC;
}
public void setEmailCC(List<String> emailCC) {
this.emailCC = emailCC;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public List<String> getAttachments() {
return attachments;
}
public void setAttachments(List<String> attachments) {
this.attachments = attachments;
}
public boolean isSayIt() {
return sayIt;
}
public void setSayIt(boolean sayIt) {
this.sayIt = sayIt;
}
public boolean isEmailIt() {
return emailIt;
}
public void setEmailIt(boolean emailIt) {
this.emailIt = emailIt;
}
public boolean isPhoneIt() {
return phoneIt;
}
public void setPhoneIt(boolean phoneIt) {
this.phoneIt = phoneIt;
}
public boolean isSmsIt() {
return smsIt;
}
public void setSmsIt(boolean smsIt) {
this.smsIt = smsIt;
}
public String getAlertLevel() {
return alertLevel;
}
public void setAlertLevel(String alertLevel) {
this.alertLevel = alertLevel;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List<String> getRecipients() {
return recipients;
}
public void setRecipients(List<String> recipients) {
this.recipients = recipients;
}
public List<String> getYahooMessenger() {
return yahooMessenger;
}
public void setYahooMessenger(List<String> yahooMessenger) {
this.yahooMessenger = yahooMessenger;
}
public String getEscalation() {
return escalation;
}
public void setEscalation(String escalation) {
this.escalation = escalation;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getEmailFrom() {
return emailFrom;
}
public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
public String getEmailFromName() {
return emailFromName;
}
public void setEmailFromName(String emailFromName) {
this.emailFromName = emailFromName;
}
public String getEmailPassword() {
return emailPassword;
}
public void setEmailPassword(String emailPassword) {
this.emailPassword = emailPassword;
}
}
@@ -0,0 +1,98 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ThemeEmail {
private static Object getCellValue(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
case Cell.CELL_TYPE_BOOLEAN:
return cell.getBooleanCellValue();
case Cell.CELL_TYPE_NUMERIC:
return cell.getNumericCellValue();
case Cell.CELL_TYPE_FORMULA:
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
return cell.getNumericCellValue();
case Cell.CELL_TYPE_STRING:
return (cell.getRichStringCellValue()).toString();
}
}
return null;
}
public static List<ThemeEmailVO> readFromExcelFile(String themeSelected) throws IOException {
List<ThemeEmailVO> themeEmailSelected = new ArrayList<ThemeEmailVO>();
List<ThemeEmailVO> themeEmailsList = new ArrayList<ThemeEmailVO>();
FileInputStream inputStream = new FileInputStream(new File(Config.getConfigValueImonitor("excel_file")));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
String themeIterate = "";
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
ThemeEmailVO themeEmailVO = new ThemeEmailVO();
while (cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int columnIndex = nextCell.getColumnIndex();
switch (columnIndex) {
case 0:
themeEmailVO.setEmail((String) getCellValue(nextCell));
break;
case 1:
themeIterate = (String) getCellValue(nextCell);
themeEmailVO.setTheme(themeIterate);
break;
case 2:
themeEmailVO.setName((String) getCellValue(nextCell));
break;
case 3:
themeEmailVO.setLastName((String) getCellValue(nextCell));
break;
case 4:
themeEmailVO.setPassword((String) getCellValue(nextCell));
break;
}
}
if (themeSelected.equalsIgnoreCase(themeIterate)) {
themeEmailSelected.add(themeEmailVO);
}
}
workbook.close();
inputStream.close();
return themeEmailSelected;
}
}
@@ -0,0 +1,53 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
public class ThemeEmailVO {
private String email;
private String theme;
private String name;
private String lastName;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,157 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor.email;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.lang3.StringUtils;
import com.fourelementscapital.imonitor.Config;
/**
* A java class to compose and send email
*/
public class Email {
/**
* Send email
* @param emailVO Email value object
* @throws IOException
*/
public static void send(EmailVO emailVO) throws Exception {
final String inputFrom = Config.getConfigValueImonitor("email_from");
final String inputPassword = Config.getConfigValueImonitor("email_password");
final String inputRecipient = StringUtils.join(emailVO.getRecipient(), ",");
final String inputRecipientCC = StringUtils.join(emailVO.getRecipientCC(), ",");
final String inputRecipientBCC = StringUtils.join(emailVO.getRecipientBCC(), ",");
final String inputReplyTo = StringUtils.join(emailVO.getReplyTo(), ",");
Properties props = new Properties();
props.put("mail.smtp.auth", Config.getConfigValueEmail("mail.smtp.auth"));
props.put("mail.smtp.starttls.enable", Config.getConfigValueEmail("mail.smtp.starttls.enable"));
props.put("mail.smtp.host", Config.getConfigValueEmail("mail.smtp.host"));
props.put("mail.smtp.port", Config.getConfigValueEmail("mail.smtp.port"));
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(inputFrom,inputPassword);
}
});
try {
if (inputRecipient == null || "".equals(inputRecipient)) {
throw new Exception("There's no email recipient");
}
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(inputRecipient));
// set cc if not null
if (inputRecipientCC != null && "".equals(inputRecipientCC.trim())) {
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(inputRecipientCC));
}
// set bcc if not null
if (inputRecipientBCC != null && "".equals(inputRecipientCC.trim())) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(inputRecipientBCC));
}
// set replyTo if not null
if (inputReplyTo != null && "".equals(inputReplyTo.trim())) {
message.setReplyTo(InternetAddress.parse(inputReplyTo));
}
message.setSubject(emailVO.getSubject());
message.setFrom(new InternetAddress(inputFrom, emailVO.getFromName()));
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// set images :
List<String> imageList = emailVO.getImages();
String images = "";
if (imageList != null && imageList.size() > 0) {
for (int i=0; i<imageList.size(); i++) {
addImages(multipart, imageList.get(i), i+"");
images += "<img alt='embeddedimage_" + i + "' src=cid:embeddedImage_" + i + ">";
}
}
// set body with images in it
String body = emailVO.getBody();
// if body is null then insert "" string to prevent error
if (body == null) {
body = "";
}
if (body.contains("{{{IMG}}}")) {
body = body.replace("{{{IMG}}}", images);
}
else {
body += "<br/>" + images;
}
messageBodyPart.setContent(body, "text/html");
multipart.addBodyPart(messageBodyPart);
// set attachments :
List<String> attachmentPathList = emailVO.getAttachmentPath();
if (attachmentPathList != null && attachmentPathList.size() > 0) {
for (int i=0; i<attachmentPathList.size(); i++) {
addAttachment(multipart, attachmentPathList.get(i));
}
}
// Send the complete message parts
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private static void addAttachment(Multipart multipart, String filename) throws MessagingException {
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
private static void addImages(Multipart multipart, String filename, String id) throws MessagingException {
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setHeader("Content-ID", "<embeddedImage_"+ id +">");
multipart.addBodyPart(messageBodyPart);
}
}
@@ -0,0 +1,126 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor.email;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Email Value Object
*/
public class EmailVO implements Serializable {
private String from;
private String fromName;
private String password;
private String subject;
private String body;
private List<String> recipient;
private List<String> recipientCC;
private List<String> recipientBCC;
private List<String> replyTo;
private List<String> attachmentPath;
private List<String> images;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public List<String> getRecipient() {
return recipient;
}
public void setRecipient(List<String> recipient) {
this.recipient = recipient;
}
public List<String> getRecipientCC() {
return recipientCC;
}
public void setRecipientCC(List<String> recipientCC) {
this.recipientCC = recipientCC;
}
public List<String> getRecipientBCC() {
return recipientBCC;
}
public void setRecipientBCC(List<String> recipientBCC) {
this.recipientBCC = recipientBCC;
}
public List<String> getReplyTo() {
return replyTo;
}
public void setReplyTo(List<String> replyTo) {
this.replyTo = replyTo;
}
public List<String> getAttachmentPath() {
return attachmentPath;
}
public void setAttachmentPath(List<String> attachmentPath) {
this.attachmentPath = attachmentPath;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
}
@@ -0,0 +1,152 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor.stackalarm;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
/**
* The DBManager class provides an Access Interface between the Database and Java.
* It can be used to get data from the database, insert new data and update existing data.
* The config file containing the details for the database hostname and credentials is located in the resources folder.
*/
class DBManager {
/**
* The database name for the current instance of DBManager
*/
private String dbName;
/**
* The connection string for the database connection. Stored in config file
*/
private String connectionString;
/**
* The resultSet which contains the returned results from the SQL Query of GetDatabase
*/
ResultSet resultSet = null;
/**
* The connection object of the current connection.
*/
private Connection conn = null;
/**
* Initialize the DBManager with the database name.
* @param dbName The name of the database e.x. trading, tradingRef, fundamentals
* @throws IOException
*/
public DBManager(String dbName) throws IOException
{
this.dbName = dbName;
}
/**
* This function connects to the dbName database;
* @throws SQLException This is thrown incase we are not able to connect to the database;
* @throws ClassNotFoundException This is thrown incase the driver is not found on this machine
* @throws IOException This is thrown incase the config file if not found on this machine under resources folder
*/
public void connect() throws SQLException, ClassNotFoundException, IOException
{
//String url = "jdbc:jtds:sqlserver://"+databaseServerAddress+";DatabaseName="+databaseName;
String driver = Utils.GetConfigValue("database_"+dbName.toLowerCase()+"_"+"driver");
Class.forName(driver);
String connStr = Utils.GetConfigValue("database_"+dbName.toLowerCase()+"_"+"connstring");
System.out.println("+++++ " + connStr);
conn = DriverManager.getConnection(connStr);
connectionString = conn.toString();
}
/**
* Closes the current Database connection.
* @throws SQLException
*/
public void closeConnection() throws SQLException
{
if(!conn.isClosed())
conn.close();
if(resultSet!=null)
resultSet.close();
}
/**
* This function returns the result set of the SQL Query used by GetDatabase;
* @param query The SQL Query passed to it.
* @return
* @throws SQLException
*/
public ResultSet executeQuery(String query) throws SQLException
{
Date start = new Date();
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
resultSet = statement.executeQuery(query);
Date end = new Date();
long duration = (end.getTime() - start.getTime());
//Utils.Log("DEBUG: Query ("+query+") took "+duration+ " miliseconds");
return resultSet;
}
/**
* Used to query a database and access the resultant data in a ResultSet
* @param tableName The name of the database table to be accessed
* @param selectedFields A list of the values to be selected through the queries. <code>new ArrayList<String>();</code>
* be passed to select all fields (*)
* @param queryParams A hashmap containing the selection filters in the format <code>[column_name]=[value]</code>
* @param customQuery Any additional parameters to be added after the Where clause. Could be a GROUP BY or ORDER BY
* @return The resulting data in a ResultSet
* @throws SQLException
*/
public ResultSet GetDatabase(String tableName,ArrayList<String> selectedFields, Map<String,Object> queryParams, String customQuery) throws SQLException
{
String queryBuilder = "";
if(selectedFields.size()==0)
{
selectedFields.add("*");
}
queryBuilder += "SELECT "+Utils.Join(selectedFields,",")+" FROM "+tableName;
if(queryParams != null && queryParams.size()>0)
{
queryBuilder += " WHERE ";
for (Map.Entry<String,Object> entry : queryParams.entrySet()) {
try{
Float f = Float.parseFloat(entry.getValue().toString());
queryBuilder += " "+entry.getKey() + " = "+entry.getValue()+" AND";
}
catch(Exception ex)
{
queryBuilder += " "+entry.getKey() + " = '"+entry.getValue()+"' AND";
}
}
if(customQuery!= null && customQuery!="")
queryBuilder += customQuery+" AND";
queryBuilder = queryBuilder.substring(0,queryBuilder.length()-3);
}
System.out.println(queryBuilder);
return executeQuery(queryBuilder);
}
}
@@ -0,0 +1,90 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor.stackalarm;
import java.sql.ResultSet;
import java.util.ArrayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A class for parsing & process stack alarms
*/
public class StackAlarm {
private static final Logger log = LogManager.getLogger(StackAlarm.class.getName());
/**
* Get recipients (email) & phone numbers
* @param theme Theme
* @param alarmLevel Alarm level (HIGH / MEDIUM /LOW)
* @return StackAlarmVO
*/
public static StackAlarmVO collectRecipients(String theme, String alarmLevel) throws Exception
{
// GET RECIPIENTS :
DBManager dbm = new DBManager("infrastructure");
dbm.connect();
theme = theme.toLowerCase();
// get alarm level from VO
if (alarmLevel == null || "".equals(alarmLevel.trim())) {
throw new Exception("alarmLevel is null");
}
if ("HIGH".equals(alarmLevel.toUpperCase())) {
alarmLevel = "b.Alarm_High";
}
else if ("MEDIUM".equals(alarmLevel.toUpperCase())) {
alarmLevel = "b.Alarm_Medium";
}
else if ("LOW".equals(alarmLevel.toUpperCase())) {
alarmLevel = "b.Alarm_Low";
}
else {
throw new Exception("No alarm level found !");
}
//log.debug("theme : " + theme + " | alarmLevel : " + alarmLevel);
StringBuilder sql = new StringBuilder();
sql.append(" SELECT a.user, c.phonenumber, c.yahoo");
sql.append(" FROM `tblTeamOrganization2` a left join tblRoleDefinition b on a." + theme + " = b.Letter ");
sql.append(" left join tblContactDetails c on a.user = c.username");
sql.append(" WHERE " + alarmLevel + "='1'");
//System.out.println(">>> sql : " + sql);
ResultSet rs = dbm.executeQuery(sql.toString());
StackAlarmVO stackAlarmVO = new StackAlarmVO();
stackAlarmVO.setTheme(theme);
ArrayList recipients = new ArrayList();
ArrayList phoneNumbers = new ArrayList();
while(rs.next()){
recipients.add(rs.getString("a.user") + "@4ecap.com");
phoneNumbers.add(rs.getString("c.phonenumber"));
}
stackAlarmVO.setRecipients(recipients);
stackAlarmVO.setPhoneNumbers(phoneNumbers);
//System.out.println(">>> recipients.size() : " + recipients.size());
return stackAlarmVO;
}
}
@@ -0,0 +1,52 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor.stackalarm;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import javax.mail.Message;
import org.apache.commons.net.smtp.SMTPClient;
/**
* Stack Alarm Value Object
*/
public class StackAlarmVO {
private String theme;
private List<String> phoneNumbers;
private List<String> recipients;
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List<String> getRecipients() {
return recipients;
}
public void setRecipients(List<String> recipients) {
this.recipients = recipients;
}
}
@@ -0,0 +1,83 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor.stackalarm;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
/**
* This class contains Static Utility functions
*/
class Utils {
/**
* Accepts an ArrayList of strings and then returns a delimiter separated string
* @param al The arraylist of strings
* @param delimiter The delimiter
* @return The delimiter separated string
*/
protected static String Join(ArrayList<String> al,String delimiter)
{
return al.toString().replaceAll("\\[|\\]", "").replaceAll(", ",delimiter);
}
/**
* Get the value of a property defined in config file
* @param propertyName - the name or key of the property you want to retrieve
* @return the string value
* @throws IOException
*/
protected static String GetConfigValue(String propertyName) throws IOException
{
Properties prop = new Properties();
String propFileName = "config_stackalarm.properties";
InputStream inputStream = Utils.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
Date time = new Date(System.currentTimeMillis());
// get the property value and print it out
String value = prop.getProperty(propertyName);
return value;
}
/**
* Capitalize first char of a word.
* Example : 'this is text. another text' will be converted to 'This Is Text. Another Text'
* @param string
* @return string
*/
protected static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
}
+4
View File
@@ -0,0 +1,4 @@
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.gmail.com
mail.smtp.port=587
@@ -0,0 +1,9 @@
excel_file=/iMonitor2/ThemeEmails.xlsx
#excel_file=C:\\iMonitor2\\ThemeEmails.xlsx
#Email configuration to send message via email
email_from=abc@gmail.com
email_password=abc2018
+11
View File
@@ -0,0 +1,11 @@
socket_server_address=127.0.0.1
#socket_server_address=10.153.64.10
socket_server_port_number=1777
#socket_server_port_number=1778
#socket_server_port_number=8080
#socket_server_address=0.0.0.0
@@ -0,0 +1,2 @@
database_infrastructure_connstring=jdbc:mysql://10.153.64.10:3306/infrastructure2?user=root&password=disaster
database_infrastructure_driver=com.mysql.jdbc.Driver
+2
View File
@@ -0,0 +1,2 @@
#mbrola_path=C:\\iMonitor2\\mbrola\\
mbrola_path=/usr/share/mbrola
@@ -0,0 +1,198 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.imonitor;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import javax.swing.JOptionPane;
import com.fourelementscapital.imonitor.email.EmailVO;
import com.fourelementscapital.imonitor.email.Email;
import com.fourelementscapital.imonitor.stackalarm.StackAlarmVO;
import com.fourelementscapital.imonitor.stackalarm.StackAlarm;
/**
* Unit test for App
*/
public class AppTest extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Empty Test
*/
public void testApp()
{
assertTrue( true );
}
/**
* Test ProcessMessage(). Convert message string to ImonitorVO.
*/
public void testProcessMessage()
{
StringBuilder sb = new StringBuilder();
sb.append("theme$#=computing,java");
sb.append("~subject$#=This is just a test");
sb.append("~body$#=This is {{{IMG}}} the email body");
sb.append("~recipients$#=ari@4ecap.com");
sb.append("~sayIt$#=true");
sb.append("~emailIt$#=false");
sb.append("~phoneCall$#=false");
sb.append("~sms$#=FALSE");
sb.append("~ym$#=FALSE");
sb.append("~numbers$#=+65 8297 1508");
sb.append("~alarmLevel$#=LOW");
sb.append("<EOF>");
String message = sb.toString();
try {
IMonitorVO iMonitorVO = IMonitor.processMessage(message);
if (iMonitorVO.isSayIt()) {
//JOptionPane.showMessageDialog(null, "IMonitor ProcessMessage done");
assertTrue(true);
}
else {
assertTrue(false);
}
}
catch(Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
/**
* Test Process(). Do email / phone / text to speech according to ImonitorVO value.
* Remove the comment tag to test.
* The code are commented out to prevent phone calling to +6287821107029
*/
public void testProcess()
{
/*
try {
IMonitorVO iMonitorVO = new IMonitorVO();
List<String> phonenumbersList = new ArrayList<String>();
phonenumbersList.add("+6287821107029");
iMonitorVO.setPhoneNumbers(phonenumbersList);
iMonitorVO.setPhoneIt(true);
iMonitorVO.setSubject("This is just a test");
//IMonitor.process(iMonitorVO);
//JOptionPane.showMessageDialog(null, "IMonitor phone call done");
assertTrue(true);
}
catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
*/
assertTrue(true);
}
/**
* Test send email
* Remove the comment tag to test after set vo.setFromName and vo.setPassword
* The code are commented out to prevent error when install this library
*/
public void testSendEmail() {
try {
EmailVO vo = new EmailVO();
vo.setFrom("abc@gmail.com");
vo.setFromName("abc");
vo.setPassword("abc2018");
vo.setSubject("Testing Subject");
vo.setBody("<strong>Dear GMail</strong>,<br/> This is just a test.");
ArrayList<String> recipientList = new ArrayList<String>();
recipientList.add("intan@kronosinvestments.net");
vo.setRecipient(recipientList);
ArrayList<String> recipientCCList = new ArrayList<String>();
recipientCCList.add("cc@gmail.com");
recipientCCList.add("dd@gmail.com");
vo.setRecipientCC(recipientCCList);
ArrayList<String> recipientBCCList = new ArrayList<String>();
recipientBCCList.add("bcc@gmail.com");
recipientBCCList.add("bcc2@gmail.com");
vo.setRecipientBCC(recipientBCCList);
ArrayList<String> replyToAL = new ArrayList<String>();
replyToAL.add("replyto@gmail.com");
replyToAL.add("reply@yahoo.com");
vo.setReplyTo(replyToAL);
//ArrayList<String> attachmentList = new ArrayList<String>();
//attachmentList.add("/home/intan/Documents/test_email.txt");
//vo.setAttachmentPath(attachmentList);
//ArrayList<String> imagesList = new ArrayList<String>();
//imagesList.add("/home/intan/Documents/Selection_020.png");
//vo.setImages(imagesList);
//Email.send(vo);
//JOptionPane.showMessageDialog(null, "Email sent succesfully");
assertTrue(true);
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
/**
* Test parse alarm using StackAlarm
* Remove the comment tag to test
* The code are commnted out to prevent collect database data when install this lib
*/
public void testParseMessage()
{
try {
// Remove the comment tag to test. The code are commented out to prevent getting data from database (edit properties file first) :
//StackAlarmVO stackAlarmVO = StackAlarm.collectRecipients("comp", "HIGH");
//JOptionPane.showMessageDialog(null, stackAlarmVO);
assertTrue( true );
}
catch (Exception e) {
e.printStackTrace();
assertTrue( false );
}
}
}