JAL-1993 close sequence fetcher when opening database chooser
[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     } catch (Exception ex)
272     {
273       ex.printStackTrace();
274     }
275
276     frame = new JInternalFrame();
277     frame.setContentPane(this);
278     if (Platform.isAMac())
279     {
280       Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 240);
281     }
282     else
283     {
284       Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 180);
285     }
286   }
287
288   private String getFrameTitle()
289   {
290     return ((alignFrame == null) ? MessageManager
291             .getString("label.new_sequence_fetcher") : MessageManager
292             .getString("label.additional_sequence_fetcher"));
293   }
294
295   private void jbInit() throws Exception
296   {
297     this.setLayout(borderLayout2);
298
299     database.setFont(JvSwingUtils.getLabelFont());
300     dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
301     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
302     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
303     jLabel1.setText(MessageManager
304             .getString("label.separate_multiple_accession_ids"));
305
306     replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
307     replacePunctuation
308             .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
309     replacePunctuation.setText(MessageManager
310             .getString("label.replace_commas_semicolons"));
311     ok.setText(MessageManager.getString("action.ok"));
312     ok.addActionListener(new ActionListener()
313     {
314       @Override
315       public void actionPerformed(ActionEvent e)
316       {
317         ok_actionPerformed();
318       }
319     });
320     clear.setText(MessageManager.getString("action.clear"));
321     clear.addActionListener(new ActionListener()
322     {
323       @Override
324       public void actionPerformed(ActionEvent e)
325       {
326         clear_actionPerformed();
327       }
328     });
329
330     example.setText(MessageManager.getString("label.example"));
331     example.addActionListener(new ActionListener()
332     {
333       @Override
334       public void actionPerformed(ActionEvent e)
335       {
336         example_actionPerformed();
337       }
338     });
339     close.setText(MessageManager.getString("action.close"));
340     close.addActionListener(new ActionListener()
341     {
342       @Override
343       public void actionPerformed(ActionEvent e)
344       {
345         close_actionPerformed(e);
346       }
347     });
348     textArea.setFont(JvSwingUtils.getLabelFont());
349     textArea.setLineWrap(true);
350     textArea.addKeyListener(new KeyAdapter()
351     {
352       @Override
353       public void keyPressed(KeyEvent e)
354       {
355         if (e.getKeyCode() == KeyEvent.VK_ENTER)
356         {
357           ok_actionPerformed();
358         }
359       }
360     });
361     jPanel3.setLayout(borderLayout1);
362     borderLayout1.setVgap(5);
363     jPanel1.add(ok);
364     jPanel1.add(example);
365     jPanel1.add(clear);
366     jPanel1.add(close);
367     jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
368     jPanel2.setLayout(borderLayout3);
369     databaseButt = /*database.getDatabaseSelectorButton();
370                    final JButton viewdbs =*/new JButton(
371             MessageManager.getString("action.select_ddbb"));
372     databaseButt.addActionListener(new ActionListener()
373     {
374
375       @Override
376       public void actionPerformed(ActionEvent arg0)
377       {
378         hidePanel();
379         database.showDialog();
380       }
381     });
382     databaseButt.setFont(JvSwingUtils.getLabelFont());
383     database.addActionListener(new ActionListener()
384     {
385       @Override
386       public void actionPerformed(ActionEvent e)
387       {
388         debounceTrap++;
389         String currentSelection = database.getSelectedItem();
390         if (currentSelection == null)
391         {
392           close_actionPerformed(null);
393         }
394
395         showPanel();
396
397         if (currentSelection.equalsIgnoreCase("pdb")
398                 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
399         {
400           pdbSourceAction();
401         }
402         else if (currentSelection.equalsIgnoreCase("uniprot")
403                 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
404         {
405           uniprotSourceAction();
406         }
407         else
408         {
409           otherSourceAction();
410         }
411         database.action = -1;
412       }
413     });
414
415     dbeg.setText("");
416     jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
417     jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
418     JPanel jPanel2a = new JPanel(new BorderLayout());
419     jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
420     jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
421     jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
422     // jPanel2.setPreferredSize(new Dimension())
423     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
424     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
425     this.add(jPanel3, java.awt.BorderLayout.CENTER);
426     this.add(jPanel2, java.awt.BorderLayout.NORTH);
427     jScrollPane1.getViewport().add(textArea);
428
429     /*
430      * open the database tree
431      */
432     database.waitForInput();
433   }
434
435   private void pdbSourceAction()
436   {
437     databaseButt.setText(database.getSelectedItem());
438     new PDBFTSPanel(this);
439     frame.dispose();
440   }
441
442   private void uniprotSourceAction()
443   {
444     databaseButt.setText(database.getSelectedItem());
445     new UniprotFTSPanel(this);
446     frame.dispose();
447   }
448   private void otherSourceAction()
449   {
450     try
451     {
452       databaseButt.setText(database.getSelectedItem()
453               + (database.getSelectedSources().size() > 1 ? " (and "
454                       + database.getSelectedSources().size() + " others)"
455                       : ""));
456       String eq = database.getExampleQueries();
457       dbeg.setText(MessageManager.formatMessage(
458               "label.example_query_param", new String[] { eq }));
459       boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
460       for (DbSourceProxy dbs : database.getSelectedSources())
461       {
462         if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
463         {
464           enablePunct = false;
465           break;
466         }
467       }
468       replacePunctuation.setEnabled(enablePunct);
469
470     } catch (Exception ex)
471     {
472       dbeg.setText("");
473       replacePunctuation.setEnabled(true);
474     }
475     jPanel2.repaint();
476   }
477
478   protected void example_actionPerformed()
479   {
480     DbSourceProxy db = null;
481     try
482     {
483       textArea.setText(database.getExampleQueries());
484     } catch (Exception ex)
485     {
486     }
487     jPanel3.repaint();
488   }
489
490   protected void clear_actionPerformed()
491   {
492     textArea.setText("");
493     jPanel3.repaint();
494   }
495
496   public void close_actionPerformed(ActionEvent e)
497   {
498     try
499     {
500       frame.setClosed(true);
501     } catch (Exception ex)
502     {
503     }
504   }
505
506   public void ok_actionPerformed()
507   {
508     databaseButt.setEnabled(false);
509     example.setEnabled(false);
510     textArea.setEnabled(false);
511     ok.setEnabled(false);
512     close.setEnabled(false);
513
514     Thread worker = new Thread(this);
515     worker.start();
516   }
517
518   private void resetDialog()
519   {
520     databaseButt.setEnabled(true);
521     example.setEnabled(true);
522     textArea.setEnabled(true);
523     ok.setEnabled(true);
524     close.setEnabled(true);
525   }
526
527   @Override
528   public void run()
529   {
530     String error = "";
531     if (!database.hasSelection())
532     {
533       error += "Please select the source database\n";
534     }
535     // TODO: make this transformation more configurable
536     com.stevesoft.pat.Regex empty;
537     if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
538     {
539       empty = new com.stevesoft.pat.Regex(
540       // replace commas and spaces with a semicolon
541               "(\\s|[,; ])+", ";");
542     }
543     else
544     {
545       // just turn spaces and semicolons into single semicolons
546       empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
547     }
548     textArea.setText(empty.replaceAll(textArea.getText()));
549     // see if there's anthing to search with
550     if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
551             .getText()))
552     {
553       error += "Please enter a (semi-colon separated list of) database id(s)";
554     }
555     if (error.length() > 0)
556     {
557       showErrorMessage(error);
558       resetDialog();
559       return;
560     }
561     // TODO: Refactor to GUI independent code and write tests.
562     // indicate if successive sources should be merged into one alignment.
563     boolean addToLast = false;
564     List<String> aresultq = new ArrayList<String>();
565     List<String> presultTitle = new ArrayList<String>();
566     List<AlignmentI> presult = new ArrayList<AlignmentI>();
567     List<AlignmentI> aresult = new ArrayList<AlignmentI>();
568     Iterator<DbSourceProxy> proxies = database.getSelectedSources()
569             .iterator();
570     String[] qries;
571     List<String> nextFetch = Arrays.asList(qries = textArea.getText()
572             .split(";"));
573     Iterator<String> en = Arrays.asList(new String[0]).iterator();
574     int nqueries = qries.length;
575
576     FeatureSettingsModelI preferredFeatureColours = null;
577     while (proxies.hasNext() && (en.hasNext() || nextFetch.size() > 0))
578     {
579       if (!en.hasNext() && nextFetch.size() > 0)
580       {
581         en = nextFetch.iterator();
582         nqueries = nextFetch.size();
583         // save the remaining queries in the original array
584         qries = nextFetch.toArray(new String[nqueries]);
585         nextFetch = new ArrayList<String>();
586       }
587
588       DbSourceProxy proxy = proxies.next();
589       try
590       {
591         // update status
592         guiWindow
593                 .setProgressBar(MessageManager.formatMessage(
594                         "status.fetching_sequence_queries_from",
595                         new String[] {
596                             Integer.valueOf(nqueries).toString(),
597                             proxy.getDbName() }), Thread.currentThread()
598                         .hashCode());
599         if (proxy.getMaximumQueryCount() == 1)
600         {
601           /*
602            * proxy only handles one accession id at a time
603            */
604           while (en.hasNext())
605           {
606             String acc = en.next();
607             if (!fetchSingleAccession(proxy, acc, aresultq, aresult))
608             {
609               nextFetch.add(acc);
610             }
611           }
612         }
613         else
614         {
615           /*
616            * proxy can fetch multiple accessions at one time
617            */
618           fetchMultipleAccessions(proxy, en, aresultq, aresult, nextFetch);
619         }
620       } catch (Exception e)
621       {
622         showErrorMessage("Error retrieving " + textArea.getText()
623                 + " from " + database.getSelectedItem());
624         // error
625         // +="Couldn't retrieve sequences from "+database.getSelectedItem();
626         System.err.println("Retrieval failed for source ='"
627                 + database.getSelectedItem() + "' and query\n'"
628                 + textArea.getText() + "'\n");
629         e.printStackTrace();
630       } catch (OutOfMemoryError e)
631       {
632         showErrorMessage("Out of Memory when retrieving "
633                 + textArea.getText()
634                 + " from "
635                 + database.getSelectedItem()
636                 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
637         e.printStackTrace();
638       } catch (Error e)
639       {
640         showErrorMessage("Serious Error retrieving " + textArea.getText()
641                 + " from " + database.getSelectedItem());
642         e.printStackTrace();
643       }
644
645       // Stack results ready for opening in alignment windows
646       if (aresult != null && aresult.size() > 0)
647       {
648         FeatureSettingsModelI proxyColourScheme = proxy
649                 .getFeatureColourScheme();
650         if (proxyColourScheme != null)
651         {
652           preferredFeatureColours = proxyColourScheme;
653         }
654
655         AlignmentI ar = null;
656         if (proxy.isAlignmentSource())
657         {
658           addToLast = false;
659           // new window for each result
660           while (aresult.size() > 0)
661           {
662             presult.add(aresult.remove(0));
663             presultTitle.add(aresultq.remove(0) + " "
664                     + getDefaultRetrievalTitle());
665           }
666         }
667         else
668         {
669           String titl = null;
670           if (addToLast && presult.size() > 0)
671           {
672             ar = presult.remove(presult.size() - 1);
673             titl = presultTitle.remove(presultTitle.size() - 1);
674           }
675           // concatenate all results in one window
676           while (aresult.size() > 0)
677           {
678             if (ar == null)
679             {
680               ar = aresult.remove(0);
681             }
682             else
683             {
684               ar.append(aresult.remove(0));
685             }
686           }
687           addToLast = true;
688           presult.add(ar);
689           presultTitle.add(titl);
690         }
691       }
692       guiWindow.setProgressBar(MessageManager
693               .getString("status.finshed_querying"), Thread.currentThread()
694               .hashCode());
695     }
696     guiWindow.setProgressBar(
697             (presult.size() > 0) ? MessageManager
698                     .getString("status.parsing_results") : MessageManager
699                     .getString("status.processing"), Thread.currentThread()
700                     .hashCode());
701     // process results
702     while (presult.size() > 0)
703     {
704       parseResult(presult.remove(0), presultTitle.remove(0), null,
705               preferredFeatureColours);
706     }
707     // only remove visual delay after we finished parsing.
708     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
709     if (nextFetch.size() > 0)
710     {
711       StringBuffer sb = new StringBuffer();
712       sb.append("Didn't retrieve the following "
713               + (nextFetch.size() == 1 ? "query" : nextFetch.size()
714                       + " queries") + ": \n");
715       int l = sb.length(), lr = 0;
716       for (String s : nextFetch)
717       {
718         if (l != sb.length())
719         {
720           sb.append("; ");
721         }
722         if (lr - sb.length() > 40)
723         {
724           sb.append("\n");
725         }
726         sb.append(s);
727       }
728       showErrorMessage(sb.toString());
729     }
730     resetDialog();
731   }
732
733   /**
734    * Tries to fetch one or more accession ids from the database proxy
735    * 
736    * @param proxy
737    * @param accessions
738    *          the queries to fetch
739    * @param aresultq
740    *          a successful queries list to add to
741    * @param aresult
742    *          a list of retrieved alignments to add to
743    * @param nextFetch
744    *          failed queries are added to this list
745    * @throws Exception
746    */
747   void fetchMultipleAccessions(DbSourceProxy proxy,
748           Iterator<String> accessions, List<String> aresultq,
749           List<AlignmentI> aresult, List<String> nextFetch)
750           throws Exception
751   {
752     StringBuilder multiacc = new StringBuilder();
753     List<String> tosend = new ArrayList<String>();
754     while (accessions.hasNext())
755     {
756       String nel = accessions.next();
757       tosend.add(nel);
758       multiacc.append(nel);
759       if (accessions.hasNext())
760       {
761         multiacc.append(proxy.getAccessionSeparator());
762       }
763     }
764
765     try
766     {
767       String query = multiacc.toString();
768       AlignmentI rslt = proxy.getSequenceRecords(query);
769       if (rslt == null || rslt.getHeight() == 0)
770       {
771         // no results - pass on all queries to next source
772         nextFetch.addAll(tosend);
773       }
774       else
775       {
776         aresultq.add(query);
777         aresult.add(rslt);
778         if (tosend.size() > 1)
779         {
780           checkResultForQueries(rslt, tosend, nextFetch, proxy);
781         }
782       }
783     } catch (OutOfMemoryError oome)
784     {
785       new OOMWarning("fetching " + multiacc + " from "
786               + database.getSelectedItem(), oome, this);
787     }
788   }
789
790   /**
791    * Query for a single accession id via the database proxy
792    * 
793    * @param proxy
794    * @param accession
795    * @param aresultq
796    *          a list of successful queries to add to
797    * @param aresult
798    *          a list of retrieved alignments to add to
799    * @return true if the fetch was successful, else false
800    */
801   boolean fetchSingleAccession(DbSourceProxy proxy, String accession,
802           List<String> aresultq, List<AlignmentI> aresult)
803   {
804     boolean success = false;
805     try
806     {
807       if (aresult != null)
808       {
809         try
810         {
811           // give the server a chance to breathe
812           Thread.sleep(5);
813         } catch (Exception e)
814         {
815           //
816         }
817       }
818
819       AlignmentI indres = null;
820       try
821       {
822         indres = proxy.getSequenceRecords(accession);
823       } catch (OutOfMemoryError oome)
824       {
825         new OOMWarning("fetching " + accession + " from "
826                 + proxy.getDbName(), oome, this);
827       }
828       if (indres != null)
829       {
830         aresultq.add(accession);
831         aresult.add(indres);
832         success = true;
833       }
834     } catch (Exception e)
835     {
836       Cache.log.info(
837               "Error retrieving " + accession
838               + " from " + proxy.getDbName(), e);
839     } finally
840     {
841       return success;
842     }
843   }
844
845   /**
846    * Checks which of the queries were successfully retrieved by searching the
847    * DBRefs of the retrieved sequences for a match. Any not found are added to
848    * the 'nextFetch' list.
849    * 
850    * @param rslt
851    * @param queries
852    * @param nextFetch
853    * @param proxy
854    */
855   void checkResultForQueries(AlignmentI rslt, List<String> queries,
856           List<String> nextFetch, DbSourceProxy proxy)
857   {
858     SequenceI[] rs = rslt.getSequencesArray();
859
860     for (String q : queries)
861     {
862       DBRefEntry[] found = null;
863       DBRefEntry dbr = new DBRefEntry();
864       dbr.setSource(proxy.getDbSource());
865       dbr.setVersion(null);
866       String accId = proxy.getAccessionIdFromQuery(q);
867       dbr.setAccessionId(accId);
868       boolean rfound = false;
869       for (int r = 0; r < rs.length; r++)
870       {
871         if (rs[r] != null)
872         {
873           found = DBRefUtils.searchRefs(rs[r].getDBRefs(), accId);
874           if (found != null && found.length > 0)
875           {
876             rfound = true;
877             break;
878           }
879         }
880       }
881       if (!rfound)
882       {
883         nextFetch.add(q);
884       }
885     }
886   }
887
888   /**
889    * 
890    * @return a standard title for any results retrieved using the currently
891    *         selected source and settings
892    */
893   public String getDefaultRetrievalTitle()
894   {
895     return "Retrieved from " + database.getSelectedItem();
896   }
897
898   AlignmentI parseResult(AlignmentI al, String title,
899           String currentFileFormat,
900           FeatureSettingsModelI preferredFeatureColours)
901   {
902
903     if (al != null && al.getHeight() > 0)
904     {
905       if (title == null)
906       {
907         title = getDefaultRetrievalTitle();
908       }
909       if (alignFrame == null)
910       {
911         AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
912                 AlignFrame.DEFAULT_HEIGHT);
913         if (currentFileFormat != null)
914         {
915           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
916           // FORMAT FOR
917           // NON-FormatAdapter Sourced
918           // Alignments?
919         }
920
921         SequenceFeature[] sfs = null;
922         List<SequenceI> alsqs;
923         synchronized (alsqs = al.getSequences())
924         {
925           for (SequenceI sq : alsqs)
926           {
927             if ((sfs = sq.getSequenceFeatures()) != null)
928             {
929               if (sfs.length > 0)
930               {
931                 af.setShowSeqFeatures(true);
932                 break;
933               }
934             }
935
936           }
937         }
938
939         if (preferredFeatureColours != null)
940         {
941           af.getViewport().applyFeaturesStyle(preferredFeatureColours);
942         }
943         if (Cache.getDefault("HIDE_INTRONS", true))
944         {
945           af.hideFeatureColumns(SequenceOntologyI.EXON, false);
946         }
947
948         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
949                 AlignFrame.DEFAULT_HEIGHT);
950
951         af.statusBar.setText(MessageManager
952                 .getString("label.successfully_pasted_alignment_file"));
953
954         try
955         {
956           af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN",
957                   false));
958         } catch (Exception ex)
959         {
960         }
961       }
962       else
963       {
964         alignFrame.viewport.addAlignment(al, title);
965       }
966     }
967     return al;
968   }
969
970   void showErrorMessage(final String error)
971   {
972     resetDialog();
973     javax.swing.SwingUtilities.invokeLater(new Runnable()
974     {
975       @Override
976       public void run()
977       {
978         JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
979                 MessageManager.getString("label.error_retrieving_data"),
980                 JOptionPane.WARNING_MESSAGE);
981       }
982     });
983   }
984
985   public IProgressIndicator getProgressIndicator()
986   {
987     return progressIndicator;
988   }
989
990   public void setProgressIndicator(IProgressIndicator progressIndicator)
991   {
992     this.progressIndicator = progressIndicator;
993   }
994
995   /**
996    * Make this panel visible (after a selection has been made in the database
997    * chooser)
998    */
999   void showPanel()
1000   {
1001     frame.setVisible(true);
1002   }
1003
1004   /**
1005    * Hide this panel (on clicking the database button to open the database
1006    * chooser)
1007    */
1008   void hidePanel()
1009   {
1010     frame.setVisible(false);
1011   }
1012 }