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