JAL-1753 statusPanel added (for ProgressBar); 'Fit to Window' menu
[jalview.git] / src / jalview / gui / PDBSearchPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.gui;
23
24 import jalview.jbgui.GPDBSearchPanel;
25 import jalview.jbgui.PDBDocFieldPreferences;
26 import jalview.util.MessageManager;
27 import jalview.ws.dbsources.PDBRestClient;
28 import jalview.ws.dbsources.PDBRestClient.PDBDocField;
29 import jalview.ws.uimodel.PDBRestRequest;
30 import jalview.ws.uimodel.PDBRestResponse;
31
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.Comparator;
36 import java.util.HashSet;
37 import java.util.List;
38
39 import javax.swing.table.DefaultTableModel;
40
41 @SuppressWarnings("serial")
42 public class PDBSearchPanel extends GPDBSearchPanel
43 {
44   private SequenceFetcher seqFetcher;
45
46   private IProgressIndicator progressIdicator;
47
48   private Collection<PDBDocField> wantedFields;
49
50   public PDBSearchPanel(SequenceFetcher seqFetcher)
51   {
52     this.seqFetcher = seqFetcher;
53     this.progressIdicator = (seqFetcher == null) ? null : seqFetcher
54             .getProgressIndicator();
55   }
56
57
58   /**
59    * Action performed when an input is detected on txt_search field.
60    */
61   @Override
62   public void txt_search_ActionPerformed()
63   {
64     errorWarning.setLength(0);
65     lbl_warning.setVisible(false);
66     btn_ok.setEnabled(false);
67     boolean allowEmptySequence = false;
68     mainFrame.setTitle(MessageManager
69             .getString("label.pdb_sequence_getcher"));
70     tbl_summary.setModel(new DefaultTableModel());
71     if (txt_search.getText().trim().length() > 0)
72     {
73       long startTime = System.currentTimeMillis();
74
75       String searchTarget = ((PDBDocField) cmb_searchTarget
76               .getSelectedItem()).getCode();
77
78       wantedFields = PDBDocFieldPreferences
79               .getSearchSummaryFields();
80
81       String searchTerm = decodeSearchTerm(txt_search.getText(),
82               searchTarget);
83
84       PDBRestRequest request = new PDBRestRequest();
85       request.setAllowEmptySeq(allowEmptySequence);
86       request.setResponseSize(100);
87       request.setFieldToSearchBy("(" + searchTarget + ":");
88       request.setSearchTerm(searchTerm + ")");
89       request.setWantedFields(wantedFields);
90       // System.out.println(">>>>>>>>>>>>>> " + request.getQuery());
91       PDBRestClient pdbRestCleint = new PDBRestClient();
92       PDBRestResponse resultList;
93       try
94       {
95         resultList = pdbRestCleint.executeRequest(request);
96       } catch (Exception e)
97       {
98         // System.out.println(">>>>>>>>>>>>>>>" + e.getMessage());
99         // JOptionPane.showMessageDialog(this, e.getMessage(),
100         // "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
101         errorWarning.append(e.getMessage());
102         checkForErrors();
103         return;
104       }
105
106       if (resultList.getSearchSummary() != null)
107       {
108         tbl_summary.setModel(PDBRestResponse.getTableModel(request,
109                 resultList.getSearchSummary()));
110       }
111
112       long endTime = System.currentTimeMillis();
113       int resultSetCount = resultList.getNumberOfItemsFound();
114       String result = (resultSetCount > 1) ? MessageManager
115               .getString("label.results") : MessageManager
116               .getString("label.result");
117       mainFrame.setTitle(frameTitle + " - " + resultSetCount + " " + result
118               + " (" + (endTime - startTime) + " milli secs)");
119     }
120   }
121
122   public static String decodeSearchTerm(String enteredText,
123           String targetField)
124   {
125     String foundSearchTerms = enteredText;
126     StringBuilder foundSearchTermsBuilder = new StringBuilder();
127     if (enteredText.contains(";"))
128     {
129       String[] searchTerms = enteredText.split(";");
130       for (String searchTerm : searchTerms)
131       {
132         if (searchTerm.contains(":"))
133         {
134           foundSearchTermsBuilder.append(targetField).append(":")
135                   .append(searchTerm.split(":")[0]).append(" OR ");
136         }
137         else
138         {
139           foundSearchTermsBuilder.append(targetField).append(":")
140                   .append(searchTerm).append(" OR ");
141         }
142       }
143       int endIndex = foundSearchTermsBuilder.lastIndexOf(" OR ");
144       foundSearchTerms = foundSearchTermsBuilder.toString();
145       if (foundSearchTerms.contains(" OR "))
146       {
147         foundSearchTerms = foundSearchTerms.substring(
148                 targetField.length() + 1, endIndex);
149       }
150     }
151     else if (enteredText.contains(":"))
152     {
153       foundSearchTerms = foundSearchTerms.split(":")[0];
154     }
155     return foundSearchTerms;
156   }
157
158
159   @Override
160   public void btn_ok_ActionPerformed()
161   {
162     loadSelectedPDBSequencesToAlignment();
163   }
164
165   @Override
166   public void btn_back_ActionPerformed()
167   {
168     mainFrame.dispose();
169     new SequenceFetcher(progressIdicator);
170   }
171
172   @Override
173   public void btn_cancel_ActionPerformed()
174   {
175     mainFrame.dispose();
176   }
177
178   public void transferToSequenceFetcher(String ids)
179   {
180     // mainFrame.dispose();
181     seqFetcher.textArea.setText(ids);
182     Thread worker = new Thread(seqFetcher);
183     worker.start();
184   }
185
186   /**
187    * Add the discovered/selected sequences to a target alignment window
188    */
189   public void loadSelectedPDBSequencesToAlignment()
190   {
191     // mainFrame.dispose();
192     StringBuilder selectedIds = new StringBuilder();
193     HashSet<String> selectedIdsSet = new HashSet<String>();
194     int pdbIdCol = PDBRestClient.getPDBIdColumIndex(wantedFields, false);
195     int[] selectedRows = tbl_summary.getSelectedRows();
196     for (int summaryRow : selectedRows)
197     {
198       String pdbIdStr = tbl_summary.getValueAt(summaryRow, pdbIdCol)
199               .toString();
200       String searchTerm = txt_search.getText();
201       selectedIdsSet.add(getPDBIdwithSpecifiedChain(pdbIdStr, searchTerm));
202     }
203
204     for (String selectedId : selectedIdsSet)
205     {
206       selectedIds.append(selectedId).append(";");
207     }
208
209     String ids = selectedIds.toString();
210     // System.out.println(">>>>>>>>>>>>>>>> selected Ids: " + ids);
211     seqFetcher.textArea.setText(ids);
212     Thread worker = new Thread(seqFetcher);
213     worker.start();
214   }
215
216   public static String getPDBIdwithSpecifiedChain(String pdbId,
217           String searchTerm)
218   {
219     String pdbIdWithChainCode = "";
220     if (searchTerm.contains(";"))
221     {
222       String[] foundTerms = searchTerm.split(";");
223       for (String foundTerm : foundTerms)
224       {
225         if (foundTerm.contains(pdbId))
226         {
227           pdbIdWithChainCode = foundTerm;
228         }
229       }
230     }
231     else if (searchTerm.contains(pdbId))
232     {
233       pdbIdWithChainCode = searchTerm;
234     }
235     else
236     {
237       pdbIdWithChainCode = pdbId;
238     }
239     return pdbIdWithChainCode;
240   }
241
242   /**
243    * Populates search target combo-box options
244    */
245   public void populateCmbSearchTargetOptions()
246   {
247     List<PDBDocField> searchableTargets = new ArrayList<PDBDocField>();
248     searchableTargets.add(PDBDocField.PDB_ID);
249     searchableTargets.add(PDBDocField.PFAM_ACCESSION);
250     searchableTargets.add(PDBDocField.MOLECULE_TYPE);
251     searchableTargets.add(PDBDocField.MOLECULE_NAME);
252     searchableTargets.add(PDBDocField.UNIPROT_ACCESSION);
253     searchableTargets.add(PDBDocField.GENE_NAME);
254     searchableTargets.add(PDBDocField.GENUS);
255     searchableTargets.add(PDBDocField.ALL);
256
257     Collections.sort(searchableTargets, new Comparator<PDBDocField>()
258     {
259       @Override
260       public int compare(PDBDocField o1, PDBDocField o2)
261       {
262         return o1.getName().compareTo(o2.getName());
263       }
264     });
265
266     for (PDBDocField searchTarget : searchableTargets)
267     {
268       cmb_searchTarget.addItem(searchTarget);
269     }
270   }
271
272   public void checkForErrors()
273   {
274     lbl_warning.setVisible(false);
275     if (errorWarning.length() > 0)
276     {
277       lbl_warning.setToolTipText(JvSwingUtils.wrapTooltip(true,
278               errorWarning.toString()));
279       lbl_warning.setVisible(true);
280     }
281   }
282 }