JAL-1648 Implemented in-memory caching for FTS (Uniprot & PDB) and Finder
[jalview.git] / src / jalview / fts / service / uniprot / UniprotFTSPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21
22 package jalview.fts.service.uniprot;
23
24 import jalview.fts.api.FTSDataColumnI;
25 import jalview.fts.api.FTSRestClientI;
26 import jalview.fts.core.FTSRestRequest;
27 import jalview.fts.core.FTSRestResponse;
28 import jalview.fts.core.GFTSPanel;
29 import jalview.gui.SequenceFetcher;
30 import jalview.util.MessageManager;
31
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Map;
35
36 @SuppressWarnings("serial")
37 public class UniprotFTSPanel extends GFTSPanel
38 {
39
40   private static String defaultFTSFrameTitle = MessageManager
41           .getString("label.uniprot_sequence_fetcher");
42
43
44   private static Map<String, Integer> tempUserPrefs = new HashMap<String, Integer>();
45
46   private static final String UNIPROT_FTS_CACHE_KEY = "UNIPROT_FTS_CACHE_KEY";
47
48   public UniprotFTSPanel(SequenceFetcher seqFetcher)
49   {
50     super();
51     pageLimit = UniProtFTSRestClient.getInstance()
52             .getDefaultResponsePageSize();
53     this.seqFetcher = seqFetcher;
54     this.progressIndicator = (seqFetcher == null) ? null : seqFetcher
55             .getProgressIndicator();
56     fireCache();
57   }
58
59   @Override
60   public void searchAction(boolean isFreshSearch)
61   {
62     if (isFreshSearch)
63     {
64       offSet = 0;
65     }
66     new Thread()
67     {
68       @Override
69       public void run()
70       {
71         reset();
72         String searchInput = getTypedText();
73         if (searchInput.length() > 0)
74         {
75           setSearchInProgress(true);
76           long startTime = System.currentTimeMillis();
77
78           String searchTarget = ((FTSDataColumnI) cmb_searchTarget
79                   .getSelectedItem()).getAltCode();
80
81           wantedFields = UniProtFTSRestClient.getInstance()
82                   .getAllDefaultDisplayedFTSDataColumns();
83           String searchTerm = decodeSearchTerm(getTypedText(),
84                   searchTarget);
85
86           FTSRestRequest request = new FTSRestRequest();
87           request.setFieldToSearchBy(searchTarget);
88           request.setSearchTerm(searchTerm);
89           request.setOffSet(offSet);
90           request.setWantedFields(wantedFields);
91           FTSRestClientI uniProtRestCleint = UniProtFTSRestClient
92                   .getInstance();
93           FTSRestResponse resultList;
94           try
95           {
96             resultList = uniProtRestCleint.executeRequest(request);
97           } catch (Exception e)
98           {
99             e.printStackTrace();
100             setErrorMessage(e.getMessage());
101             checkForErrors();
102             return;
103           }
104
105           if (resultList.getSearchSummary() != null
106                   && resultList.getSearchSummary().size() > 0)
107           {
108             getResultTable().setModel(
109                     FTSRestResponse.getTableModel(request,
110                             resultList.getSearchSummary()));
111             FTSRestResponse.configureTableColumn(getResultTable(),
112                     wantedFields, tempUserPrefs);
113             getResultTable().setVisible(true);
114           }
115
116           long endTime = System.currentTimeMillis();
117           totalResultSetCount = resultList.getNumberOfItemsFound();
118           resultSetCount = resultList.getSearchSummary() == null ? 0
119                   : resultList.getSearchSummary().size();
120           String result = (resultSetCount > 0) ? MessageManager
121                   .getString("label.results") : MessageManager
122                   .getString("label.result");
123           if (isPaginationEnabled() && resultSetCount > 0)
124           {
125             updateSearchFrameTitle(defaultFTSFrameTitle
126                     + " - "
127                     + result
128                     + " "
129                     + totalNumberformatter.format((Number) (offSet + 1))
130                     + " to "
131                     + totalNumberformatter
132                             .format((Number) (offSet + resultSetCount))
133                     + " of "
134                     + totalNumberformatter
135                             .format((Number) totalResultSetCount) + " "
136                     + " (" + (endTime - startTime) + " milli secs)");
137           }
138           else
139           {
140             updateSearchFrameTitle(defaultFTSFrameTitle + " - "
141                     + resultSetCount + " " + result + " ("
142                     + (endTime - startTime) + " milli secs)");
143           }
144           setSearchInProgress(false);
145           refreshPaginatorState();
146           updateSummaryTableSelections();
147         }
148         fireCache();
149       }
150     }.start();
151
152   }
153
154   public String decodeSearchTerm(String enteredText, String targetField)
155   {
156     int searchTargetLength = targetField.equalsIgnoreCase("Search All") ? 0
157             : targetField.length() + 1;
158     String searchTarget = targetField.equalsIgnoreCase("Search All") ? ""
159             : targetField + ":";
160     String foundSearchTerms = enteredText;
161     StringBuilder foundSearchTermsBuilder = new StringBuilder();
162     if (enteredText.contains(";"))
163     {
164       String[] searchTerms = enteredText.split(";");
165       for (String searchTerm : searchTerms)
166       {
167         foundSearchTermsBuilder.append(searchTarget).append(searchTerm)
168                 .append(" OR ");
169       }
170       int endIndex = foundSearchTermsBuilder.lastIndexOf(" OR ");
171       foundSearchTerms = foundSearchTermsBuilder.toString();
172       if (foundSearchTerms.contains(" OR "))
173       {
174         foundSearchTerms = foundSearchTerms.substring(searchTargetLength,
175                 endIndex);
176       }
177     }
178     return foundSearchTerms;
179   }
180
181   @Override
182   public boolean isPaginationEnabled()
183   {
184     return true;
185   }
186
187   @Override
188   public void okAction()
189   {
190     disableActionButtons();
191     StringBuilder selectedIds = new StringBuilder();
192     HashSet<String> selectedIdsSet = new HashSet<String>();
193     int primaryKeyColIndex = 0;
194     try
195     {
196       primaryKeyColIndex = getFTSRestClient().getPrimaryKeyColumIndex(
197               wantedFields, false);
198     } catch (Exception e)
199     {
200       e.printStackTrace();
201     }
202     int[] selectedRows = getResultTable().getSelectedRows();
203     for (int summaryRow : selectedRows)
204     {
205       String idStr = getResultTable().getValueAt(summaryRow,
206               primaryKeyColIndex).toString();
207       selectedIdsSet.add(idStr);
208     }
209     selectedIdsSet.addAll(paginatorCart);
210     for (String selectedId : selectedIdsSet)
211     {
212       selectedIds.append(selectedId).append(";");
213     }
214
215     String ids = selectedIds.toString();
216     // System.out.println(">>>>>>>>>>>>>>>> selected Ids: " + ids);
217     seqFetcher.getTextArea().setText(ids);
218     Thread worker = new Thread(seqFetcher);
219     worker.start();
220     delayAndEnableActionButtons();
221   }
222
223   @Override
224   public FTSRestClientI getFTSRestClient()
225   {
226     return UniProtFTSRestClient.getInstance();
227   }
228
229   @Override
230   public String getFTSFrameTitle()
231   {
232     return defaultFTSFrameTitle;
233   }
234
235   @Override
236   public Map<String, Integer> getTempUserPrefs()
237   {
238     return tempUserPrefs;
239   }
240
241   @Override
242   public String getCacheKey()
243   {
244     return UNIPROT_FTS_CACHE_KEY;
245   }
246 }