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