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