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