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