JAL-2738 copy to spikes/mungo
[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   public PDBFTSPanel(SequenceFetcher seqFetcher)
47   {
48     super();
49     pageLimit = PDBFTSRestClient.getInstance().getDefaultResponsePageSize();
50     this.seqFetcher = seqFetcher;
51     this.progressIndicator = (seqFetcher == null) ? null
52             : seqFetcher.getProgressIndicator();
53   }
54
55   @Override
56   public void searchAction(boolean isFreshSearch)
57   {
58     mainFrame.requestFocusInWindow();
59     if (isFreshSearch)
60     {
61       offSet = 0;
62     }
63     new Thread()
64     {
65       @Override
66       public void run()
67       {
68         reset();
69         boolean allowEmptySequence = false;
70         if (getTypedText().length() > 0)
71         {
72           setSearchInProgress(true);
73           long startTime = System.currentTimeMillis();
74
75           String searchTarget = ((FTSDataColumnI) cmb_searchTarget
76                   .getSelectedItem()).getCode();
77           wantedFields = PDBFTSRestClient.getInstance()
78                   .getAllDefaultDisplayedFTSDataColumns();
79           String searchTerm = decodeSearchTerm(getTypedText(),
80                   searchTarget);
81
82           FTSRestRequest request = new FTSRestRequest();
83           request.setAllowEmptySeq(allowEmptySequence);
84           request.setResponseSize(100);
85           request.setFieldToSearchBy("(" + searchTarget + ":");
86           request.setSearchTerm(searchTerm + ")");
87           request.setOffSet(offSet);
88           request.setWantedFields(wantedFields);
89           FTSRestClientI pdbRestCleint = PDBFTSRestClient.getInstance();
90           FTSRestResponse resultList;
91           try
92           {
93             resultList = pdbRestCleint.executeRequest(request);
94           } catch (Exception e)
95           {
96             setErrorMessage(e.getMessage());
97             checkForErrors();
98             return;
99           }
100
101           if (resultList.getSearchSummary() != null
102                   && resultList.getSearchSummary().size() > 0)
103           {
104             getResultTable().setModel(FTSRestResponse.getTableModel(request,
105                     resultList.getSearchSummary()));
106             FTSRestResponse.configureTableColumn(getResultTable(),
107                     wantedFields, tempUserPrefs);
108             getResultTable().setVisible(true);
109           }
110
111           long endTime = System.currentTimeMillis();
112           totalResultSetCount = resultList.getNumberOfItemsFound();
113           resultSetCount = resultList.getSearchSummary() == null ? 0
114                   : resultList.getSearchSummary().size();
115           String result = (resultSetCount > 0)
116                   ? MessageManager.getString("label.results")
117                   : MessageManager.getString("label.result");
118
119           if (isPaginationEnabled() && resultSetCount > 0)
120           {
121             updateSearchFrameTitle(defaultFTSFrameTitle + " - " + result
122                     + " "
123                     + totalNumberformatter.format((Number) (offSet + 1))
124                     + " to "
125                     + totalNumberformatter
126                             .format((Number) (offSet + resultSetCount))
127                     + " of "
128                     + totalNumberformatter
129                             .format((Number) totalResultSetCount)
130                     + " " + " (" + (endTime - startTime) + " milli secs)");
131           }
132           else
133           {
134             updateSearchFrameTitle(defaultFTSFrameTitle + " - "
135                     + resultSetCount + " " + result + " ("
136                     + (endTime - startTime) + " milli secs)");
137           }
138
139           setSearchInProgress(false);
140           refreshPaginatorState();
141           updateSummaryTableSelections();
142         }
143         txt_search.updateCache();
144       }
145     }.start();
146   }
147
148   public static String decodeSearchTerm(String enteredText,
149           String targetField)
150   {
151     String foundSearchTerms = enteredText;
152     StringBuilder foundSearchTermsBuilder = new StringBuilder();
153     if (enteredText.contains(";"))
154     {
155       String[] searchTerms = enteredText.split(";");
156       for (String searchTerm : searchTerms)
157       {
158         if (searchTerm.contains(":"))
159         {
160           foundSearchTermsBuilder.append(targetField).append(":")
161                   .append(searchTerm.split(":")[0]).append(" OR ");
162         }
163         else
164         {
165           foundSearchTermsBuilder.append(targetField).append(":")
166                   .append(searchTerm).append(" OR ");
167         }
168       }
169       int endIndex = foundSearchTermsBuilder.lastIndexOf(" OR ");
170       foundSearchTerms = foundSearchTermsBuilder.toString();
171       if (foundSearchTerms.contains(" OR "))
172       {
173         foundSearchTerms = foundSearchTerms
174                 .substring(targetField.length() + 1, endIndex);
175       }
176     }
177     else if (enteredText.contains(":"))
178     {
179       foundSearchTerms = foundSearchTerms.split(":")[0];
180     }
181     return foundSearchTerms;
182   }
183
184   @Override
185   public void okAction()
186   {
187     // mainFrame.dispose();
188     disableActionButtons();
189     StringBuilder selectedIds = new StringBuilder();
190     HashSet<String> selectedIdsSet = new HashSet<String>();
191     int primaryKeyColIndex = 0;
192     try
193     {
194       primaryKeyColIndex = getFTSRestClient()
195               .getPrimaryKeyColumIndex(wantedFields, false);
196     } catch (Exception e)
197     {
198       e.printStackTrace();
199     }
200     int[] selectedRows = getResultTable().getSelectedRows();
201     String searchTerm = getTypedText();
202     for (int summaryRow : selectedRows)
203     {
204       String idStr = getResultTable()
205               .getValueAt(summaryRow, primaryKeyColIndex).toString();
206       selectedIdsSet.add(getPDBIdwithSpecifiedChain(idStr, searchTerm));
207     }
208
209     for (String idStr : paginatorCart)
210     {
211       selectedIdsSet.add(getPDBIdwithSpecifiedChain(idStr, searchTerm));
212     }
213
214     for (String selectedId : selectedIdsSet)
215     {
216       selectedIds.append(selectedId).append(";");
217     }
218
219     String ids = selectedIds.toString();
220     // System.out.println(">>>>>>>>>>>>>>>> selected Ids: " + ids);
221     seqFetcher.getTextArea().setText(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 }