From c4793d357fc19e09939ae7003026c9e0c4ae337f Mon Sep 17 00:00:00 2001 From: Maxim Dominichenko Date: Sat, 13 Jun 2015 17:21:59 -0400 Subject: [PATCH] inbox script exit code introduced + extended config accordingly + fixed StopMessage processing logic --- data/config-template.properties | 6 +++ pom.xml | 2 +- .../java/org/mail/bridge/AbstractMonitor.java | 2 + src/main/java/org/mail/bridge/Config.java | 9 +++++ .../java/org/mail/bridge/ExchangeMonitor.java | 19 ++++++++-- .../java/org/mail/bridge/FolderMonitor.java | 37 +++++++++++++++---- src/main/java/org/mail/bridge/Main.java | 3 ++ 7 files changed, 66 insertions(+), 12 deletions(-) diff --git a/data/config-template.properties b/data/config-template.properties index 9f53439..c686a6f 100644 --- a/data/config-template.properties +++ b/data/config-template.properties @@ -99,6 +99,12 @@ inbox.folder = # environment variable. #inbox.script = +# Optional integer value that should be considered as application stop code. +# I.e. if script exits with specified code then application exits as well. +# Value of 0 means that exit code of script will not be processed. +# Default value is 0 +#inbox.script.stop.code = + ######################################### ## EMail message processing settings ## ######################################### diff --git a/pom.xml b/pom.xml index 73e1ab3..70bb144 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.exchange.git email-bridge - 0.0.3 + 0.0.4 jar email-bridge diff --git a/src/main/java/org/mail/bridge/AbstractMonitor.java b/src/main/java/org/mail/bridge/AbstractMonitor.java index 470bc18..501f3b6 100644 --- a/src/main/java/org/mail/bridge/AbstractMonitor.java +++ b/src/main/java/org/mail/bridge/AbstractMonitor.java @@ -59,4 +59,6 @@ protected void postMessage(Message message) { public abstract AbstractMonitor scan(); public abstract AbstractMonitor monitor(); + + public abstract AbstractMonitor stop(); } diff --git a/src/main/java/org/mail/bridge/Config.java b/src/main/java/org/mail/bridge/Config.java index e197a10..dd6cdc0 100644 --- a/src/main/java/org/mail/bridge/Config.java +++ b/src/main/java/org/mail/bridge/Config.java @@ -66,6 +66,7 @@ public class Config { private final String inboxFolder; private final String inboxScript; + private final int inboxScriptStopCode; private final String emailTagIncoming; private final String emailTagOutgoing; @@ -115,6 +116,8 @@ public Config(String propertiesFileName) throws IOException { s = config.getProperty("inbox.folder", ""); inboxFolder = s.isEmpty() ? System.getProperty("java.io.tmpdir") + File.separator + "inbox" : s; inboxScript = config.getProperty("inbox.script", ""); + s = config.getProperty("inbox.script.stop.code", ""); + inboxScriptStopCode = s.isEmpty() ? 0 : Integer.parseInt(s); s = config.getProperty("email.tag.incoming", ""); emailTagIncoming = s.isEmpty() ? "email-bridge" : s; @@ -229,6 +232,10 @@ public String getInboxScript() { return inboxScript; } + public int getInboxScriptStopCode() { + return inboxScriptStopCode; + } + public boolean isEmailInboxCleanup() { return emailInboxCleanup; } @@ -296,6 +303,7 @@ public Map asEnvironmentMap() { result.put("OUTBOX_FILE_REGEXP", outboxFileRegexp); result.put("INBOX_FOLDER", inboxFolder); result.put("INBOX_SCRIPT", inboxScript); + result.put("INBOX_SCRIPT_STOP_CODE", "" + inboxScriptStopCode); result.put("EMAIL_TAG_INCOMING", emailTagIncoming); result.put("EMAIL_TAG_OUTGOING", emailTagOutgoing); result.put("EMAIL_SUBJECT_FORMAT", emailSubjectFormat.toPattern()); @@ -331,6 +339,7 @@ public String toString() { ",\n\toutboxFileRegexp='" + outboxFileRegexp + '\'' + ",\n\tinboxFolder='" + inboxFolder + '\'' + ",\n\tinboxScript='" + inboxScript + '\'' + + ",\n\tinboxScriptStopCode=" + inboxScriptStopCode + ",\n\temailTagIncoming='" + emailTagIncoming + '\'' + ",\n\temailTagOutgoing='" + emailTagOutgoing + '\'' + ",\n\temailSubjectFormat='" + emailSubjectFormat.toPattern() + '\'' + diff --git a/src/main/java/org/mail/bridge/ExchangeMonitor.java b/src/main/java/org/mail/bridge/ExchangeMonitor.java index 6d488c0..6bae8f8 100644 --- a/src/main/java/org/mail/bridge/ExchangeMonitor.java +++ b/src/main/java/org/mail/bridge/ExchangeMonitor.java @@ -241,7 +241,7 @@ public synchronized ExchangeMonitor monitor() { try { StreamingSubscription subscription = service.subscribeToStreamingNotifications( Collections.singletonList(new FolderId(WellKnownFolderName.Inbox)), EventType.NewMail); - LOG.info("Setup streaming connection"); + LOG.debug("Setup streaming connection"); StreamingSubscriptionConnection subscriptionConn = new StreamingSubscriptionConnection(service, config.getEwsSubscriptionLifetime()); subscriptionConn.addSubscription(subscription); @@ -257,6 +257,14 @@ public synchronized ExchangeMonitor monitor() { return this; } + @Override + public ExchangeMonitor stop() { + LOG.info("Stop connection to EWS server"); + service.close(); + service = null; + return this; + } + @Override public void notificationEventDelegate(Object sender, NotificationEventArgs args) { LOG.debug("Streaming subscription received notification"); @@ -272,7 +280,8 @@ public void notificationEventDelegate(Object sender, NotificationEventArgs args) @Override public void subscriptionErrorDelegate(Object sender, SubscriptionErrorEventArgs args) { LOG.warn("Streaming subscription is disconnected", args.getException()); - postMessage(new ReopenMonitorMessage()); + if (service != null) + postMessage(new ReopenMonitorMessage()); } public synchronized void sendFiles(List files) { @@ -292,8 +301,10 @@ public synchronized void sendFiles(List files) { final Map attachmentStreams = new HashMap<>(); for (File file : files) { final Object[] params = {config.getEmailTagOutgoing(), new Date(), file.getName()}; - subjectBuilder.append(config.getEmailSubjectFormat().format(params)).append(" "); - bodyBuilder.append(config.getEmailBodyFormat().format(params)).append("\n"); + if (subjectBuilder.length() > 0) subjectBuilder.append(" "); + subjectBuilder.append(config.getEmailSubjectFormat().format(params)); + if (bodyBuilder.length() > 0) bodyBuilder.append("\n"); + bodyBuilder.append(config.getEmailBodyFormat().format(params)); attachmentStreams.put(file, addFileAttachment(msg.getAttachments(), file)); } msg.setSubject(Utils.makeTeaser(subjectBuilder.toString(), 78, "...")); diff --git a/src/main/java/org/mail/bridge/FolderMonitor.java b/src/main/java/org/mail/bridge/FolderMonitor.java index 1db4500..ec98d9b 100644 --- a/src/main/java/org/mail/bridge/FolderMonitor.java +++ b/src/main/java/org/mail/bridge/FolderMonitor.java @@ -71,8 +71,8 @@ public void run() { private final Config config; private final File outboxFolder; - private final WatchService watcher; private final ArrayList files = new ArrayList<>(); + private Thread monitorThread; private Timer timer; private final FileFilter fileFilter = new FileFilter() { @@ -93,7 +93,6 @@ public int compare(File o1, File o2) { public FolderMonitor(Config config) throws IOException { this.config = config; outboxFolder = new File(config.getOutboxFolder()); - watcher = FileSystems.getDefault().newWatchService(); if (outboxFolder.exists()) { if (!outboxFolder.isDirectory()) throw new IOException("Specified path '" + outboxFolder.getAbsolutePath() + "' is a file, but folder expected"); @@ -113,14 +112,14 @@ public FolderMonitor addSendFileCallback(MonitorCallback> callback) { } private void processFiles(List files) throws IOException { - LOG.debug("Process files '{}'", files); + LOG.debug("Process files {}", files); if (Utils.isEmpty(files)) return; postMessage(new SendFileMessage(files)); } public synchronized void runScriptAgainstReceivedFiles(List inboxFiles) { if (config.getInboxScript().isEmpty() || Utils.isEmpty(inboxFiles)) return; - LOG.debug("Run script '{}' against files '{}'", config.getInboxScript(), inboxFiles); + LOG.debug("Run script '{}' against files {}", config.getInboxScript(), inboxFiles); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { CommandLine cmd = CommandLine.parse(config.getInboxScript()); @@ -132,8 +131,16 @@ public synchronized void runScriptAgainstReceivedFiles(List inboxFiles) { Map environment = EnvironmentUtils.getProcEnvironment(); environment.putAll(config.asEnvironmentMap()); executor.execute(cmd, environment); - LOG.info("Script {} successfully finished", config.getInboxScript()); + LOG.info("Script '{}' successfully finished", config.getInboxScript()); LOG.debug("Script output:\n{}", out.toString()); + } catch (ExecuteException e) { + LOG.error(e.getMessage(), e); + LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString()); + int c = config.getInboxScriptStopCode(); + if (c != 0 && c == e.getExitValue()) + postMessage(new Main.StopMessage( + String.format("Script '%s' exited with code %d that is configured as stop code", + config.getInboxScript(), c))); } catch (IOException e) { LOG.error(e.getMessage(), e); LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString()); @@ -157,16 +164,31 @@ public synchronized FolderMonitor scan() { @Override public FolderMonitor monitor() { - new Thread(this, FolderMonitor.class.getSimpleName()).start(); + LOG.info("Start monitoring '{}' folder", outboxFolder.getAbsolutePath()); + if (monitorThread == null) { + monitorThread = new Thread(this, FolderMonitor.class.getSimpleName()); + monitorThread.start(); + } + return this; + } + + @Override + public FolderMonitor stop() { + LOG.info("Stop monitoring '{}' folder", outboxFolder.getAbsolutePath()); + if (monitorThread != null) { + monitorThread.interrupt(); + monitorThread = null; + } return this; } @SuppressWarnings("unchecked") @Override public void run() { - LOG.info("Start monitoring '{}' folder", outboxFolder.getAbsolutePath()); Path outboxPath = outboxFolder.toPath(); + WatchService watcher; try { + watcher = FileSystems.getDefault().newWatchService(); outboxPath.register(watcher, ENTRY_CREATE); } catch (IOException e) { LOG.error(e.getMessage(), e); @@ -204,5 +226,6 @@ public void run() { break; } } + monitorThread = null; } } diff --git a/src/main/java/org/mail/bridge/Main.java b/src/main/java/org/mail/bridge/Main.java index 0102d4b..d31acbb 100644 --- a/src/main/java/org/mail/bridge/Main.java +++ b/src/main/java/org/mail/bridge/Main.java @@ -128,6 +128,9 @@ else if (message instanceof FolderMonitor.SendFileMessage) exchangeMonitor.sendFiles(((FolderMonitor.SendFileMessage) message).getData()); else if (message instanceof StopMessage) { System.out.println(((StopMessage) message).getData()); + exchangeMonitor.stop(); + folderMonitor.stop(); + Thread.currentThread().interrupt(); break; } else LOG.warn("Unsupported message {}", message); Thread.sleep(10);