fca130ba881f8cb11e8a0ab7ad02debfeb7cdd8a
[jalview.git] / src / jalview / gui / SequenceFetcher.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.gui;
22
23 import jalview.api.FeatureSettingsModelI;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.service.pdb.PDBFTSPanel;
30 import jalview.fts.service.uniprot.UniprotFTSPanel;
31 import jalview.io.FileFormatI;
32 import jalview.io.gff.SequenceOntologyI;
33 import jalview.util.DBRefUtils;
34 import jalview.util.MessageManager;
35 import jalview.util.Platform;
36 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
37 import jalview.ws.seqfetcher.DbSourceProxy;
38
39 import java.awt.BorderLayout;
40 import java.awt.Font;
41 import java.awt.event.ActionEvent;
42 import java.awt.event.ActionListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Iterator;
48 import java.util.List;
49
50 import javax.swing.JButton;
51 import javax.swing.JCheckBox;
52 import javax.swing.JInternalFrame;
53 import javax.swing.JLabel;
54 import javax.swing.JOptionPane;
55 import javax.swing.JPanel;
56 import javax.swing.JScrollPane;
57 import javax.swing.JTextArea;
58 import javax.swing.SwingConstants;
59 import javax.swing.tree.DefaultMutableTreeNode;
60
61 public class SequenceFetcher extends JPanel implements Runnable
62 {
63   JLabel dbeg = new JLabel();
64
65   JDatabaseTree database;
66
67   JButton databaseButt;
68
69   JLabel jLabel1 = new JLabel();
70
71   JCheckBox replacePunctuation = new JCheckBox();
72
73   JButton ok = new JButton();
74
75   JButton clear = new JButton();
76
77   JButton example = new JButton();
78
79   JButton close = new JButton();
80
81   JPanel jPanel1 = new JPanel();
82
83   JTextArea textArea = new JTextArea();
84
85   JScrollPane jScrollPane1 = new JScrollPane();
86
87   JPanel jPanel2 = new JPanel();
88
89   JPanel jPanel3 = new JPanel();
90
91   JPanel jPanel4 = new JPanel();
92
93   BorderLayout borderLayout1 = new BorderLayout();
94
95   BorderLayout borderLayout2 = new BorderLayout();
96
97   BorderLayout borderLayout3 = new BorderLayout();
98
99   JInternalFrame frame;
100
101   IProgressIndicator guiWindow;
102
103   AlignFrame alignFrame;
104
105   StringBuffer result;
106
107   final String noDbSelected = "-- Select Database --";
108
109   private static jalview.ws.SequenceFetcher sfetch = null;
110
111   private static long lastDasSourceRegistry = -3;
112
113   private static DasSourceRegistryI dasRegistry = null;
114
115   private static boolean _initingFetcher = false;
116
117   private static Thread initingThread = null;
118
119   int debounceTrap = 0;
120
121   public JTextArea getTextArea()
122   {
123     return textArea;
124   }
125
126   /**
127    * Blocking method that initialises and returns the shared instance of the
128    * SequenceFetcher client
129    * 
130    * @param guiWindow
131    *          - where the initialisation delay message should be shown
132    * @return the singleton instance of the sequence fetcher client
133    */
134   public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
135           final IProgressIndicator guiWindow)
136   {
137     if (_initingFetcher && initingThread != null && initingThread.isAlive())
138     {
139       if (guiWindow != null)
140       {
141         guiWindow
142                 .setProgressBar(
143                         MessageManager
144                                 .getString("status.waiting_sequence_database_fetchers_init"),
145                         Thread.currentThread().hashCode());
146       }
147       // initting happening on another thread - so wait around to see if it
148       // finishes.
149       while (_initingFetcher && initingThread != null
150               && initingThread.isAlive())
151       {
152         try
153         {
154           Thread.sleep(10);
155         } catch (Exception e)
156         {
157         }
158         ;
159       }
160       if (guiWindow != null)
161       {
162         guiWindow
163                 .setProgressBar(
164                         MessageManager
165                                 .getString("status.waiting_sequence_database_fetchers_init"),
166                         Thread.currentThread().hashCode());
167       }
168     }
169     if (sfetch == null
170             || dasRegistry != Cache.getDasSourceRegistry()
171             || lastDasSourceRegistry != (Cache.getDasSourceRegistry()
172                     .getDasRegistryURL() + Cache
173                     .getDasSourceRegistry().getLocalSourceString())
174                     .hashCode())
175     {
176       _initingFetcher = true;
177       initingThread = Thread.currentThread();
178       /**
179        * give a visual indication that sequence fetcher construction is occuring
180        */
181       if (guiWindow != null)
182       {
183         guiWindow.setProgressBar(MessageManager
184                 .getString("status.init_sequence_database_fetchers"),
185                 Thread.currentThread().hashCode());
186       }
187       dasRegistry = Cache.getDasSourceRegistry();
188       dasRegistry.refreshSources();
189
190       jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
191       if (guiWindow != null)
192       {
193         guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
194       }
195       lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
196               .getLocalSourceString()).hashCode();
197       sfetch = sf;
198       _initingFetcher = false;
199       initingThread = null;
200     }
201     return sfetch;
202   }
203
204   private IProgressIndicator progressIndicator;
205
206   public SequenceFetcher(IProgressIndicator guiIndic)
207   {
208     this.progressIndicator = guiIndic;
209     final SequenceFetcher us = this;
210     // launch initialiser thread
211     Thread sf = new Thread(new Runnable()
212     {
213
214       @Override
215       public void run()
216       {
217         if (getSequenceFetcherSingleton(progressIndicator) != null)
218         {
219           us.initGui(progressIndicator);
220         }
221         else
222         {
223           javax.swing.SwingUtilities.invokeLater(new Runnable()
224           {
225             @Override
226             public void run()
227             {
228               JOptionPane
229                       .showInternalMessageDialog(
230                               Desktop.desktop,
231                               MessageManager
232                                       .getString("warn.couldnt_create_sequence_fetcher_client"),
233                               MessageManager
234                                       .getString("label.couldnt_create_sequence_fetcher"),
235                               JOptionPane.ERROR_MESSAGE);
236             }
237           });
238
239           // raise warning dialog
240         }
241       }
242     });
243     sf.start();
244   }
245
246   private class DatabaseAuthority extends DefaultMutableTreeNode
247   {
248
249   };
250
251   private class DatabaseSource extends DefaultMutableTreeNode
252   {
253
254   };
255
256   /**
257    * called by thread spawned by constructor
258    * 
259    * @param guiWindow
260    */
261   private void initGui(IProgressIndicator guiWindow)
262   {
263     this.guiWindow = guiWindow;
264     if (guiWindow instanceof AlignFrame)
265     {
266       alignFrame = (AlignFrame) guiWindow;
267     }
268     database = new JDatabaseTree(sfetch);
269     try
270     {
271       jbInit();
272     } catch (Exception ex)
273     {
274       ex.printStackTrace();
275     }
276
277     frame = new JInternalFrame();
278     frame.setContentPane(this);
279     if (Platform.isAMac())
280     {
281       Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 240);
282     }
283     else
284     {
285       Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 180);
286     }
287   }
288
289   private String getFrameTitle()
290   {
291     return ((alignFrame == null) ? MessageManager
292             .getString("label.new_sequence_fetcher") : MessageManager
293             .getString("label.additional_sequence_fetcher"));
294   }
295
296   private void jbInit() throws Exception
297   {
298     this.setLayout(borderLayout2);
299
300     database.setFont(JvSwingUtils.getLabelFont());
301     dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
302     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
303     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
304     jLabel1.setText(MessageManager
305             .getString("label.separate_multiple_accession_ids"));
306
307     replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
308     replacePunctuation
309             .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
310     replacePunctuation.setText(MessageManager
311             .getString("label.replace_commas_semicolons"));
312     ok.setText(MessageManager.getString("action.ok"));
313     ok.addActionListener(new ActionListener()
314     {
315       @Override
316       public void actionPerformed(ActionEvent e)
317       {
318         ok_actionPerformed();
319       }
320     });
321     clear.setText(MessageManager.getString("action.clear"));
322     clear.addActionListener(new ActionListener()
323     {
324       @Override
325       public void actionPerformed(ActionEvent e)
326       {
327         clear_actionPerformed();
328       }
329     });
330
331     example.setText(MessageManager.getString("label.example"));
332     example.addActionListener(new ActionListener()
333     {
334       @Override
335       public void actionPerformed(ActionEvent e)
336       {
337         example_actionPerformed();
338       }
339     });
340     close.setText(MessageManager.getString("action.close"));
341     close.addActionListener(new ActionListener()
342     {
343       @Override
344       public void actionPerformed(ActionEvent e)
345       {
346         close_actionPerformed(e);
347       }
348     });
349     textArea.setFont(JvSwingUtils.getLabelFont());
350     textArea.setLineWrap(true);
351     textArea.addKeyListener(new KeyAdapter()
352     {
353       @Override
354       public void keyPressed(KeyEvent e)
355       {
356         if (e.getKeyCode() == KeyEvent.VK_ENTER)
357         {
358           ok_actionPerformed();
359         }
360       }
361     });
362     jPanel3.setLayout(borderLayout1);
363     borderLayout1.setVgap(5);
364     jPanel1.add(ok);
365     jPanel1.add(example);
366     jPanel1.add(clear);
367     jPanel1.add(close);
368     jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
369     jPanel2.setLayout(borderLayout3);
370     databaseButt = /*database.getDatabaseSelectorButton();
371                    final JButton viewdbs =*/new JButton(
372             MessageManager.getString("action.select_ddbb"));
373     databaseButt.addActionListener(new ActionListener()
374     {
375
376       @Override
377       public void actionPerformed(ActionEvent arg0)
378       {
379         hidePanel();
380         database.showDialog();
381       }
382     });
383     databaseButt.setFont(JvSwingUtils.getLabelFont());
384     database.addActionListener(new ActionListener()
385     {
386       @Override
387       public void actionPerformed(ActionEvent e)
388       {
389         debounceTrap++;
390         String currentSelection = database.getSelectedItem();
391         if (currentSelection == null)
392         {
393           close_actionPerformed(null);
394         }
395
396         showPanel();
397
398         if (currentSelection.equalsIgnoreCase("pdb")
399                 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
400         {
401           pdbSourceAction();
402         }
403         else if (currentSelection.equalsIgnoreCase("uniprot")
404                 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
405         {
406           uniprotSourceAction();
407         }
408         else
409         {
410           otherSourceAction();
411         }
412         database.action = -1;
413       }
414     });
415
416     dbeg.setText("");
417     jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
418     jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
419     JPanel jPanel2a = new JPanel(new BorderLayout());
420     jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
421     jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
422     jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
423     // jPanel2.setPreferredSize(new Dimension())
424     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
425     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
426     this.add(jPanel3, java.awt.BorderLayout.CENTER);
427     this.add(jPanel2, java.awt.BorderLayout.NORTH);
428     jScrollPane1.getViewport().add(textArea);
429
430     /*
431      * open the database tree
432      */
433     database.waitForInput();
434   }
435
436   private void pdbSourceAction()
437   {
438     databaseButt.setText(database.getSelectedItem());
439     new PDBFTSPanel(this);
440     frame.dispose();
441   }
442
443   private void uniprotSourceAction()
444   {
445     databaseButt.setText(database.getSelectedItem());
446     new UniprotFTSPanel(this);
447     frame.dispose();
448   }
449   private void otherSourceAction()
450   {
451     try
452     {
453       databaseButt.setText(database.getSelectedItem()
454               + (database.getSelectedSources().size() > 1 ? " (and "
455                       + database.getSelectedSources().size() + " others)"
456                       : ""));
457       String eq = database.getExampleQueries();
458       dbeg.setText(MessageManager.formatMessage(
459               "label.example_query_param", new String[] { eq }));
460       boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
461       for (DbSourceProxy dbs : database.getSelectedSources())
462       {
463         if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
464         {
465           enablePunct = false;
466           break;
467         }
468       }
469       replacePunctuation.setEnabled(enablePunct);
470
471     } catch (Exception ex)
472     {
473       dbeg.setText("");
474       replacePunctuation.setEnabled(true);
475     }
476     jPanel2.repaint();
477   }
478
479   protected void example_actionPerformed()
480   {
481     DbSourceProxy db = null;
482     try
483     {
484       textArea.setText(database.getExampleQueries());
485     } catch (Exception ex)
486     {
487     }
488     jPanel3.repaint();
489   }
490
491   protected void clear_actionPerformed()
492   {
493     textArea.setText("");
494     jPanel3.repaint();
495   }
496
497   public void close_actionPerformed(ActionEvent e)
498   {
499     try
500     {
501       frame.setClosed(true);
502     } catch (Exception ex)
503     {
504     }
505   }
506
507   public void ok_actionPerformed()
508   {
509     databaseButt.setEnabled(false);
510     example.setEnabled(false);
511     textArea.setEnabled(false);
512     ok.setEnabled(false);
513     close.setEnabled(false);
514
515     Thread worker = new Thread(this);
516     worker.start();
517   }
518
519   private void resetDialog()
520   {
521     databaseButt.setEnabled(true);
522     example.setEnabled(true);
523     textArea.setEnabled(true);
524     ok.setEnabled(true);
525     close.setEnabled(true);
526   }
527
528   @Override
529   public void run()
530   {
531     String error = "";
532     if (!database.hasSelection())
533     {
534       error += "Please select the source database\n";
535     }
536     // TODO: make this transformation more configurable
537     com.stevesoft.pat.Regex empty;
538     if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
539     {
540       empty = new com.stevesoft.pat.Regex(
541       // replace commas and spaces with a semicolon
542               "(\\s|[,; ])+", ";");
543     }
544     else
545     {
546       // just turn spaces and semicolons into single semicolons
547       empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
548     }
549     textArea.setText(empty.replaceAll(textArea.getText()));
550     // see if there's anthing to search with
551     if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
552             .getText()))
553     {
554       error += "Please enter a (semi-colon separated list of) database id(s)";
555     }
556     if (error.length() > 0)
557     {
558       showErrorMessage(error);
559       resetDialog();
560       return;
561     }
562     // TODO: Refactor to GUI independent code and write tests.
563     // indicate if successive sources should be merged into one alignment.
564     boolean addToLast = false;
565     List<String> aresultq = new ArrayList<String>();
566     List<String> presultTitle = new ArrayList<String>();
567     List<AlignmentI> presult = new ArrayList<AlignmentI>();
568     List<AlignmentI> aresult = new ArrayList<AlignmentI>();
569     Iterator<DbSourceProxy> proxies = database.getSelectedSources()
570             .iterator();
571     String[] qries;
572     List<String> nextFetch = Arrays.asList(qries = textArea.getText()
573             .split(";"));
574     Iterator<String> en = Arrays.asList(new String[0]).iterator();
575     int nqueries = qries.length;
576
577     FeatureSettingsModelI preferredFeatureColours = null;
578     while (proxies.hasNext() && (en.hasNext() || nextFetch.size() > 0))
579     {
580       if (!en.hasNext() && nextFetch.size() > 0)
581       {
582         en = nextFetch.iterator();
583         nqueries = nextFetch.size();
584         // save the remaining queries in the original array
585         qries = nextFetch.toArray(new String[nqueries]);
586         nextFetch = new ArrayList<String>();
587       }
588
589       DbSourceProxy proxy = proxies.next();
590       try
591       {
592         // update status
593         guiWindow
594                 .setProgressBar(MessageManager.formatMessage(
595                         "status.fetching_sequence_queries_from",
596                         new String[] {
597                             Integer.valueOf(nqueries).toString(),
598                             proxy.getDbName() }), Thread.currentThread()
599                         .hashCode());
600         if (proxy.getMaximumQueryCount() == 1)
601         {
602           /*
603            * proxy only handles one accession id at a time
604            */
605           while (en.hasNext())
606           {
607             String acc = en.next();
608             if (!fetchSingleAccession(proxy, acc, aresultq, aresult))
609             {
610               nextFetch.add(acc);
611             }
612           }
613         }
614         else
615         {
616           /*
617            * proxy can fetch multiple accessions at one time
618            */
619           fetchMultipleAccessions(proxy, en, aresultq, aresult, nextFetch);
620         }
621       } catch (Exception e)
622       {
623         showErrorMessage("Error retrieving " + textArea.getText()
624                 + " from " + database.getSelectedItem());
625         // error
626         // +="Couldn't retrieve sequences from "+database.getSelectedItem();
627         System.err.println("Retrieval failed for source ='"
628                 + database.getSelectedItem() + "' and query\n'"
629                 + textArea.getText() + "'\n");
630         e.printStackTrace();
631       } catch (OutOfMemoryError e)
632       {
633         showErrorMessage("Out of Memory when retrieving "
634                 + textArea.getText()
635                 + " from "
636                 + database.getSelectedItem()
637                 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
638         e.printStackTrace();
639       } catch (Error e)
640       {
641         showErrorMessage("Serious Error retrieving " + textArea.getText()
642                 + " from " + database.getSelectedItem());
643         e.printStackTrace();
644       }
645
646       // Stack results ready for opening in alignment windows
647       if (aresult != null && aresult.size() > 0)
648       {
649         FeatureSettingsModelI proxyColourScheme = proxy
650                 .getFeatureColourScheme();
651         if (proxyColourScheme != null)
652         {
653           preferredFeatureColours = proxyColourScheme;
654         }
655
656         AlignmentI ar = null;
657         if (proxy.isAlignmentSource())
658         {
659           addToLast = false;
660           // new window for each result
661           while (aresult.size() > 0)
662           {
663             presult.add(aresult.remove(0));
664             presultTitle.add(aresultq.remove(0) + " "
665                     + getDefaultRetrievalTitle());
666           }
667         }
668         else
669         {
670           String titl = null;
671           if (addToLast && presult.size() > 0)
672           {
673             ar = presult.remove(presult.size() - 1);
674             titl = presultTitle.remove(presultTitle.size() - 1);
675           }
676           // concatenate all results in one window
677           while (aresult.size() > 0)
678           {
679             if (ar == null)
680             {
681               ar = aresult.remove(0);
682             }
683             else
684             {
685               ar.append(aresult.remove(0));
686             }
687           }
688           addToLast = true;
689           presult.add(ar);
690           presultTitle.add(titl);
691         }
692       }
693       guiWindow.setProgressBar(MessageManager
694               .getString("status.finshed_querying"), Thread.currentThread()
695               .hashCode());
696     }
697     guiWindow.setProgressBar(
698             (presult.size() > 0) ? MessageManager
699                     .getString("status.parsing_results") : MessageManager
700                     .getString("status.processing"), Thread.currentThread()
701                     .hashCode());
702     // process results
703     while (presult.size() > 0)
704     {
705       parseResult(presult.remove(0), presultTitle.remove(0), null,
706               preferredFeatureColours);
707     }
708     // only remove visual delay after we finished parsing.
709     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
710     if (nextFetch.size() > 0)
711     {
712       StringBuffer sb = new StringBuffer();
713       sb.append("Didn't retrieve the following "
714               + (nextFetch.size() == 1 ? "query" : nextFetch.size()
715                       + " queries") + ": \n");
716       int l = sb.length(), lr = 0;
717       for (String s : nextFetch)
718       {
719         if (l != sb.length())
720         {
721           sb.append("; ");
722         }
723         if (lr - sb.length() > 40)
724         {
725           sb.append("\n");
726         }
727         sb.append(s);
728       }
729       showErrorMessage(sb.toString());
730     }
731     resetDialog();
732   }
733
734   /**
735    * Tries to fetch one or more accession ids from the database proxy
736    * 
737    * @param proxy
738    * @param accessions
739    *          the queries to fetch
740    * @param aresultq
741    *          a successful queries list to add to
742    * @param aresult
743    *          a list of retrieved alignments to add to
744    * @param nextFetch
745    *          failed queries are added to this list
746    * @throws Exception
747    */
748   void fetchMultipleAccessions(DbSourceProxy proxy,
749           Iterator<String> accessions, List<String> aresultq,
750           List<AlignmentI> aresult, List<String> nextFetch)
751           throws Exception
752   {
753     StringBuilder multiacc = new StringBuilder();
754     List<String> tosend = new ArrayList<String>();
755     while (accessions.hasNext())
756     {
757       String nel = accessions.next();
758       tosend.add(nel);
759       multiacc.append(nel);
760       if (accessions.hasNext())
761       {
762         multiacc.append(proxy.getAccessionSeparator());
763       }
764     }
765
766     try
767     {
768       String query = multiacc.toString();
769       AlignmentI rslt = proxy.getSequenceRecords(query);
770       if (rslt == null || rslt.getHeight() == 0)
771       {
772         // no results - pass on all queries to next source
773         nextFetch.addAll(tosend);
774       }
775       else
776       {
777         aresultq.add(query);
778         aresult.add(rslt);
779         if (tosend.size() > 1)
780         {
781           checkResultForQueries(rslt, tosend, nextFetch, proxy);
782         }
783       }
784     } catch (OutOfMemoryError oome)
785     {
786       new OOMWarning("fetching " + multiacc + " from "
787               + database.getSelectedItem(), oome, this);
788     }
789   }
790
791   /**
792    * Query for a single accession id via the database proxy
793    * 
794    * @param proxy
795    * @param accession
796    * @param aresultq
797    *          a list of successful queries to add to
798    * @param aresult
799    *          a list of retrieved alignments to add to
800    * @return true if the fetch was successful, else false
801    */
802   boolean fetchSingleAccession(DbSourceProxy proxy, String accession,
803           List<String> aresultq, List<AlignmentI> aresult)
804   {
805     boolean success = false;
806     try
807     {
808       if (aresult != null)
809       {
810         try
811         {
812           // give the server a chance to breathe
813           Thread.sleep(5);
814         } catch (Exception e)
815         {
816           //
817         }
818       }
819
820       AlignmentI indres = null;
821       try
822       {
823         indres = proxy.getSequenceRecords(accession);
824       } catch (OutOfMemoryError oome)
825       {
826         new OOMWarning("fetching " + accession + " from "
827                 + proxy.getDbName(), oome, this);
828       }
829       if (indres != null)
830       {
831         aresultq.add(accession);
832         aresult.add(indres);
833         success = true;
834       }
835     } catch (Exception e)
836     {
837       Cache.log.info(
838               "Error retrieving " + accession
839               + " from " + proxy.getDbName(), e);
840     }
841     return success;
842   }
843
844   /**
845    * Checks which of the queries were successfully retrieved by searching the
846    * DBRefs of the retrieved sequences for a match. Any not found are added to
847    * the 'nextFetch' list.
848    * 
849    * @param rslt
850    * @param queries
851    * @param nextFetch
852    * @param proxy
853    */
854   void checkResultForQueries(AlignmentI rslt, List<String> queries,
855           List<String> nextFetch, DbSourceProxy proxy)
856   {
857     SequenceI[] rs = rslt.getSequencesArray();
858
859     for (String q : queries)
860     {
861       DBRefEntry dbr = new DBRefEntry();
862       dbr.setSource(proxy.getDbSource());
863       dbr.setVersion(null);
864       String accId = proxy.getAccessionIdFromQuery(q);
865       dbr.setAccessionId(accId);
866       boolean rfound = false;
867       for (int r = 0; r < rs.length; r++)
868       {
869         if (rs[r] != null)
870         {
871           List<DBRefEntry> found = DBRefUtils.searchRefs(rs[r].getDBRefs(),
872                   accId);
873           if (!found.isEmpty())
874           {
875             rfound = true;
876             break;
877           }
878         }
879       }
880       if (!rfound)
881       {
882         nextFetch.add(q);
883       }
884     }
885   }
886
887   /**
888    * 
889    * @return a standard title for any results retrieved using the currently
890    *         selected source and settings
891    */
892   public String getDefaultRetrievalTitle()
893   {
894     return "Retrieved from " + database.getSelectedItem();
895   }
896
897   AlignmentI parseResult(AlignmentI al, String title,
898           FileFormatI currentFileFormat,
899           FeatureSettingsModelI preferredFeatureColours)
900   {
901
902     if (al != null && al.getHeight() > 0)
903     {
904       if (title == null)
905       {
906         title = getDefaultRetrievalTitle();
907       }
908       if (alignFrame == null)
909       {
910         AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
911                 AlignFrame.DEFAULT_HEIGHT);
912         if (currentFileFormat != null)
913         {
914           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
915           // FORMAT FOR
916           // NON-FormatAdapter Sourced
917           // Alignments?
918         }
919
920         SequenceFeature[] sfs = null;
921         List<SequenceI> alsqs;
922         synchronized (alsqs = al.getSequences())
923         {
924           for (SequenceI sq : alsqs)
925           {
926             if ((sfs = sq.getSequenceFeatures()) != null)
927             {
928               if (sfs.length > 0)
929               {
930                 af.setShowSeqFeatures(true);
931                 break;
932               }
933             }
934
935           }
936         }
937
938         if (preferredFeatureColours != null)
939         {
940           af.getViewport().applyFeaturesStyle(preferredFeatureColours);
941         }
942         if (Cache.getDefault("HIDE_INTRONS", true))
943         {
944           af.hideFeatureColumns(SequenceOntologyI.EXON, false);
945         }
946
947         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
948                 AlignFrame.DEFAULT_HEIGHT);
949
950         af.statusBar.setText(MessageManager
951                 .getString("label.successfully_pasted_alignment_file"));
952
953         try
954         {
955           af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN",
956                   false));
957         } catch (Exception ex)
958         {
959         }
960       }
961       else
962       {
963         alignFrame.viewport.addAlignment(al, title);
964       }
965     }
966     return al;
967   }
968
969   void showErrorMessage(final String error)
970   {
971     resetDialog();
972     javax.swing.SwingUtilities.invokeLater(new Runnable()
973     {
974       @Override
975       public void run()
976       {
977         JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
978                 MessageManager.getString("label.error_retrieving_data"),
979                 JOptionPane.WARNING_MESSAGE);
980       }
981     });
982   }
983
984   public IProgressIndicator getProgressIndicator()
985   {
986     return progressIndicator;
987   }
988
989   public void setProgressIndicator(IProgressIndicator progressIndicator)
990   {
991     this.progressIndicator = progressIndicator;
992   }
993
994   /**
995    * Make this panel visible (after a selection has been made in the database
996    * chooser)
997    */
998   void showPanel()
999   {
1000     frame.setVisible(true);
1001   }
1002
1003   /**
1004    * Hide this panel (on clicking the database button to open the database
1005    * chooser)
1006    */
1007   void hidePanel()
1008   {
1009     frame.setVisible(false);
1010   }
1011 }