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