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