JAL-1648 Implemented in-memory caching for FTS (Uniprot & PDB) and Finder
[jalview.git] / src / jalview / io / cache / AppCache.java
diff --git a/src/jalview/io/cache/AppCache.java b/src/jalview/io/cache/AppCache.java
new file mode 100644 (file)
index 0000000..9201341
--- /dev/null
@@ -0,0 +1,89 @@
+package jalview.io.cache;
+
+
+import java.util.Hashtable;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+
+public class AppCache implements AppCacheI
+{
+  private static AppCache instance = null;
+
+  private Hashtable<String, LinkedHashSet<String>> cacheItems;
+
+  private AppCache()
+  {
+    cacheItems = new Hashtable<String, LinkedHashSet<String>>();
+  }
+
+  @Override
+  public LinkedHashSet<String> getAllCachedItemsFor(String cacheKey)
+  {
+    LinkedHashSet<String> foundCache = cacheItems.get(cacheKey);
+    if (foundCache == null)
+    {
+      foundCache = new LinkedHashSet<String>();
+      cacheItems.put(cacheKey, foundCache);
+    }
+    return foundCache;
+  }
+
+
+  public static AppCache getInstance()
+  {
+    if (instance == null)
+    {
+      instance = new AppCache();
+    }
+    return instance;
+  }
+
+  @Override
+  public void updateCache(Cacheable cacheable)
+  {
+    JComboBox<String> cacheComboBox = cacheable.getCacheComboBox();
+    String cacheKey = cacheable.getCacheKey();
+    JComponent nextFocusableComponent = cacheable.getNextFocusableElement();
+    String userInput = cacheComboBox.getEditor().getItem() == null ? ""
+            : cacheComboBox.getEditor().getItem().toString().trim();
+
+    if (userInput != null && !userInput.isEmpty())
+    {
+      LinkedHashSet<String> foundCache = getAllCachedItemsFor(cacheKey);
+      foundCache.add(userInput);
+      cacheItems.put(cacheKey, foundCache);
+    }
+
+    String lastSearch = userInput;
+    nextFocusableComponent.requestFocusInWindow();
+    if (cacheComboBox.getItemCount() > 0)
+    {
+      cacheComboBox.removeAllItems();
+    }
+
+    Set<String> cacheItems = getAllCachedItemsFor(cacheKey);
+    if (cacheItems != null && !cacheItems.isEmpty())
+    {
+      for (String cacheItem : cacheItems)
+      {
+        cacheComboBox.addItem(cacheItem);
+      }
+    }
+
+    if (!lastSearch.isEmpty())
+    {
+      cacheComboBox.setSelectedItem(lastSearch);
+      cacheComboBox.requestFocus();
+    }
+    else
+    {
+      cacheable.init();
+      cacheComboBox.addItem("");
+      cacheComboBox.setSelectedItem("");
+    }
+  }
+
+}