JAL-1648 Implemented in-memory caching for FTS (Uniprot & PDB) and Finder
[jalview.git] / src / jalview / io / cache / AppCache.java
1 package jalview.io.cache;
2
3
4 import java.util.Hashtable;
5 import java.util.LinkedHashSet;
6 import java.util.Set;
7
8 import javax.swing.JComboBox;
9 import javax.swing.JComponent;
10
11 public class AppCache implements AppCacheI
12 {
13   private static AppCache instance = null;
14
15   private Hashtable<String, LinkedHashSet<String>> cacheItems;
16
17   private AppCache()
18   {
19     cacheItems = new Hashtable<String, LinkedHashSet<String>>();
20   }
21
22   @Override
23   public LinkedHashSet<String> getAllCachedItemsFor(String cacheKey)
24   {
25     LinkedHashSet<String> foundCache = cacheItems.get(cacheKey);
26     if (foundCache == null)
27     {
28       foundCache = new LinkedHashSet<String>();
29       cacheItems.put(cacheKey, foundCache);
30     }
31     return foundCache;
32   }
33
34
35   public static AppCache getInstance()
36   {
37     if (instance == null)
38     {
39       instance = new AppCache();
40     }
41     return instance;
42   }
43
44   @Override
45   public void updateCache(Cacheable cacheable)
46   {
47     JComboBox<String> cacheComboBox = cacheable.getCacheComboBox();
48     String cacheKey = cacheable.getCacheKey();
49     JComponent nextFocusableComponent = cacheable.getNextFocusableElement();
50     String userInput = cacheComboBox.getEditor().getItem() == null ? ""
51             : cacheComboBox.getEditor().getItem().toString().trim();
52
53     if (userInput != null && !userInput.isEmpty())
54     {
55       LinkedHashSet<String> foundCache = getAllCachedItemsFor(cacheKey);
56       foundCache.add(userInput);
57       cacheItems.put(cacheKey, foundCache);
58     }
59
60     String lastSearch = userInput;
61     nextFocusableComponent.requestFocusInWindow();
62     if (cacheComboBox.getItemCount() > 0)
63     {
64       cacheComboBox.removeAllItems();
65     }
66
67     Set<String> cacheItems = getAllCachedItemsFor(cacheKey);
68     if (cacheItems != null && !cacheItems.isEmpty())
69     {
70       for (String cacheItem : cacheItems)
71       {
72         cacheComboBox.addItem(cacheItem);
73       }
74     }
75
76     if (!lastSearch.isEmpty())
77     {
78       cacheComboBox.setSelectedItem(lastSearch);
79       cacheComboBox.requestFocus();
80     }
81     else
82     {
83       cacheable.init();
84       cacheComboBox.addItem("");
85       cacheComboBox.setSelectedItem("");
86     }
87   }
88
89 }