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