From ddbf5d1ac05d0f03f7cbe9275c303541cca945be Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Thu, 8 Nov 2012 17:01:10 +0100 Subject: wip --- .../io/trygvis/esper/testing/ResourceManager.java | 62 ++++++++++++++++++---- 1 file changed, 52 insertions(+), 10 deletions(-) (limited to 'src/main/java/io/trygvis/esper/testing/ResourceManager.java') diff --git a/src/main/java/io/trygvis/esper/testing/ResourceManager.java b/src/main/java/io/trygvis/esper/testing/ResourceManager.java index e9a0068..dff19bd 100644 --- a/src/main/java/io/trygvis/esper/testing/ResourceManager.java +++ b/src/main/java/io/trygvis/esper/testing/ResourceManager.java @@ -1,31 +1,73 @@ package io.trygvis.esper.testing; -import fj.*; - +import java.io.*; import java.util.*; import java.util.concurrent.*; -public class ResourceManager { - private final Equal equal; - private final Callable> discoverer; +public class ResourceManager, V> implements Closeable { + private final ResourceManagerCallbacks callbacks; + private final ScheduledFuture future; + private Map map = Collections.emptyMap(); - public ResourceManager(Equal equal, ScheduledExecutorService executorService, int delay, Callable> discoverer) { - this.equal = equal; - this.discoverer = discoverer; + public interface ResourceManagerCallbacks, V> { + Set discover() throws Exception; + + V onNew(K key); + + void onGone(K key, V value); + } + + public ResourceManager(ScheduledExecutorService executorService, int delay, + ResourceManagerCallbacks callbacks) { + this.callbacks = callbacks; - executorService.scheduleWithFixedDelay(new Runnable() { + future = executorService.scheduleWithFixedDelay(new Runnable() { public void run() { work(); } }, delay, delay, TimeUnit.MILLISECONDS); + } private void work() { try { - List keys = discoverer.call(); + System.out.println("Discovering..."); + Set keys = callbacks.discover(); + + Set found = new HashSet<>(); + + for (K key : keys) { + if (map.containsKey(key)) { + continue; + } + + found.add(key); + } + + Set lost = new HashSet<>(map.keySet()); + lost.retainAll(found); + + System.out.println("Discovered " + keys.size() + " keys, new: " + found.size() + ", gone=" + lost.size()); + + Map newMap = new HashMap<>(found.size()); + + for (K k : found) { + newMap.put(k, callbacks.onNew(k)); + } + + for (K k : lost) { + callbacks.onGone(k, map.get(k)); + } + + map = newMap; } catch (Exception e) { + e.printStackTrace(); return; } } + + public void close() { + future.cancel(true); + } } -- cgit v1.2.3