1 package org.wamblee.upnpmonitor;
4 import java.io.IOException;
5 import java.util.concurrent.ScheduledThreadPoolExecutor;
6 import java.util.concurrent.TimeUnit;
7 import java.util.logging.Level;
8 import java.util.logging.Logger;
10 import org.wamblee.io.SimpleProcess;
12 public class Monitor implements Runnable {
14 private static final Logger LOGGER = Logger.getLogger(Monitor.class
17 private ScheduledThreadPoolExecutor executor;
18 private Config config;
19 private boolean serviceFound;
20 private UpnpStack stack;
22 public Monitor(Config aConfig) {
24 executor = new ScheduledThreadPoolExecutor(1);
29 executor.scheduleWithFixedDelay(this, 0, config.getIntervalSeconds(),
31 executeCommand(config.getStartupCommand());
34 public synchronized void setServiceFound(boolean aServiceFound) {
35 serviceFound = aServiceFound;
38 public synchronized void run() {
41 LOGGER.info("UPNP service is down, executing recovery");
42 // we need to execute recovery.
43 executeCommand(config.getShutdownCommand());
44 executeCommand(config.getStartupCommand());
45 setServiceFound(true);
46 // give process a chance to startup.
52 setServiceFound(false);
54 stack = new UpnpStack(new UpnpStack.Listener() {
56 public void deviceAdded(String aDeviceString) {
57 LOGGER.fine("Device added: " + aDeviceString);
58 if (aDeviceString.toLowerCase().contains(
59 config.getPattern().toLowerCase())) {
60 synchronized (Monitor.this) {
61 setServiceFound(true);
67 public void deviceRemoved(String aDeviceString) {
68 LOGGER.fine("Device removed:" + aDeviceString);
74 private void shutdownStack() {
81 private void executeCommand(String command) {
82 LOGGER.info("Executing command: " + command);
83 SimpleProcess process = new SimpleProcess(new File("."), new String[] {
84 "sh", "-c", command });
87 int ret = process.run();
88 LOGGER.info(process.getStdout());
89 LOGGER.info(process.getStderr());
90 LOGGER.info("Exit status: " + ret);
91 } catch (IOException e) {
92 LOGGER.log(Level.INFO, "Problem executing command", e);
99 executeCommand(config.getShutdownCommand());