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