JAL-3144 SequenceFetcher without JDatabaseTree
[jalview.git] / src / jalview / fts / service / pdb / PDBFTSPanel.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.pdb;
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 PDBFTSPanel extends GFTSPanel
38 {
39   private static String defaultFTSFrameTitle = MessageManager
40           .getString("label.pdb_sequence_fetcher");
41
42   private static Map<String, Integer> tempUserPrefs = new HashMap<String, Integer>();
43
44   private static final String PDB_FTS_CACHE_KEY = "CACHE.PDB_FTS";
45
46   private static final String PDB_AUTOSEARCH = "FTS.PDB.AUTOSEARCH";
47
48   public PDBFTSPanel(SequenceFetcher fetcher)
49   {
50     super(fetcher);
51     pageLimit = PDBFTSRestClient.getInstance().getDefaultResponsePageSize();
52     this.seqFetcher = fetcher;
53     this.progressIndicator = (fetcher == null) ? null
54             : fetcher.getProgressIndicator();
55   }
56
57   @Override
58   public void searchAction(boolean isFreshSearch)
59   {
60     mainFrame.requestFocusInWindow();
61     if (isFreshSearch)
62     {
63       offSet = 0;
64     }
65     new Thread()
66     {
67       @Override
68       public void run()
69       {
70         reset();
71         boolean allowEmptySequence = false;
72         if (getTypedText().length() > 0)
73         {
74           setSearchInProgress(true);
75           long startTime = System.currentTimeMillis();
76
77           String searchTarget = ((FTSDataColumnI) cmb_searchTarget
78                   .getSelectedItem()).getCode();
79           wantedFields = PDBFTSRestClient.getInstance()
80                   .getAllDefaultDisplayedFTSDataColumns();
81           String searchTerm = decodeSearchTerm(getTypedText(),
82                   searchTarget);
83
84           FTSRestRequest request = new FTSRestRequest();
85           request.setAllowEmptySeq(allowEmptySequence);
86           request.setResponseSize(100);
87           request.setFieldToSearchBy("(" + searchTarget + ":");
88           request.setSearchTerm(searchTerm + ")");
89           request.setOffSet(offSet);
90           request.setWantedFields(wantedFields);
91           FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
92           FTSRestResponse resultList;
93           try
94           {
95             resultList = pdbRestClient.executeRequest(request);
96           } catch (Exception e)
97           {
98             setErrorMessage(e.getMessage());
99             checkForErrors();
100             setSearchInProgress(false);
101             return;
102           }
103
104           if (resultList.getSearchSummary() != null
105                   && resultList.getSearchSummary().size() > 0)
106           {
107             getResultTable().setModel(FTSRestResponse.getTableModel(request,
108                     resultList.getSearchSummary()));
109             FTSRestResponse.configureTableColumn(getResultTable(),
110                     wantedFields, tempUserPrefs);
111             getResultTable().setVisible(true);
112           }
113
114           long endTime = System.currentTimeMillis();
115           totalResultSetCount = resultList.getNumberOfItemsFound();
116           resultSetCount = resultList.getSearchSummary() == null ? 0
117                   : resultList.getSearchSummary().size();
118           String result = (resultSetCount > 0)
119                   ? MessageManager.getString("label.results")
120                   : MessageManager.getString("label.result");
121
122           if (isPaginationEnabled() && resultSetCount > 0)
123           {
124             String f1 = totalNumberformatter.format(Integer.valueOf(offSet + 1));
125             String f2 = totalNumberformatter
126                     .format(Integer.valueOf(offSet + resultSetCount));
127             String f3 = totalNumberformatter
128                     .format(Integer.valueOf(totalResultSetCount));
129             updateSearchFrameTitle(defaultFTSFrameTitle + " - " + result
130                     + " " + f1 + " to " + f2 + " of " + f3 + " " + " ("
131                     + (endTime - startTime) + " milli secs)");
132           }
133           else
134           {
135             updateSearchFrameTitle(defaultFTSFrameTitle + " - "
136                     + resultSetCount + " " + result + " ("
137                     + (endTime - startTime) + " milli secs)");
138           }
139
140           setSearchInProgress(false);
141           refreshPaginatorState();
142           updateSummaryTableSelections();
143         }
144         txt_search.updateCache();
145       }
146     }.start();
147   }
148
149   public static String decodeSearchTerm(String enteredText,
150           String targetField)
151   {
152     String foundSearchTerms = enteredText;
153     StringBuilder foundSearchTermsBuilder = new StringBuilder();
154     if (enteredText.contains(";"))
155     {
156       String[] searchTerms = enteredText.split(";");
157       for (String searchTerm : searchTerms)
158       {
159         if (searchTerm.contains(":"))
160         {
161           foundSearchTermsBuilder.append(targetField).append(":")
162                   .append(searchTerm.split(":")[0]).append(" OR ");
163         }
164         else
165         {
166           foundSearchTermsBuilder.append(targetField).append(":")
167                   .append(searchTerm).append(" OR ");
168         }
169       }
170       int endIndex = foundSearchTermsBuilder.lastIndexOf(" OR ");
171       foundSearchTerms = foundSearchTermsBuilder.toString();
172       if (foundSearchTerms.contains(" OR "))
173       {
174         foundSearchTerms = foundSearchTerms
175                 .substring(targetField.length() + 1, endIndex);
176       }
177     }
178     else if (enteredText.contains(":"))
179     {
180       foundSearchTerms = foundSearchTerms.split(":")[0];
181     }
182     return foundSearchTerms;
183   }
184
185   @Override
186   public void okAction()
187   {
188     // mainFrame.dispose();
189     disableActionButtons();
190     StringBuilder selectedIds = new StringBuilder();
191     HashSet<String> selectedIdsSet = new HashSet<String>();
192     int primaryKeyColIndex = 0;
193     try
194     {
195       primaryKeyColIndex = getFTSRestClient()
196               .getPrimaryKeyColumIndex(wantedFields, false);
197     } catch (Exception e)
198     {
199       e.printStackTrace();
200     }
201     int[] selectedRows = getResultTable().getSelectedRows();
202     String searchTerm = getTypedText();
203     for (int summaryRow : selectedRows)
204     {
205       String idStr = getResultTable()
206               .getValueAt(summaryRow, primaryKeyColIndex).toString();
207       selectedIdsSet.add(getPDBIdwithSpecifiedChain(idStr, searchTerm));
208     }
209
210     for (String idStr : paginatorCart)
211     {
212       selectedIdsSet.add(getPDBIdwithSpecifiedChain(idStr, searchTerm));
213     }
214
215     for (String selectedId : selectedIdsSet)
216     {
217       selectedIds.append(selectedId).append(";");
218     }
219
220     String ids = selectedIds.toString();
221     seqFetcher.setQuery(ids);
222     Thread worker = new Thread(seqFetcher);
223     worker.start();
224     delayAndEnableActionButtons();
225   }
226
227   public static String getPDBIdwithSpecifiedChain(String pdbId,
228           String searchTerm)
229   {
230     String pdbIdWithChainCode = "";
231     if (searchTerm.contains(";"))
232     {
233       String[] foundTerms = searchTerm.split(";");
234       for (String foundTerm : foundTerms)
235       {
236         if (foundTerm.contains(pdbId))
237         {
238           pdbIdWithChainCode = foundTerm;
239         }
240       }
241     }
242     else if (searchTerm.contains(pdbId))
243     {
244       pdbIdWithChainCode = searchTerm;
245     }
246     else
247     {
248       pdbIdWithChainCode = pdbId;
249     }
250     return pdbIdWithChainCode;
251   }
252
253   @Override
254   public FTSRestClientI getFTSRestClient()
255   {
256     return PDBFTSRestClient.getInstance();
257   }
258
259   @Override
260   public String getFTSFrameTitle()
261   {
262     return defaultFTSFrameTitle;
263   }
264
265   @Override
266   public boolean isPaginationEnabled()
267   {
268     return true;
269   }
270
271   @Override
272   public Map<String, Integer> getTempUserPrefs()
273   {
274     return tempUserPrefs;
275   }
276
277   @Override
278   public String getCacheKey()
279   {
280     return PDB_FTS_CACHE_KEY;
281   }
282
283   @Override
284   public String getAutosearchPreference()
285   {
286     return PDB_AUTOSEARCH;
287   }
288 }