JAL-4036 removing the query field code from the dropdown indexes
[jalview.git] / src / jalview / fts / service / threedbeacons / TDBeaconsFTSPanel.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 package jalview.fts.service.threedbeacons;
22
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStreamReader;
26 import java.net.HttpURLConnection;
27 import java.net.MalformedURLException;
28 import java.net.URL;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Map;
32
33 import javax.swing.SwingUtilities;
34
35 import org.json.JSONArray;
36 import org.json.JSONObject;
37
38 import jalview.bin.Console;
39 import jalview.datamodel.AlignmentI;
40 import jalview.fts.api.FTSDataColumnI;
41 import jalview.fts.api.FTSRestClientI;
42 import jalview.fts.core.FTSRestRequest;
43 import jalview.fts.core.FTSRestResponse;
44 import jalview.fts.core.GFTSPanel;
45 import jalview.fts.service.pdb.PDBFTSRestClient;
46 import jalview.gui.SequenceFetcher;
47 import jalview.io.DataSourceType;
48 import jalview.io.FileFormat;
49 import jalview.io.FileFormatI;
50 import jalview.io.FileLoader;
51 import jalview.io.FormatAdapter;
52 import jalview.util.MessageManager;
53
54 @SuppressWarnings("serial")
55 public class TDBeaconsFTSPanel extends GFTSPanel
56 {
57   private static String defaultFTSFrameTitle = MessageManager
58           .getString("label.pdb_sequence_fetcher");
59
60   private static Map<String, Integer> tempUserPrefs = new HashMap<>();
61
62   private static final String THREEDB_FTS_CACHE_KEY = "CACHE.THREEDB_FTS";
63
64   private static final String THREEDB_AUTOSEARCH = "FTS.THREEDB.AUTOSEARCH";
65
66   private static HttpURLConnection connection;
67
68   public TDBeaconsFTSPanel(SequenceFetcher fetcher)
69   {
70     // no ID retrieval option for TD Beacons just now
71     super(null);
72     pageLimit = TDBeaconsFTSRestClient.getInstance()
73             .getDefaultResponsePageSize();
74     this.seqFetcher = fetcher;
75     this.progressIndicator = (fetcher == null) ? null
76             : fetcher.getProgressIndicator();
77   }
78
79   @Override
80   public void searchAction(boolean isFreshSearch)
81   {
82     mainFrame.requestFocusInWindow();
83     if (isFreshSearch)
84     {
85       offSet = 0;
86     }
87     new Thread()
88     {
89       @Override
90       public void run()
91       {
92         reset();
93         boolean allowEmptySequence = false;
94         if (getTypedText().length() > 0)
95         {
96           setSearchInProgress(true);
97           long startTime = System.currentTimeMillis();
98
99           String searchTarget = ((FTSDataColumnI) cmb_searchTarget
100                   .getSelectedItem()).getCode();
101           wantedFields = TDBeaconsFTSRestClient.getInstance()
102                   .getAllDefaultDisplayedFTSDataColumns();
103           String searchTerm = getTypedText(); // to add : decodeSearchTerm
104
105           FTSRestRequest request = new FTSRestRequest();
106           request.setAllowEmptySeq(allowEmptySequence);
107           request.setResponseSize(100);
108           // expect it to be uniprot accesssion
109           request.setSearchTerm(searchTerm + ".json");
110           request.setOffSet(offSet);
111           request.setWantedFields(wantedFields);
112           FTSRestClientI tdbRestClient = TDBeaconsFTSRestClient
113                   .getInstance();
114           FTSRestResponse resultList;
115           try
116           {
117             resultList = tdbRestClient.executeRequest(request);
118           } catch (Exception e)
119           {
120             setErrorMessage(e.getMessage());
121             checkForErrors();
122             setSearchInProgress(false);
123             return;
124           }
125
126           if (resultList.getSearchSummary() != null
127                   && resultList.getSearchSummary().size() > 0)
128           {
129             getResultTable().setModel(FTSRestResponse.getTableModel(request,
130                     resultList.getSearchSummary()));
131             FTSRestResponse.configureTableColumn(getResultTable(),
132                     wantedFields, tempUserPrefs);
133             getResultTable().setVisible(true);
134           }
135
136           long endTime = System.currentTimeMillis();
137           totalResultSetCount = resultList.getNumberOfItemsFound();
138           resultSetCount = resultList.getSearchSummary() == null ? 0
139                   : resultList.getSearchSummary().size();
140           String result = (resultSetCount > 0)
141                   ? MessageManager.getString("label.results")
142                   : MessageManager.getString("label.result");
143
144           if (isPaginationEnabled() && resultSetCount > 0)
145           {
146             String f1 = totalNumberformatter
147                     .format(Integer.valueOf(offSet + 1));
148             String f2 = totalNumberformatter
149                     .format(Integer.valueOf(offSet + resultSetCount));
150             String f3 = totalNumberformatter
151                     .format(Integer.valueOf(totalResultSetCount));
152             updateSearchFrameTitle(defaultFTSFrameTitle + " - " + result
153                     + " " + f1 + " to " + f2 + " of " + f3 + " " + " ("
154                     + (endTime - startTime) + " milli secs)");
155           }
156           else
157           {
158             updateSearchFrameTitle(defaultFTSFrameTitle + " - "
159                     + resultSetCount + " " + result + " ("
160                     + (endTime - startTime) + " milli secs)");
161           }
162
163           setSearchInProgress(false);
164           refreshPaginatorState();
165           updateSummaryTableSelections();
166         }
167         txt_search.updateCache();
168       }
169     }.start();
170   }
171
172   @Override
173   public void okAction()
174   {
175     // mainFrame.dispose();
176     disableActionButtons();
177     StringBuilder selectedIds = new StringBuilder();
178     final HashSet<String> selectedIdsSet = new HashSet<>();
179     int primaryKeyColIndex = 0;
180     try
181     {
182       primaryKeyColIndex = getFTSRestClient()
183               .getPrimaryKeyColumIndex(wantedFields, false);
184     } catch (Exception e)
185     {
186       e.printStackTrace();
187     }
188     int[] selectedRows = getResultTable().getSelectedRows();
189     String searchTerm = getTypedText();
190     for (int summaryRow : selectedRows)
191     {
192       String idStr = getResultTable()
193               .getValueAt(summaryRow, primaryKeyColIndex).toString();
194       selectedIdsSet.add(idStr);
195     }
196
197     for (String idStr : paginatorCart)
198     {
199       selectedIdsSet.add(idStr);
200     }
201
202     for (String selectedId : selectedIdsSet)
203     {
204       selectedIds.append(selectedId).append(";");
205     }
206
207     SwingUtilities.invokeLater(new Runnable()
208     {
209       @Override
210       public void run()
211       {
212         AlignmentI allSeqs = null;
213         FormatAdapter fl = new jalview.io.FormatAdapter();
214         for (String tdbURL : selectedIdsSet)
215         {
216           try
217           {
218             // retrieve the structure via its URL
219             AlignmentI tdbAl = fl.readFile(tdbURL, DataSourceType.URL,
220                     FileFormat.MMCif);
221
222             // TODO: pad structure according to its Uniprot Start so all line up
223             // w.r.t. the Uniprot reference sequence
224             // TODO: give the structure a sensible name (not the giant URL *:o)
225             // )
226             if (tdbAl != null)
227             {
228               if (allSeqs != null)
229               {
230                 allSeqs.append(tdbAl);
231               }
232               else
233               {
234                 allSeqs = tdbAl;
235               }
236             }
237           } catch (Exception x)
238           {
239             Console.warn("Couldn't retrieve 3d-beacons model for uniprot id"
240                     + searchTerm + " : " + tdbURL, x);
241           }
242         }
243         seqFetcher.parseResult(allSeqs,
244                 "3D-Beacons models for " + searchTerm, FileFormat.MMCif,
245                 null);
246
247       }
248     });
249     delayAndEnableActionButtons();
250   }
251
252   @Override
253   public FTSRestClientI getFTSRestClient()
254   {
255     return TDBeaconsFTSRestClient.getInstance();
256   }
257
258   @Override
259   public String getFTSFrameTitle()
260   {
261     return defaultFTSFrameTitle;
262   }
263
264   @Override
265   public boolean isPaginationEnabled()
266   {
267     return true;
268   }
269
270   @Override
271   public Map<String, Integer> getTempUserPrefs()
272   {
273     return tempUserPrefs;
274   }
275
276   @Override
277   public String getCacheKey()
278   {
279     return THREEDB_FTS_CACHE_KEY;
280   }
281
282   @Override
283   public String getAutosearchPreference()
284   {
285     return THREEDB_AUTOSEARCH;
286   }
287
288   @Override
289   protected void showHelp()
290   {
291     System.out.println("No help implemented yet.");
292
293   }
294
295   public static String decodeSearchTerm(String enteredText)
296   {
297     // no multiple query support yet
298     return enteredText;
299   }
300 }