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