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