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 stack = new UpnpStack(new UpnpStack.Listener() {
31 public void deviceAdded(String aDeviceString) {
32 LOGGER.fine("Device added: " + aDeviceString);
33 if (aDeviceString.toLowerCase().contains(
34 config.getPattern().toLowerCase())) {
35 synchronized (Monitor.this) {
36 setServiceFound(true);
42 public void deviceRemoved(String aDeviceString) {
43 LOGGER.fine("Device removed:" + aDeviceString);
46 executor.scheduleWithFixedDelay(this, 0, config.getIntervalSeconds(),
48 executeCommand(config.getStartupCommand());
51 public synchronized void setServiceFound(boolean aServiceFound) {
52 serviceFound = aServiceFound;
55 public synchronized void run() {
58 LOGGER.info("UPNP service is down, executing recovery");
59 // we need to execute recovery.
60 executeCommand(config.getShutdownCommand());
61 executeCommand(config.getStartupCommand());
62 setServiceFound(true);
63 // give process a chance to startup.
67 setServiceFound(false);
71 private void shutdownStack() {
78 private void executeCommand(String command) {
79 LOGGER.info("Executing command: " + command);
80 SimpleProcess process = new SimpleProcess(new File("."), new String[] {
81 "sh", "-c", command });
84 int ret = process.run();
85 LOGGER.info(process.getStdout());
86 LOGGER.info(process.getStderr());
87 LOGGER.info("Exit status: " + ret);
88 } catch (IOException e) {
89 LOGGER.log(Level.INFO, "Problem executing command", e);
96 executeCommand(config.getShutdownCommand());