Skip to content

Commit

Permalink
inbox script exit code introduced
Browse files Browse the repository at this point in the history
+ extended config accordingly
+ fixed StopMessage processing logic
  • Loading branch information
domax committed Jun 13, 2015
1 parent c8e5d1a commit c4793d3
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 12 deletions.
6 changes: 6 additions & 0 deletions data/config-template.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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 ##
#########################################
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>org.exchange.git</groupId>
<artifactId>email-bridge</artifactId>
<version>0.0.3</version>
<version>0.0.4</version>
<packaging>jar</packaging>

<name>email-bridge</name>
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/org/mail/bridge/AbstractMonitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ protected <T> void postMessage(Message<T> message) {
public abstract AbstractMonitor scan();

public abstract AbstractMonitor monitor();

public abstract AbstractMonitor stop();
}
9 changes: 9 additions & 0 deletions src/main/java/org/mail/bridge/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -229,6 +232,10 @@ public String getInboxScript() {
return inboxScript;
}

public int getInboxScriptStopCode() {
return inboxScriptStopCode;
}

public boolean isEmailInboxCleanup() {
return emailInboxCleanup;
}
Expand Down Expand Up @@ -296,6 +303,7 @@ public Map<String, String> 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());
Expand Down Expand Up @@ -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() + '\'' +
Expand Down
19 changes: 15 additions & 4 deletions src/main/java/org/mail/bridge/ExchangeMonitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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");
Expand All @@ -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<File> files) {
Expand All @@ -292,8 +301,10 @@ public synchronized void sendFiles(List<File> files) {
final Map<File, InputStream> 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, "..."));
Expand Down
37 changes: 30 additions & 7 deletions src/main/java/org/mail/bridge/FolderMonitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ public void run() {

private final Config config;
private final File outboxFolder;
private final WatchService watcher;
private final ArrayList<File> files = new ArrayList<>();
private Thread monitorThread;
private Timer timer;

private final FileFilter fileFilter = new FileFilter() {
Expand All @@ -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");
Expand All @@ -113,14 +112,14 @@ public FolderMonitor addSendFileCallback(MonitorCallback<List<File>> callback) {
}

private void processFiles(List<File> 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<File> 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());
Expand All @@ -132,8 +131,16 @@ public synchronized void runScriptAgainstReceivedFiles(List<File> inboxFiles) {
Map<String, String> 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());
Expand All @@ -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);
Expand Down Expand Up @@ -204,5 +226,6 @@ public void run() {
break;
}
}
monitorThread = null;
}
}
3 changes: 3 additions & 0 deletions src/main/java/org/mail/bridge/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit c4793d3

Please sign in to comment.