JAL-1919, JAL-1960 fix to disable refetching dbrefs when viewing structures
[jalview.git] / src / jalview / gui / StructureChooser.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.gui;
23
24 import jalview.bin.Jalview;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.api.FTSData;
30 import jalview.fts.api.FTSDataColumnI;
31 import jalview.fts.api.FTSRestClientI;
32 import jalview.fts.core.FTSRestRequest;
33 import jalview.fts.core.FTSRestResponse;
34 import jalview.fts.service.pdb.PDBFTSRestClient;
35 import jalview.jbgui.GStructureChooser;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.MessageManager;
38 import jalview.ws.DBRefFetcher;
39 import jalview.ws.sifts.SiftsSettings;
40
41 import java.awt.event.ItemEvent;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.HashSet;
45 import java.util.LinkedHashSet;
46 import java.util.List;
47 import java.util.Objects;
48 import java.util.Vector;
49
50 import javax.swing.JCheckBox;
51 import javax.swing.JComboBox;
52 import javax.swing.JLabel;
53 import javax.swing.JOptionPane;
54 import javax.swing.table.AbstractTableModel;
55
56 /**
57  * Provides the behaviors for the Structure chooser Panel
58  * 
59  * @author tcnofoegbu
60  *
61  */
62 @SuppressWarnings("serial")
63 public class StructureChooser extends GStructureChooser implements
64         IProgressIndicator
65 {
66   private boolean structuresDiscovered = false;
67
68   private SequenceI selectedSequence;
69
70   private SequenceI[] selectedSequences;
71
72   private IProgressIndicator progressIndicator;
73
74   private Collection<FTSData> discoveredStructuresSet;
75
76   private FTSRestRequest lastPdbRequest;
77
78   private FTSRestClientI pdbRestCleint;
79
80   private String selectedPdbFileName;
81
82   private boolean isValidPBDEntry;
83
84   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
85           AlignmentPanel ap)
86   {
87     this.ap = ap;
88     this.selectedSequence = selectedSeq;
89     this.selectedSequences = selectedSeqs;
90     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
91     init();
92   }
93
94   /**
95    * Initializes parameters used by the Structure Chooser Panel
96    */
97   public void init()
98   {
99     if (!Jalview.isHeadlessMode())
100     {
101       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
102     }
103
104     Thread discoverPDBStructuresThread = new Thread(new Runnable()
105     {
106       @Override
107       public void run()
108       {
109         long startTime = System.currentTimeMillis();
110         updateProgressIndicator(MessageManager
111                 .getString("status.loading_cached_pdb_entries"), startTime);
112         loadLocalCachedPDBEntries();
113         updateProgressIndicator(null, startTime);
114         updateProgressIndicator(MessageManager
115                 .getString("status.searching_for_pdb_structures"),
116                 startTime);
117         fetchStructuresMetaData();
118         populateFilterComboBox();
119         updateProgressIndicator(null, startTime);
120         mainFrame.setVisible(true);
121         updateCurrentView();
122       }
123     });
124     discoverPDBStructuresThread.start();
125   }
126
127   /**
128    * Updates the progress indicator with the specified message
129    * 
130    * @param message
131    *          displayed message for the operation
132    * @param id
133    *          unique handle for this indicator
134    */
135   public void updateProgressIndicator(String message, long id)
136   {
137     if (progressIndicator != null)
138     {
139       progressIndicator.setProgressBar(message, id);
140     }
141   }
142
143   /**
144    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
145    * selection group
146    */
147   public void fetchStructuresMetaData()
148   {
149     long startTime = System.currentTimeMillis();
150     pdbRestCleint = PDBFTSRestClient.getInstance();
151     Collection<FTSDataColumnI> wantedFields = pdbRestCleint
152             .getAllDefaulDisplayedDataColumns();
153
154     discoveredStructuresSet = new LinkedHashSet<FTSData>();
155     HashSet<String> errors = new HashSet<String>();
156     for (SequenceI seq : selectedSequences)
157     {
158       FTSRestRequest pdbRequest = new FTSRestRequest();
159       pdbRequest.setAllowEmptySeq(false);
160       pdbRequest.setResponseSize(500);
161       pdbRequest.setFieldToSearchBy("(");
162       pdbRequest.setWantedFields(wantedFields);
163       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
164       pdbRequest.setAssociatedSequence(seq);
165       FTSRestResponse resultList;
166       try
167       {
168         resultList = pdbRestCleint.executeRequest(pdbRequest);
169       } catch (Exception e)
170       {
171         e.printStackTrace();
172         errors.add(e.getMessage());
173         continue;
174       }
175       lastPdbRequest = pdbRequest;
176       if (resultList.getSearchSummary() != null
177               && !resultList.getSearchSummary().isEmpty())
178       {
179         discoveredStructuresSet.addAll(resultList.getSearchSummary());
180       }
181     }
182
183     int noOfStructuresFound = 0;
184     String totalTime = (System.currentTimeMillis() - startTime)
185             + " milli secs";
186     if (discoveredStructuresSet != null
187             && !discoveredStructuresSet.isEmpty())
188     {
189       tbl_summary.setModel(FTSRestResponse.getTableModel(lastPdbRequest,
190               discoveredStructuresSet));
191       structuresDiscovered = true;
192       noOfStructuresFound = discoveredStructuresSet.size();
193       mainFrame.setTitle(MessageManager.formatMessage(
194               "label.structure_chooser_no_of_structures",
195               noOfStructuresFound, totalTime));
196     }
197     else
198     {
199       mainFrame.setTitle(MessageManager
200               .getString("label.structure_chooser_manual_association"));
201       if (errors.size() > 0)
202       {
203         StringBuilder errorMsg = new StringBuilder();
204         for (String error : errors)
205         {
206           errorMsg.append(error).append("\n");
207         }
208         JOptionPane.showMessageDialog(this, errorMsg.toString(),
209                 MessageManager.getString("label.pdb_web-service_error"),
210                 JOptionPane.ERROR_MESSAGE);
211       }
212     }
213   }
214
215   public void loadLocalCachedPDBEntries()
216   {
217     ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
218     for (SequenceI seq : selectedSequences)
219     {
220       if (seq.getDatasetSequence() != null
221               && seq.getDatasetSequence().getAllPDBEntries() != null)
222       {
223         for (PDBEntry pdbEntry : seq.getDatasetSequence()
224                 .getAllPDBEntries())
225         {
226           if (pdbEntry.getFile() != null)
227           {
228             entries.add(new CachedPDB(seq, pdbEntry));
229           }
230         }
231       }
232     }
233
234     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
235     tbl_local_pdb.setModel(tableModelx);
236   }
237
238   /**
239    * Builds a query string for a given sequences using its DBRef entries
240    * 
241    * @param seq
242    *          the sequences to build a query for
243    * @return the built query string
244    */
245
246   public static String buildQuery(SequenceI seq)
247   {
248     boolean isPDBRefsFound = false;
249     boolean isUniProtRefsFound = false;
250     StringBuilder queryBuilder = new StringBuilder();
251     HashSet<String> seqRefs = new LinkedHashSet<String>();
252
253     if (seq.getAllPDBEntries() != null)
254     {
255       for (PDBEntry entry : seq.getAllPDBEntries())
256       {
257         if (isValidSeqName(entry.getId()))
258         {
259           queryBuilder.append("pdb_id")
260                   .append(":")
261 .append(entry.getId().toLowerCase())
262                   .append(" OR ");
263           isPDBRefsFound = true;
264           // seqRefs.add(entry.getId());
265         }
266       }
267     }
268
269     if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
270     {
271       for (DBRefEntry dbRef : seq.getDBRefs())
272       {
273         if (isValidSeqName(getDBRefId(dbRef)))
274         {
275           if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
276           {
277             queryBuilder
278 .append("uniprot_accession").append(":")
279                     .append(getDBRefId(dbRef))
280                     .append(" OR ");
281             queryBuilder
282 .append("uniprot_id")
283                     .append(":")
284                     .append(getDBRefId(dbRef)).append(" OR ");
285             isUniProtRefsFound = true;
286           }
287           else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
288           {
289
290             queryBuilder.append("pdb_id")
291                     .append(":").append(getDBRefId(dbRef).toLowerCase())
292                     .append(" OR ");
293             isPDBRefsFound = true;
294           }
295           else
296           {
297             seqRefs.add(getDBRefId(dbRef));
298           }
299         }
300       }
301     }
302
303     if (!isPDBRefsFound && !isUniProtRefsFound)
304     {
305       String seqName = seq.getName();
306       seqName = sanitizeSeqName(seqName);
307       String[] names = seqName.toLowerCase().split("\\|");
308       for (String name : names)
309       {
310         // System.out.println("Found name : " + name);
311         name.trim();
312         if (isValidSeqName(name))
313         {
314           seqRefs.add(name);
315         }
316       }
317
318       for (String seqRef : seqRefs)
319       {
320         queryBuilder.append("text:").append(seqRef).append(" OR ");
321       }
322     }
323
324     int endIndex = queryBuilder.lastIndexOf(" OR ");
325     if (queryBuilder.toString().length() < 6)
326     {
327       return null;
328     }
329     String query = queryBuilder.toString().substring(0, endIndex);
330     return query;
331   }
332
333   /**
334    * Remove the following special characters from input string +, -, &, !, (, ),
335    * {, }, [, ], ^, ", ~, *, ?, :, \
336    * 
337    * @param seqName
338    * @return
339    */
340   private static String sanitizeSeqName(String seqName)
341   {
342     Objects.requireNonNull(seqName);
343     return seqName.replaceAll("\\[\\d*\\]", "")
344             .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
345   }
346
347
348   /**
349    * Ensures sequence ref names are not less than 3 characters and does not
350    * contain a database name
351    * 
352    * @param seqName
353    * @return
354    */
355   public static boolean isValidSeqName(String seqName)
356   {
357     // System.out.println("seqName : " + seqName);
358     String ignoreList = "pdb,uniprot,swiss-prot";
359     if (seqName.length() < 3)
360     {
361       return false;
362     }
363     if (seqName.contains(":"))
364     {
365       return false;
366     }
367     seqName = seqName.toLowerCase();
368     for (String ignoredEntry : ignoreList.split(","))
369     {
370       if (seqName.contains(ignoredEntry))
371       {
372         return false;
373       }
374     }
375     return true;
376   }
377
378   public static String getDBRefId(DBRefEntry dbRef)
379   {
380     String ref = dbRef.getAccessionId().replaceAll("GO:", "");
381     return ref;
382   }
383
384   /**
385    * Filters a given list of discovered structures based on supplied argument
386    * 
387    * @param fieldToFilterBy
388    *          the field to filter by
389    */
390   public void filterResultSet(final String fieldToFilterBy)
391   {
392     Thread filterThread = new Thread(new Runnable()
393     {
394       @Override
395       public void run()
396       {
397         long startTime = System.currentTimeMillis();
398         pdbRestCleint = PDBFTSRestClient.getInstance();
399         lbl_loading.setVisible(true);
400         Collection<FTSDataColumnI> wantedFields = pdbRestCleint
401                 .getAllDefaulDisplayedDataColumns();
402         Collection<FTSData> filteredResponse = new HashSet<FTSData>();
403         HashSet<String> errors = new HashSet<String>();
404
405         for (SequenceI seq : selectedSequences)
406         {
407           FTSRestRequest pdbRequest = new FTSRestRequest();
408           if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
409           {
410             System.out.println(">>>>>> Filtering with uniprot coverate");
411             pdbRequest.setAllowEmptySeq(false);
412             pdbRequest.setResponseSize(1);
413             pdbRequest.setFieldToSearchBy("(");
414             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
415             pdbRequest.setWantedFields(wantedFields);
416             pdbRequest.setAssociatedSequence(seq);
417             pdbRequest.setFacet(true);
418             pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
419             pdbRequest.setFacetPivotMinCount(1);
420           }
421           else
422           {
423             pdbRequest.setAllowEmptySeq(false);
424             pdbRequest.setResponseSize(1);
425             pdbRequest.setFieldToSearchBy("(");
426             pdbRequest.setFieldToSortBy(fieldToFilterBy,
427                     !chk_invertFilter.isSelected());
428             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
429             pdbRequest.setWantedFields(wantedFields);
430             pdbRequest.setAssociatedSequence(seq);
431           }
432           FTSRestResponse resultList;
433           try
434           {
435             resultList = pdbRestCleint.executeRequest(pdbRequest);
436           } catch (Exception e)
437           {
438             e.printStackTrace();
439             errors.add(e.getMessage());
440             continue;
441           }
442           lastPdbRequest = pdbRequest;
443           if (resultList.getSearchSummary() != null
444                   && !resultList.getSearchSummary().isEmpty())
445           {
446             filteredResponse.addAll(resultList.getSearchSummary());
447           }
448         }
449
450         String totalTime = (System.currentTimeMillis() - startTime)
451                 + " milli secs";
452         if (!filteredResponse.isEmpty())
453         {
454           final int filterResponseCount = filteredResponse.size();
455           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<FTSData>();
456           reorderedStructuresSet.addAll(filteredResponse);
457           reorderedStructuresSet.addAll(discoveredStructuresSet);
458           tbl_summary.setModel(FTSRestResponse.getTableModel(
459                   lastPdbRequest, reorderedStructuresSet));
460
461           FTSRestResponse.configureTableColumn(tbl_summary, wantedFields);
462           tbl_summary.getColumn("Ref Sequence").setPreferredWidth(120);
463           tbl_summary.getColumn("Ref Sequence").setMinWidth(100);
464           tbl_summary.getColumn("Ref Sequence").setMaxWidth(200);
465           // Update table selection model here
466           tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
467           mainFrame.setTitle(MessageManager.formatMessage(
468                   "label.structure_chooser_filter_time", totalTime));
469         }
470         else
471         {
472           mainFrame.setTitle(MessageManager.formatMessage(
473                   "label.structure_chooser_filter_time", totalTime));
474           if (errors.size() > 0)
475           {
476             StringBuilder errorMsg = new StringBuilder();
477             for (String error : errors)
478             {
479               errorMsg.append(error).append("\n");
480             }
481             JOptionPane.showMessageDialog(
482                     null,
483                     errorMsg.toString(),
484                     MessageManager.getString("label.pdb_web-service_error"),
485                     JOptionPane.ERROR_MESSAGE);
486           }
487         }
488
489         lbl_loading.setVisible(false);
490
491         validateSelections();
492       }
493     });
494     filterThread.start();
495   }
496
497   /**
498    * Handles action event for btn_pdbFromFile
499    */
500   @Override
501   public void pdbFromFile_actionPerformed()
502   {
503     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
504             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
505     chooser.setFileView(new jalview.io.JalviewFileView());
506     chooser.setDialogTitle(MessageManager.formatMessage(
507             "label.select_pdb_file_for",
508             selectedSequence.getDisplayId(false)));
509     chooser.setToolTipText(MessageManager.formatMessage(
510             "label.load_pdb_file_associate_with_sequence",
511             selectedSequence.getDisplayId(false)));
512
513     int value = chooser.showOpenDialog(null);
514     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
515     {
516       selectedPdbFileName = chooser.getSelectedFile().getPath();
517       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
518       validateSelections();
519     }
520   }
521
522   /**
523    * Populates the filter combo-box options dynamically depending on discovered
524    * structures
525    */
526   @Override
527   protected void populateFilterComboBox()
528   {
529     if (isStructuresDiscovered())
530     {
531       cmb_filterOption.addItem(new FilterOption("Best Quality",
532               "overall_quality", VIEWS_FILTER));
533       cmb_filterOption.addItem(new FilterOption("Most UniProt Coverage",
534               "uniprot_coverage", VIEWS_FILTER));
535       cmb_filterOption.addItem(new FilterOption("Best Resolution",
536               "resolution", VIEWS_FILTER));
537       cmb_filterOption.addItem(new FilterOption("Most Protein Chain",
538               "number_of_protein_chains", VIEWS_FILTER));
539       cmb_filterOption.addItem(new FilterOption("Most Bound Molecules",
540               "number_of_bound_molecules", VIEWS_FILTER));
541       cmb_filterOption.addItem(new FilterOption("Most Polymer Residues",
542               "number_of_polymer_residues", VIEWS_FILTER));
543     }
544     cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
545             VIEWS_ENTER_ID));
546     cmb_filterOption.addItem(new FilterOption("From File", "-",
547             VIEWS_FROM_FILE));
548     cmb_filterOption.addItem(new FilterOption("Cached PDB Entries", "-",
549             VIEWS_LOCAL_PDB));
550   }
551
552   /**
553    * Updates the displayed view based on the selected filter option
554    */
555   @Override
556   protected void updateCurrentView()
557   {
558     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
559             .getSelectedItem());
560     layout_switchableViews.show(pnl_switchableViews,
561             selectedFilterOpt.getView());
562     String filterTitle = mainFrame.getTitle();
563     mainFrame.setTitle(frameTitle);
564     chk_invertFilter.setVisible(false);
565     if (selectedFilterOpt.getView() == VIEWS_FILTER)
566     {
567       mainFrame.setTitle(filterTitle);
568       chk_invertFilter.setVisible(true);
569       filterResultSet(selectedFilterOpt.getValue());
570     }
571     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
572             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
573     {
574       mainFrame.setTitle(MessageManager
575               .getString("label.structure_chooser_manual_association"));
576       idInputAssSeqPanel.loadCmbAssSeq();
577       fileChooserAssSeqPanel.loadCmbAssSeq();
578     }
579     validateSelections();
580   }
581
582   /**
583    * Validates user selection and activates the view button if all parameters
584    * are correct
585    */
586   @Override
587   public void validateSelections()
588   {
589     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
590             .getSelectedItem());
591     btn_view.setEnabled(false);
592     String currentView = selectedFilterOpt.getView();
593     if (currentView == VIEWS_FILTER)
594     {
595       if (tbl_summary.getSelectedRows().length > 0)
596       {
597         btn_view.setEnabled(true);
598       }
599     }
600     else if (currentView == VIEWS_LOCAL_PDB)
601     {
602       if (tbl_local_pdb.getSelectedRows().length > 0)
603       {
604         btn_view.setEnabled(true);
605       }
606     }
607     else if (currentView == VIEWS_ENTER_ID)
608     {
609       validateAssociationEnterPdb();
610     }
611     else if (currentView == VIEWS_FROM_FILE)
612     {
613       validateAssociationFromFile();
614     }
615   }
616
617   /**
618    * Validates inputs from the Manual PDB entry panel
619    */
620   public void validateAssociationEnterPdb()
621   {
622     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
623             .getCmb_assSeq().getSelectedItem();
624     lbl_pdbManualFetchStatus.setIcon(errorImage);
625     lbl_pdbManualFetchStatus.setToolTipText("");
626     if (txt_search.getText().length() > 0)
627     {
628       lbl_pdbManualFetchStatus
629               .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
630                       .formatMessage("info.no_pdb_entry_found_for",
631                               txt_search.getText())));
632     }
633
634     if (errorWarning.length() > 0)
635     {
636       lbl_pdbManualFetchStatus.setIcon(warningImage);
637       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
638               true, errorWarning.toString()));
639     }
640
641     if (selectedSequences.length == 1
642             || !assSeqOpt.getName().equalsIgnoreCase(
643                     "-Select Associated Seq-"))
644     {
645       txt_search.setEnabled(true);
646       if (isValidPBDEntry)
647       {
648         btn_view.setEnabled(true);
649         lbl_pdbManualFetchStatus.setToolTipText("");
650         lbl_pdbManualFetchStatus.setIcon(goodImage);
651       }
652     }
653     else
654     {
655       txt_search.setEnabled(false);
656       lbl_pdbManualFetchStatus.setIcon(errorImage);
657     }
658   }
659
660   /**
661    * Validates inputs for the manual PDB file selection options
662    */
663   public void validateAssociationFromFile()
664   {
665     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
666             .getCmb_assSeq().getSelectedItem();
667     lbl_fromFileStatus.setIcon(errorImage);
668     if (selectedSequences.length == 1
669             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
670                     "-Select Associated Seq-")))
671     {
672       btn_pdbFromFile.setEnabled(true);
673       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
674       {
675         btn_view.setEnabled(true);
676         lbl_fromFileStatus.setIcon(goodImage);
677       }
678     }
679     else
680     {
681       btn_pdbFromFile.setEnabled(false);
682       lbl_fromFileStatus.setIcon(errorImage);
683     }
684   }
685
686   @Override
687   public void cmbAssSeqStateChanged()
688   {
689     validateSelections();
690   }
691
692   /**
693    * Handles the state change event for the 'filter' combo-box and 'invert'
694    * check-box
695    */
696   @Override
697   protected void stateChanged(ItemEvent e)
698   {
699     if (e.getSource() instanceof JCheckBox)
700     {
701       updateCurrentView();
702     }
703     else
704     {
705       if (e.getStateChange() == ItemEvent.SELECTED)
706       {
707         updateCurrentView();
708       }
709     }
710
711   }
712
713   /**
714    * Handles action event for btn_ok
715    */
716   @Override
717   public void ok_ActionPerformed()
718   {
719     final long progressSessionId = System.currentTimeMillis();
720     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
721     ssm.setProgressIndicator(this);
722     ssm.setProgressSessionId(progressSessionId);
723     new Thread(new Runnable()
724     {
725       @Override
726       public void run()
727       {
728     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
729             .getSelectedItem());
730     String currentView = selectedFilterOpt.getView();
731     if (currentView == VIEWS_FILTER)
732     {
733           int pdbIdColIndex = tbl_summary.getColumn("PDB Id")
734                   .getModelIndex();
735           int refSeqColIndex = tbl_summary.getColumn("Ref Sequence")
736               .getModelIndex();
737           int[] selectedRows = tbl_summary.getSelectedRows();
738       PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
739       int count = 0;
740       ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
741       for (int row : selectedRows)
742       {
743             String pdbIdStr = tbl_summary.getValueAt(row, pdbIdColIndex)
744                 .toString();
745             SequenceI selectedSeq = (SequenceI) tbl_summary.getValueAt(row,
746                 refSeqColIndex);
747         selectedSeqsToView.add(selectedSeq);
748             PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
749             if (pdbEntry == null)
750             {
751               pdbEntry = getFindEntry(pdbIdStr,
752                       selectedSeq.getAllPDBEntries());
753             }
754         if (pdbEntry == null)
755         {
756           pdbEntry = new PDBEntry();
757           pdbEntry.setId(pdbIdStr);
758           pdbEntry.setType(PDBEntry.Type.PDB);
759           selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
760         }
761         pdbEntriesToView[count++] = pdbEntry;
762       }
763       SequenceI[] selectedSeqs = selectedSeqsToView
764               .toArray(new SequenceI[selectedSeqsToView.size()]);
765           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
766     }
767     else if (currentView == VIEWS_LOCAL_PDB)
768     {
769       int[] selectedRows = tbl_local_pdb.getSelectedRows();
770       PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
771       int count = 0;
772           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
773                   .getModelIndex();
774       int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
775               .getModelIndex();
776       ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
777       for (int row : selectedRows)
778       {
779         PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
780                 pdbIdColIndex);
781         pdbEntriesToView[count++] = pdbEntry;
782         SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(row,
783                 refSeqColIndex);
784         selectedSeqsToView.add(selectedSeq);
785       }
786       SequenceI[] selectedSeqs = selectedSeqsToView
787               .toArray(new SequenceI[selectedSeqsToView.size()]);
788           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
789     }
790     else if (currentView == VIEWS_ENTER_ID)
791     {
792       SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
793               .getCmb_assSeq().getSelectedItem()).getSequence();
794       if (userSelectedSeq != null)
795       {
796         selectedSequence = userSelectedSeq;
797       }
798
799       String pdbIdStr = txt_search.getText();
800       PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
801       if (pdbEntry == null)
802       {
803         pdbEntry = new PDBEntry();
804             if (pdbIdStr.split(":").length > 1)
805             {
806               pdbEntry.setChainCode(pdbIdStr.split(":")[1]);
807             }
808         pdbEntry.setId(pdbIdStr);
809         pdbEntry.setType(PDBEntry.Type.PDB);
810         selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
811       }
812
813       PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
814           launchStructureViewer(ssm, pdbEntriesToView, ap,
815                   new SequenceI[] { selectedSequence });
816     }
817     else if (currentView == VIEWS_FROM_FILE)
818     {
819       SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
820               .getCmb_assSeq().getSelectedItem()).getSequence();
821       if (userSelectedSeq != null)
822       {
823         selectedSequence = userSelectedSeq;
824       }
825       PDBEntry fileEntry = new AssociatePdbFileWithSeq()
826               .associatePdbWithSeq(selectedPdbFileName,
827                       jalview.io.AppletFormatAdapter.FILE,
828                       selectedSequence, true, Desktop.instance);
829
830           launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap,
831                   new SequenceI[] { selectedSequence });
832     }
833     mainFrame.dispose();
834       }
835     }).start();
836   }
837
838   private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
839   {
840     Objects.requireNonNull(id);
841     Objects.requireNonNull(pdbEntries);
842     PDBEntry foundEntry = null;
843     for (PDBEntry entry : pdbEntries)
844     {
845       if (entry.getId().equalsIgnoreCase(id))
846       {
847         return entry;
848       }
849     }
850     return foundEntry;
851   }
852
853   private void launchStructureViewer(StructureSelectionManager ssm,
854           final PDBEntry[] pdbEntriesToView,
855           final AlignmentPanel alignPanel, SequenceI[] sequences)
856   {
857     ssm.setProgressBar("Launching PDB structure viewer..");
858     final StructureViewer sViewer = new StructureViewer(ssm);
859
860     if (SiftsSettings.isMapWithSifts())
861     {
862       ArrayList<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
863       for (SequenceI seq : sequences)
864       {
865         if (seq.getSourceDBRef() == null)
866         {
867           if (seq.getDBRefs() == null)
868           {
869             seqsWithoutSourceDBRef.add(seq);
870             continue;
871           }
872           for (DBRefEntry dbRef : seq.getDBRefs())
873           {
874             if (dbRef.getSource().equalsIgnoreCase("uniprot"))
875             {
876               seq.setSourceDBRef(dbRef);
877               break;
878             }
879           }
880           for (DBRefEntry dbRef : seq.getDBRefs())
881           {
882             if (dbRef.getSource().equalsIgnoreCase("pdb"))
883             {
884               seq.setSourceDBRef(dbRef);
885               break;
886             }
887           }
888           if (seq.getSourceDBRef() == null)
889           {
890             seqsWithoutSourceDBRef.add(seq);
891           }
892         }
893       }
894       if (!seqsWithoutSourceDBRef.isEmpty())
895       {
896         int y = seqsWithoutSourceDBRef.size();
897         ssm.setProgressBar(null);
898         ssm.setProgressBar(">>>>> Fetching Database refs for " + y
899                 + " sequence" + (y > 1 ? "s" : "")
900                 + " with no valid uniprot or pdb ref for SIFTS mapping");
901         System.out.println(">>>>> Fetching Database refs for " + y
902                 + " sequence" + (y > 1 ? "s" : "")
903                 + " with no valid uniprot or pdb ref for SIFTS mapping");
904         SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
905         int x = 0;
906         for (SequenceI fSeq : seqsWithoutSourceDBRef)
907         {
908           seqWithoutSrcDBRef[x++] = fSeq;
909         }
910         new DBRefFetcher(seqWithoutSrcDBRef).fetchDBRefs(true);
911       }
912     }
913     if (pdbEntriesToView.length > 1)
914     {
915       ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
916       for (SequenceI seq : sequences)
917       {
918         seqsMap.add(new SequenceI[] { seq });
919       }
920       SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
921       ssm.setProgressBar(null);
922       ssm.setProgressBar("Fetching PDB Structures for selected entries..");
923       sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
924     }
925     else
926     {
927       ssm.setProgressBar(null);
928       ssm.setProgressBar("Fetching PDB Structure for "
929               + pdbEntriesToView[0].getId());
930       sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
931     }
932   }
933
934   /**
935    * Populates the combo-box used in associating manually fetched structures to
936    * a unique sequence when more than one sequence selection is made.
937    */
938   @Override
939   public void populateCmbAssociateSeqOptions(
940           JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
941   {
942     cmb_assSeq.removeAllItems();
943     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
944             null));
945     lbl_associateSeq.setVisible(false);
946     if (selectedSequences.length > 1)
947     {
948       for (SequenceI seq : selectedSequences)
949       {
950         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
951       }
952     }
953     else
954     {
955       String seqName = selectedSequence.getDisplayId(false);
956       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
957       lbl_associateSeq.setText(seqName);
958       lbl_associateSeq.setVisible(true);
959       cmb_assSeq.setVisible(false);
960     }
961   }
962
963   public boolean isStructuresDiscovered()
964   {
965     return structuresDiscovered;
966   }
967
968   public void setStructuresDiscovered(boolean structuresDiscovered)
969   {
970     this.structuresDiscovered = structuresDiscovered;
971   }
972
973   public Collection<FTSData> getDiscoveredStructuresSet()
974   {
975     return discoveredStructuresSet;
976   }
977
978   @Override
979   protected void txt_search_ActionPerformed()
980   {
981     new Thread()
982     {
983       @Override
984       public void run()
985       {
986         errorWarning.setLength(0);
987         isValidPBDEntry = false;
988         if (txt_search.getText().length() > 0)
989         {
990           String searchTerm = txt_search.getText().toLowerCase();
991           searchTerm = searchTerm.split(":")[0];
992           System.out.println(">>>>> search term : " + searchTerm);
993           List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
994           FTSRestRequest pdbRequest = new FTSRestRequest();
995           pdbRequest.setAllowEmptySeq(false);
996           pdbRequest.setResponseSize(1);
997           pdbRequest.setFieldToSearchBy("(pdb_id:");
998           pdbRequest.setWantedFields(wantedFields);
999           pdbRequest
1000 .setSearchTerm(searchTerm + ")");
1001           pdbRequest.setAssociatedSequence(selectedSequence);
1002           pdbRestCleint = PDBFTSRestClient.getInstance();
1003           wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1004           FTSRestResponse resultList;
1005           try
1006           {
1007             resultList = pdbRestCleint.executeRequest(pdbRequest);
1008           } catch (Exception e)
1009           {
1010             errorWarning.append(e.getMessage());
1011             return;
1012           } finally
1013           {
1014             validateSelections();
1015           }
1016           if (resultList.getSearchSummary() != null
1017                   && resultList.getSearchSummary().size() > 0)
1018           {
1019             isValidPBDEntry = true;
1020           }
1021         }
1022         validateSelections();
1023       }
1024     }.start();
1025   }
1026
1027   @Override
1028   public void tabRefresh()
1029   {
1030     if (selectedSequences != null)
1031     {
1032       Thread refreshThread = new Thread(new Runnable()
1033       {
1034         @Override
1035         public void run()
1036         {
1037           fetchStructuresMetaData();
1038           filterResultSet(((FilterOption) cmb_filterOption
1039                   .getSelectedItem()).getValue());
1040         }
1041       });
1042       refreshThread.start();
1043     }
1044   }
1045
1046   public class PDBEntryTableModel extends AbstractTableModel
1047   {
1048     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1049
1050     private List<CachedPDB> pdbEntries;
1051
1052     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1053     {
1054       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1055     }
1056
1057     @Override
1058     public String getColumnName(int columnIndex)
1059     {
1060       return columns[columnIndex];
1061     }
1062
1063     @Override
1064     public int getRowCount()
1065     {
1066       return pdbEntries.size();
1067     }
1068
1069     @Override
1070     public int getColumnCount()
1071     {
1072       return columns.length;
1073     }
1074
1075     @Override
1076     public boolean isCellEditable(int row, int column)
1077     {
1078       return false;
1079     }
1080
1081     @Override
1082     public Object getValueAt(int rowIndex, int columnIndex)
1083     {
1084       Object value = "??";
1085       CachedPDB entry = pdbEntries.get(rowIndex);
1086       switch (columnIndex)
1087       {
1088       case 0:
1089         value = entry.getSequence();
1090         break;
1091       case 1:
1092         value = entry.getPdbEntry();
1093         break;
1094       case 2:
1095         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1096                 .getPdbEntry().getChainCode();
1097         break;
1098       case 3:
1099         value = entry.getPdbEntry().getType();
1100         break;
1101       case 4:
1102         value = entry.getPdbEntry().getFile();
1103         break;
1104       }
1105       return value;
1106     }
1107
1108     @Override
1109     public Class<?> getColumnClass(int columnIndex)
1110     {
1111       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1112     }
1113
1114     public CachedPDB getPDBEntryAt(int row)
1115     {
1116       return pdbEntries.get(row);
1117     }
1118
1119   }
1120
1121   private class CachedPDB
1122   {
1123     private SequenceI sequence;
1124
1125     private PDBEntry pdbEntry;
1126
1127     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1128     {
1129       this.sequence = sequence;
1130       this.pdbEntry = pdbEntry;
1131     }
1132
1133     public SequenceI getSequence()
1134     {
1135       return sequence;
1136     }
1137
1138     public PDBEntry getPdbEntry()
1139     {
1140       return pdbEntry;
1141     }
1142
1143   }
1144
1145   private IProgressIndicator progressBar;
1146
1147   @Override
1148   public void setProgressBar(String message, long id)
1149   {
1150     progressBar.setProgressBar(message, id);
1151   }
1152
1153   @Override
1154   public void registerHandler(long id, IProgressIndicatorHandler handler)
1155   {
1156     progressBar.registerHandler(id, handler);
1157   }
1158
1159   @Override
1160   public boolean operationInProgress()
1161   {
1162     return progressBar.operationInProgress();
1163   }
1164 }