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