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